Compare commits

..
Author SHA1 Message Date
Chris Tate 09f8d56a9c fixes 2026-02-24 22:53:23 -06:00
Chris Tate 2e54a867e4 fixes 2026-02-24 22:43:32 -06:00
Chris Tate 2913192cbe fixes 2026-02-24 09:34:17 -06:00
Chris Tate 43694d6046 tests 2026-02-24 09:32:40 -06:00
Chris Tate 7b67f33bab update turbo 2026-02-24 09:11:36 -06:00
Chris Tate 945d1d232a fixes 2026-02-24 09:10:14 -06:00
Chris Tate 44c135bf3b tests 2026-02-24 09:00:00 -06:00
Chris Tate 7a610fc2b6 fixes 2026-02-24 08:45:33 -06:00
Chris Tate 5b3c2c167b fixes 2026-02-24 08:37:22 -06:00
Chris Tate f9459e1001 fixes 2026-02-24 07:54:51 -06:00
Chris Tate cc00444546 fixes 2026-02-24 07:45:27 -06:00
Chris Tate 7655ab4822 fixes 2026-02-24 07:34:58 -06:00
Chris Tate cc8f3ff139 fixes 2026-02-24 07:26:18 -06:00
Chris Tate d694e0efde fixes 2026-02-24 07:14:37 -06:00
Chris Tate 7fde7cd0a9 add dynamic forms support: computed values, watchers, cross-field validation
- `$computed` and `$template` prop expressions for derived values and string interpolation
- Element-level `watch` field for cascading state dependencies
- Cross-field validators (`lessThan`, `greaterThan`, `equalTo`, `requiredIf`) with deep arg resolution
- `validateForm` built-in action for form-level validation
2026-02-24 06:43:58 -06:00
122 changed files with 161 additions and 9656 deletions
+1 -3
View File
@@ -13,9 +13,7 @@
"@json-render/codegen",
"@json-render/zustand",
"@json-render/redux",
"@json-render/jotai",
"@json-render/vue",
"@json-render/xstate"
"@json-render/jotai"
]
],
"linked": [],
+5 -50
View File
@@ -5,18 +5,15 @@
Generate dynamic, personalized UIs from prompts without sacrificing reliability. Predefined components and actions for safe, predictable output.
```bash
# for React
npm install @json-render/core @json-render/react
# for React with pre-built shadcn/ui components
# pre-built shadcn/ui components
npm install @json-render/shadcn
# or for React Native
# or for mobile
npm install @json-render/core @json-render/react-native
# or for video
npm install @json-render/core @json-render/remotion
# or for PDF documents
npm install @json-render/core @json-render/react-pdf
# or for Vue
npm install @json-render/core @json-render/vue
```
## Why json-render?
@@ -26,7 +23,7 @@ json-render is a **Generative UI** framework: AI generates interfaces from natur
- **Guardrailed** - AI can only use components in your catalog
- **Predictable** - JSON output matches your schema, every time
- **Fast** - Stream and render progressively as the model responds
- **Cross-Platform** - React, Vue (web), React Native (mobile) from the same catalog
- **Cross-Platform** - React (web) and React Native (mobile) from the same catalog
- **Batteries Included** - 36 pre-built shadcn/ui components ready to use
## Quick Start
@@ -113,7 +110,6 @@ function Dashboard({ spec }) {
|---------|-------------|
| `@json-render/core` | Schemas, catalogs, AI prompts, dynamic props, SpecStream utilities |
| `@json-render/react` | React renderer, contexts, hooks |
| `@json-render/vue` | Vue 3 renderer, composables, providers |
| `@json-render/shadcn` | 36 pre-built shadcn/ui components (Radix UI + Tailwind CSS) |
| `@json-render/react-native` | React Native renderer with standard mobile components |
| `@json-render/remotion` | Remotion video renderer, timeline schema |
@@ -121,7 +117,6 @@ function Dashboard({ spec }) {
| `@json-render/redux` | Redux / Redux Toolkit adapter for `StateStore` |
| `@json-render/zustand` | Zustand adapter for `StateStore` |
| `@json-render/jotai` | Jotai adapter for `StateStore` |
| `@json-render/xstate` | XState Store (atom) adapter for `StateStore` |
## Renderers
@@ -153,26 +148,6 @@ const { registry } = defineRegistry(catalog, { components });
<Renderer spec={spec} registry={registry} />
```
### Vue (UI)
```typescript
import { h } from "vue";
import { defineRegistry, Renderer } from "@json-render/vue";
import { schema } from "@json-render/vue/schema";
const { registry } = defineRegistry(catalog, {
components: {
Card: ({ props, children }) =>
h("div", { class: "card" }, [h("h3", null, props.title), children]),
Button: ({ props, emit }) =>
h("button", { onClick: () => emit("press") }, props.label),
},
});
// In your Vue component template:
// <Renderer :spec="spec" :registry="registry" />
```
### shadcn/ui (Web)
```tsx
@@ -342,12 +317,10 @@ Any prop value can be data-driven using expressions:
}
```
Expression forms:
Two expression forms:
- **`{ "$state": "/state/key" }`** - reads a value from the state model
- **`{ "$cond": <condition>, "$then": <value>, "$else": <value> }`** - evaluates a condition and picks a branch
- **`{ "$template": "Hello, ${/user/name}!" }`** - interpolates state values into strings
- **`{ "$computed": "fn", "args": { ... } }`** - calls a registered function with resolved args
- **`{ "$cond": <condition>, "$then": <value>, "$else": <value> }`** - evaluates a condition (same syntax as visibility conditions) and picks a branch
### Actions
@@ -363,22 +336,6 @@ Components can trigger actions, including the built-in `setState` action:
The `setState` action updates the state model directly, which re-evaluates visibility conditions and dynamic prop expressions.
### State Watchers
React to state changes by triggering actions:
```json
{
"type": "Select",
"props": { "value": { "$bindState": "/form/country" }, "options": ["US", "Canada", "UK"] },
"watch": {
"/form/country": { "action": "loadCities", "params": { "country": { "$state": "/form/country" } } }
}
}
```
`watch` is a top-level field on elements (sibling of `type`/`props`/`children`). Watchers fire when the watched value changes, not on initial render.
---
## Demo
@@ -394,8 +351,6 @@ pnpm dev
- http://dashboard-demo.json-render.localhost:1355 - Example Dashboard
- http://remotion-demo.json-render.localhost:1355 - Remotion Video Example
- Chat Example: run `pnpm dev` in `examples/chat`
- Vue Example: run `pnpm dev` in `examples/vue`
- Vite Renderers (React + Vue): run `pnpm dev` in `examples/vite-renderers`
- React Native example: run `npx expo start` in `examples/react-native`
## How It Works
-18
View File
@@ -1,23 +1,5 @@
# web
## 0.1.3
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
- @json-render/react@0.10.0
- @json-render/codegen@0.10.0
## 0.1.2
### Patch Changes
- Updated dependencies [b103676]
- @json-render/react@0.9.1
- @json-render/core@0.9.1
- @json-render/codegen@0.9.1
## 0.1.1
### Patch Changes
@@ -109,27 +109,6 @@ const { registry } = defineRegistry(catalog, {
type Registry = Record<string, React.ComponentType<ComponentRenderProps>>;
```
### JSONUIProvider
Convenience wrapper that combines `StateProvider`, `VisibilityProvider`, `ValidationProvider`, and `ActionProvider`. Accepts all their props plus:
| Prop | Type | Description |
|------|------|-------------|
| `functions` | `Record<string, ComputedFunction>` | Named functions for `$computed` expressions in props |
```tsx
<JSONUIProvider
spec={spec}
catalog={catalog}
handlers={{ submit: async () => { /* ... */ } }}
functions={{ fullName: (args) => `${args.first} ${args.last}` }}
>
<Renderer spec={spec} registry={registry} />
</JSONUIProvider>
```
The `functions` prop is also available on `createRenderer`.
### Component Props (via defineRegistry)
```tsx
@@ -258,15 +237,6 @@ const {
`ValidationConfig` is `{ checks?: ValidationCheck[], validateOn?: 'change' | 'blur' | 'submit' }`.
### useOptionalValidation
Non-throwing variant of `useValidation()`. Returns `null` when no `ValidationProvider` is present, instead of throwing. Useful in components that may or may not be rendered inside a validation context.
```typescript
const validation = useOptionalValidation();
// ValidationContextValue | null
```
### useBoundProp
Two-way binding helper for `$bindState` / `$bindItem` expressions. Returns `[value, setValue]` where `setValue` writes back to the bound state path.
-246
View File
@@ -1,246 +0,0 @@
import { pageMetadata } from "@/lib/page-metadata"
export const metadata = pageMetadata("docs/api/vue")
# @json-render/vue
Vue 3 components, providers, and composables.
## Providers
### StateProvider
```vue
<StateProvider :initial-state="object" :on-state-change="fn">
<!-- children -->
</StateProvider>
```
| Prop | Type | Description |
|------|------|-------------|
| `store` | `StateStore` | External store (controlled mode). When provided, `initialState` and `onStateChange` are ignored. |
| `initialState` | `Record<string, unknown>` | Initial state model (uncontrolled mode). |
| `onStateChange` | `(changes: Array<{ path: string; value: unknown }>) => void` | Callback when state changes (uncontrolled mode). Called once per `set` or `update` with all changed entries. |
#### External Store (Controlled Mode)
Pass a `StateStore` to bypass the internal state and wire json-render to any state management library:
```typescript
import { createStateStore, type StateStore } from "@json-render/vue";
const store = createStateStore({ count: 0 });
```
```vue
<StateProvider :store="store">
<!-- children -->
</StateProvider>
```
```typescript
// Mutate from anywhere — Vue re-renders automatically:
store.set("/count", 1);
```
### ActionProvider
```vue
<ActionProvider :handlers="Record<string, ActionHandler>" :navigate="fn">
<!-- children -->
</ActionProvider>
// type ActionHandler = (params: Record<string, unknown>) => void | Promise<void>;
```
### VisibilityProvider
```vue
<VisibilityProvider>
<!-- children -->
</VisibilityProvider>
```
`VisibilityProvider` reads state from the parent `StateProvider` automatically. Conditions in specs use the `VisibilityCondition` format with `$state` paths (e.g. `{ "$state": "/path" }`, `{ "$state": "/path", "eq": value }`). See [visibility](/docs/visibility) for the full syntax.
### ValidationProvider
```vue
<ValidationProvider :custom-functions="Record<string, ValidationFunction>">
<!-- children -->
</ValidationProvider>
// type ValidationFunction = (value: unknown, args?: object) => boolean | Promise<boolean>;
```
## defineRegistry
Create a type-safe component registry from a catalog. Components receive `props`, `children`, `emit`, `on`, and `loading` with catalog-inferred types.
When the catalog declares actions, the `actions` field is required. When the catalog has no actions (e.g. `actions: {}`), the field is optional. When passing stubs, any `async () => {}` is sufficient.
```typescript
import { h } from "vue";
import { defineRegistry } from "@json-render/vue";
const { registry } = defineRegistry(catalog, {
components: {
Card: ({ props, children }) =>
h("div", { class: "card" }, [h("h3", null, props.title), children]),
Button: ({ props, emit }) =>
h("button", { onClick: () => emit("press") }, props.label),
},
// Required when catalog declares actions:
actions: {
submit: async (params) => { /* ... */ },
},
});
// Pass to <Renderer>
// <Renderer :spec="spec" :registry="registry" />
```
## Components
### Renderer
```vue
<Renderer
:spec="Spec" // The UI spec to render
:registry="Registry" // Component registry (from defineRegistry)
:loading="boolean" // Optional loading state
:fallback="Component" // Optional fallback for unknown types
/>
```
### Component Props (via defineRegistry)
```typescript
import type { VNode } from "vue";
interface ComponentContext<P> {
props: P; // Typed props from catalog
children?: VNode | VNode[]; // Rendered children (for container components)
emit: (event: string) => void; // Emit a named event (always defined)
on: (event: string) => EventHandle; // Get event handle with metadata
loading?: boolean;
bindings?: Record<string, string>; // State paths from $bindState/$bindItem expressions
}
interface EventHandle {
emit: () => void; // Fire the event
shouldPreventDefault: boolean; // Whether any binding requested preventDefault
bound: boolean; // Whether any handler is bound
}
```
Use `emit("press")` for simple event firing. Use `on("click")` when you need metadata like `shouldPreventDefault`:
```typescript
Link: ({ props, on }) => {
const click = on("click");
return h("a", {
href: props.href,
onClick: (e: MouseEvent) => {
if (click.shouldPreventDefault) e.preventDefault();
click.emit();
},
}, props.label);
},
```
### BaseComponentProps
Catalog-agnostic base type for building reusable component libraries that are not tied to a specific catalog:
```typescript
import type { BaseComponentProps } from "@json-render/vue";
const Card = ({ props, children }: BaseComponentProps<{ title?: string }>) =>
h("div", null, [props.title, children]);
```
## Composables
### useStateStore
```typescript
const {
state, // ShallowRef<StateModel> — access with state.value
get, // (path: string) => unknown
set, // (path: string, value: unknown) => void
update, // (updates: Record<string, unknown>) => void
} = useStateStore();
```
> **Note:** `state` is a `ShallowRef<StateModel>`, not a plain object. Use `state.value` to read the current state. This differs from the React renderer.
### useStateValue
```typescript
const value = useStateValue(path: string); // ComputedRef<T | undefined>
```
Returns a `ComputedRef` that automatically updates when the state at `path` changes. Use `.value` to access the current value.
### useStateBinding (deprecated)
> **Deprecated.** Use `$bindState` expressions with `bindings` prop instead.
```typescript
const [value, setValue] = useStateBinding(path: string);
// value: ComputedRef<T | undefined>
// setValue: (value: T) => void
```
### useActions
```typescript
const { execute } = useActions();
// execute(binding: ActionBinding) => Promise<void>
```
### useAction
```typescript
const { execute, isLoading } = useAction(binding: ActionBinding);
// execute: () => Promise<void>
// isLoading: ComputedRef<boolean>
```
### useIsVisible
```typescript
const isVisible = useIsVisible(condition?: VisibilityCondition);
```
### useFieldValidation
```typescript
const {
state, // ComputedRef<FieldValidationState>
validate, // () => ValidationResult
touch, // () => void
clear, // () => void
errors, // ComputedRef<string[]>
isValid, // ComputedRef<boolean>
} = useFieldValidation(path: string, config?: ValidationConfig);
```
`ValidationConfig` is `{ checks?: ValidationCheck[], validateOn?: 'change' | 'blur' | 'submit' }`.
## Differences from `@json-render/react`
| API | React | Vue | Note |
|-----|-------|-----|------|
| `useStateStore().state` | `StateModel` (plain object) | `ShallowRef<StateModel>` | Vue reactivity; use `state.value` |
| `useStateValue()` | `T \| undefined` | `ComputedRef<T \| undefined>` | Vue reactivity; use `.value` |
| `useStateBinding()` | `[T \| undefined, setter]` | `[ComputedRef<T \| undefined>, setter]` | Vue reactivity; use `value.value` |
| `useAction().isLoading` | `boolean` | `ComputedRef<boolean>` | Vue reactivity; use `.value` |
| `useFieldValidation().state` | `FieldValidationState` | `ComputedRef<FieldValidationState>` | Vue reactivity; use `.value` |
| `useFieldValidation().errors` | `string[]` | `ComputedRef<string[]>` | Vue reactivity; use `.value` |
| `useFieldValidation().isValid` | `boolean` | `ComputedRef<boolean>` | Vue reactivity; use `.value` |
| `VisibilityContextValue.ctx` | `CoreVisibilityContext` | `ComputedRef<CoreVisibilityContext>` | Vue reactivity; use `ctx.value` |
| `children` type | `React.ReactNode` | `VNode \| VNode[]` | Platform-specific |
| `useBoundProp` | exported | exported | Same API; returns `[value, setValue]` |
| `VisibilityProviderProps` | exported | not exported (no props) | Vue uses slot, no prop needed |
| Streaming hooks | `useUIStream`, `useChatUI` | `useUIStream`, `useChatUI` | Same API; returns Vue `Ref` values |
-123
View File
@@ -5,129 +5,6 @@ export const metadata = pageMetadata("docs/changelog")
Notable changes and updates to json-render.
## v0.10.0
February 2026
### New: `@json-render/vue`
Vue 3 renderer for json-render with full feature parity with `@json-render/react`. Data binding, visibility conditions, actions, validation, repeat scopes, streaming, and external store support.
```bash
npm install @json-render/core @json-render/vue
```
```typescript
import { h } from "vue";
import { defineRegistry, Renderer } from "@json-render/vue";
import { schema } from "@json-render/vue/schema";
const { registry } = defineRegistry(catalog, {
components: {
Card: ({ props, children }) =>
h("div", { class: "card" }, [h("h3", null, props.title), children]),
Button: ({ props, emit }) =>
h("button", { onClick: () => emit("press") }, props.label),
},
});
```
Providers: `StateProvider`, `ActionProvider`, `VisibilityProvider`, `ValidationProvider`. Composables: `useStateStore`, `useStateValue`, `useActions`, `useAction`, `useIsVisible`, `useFieldValidation`, `useBoundProp`, `useUIStream`, `useChatUI`.
See the [Vue API reference](/docs/api/vue) for details.
### New: `@json-render/xstate`
[XState Store](https://stately.ai/docs/xstate-store) (atom) adapter for json-render's `StateStore` interface. Wire an `@xstate/store` atom as the state backend for any renderer.
```bash
npm install @json-render/xstate @xstate/store
```
```typescript
import { createAtom } from "@xstate/store";
import { xstateStoreStateStore } from "@json-render/xstate";
const atom = createAtom({ count: 0 });
const store = xstateStoreStateStore({ atom });
```
Requires `@xstate/store` v3+.
### New: `$computed` and `$template` Expressions
Two new prop expression types for dynamic values:
- **`$template`** -- interpolate state values into strings: `{ "$template": "Hello, ${/user/name}!" }`
- **`$computed`** -- call registered functions: `{ "$computed": "fullName", "args": { "first": { "$state": "/form/firstName" } } }`
Register functions via the `functions` prop on `JSONUIProvider` or `createRenderer`. See [Computed Values](/docs/computed-values) for details.
### New: State Watchers
Elements can declare a `watch` field to trigger actions when state values change. Useful for cascading dependencies like country/city selects.
```json
{
"type": "Select",
"props": { "value": { "$bindState": "/form/country" }, "options": ["US", "Canada"] },
"watch": {
"/form/country": { "action": "loadCities", "params": { "country": { "$state": "/form/country" } } }
}
}
```
`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. See [Watchers](/docs/watchers) for details.
### New: Cross-Field Validation
New built-in validation functions for cross-field comparisons:
- `equalTo` -- alias for `matches` with clearer semantics
- `lessThan` -- value must be less than another field
- `greaterThan` -- value must be greater than another field
- `requiredIf` -- required only when a condition field is truthy
Validation check args now resolve through `resolvePropValue`, so `$state` expressions work consistently.
### New: `validateForm` Action
Built-in action (React) that validates all registered form fields at once and writes `{ valid, errors }` to state:
```json
{
"on": {
"press": [
{ "action": "validateForm", "params": { "statePath": "/formResult" } },
{ "action": "submitForm" }
]
}
}
```
### Improved: shadcn/ui Validation
All form components now support `checks` and `validateOn` props:
- Checkbox, Radio, Switch added validation support
- `validateOn` controls timing: `"change"` (default for Select, Checkbox, Radio, Switch), `"blur"` (default for Input, Textarea), or `"submit"`
### New Examples
- **Vue example** -- standalone Vue 3 app with custom components
- **Vite Renderers** -- side-by-side React and Vue renderers with shared catalog
---
## v0.9.1
February 2026
### Fixed: Install failure due to private dependency
`@json-render/react`, `@json-render/react-pdf`, and `@json-render/react-native` v0.9.0 failed to install because `@internal/react-state` (a private workspace package) was published as a dependency. The internal package is now bundled into each renderer at build time, so it no longer needs to be resolved from npm.
---
## v0.9.0
February 2026
+9 -14
View File
@@ -9,18 +9,6 @@ Install the core package plus your renderer of choice.
<PackageInstall packages="@json-render/core @json-render/react" />
Peer dependencies: `react ^19.0.0` and `zod ^4.0.0`.
<PackageInstall packages="react zod" />
## For Vue
<PackageInstall packages="@json-render/core @json-render/vue" />
Peer dependencies: `vue ^3.5.0` and `zod ^4.0.0`.
<PackageInstall packages="vue zod" />
## For React UI with shadcn/ui
Pre-built components for fast prototyping and production use:
@@ -47,10 +35,17 @@ If you want to wire json-render to an existing state management library instead
<PackageInstall packages="@json-render/jotai" />
<PackageInstall packages="@json-render/xstate" />
See the [Data Binding](/docs/data-binding#external-store-controlled-mode) guide for usage.
## Peer Dependencies
json-render requires the following peer dependencies:
- `react` ^19.0.0
- `zod` ^4.0.0
<PackageInstall packages="react zod" />
## For AI Integration
To use json-render with AI models, you'll also need the Vercel AI SDK:
-11
View File
@@ -69,16 +69,6 @@ export const docsNavigation: NavSection[] = [
href: "https://github.com/vercel-labs/json-render/tree/main/examples/remotion",
external: true,
},
{
title: "Vue",
href: "https://github.com/vercel-labs/json-render/tree/main/examples/vue",
external: true,
},
{
title: "Renders with Vite (Vue / React)",
href: "https://github.com/vercel-labs/json-render/tree/main/examples/vite-renderers",
external: true,
},
],
},
{
@@ -107,7 +97,6 @@ export const docsNavigation: NavSection[] = [
{ title: "@json-render/shadcn", href: "/docs/api/shadcn" },
{ title: "@json-render/react-native", href: "/docs/api/react-native" },
{ title: "@json-render/remotion", href: "/docs/api/remotion" },
{ title: "@json-render/vue", href: "/docs/api/vue" },
{ title: "@json-render/codegen", href: "/docs/api/codegen" },
],
},
-3
View File
@@ -23,9 +23,7 @@ export const PAGE_TITLES: Record<string, string> = {
"docs/streaming": "Streaming",
"docs/validation": "Validation",
"docs/data-binding": "Data Binding",
"docs/computed-values": "Computed Values",
"docs/visibility": "Visibility",
"docs/watchers": "Watchers",
"docs/generation-modes": "Generation Modes",
"docs/code-export": "Code Export",
"docs/custom-schema": "Custom Schema & Renderer",
@@ -40,7 +38,6 @@ export const PAGE_TITLES: Record<string, string> = {
// API references
"docs/api/core": "@json-render/core API",
"docs/api/react": "@json-render/react API",
"docs/api/vue": "@json-render/vue API",
"docs/api/react-pdf": "@json-render/react-pdf API",
"docs/api/react-native": "@json-render/react-native API",
"docs/api/codegen": "@json-render/codegen API",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "web",
"version": "0.1.3",
"version": "0.1.1",
"type": "module",
"private": true,
"license": "Apache-2.0",
-18
View File
@@ -1,23 +1,5 @@
# example-chat
## 0.1.3
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
- @json-render/react@0.10.0
- @json-render/shadcn@0.10.0
## 0.1.2
### Patch Changes
- Updated dependencies [b103676]
- @json-render/react@0.9.1
- @json-render/shadcn@0.9.1
- @json-render/core@0.9.1
## 0.1.1
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "example-chat",
"version": "0.1.3",
"version": "0.1.1",
"type": "module",
"private": true,
"scripts": {
-18
View File
@@ -1,23 +1,5 @@
# example-dashboard
## 0.1.3
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
- @json-render/react@0.10.0
- @json-render/codegen@0.10.0
## 0.1.2
### Patch Changes
- Updated dependencies [b103676]
- @json-render/react@0.9.1
- @json-render/core@0.9.1
- @json-render/codegen@0.9.1
## 0.1.1
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "example-dashboard",
"version": "0.1.3",
"version": "0.1.1",
"type": "module",
"private": true,
"scripts": {
-18
View File
@@ -1,23 +1,5 @@
# example-no-ai
## 0.1.3
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
- @json-render/react@0.10.0
- @json-render/shadcn@0.10.0
## 0.1.2
### Patch Changes
- Updated dependencies [b103676]
- @json-render/react@0.9.1
- @json-render/shadcn@0.9.1
- @json-render/core@0.9.1
## 0.1.1
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "example-no-ai",
"version": "0.1.3",
"version": "0.1.1",
"type": "module",
"private": true,
"scripts": {
-16
View File
@@ -1,21 +1,5 @@
# example-react-native
## 0.1.3
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
- @json-render/react-native@0.10.0
## 0.1.2
### Patch Changes
- Updated dependencies [b103676]
- @json-render/react-native@0.9.1
- @json-render/core@0.9.1
## 0.1.1
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "example-react-native",
"version": "0.1.3",
"version": "0.1.1",
"private": true,
"main": "expo-router/entry",
"scripts": {
-16
View File
@@ -1,21 +1,5 @@
# example-react-pdf
## 0.1.3
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
- @json-render/react-pdf@0.10.0
## 0.1.2
### Patch Changes
- Updated dependencies [b103676]
- @json-render/react-pdf@0.9.1
- @json-render/core@0.9.1
## 0.1.1
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "example-react-pdf",
"version": "0.1.3",
"version": "0.1.1",
"type": "module",
"private": true,
"scripts": {
-15
View File
@@ -1,20 +1,5 @@
# example-remotion
## 0.1.3
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
- @json-render/remotion@0.10.0
## 0.1.2
### Patch Changes
- @json-render/core@0.9.1
- @json-render/remotion@0.9.1
## 0.1.1
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "example-remotion",
"version": "0.1.3",
"version": "0.1.1",
"type": "module",
"private": true,
"scripts": {
@@ -1,21 +1,5 @@
# com.example.json-render-demo
## 0.0.4
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
- @json-render/react@0.10.0
## 0.0.3
### Patch Changes
- Updated dependencies [b103676]
- @json-render/react@0.9.1
- @json-render/core@0.9.1
## 0.0.2
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "com.example.json-render-demo",
"version": "0.0.4",
"version": "0.0.2",
"description": "Test",
"private": true,
"license": "~~proprietary~~",
@@ -1,21 +1,5 @@
# com.example.json-render-fullpage-demo
## 0.0.4
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
- @json-render/react@0.10.0
## 0.0.3
### Patch Changes
- Updated dependencies [b103676]
- @json-render/react@0.9.1
- @json-render/core@0.9.1
## 0.0.2
### Patch Changes
@@ -1,6 +1,6 @@
{
"name": "com.example.json-render-fullpage-demo",
"version": "0.0.4",
"version": "0.0.2",
"description": "Full-page Stripe App example (alpha)",
"private": true,
"license": "~~proprietary~~",
-10
View File
@@ -1,10 +0,0 @@
# vite-renderers
## 0.1.1
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
- @json-render/react@0.10.0
- @json-render/vue@0.10.0
-31
View File
@@ -1,31 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@json-render multi-renderer demo</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #f3f4f6;
min-height: 100vh;
}
#renderer-root {
max-width: 640px;
margin: 0 auto;
padding: 24px;
}
</style>
</head>
<body>
<div id="renderer-root"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
-27
View File
@@ -1,27 +0,0 @@
{
"name": "vite-renderers",
"version": "0.1.1",
"private": true,
"scripts": {
"dev": "portless vite-renderers.json-render vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@json-render/core": "workspace:*",
"@json-render/react": "workspace:*",
"@json-render/vue": "workspace:*",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"vue": "^3.5.29",
"zod": "^4.3.6"
},
"devDependencies": {
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.4",
"@vitejs/plugin-vue": "^6.0.4",
"typescript": "^5.9.3",
"vite": "^7.3.1"
}
}
-30
View File
@@ -1,30 +0,0 @@
import "./shared/styles.css";
import { demoSpec } from "./spec";
type Renderer = "vue" | "react";
const container = document.getElementById("renderer-root") as HTMLElement;
let unmountCurrent: (() => void) | null = null;
async function switchTo(renderer: Renderer) {
unmountCurrent?.();
container.innerHTML = "";
if (renderer === "vue") {
const mod = await import("./vue/mount.ts");
mod.mount(container, renderer, demoSpec);
unmountCurrent = mod.unmount;
} else {
const mod = await import("./react/mount.tsx");
mod.mount(container, renderer, demoSpec);
unmountCurrent = mod.unmount;
}
}
// The RendererTabs component (rendered by JSON renderer) dispatches this event
document.addEventListener("switch-renderer", (e: Event) => {
switchTo((e as CustomEvent<string>).detail as Renderer);
});
// Default: Vue
switchTo("vue");
-51
View File
@@ -1,51 +0,0 @@
import { useMemo } from "react";
import type { Spec } from "@json-render/core";
import {
StateProvider,
ActionProvider,
VisibilityProvider,
ValidationProvider,
Renderer,
defineRegistry,
useStateStore,
} from "@json-render/react";
import { catalog } from "./catalog";
import { components } from "./registry";
import { actionStubs, makeHandlers } from "../shared/handlers";
const { registry } = defineRegistry(catalog, {
components,
actions: actionStubs,
});
function DemoRenderer({ spec }: { spec: Spec }) {
const { get, set } = useStateStore();
const handlers = useMemo(() => makeHandlers(get, set), [get, set]);
return (
<ActionProvider handlers={handlers}>
<VisibilityProvider>
<ValidationProvider>
<Renderer spec={spec} registry={registry} />
</ValidationProvider>
</VisibilityProvider>
</ActionProvider>
);
}
export default function App({
initialRenderer = "vue",
spec,
}: {
initialRenderer?: string;
spec: Spec;
}) {
return (
<div className={`renderer-${initialRenderer}`}>
<StateProvider
initialState={{ ...spec.state, renderer: initialRenderer }}
>
<DemoRenderer spec={spec} />
</StateProvider>
</div>
);
}
@@ -1,5 +0,0 @@
import { schema } from "@json-render/react/schema";
import { catalogDef } from "../shared/catalog-def";
export const catalog = schema.createCatalog(catalogDef);
export type AppCatalog = typeof catalog;
@@ -1,15 +0,0 @@
import { createRoot, type Root } from "react-dom/client";
import type { Spec } from "@json-render/core";
import App from "./App";
let root: Root | null = null;
export function mount(container: HTMLElement, renderer: string, spec: Spec) {
root = createRoot(container);
root.render(<App initialRenderer={renderer} spec={spec} />);
}
export function unmount() {
root?.unmount();
root = null;
}
@@ -1,155 +0,0 @@
import type { Components } from "@json-render/react";
import type { AppCatalog } from "./catalog";
export const components: Components<AppCatalog> = {
Stack: ({ props, children }) => (
<div
className={[
"json-render-stack",
props.direction === "horizontal" && "json-render-stack--horizontal",
props.align && `json-render-stack--align-${props.align}`,
]
.filter(Boolean)
.join(" ")}
style={{
gap: props.gap ? `${props.gap}px` : undefined,
padding: props.padding ? `${props.padding}px` : undefined,
}}
>
{children}
</div>
),
Card: ({ props, children }) => (
<div className="json-render-card">
{props.title && (
<div className="json-render-card-title-wrap">
<h2 className="json-render-card-title">{props.title}</h2>
</div>
)}
{props.subtitle && (
<p className="json-render-card-subtitle">{props.subtitle}</p>
)}
{children}
</div>
),
Text: ({ props }) => (
<span
className={[
"json-render-text",
props.size && props.size !== "md" && `json-render-text--${props.size}`,
props.weight &&
props.weight !== "normal" &&
`json-render-text--${props.weight}`,
]
.filter(Boolean)
.join(" ")}
style={props.color ? { color: props.color } : undefined}
>
{String(props.content ?? "")}
</span>
),
Button: ({ props, emit }) => (
<button
disabled={props.disabled}
onClick={() => emit("press")}
className={[
"json-render-button",
props.variant && `json-render-button--${props.variant}`,
]
.filter(Boolean)
.join(" ")}
>
{props.label}
</button>
),
Badge: ({ props }) => (
<span
className="json-render-badge"
style={
props.color
? {
backgroundColor: `${props.color}20`,
color: props.color,
borderColor: `${props.color}40`,
}
: undefined
}
>
{props.label}
</span>
),
ListItem: ({ props, emit }) => (
<div
onClick={() => emit("press")}
className={[
"json-render-list-item",
props.completed && "json-render-list-item--done",
]
.filter(Boolean)
.join(" ")}
>
<div
className={[
"json-render-list-item-check",
props.completed && "json-render-list-item-check--done",
]
.filter(Boolean)
.join(" ")}
>
{props.completed ? "✓" : ""}
</div>
<span
className={[
"json-render-list-item-text",
props.completed && "json-render-list-item-text--done",
]
.filter(Boolean)
.join(" ")}
>
{props.title}
</span>
</div>
),
RendererBadge: ({ props }) => (
<span className="json-render-renderer-badge">
<span className="json-render-renderer-dot" />
{props.renderer === "vue" ? "Rendered with Vue" : "Rendered with React"}
</span>
),
RendererTabs: ({ props, emit }) => (
<div className="json-render-renderer-tabs-wrapper">
<span className="json-render-renderer-tabs-label">Render</span>
<div className="json-render-renderer-tabs">
<button
onClick={() => emit("pressVue")}
className={[
"json-render-renderer-tab",
props.renderer === "vue" && "json-render-renderer-tab--active",
]
.filter(Boolean)
.join(" ")}
>
Vue
</button>
<button
onClick={() => emit("pressReact")}
className={[
"json-render-renderer-tab",
props.renderer === "react" && "json-render-renderer-tab--active",
]
.filter(Boolean)
.join(" ")}
>
React
</button>
</div>
</div>
),
};
@@ -1,99 +0,0 @@
import { z } from "zod";
/**
* Shared catalog definition — imported by both vue/catalog.ts and react/catalog.ts.
* Each renderer calls schema.createCatalog(catalogDef) with its own schema instance.
*/
export const catalogDef = {
components: {
Stack: {
props: z.object({
gap: z.number().optional(),
padding: z.number().optional(),
direction: z.enum(["vertical", "horizontal"]).optional(),
align: z.enum(["start", "center", "end"]).optional(),
}),
slots: ["default"],
description:
"Layout container that stacks children vertically or horizontally",
},
Card: {
props: z.object({
title: z.string().optional(),
subtitle: z.string().optional(),
}),
slots: ["default"],
description: "A card container with optional title and subtitle",
},
Text: {
props: z.object({
content: z.string(),
size: z.enum(["sm", "md", "lg", "xl"]).optional(),
weight: z.enum(["normal", "medium", "bold"]).optional(),
color: z.string().optional(),
}),
slots: [],
description: "Displays a text string",
},
Button: {
props: z.object({
label: z.string(),
variant: z.enum(["primary", "secondary", "danger"]).optional(),
disabled: z.boolean().optional(),
}),
slots: [],
description: "A clickable button that emits a 'press' event",
},
Badge: {
props: z.object({
label: z.string(),
color: z.string().optional(),
}),
slots: [],
description: "A small badge/tag label",
},
ListItem: {
props: z.object({
title: z.string(),
description: z.string().optional(),
completed: z.boolean().optional(),
}),
slots: [],
description: "A single item in a list",
},
RendererTabs: {
props: z.object({ renderer: z.string() }),
slots: [],
description:
"Segmented tab control for switching between Vue and React renderers",
},
RendererBadge: {
props: z.object({ renderer: z.string() }),
slots: [],
description: "Badge indicating which renderer is currently active",
},
},
actions: {
increment: {
params: z.object({}),
description: "Increment the counter by 1",
},
decrement: {
params: z.object({}),
description: "Decrement the counter by 1",
},
reset: { params: z.object({}), description: "Reset the counter to 0" },
toggleItem: {
params: z.object({ index: z.number() }),
description: "Toggle the completed state of a todo item",
},
switchToVue: {
params: z.object({}),
description: "Switch to the Vue renderer",
},
switchToReact: {
params: z.object({}),
description: "Switch to the React renderer",
},
},
};
@@ -1,50 +0,0 @@
type Get = (path: string) => unknown;
type Set = (path: string, value: unknown) => void;
/** Stub actions for defineRegistry (no-ops; real logic is in makeHandlers) */
export const actionStubs = {
increment: async () => {},
decrement: async () => {},
reset: async () => {},
toggleItem: async () => {},
switchToVue: async () => {},
switchToReact: async () => {},
};
/** Creates action handlers that close over the state store's get/set */
export function makeHandlers(get: Get, set: Set) {
return {
increment: async () => {
set("/count", Number(get("/count") || 0) + 1);
},
decrement: async () => {
set("/count", Math.max(0, Number(get("/count") || 0) - 1));
},
reset: async () => {
set("/count", 0);
},
toggleItem: async (params: Record<string, unknown>) => {
const index = params.index as number;
const todos = (
get("/todos") as Array<{
id: number;
title: string;
completed: boolean;
}>
).slice();
const item = todos[index];
if (item) todos[index] = { ...item, completed: !item.completed };
set("/todos", todos);
},
switchToVue: async () => {
document.dispatchEvent(
new CustomEvent("switch-renderer", { detail: "vue" }),
);
},
switchToReact: async () => {
document.dispatchEvent(
new CustomEvent("switch-renderer", { detail: "react" }),
);
},
};
}
@@ -1,248 +0,0 @@
/* ---- Stack ---------------------------------------------------------------- */
.json-render-stack {
display: flex;
flex-direction: column;
align-items: stretch;
}
.json-render-stack--horizontal {
flex-direction: row;
align-items: center;
}
.json-render-stack--align-start { align-items: flex-start; }
.json-render-stack--align-center { align-items: center; }
.json-render-stack--align-end { align-items: flex-end; }
/* ---- Card ----------------------------------------------------------------- */
.json-render-card {
background-color: white;
border-radius: 12px;
border: 1px solid #e5e7eb;
padding: 20px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}
.json-render-card-title-wrap {
margin-bottom: 4px;
}
.json-render-card-title {
font-size: 16px;
font-weight: 600;
color: #111827;
margin: 0;
}
.json-render-card-subtitle {
font-size: 13px;
color: #6b7280;
margin: 0 0 12px 0;
}
/* ---- Text ----------------------------------------------------------------- */
.json-render-text {
font-size: 14px;
font-weight: 400;
color: #111827;
}
.json-render-text--sm { font-size: 12px; }
.json-render-text--lg { font-size: 16px; }
.json-render-text--xl { font-size: 24px; }
.json-render-text--medium { font-weight: 500; }
.json-render-text--bold { font-weight: 700; }
/* ---- Button --------------------------------------------------------------- */
.json-render-button {
padding: 8px 16px;
border-radius: 8px;
border: none;
cursor: pointer;
font-weight: 500;
font-size: 14px;
transition: background 0.15s;
background-color: #3b82f6;
color: white;
}
.json-render-button:disabled {
cursor: not-allowed;
opacity: 0.5;
}
.json-render-button--primary {
background-color: #3b82f6;
color: white;
}
.json-render-button--secondary {
background-color: #f3f4f6;
color: #374151;
}
.json-render-button--danger {
background-color: #fee2e2;
color: #dc2626;
}
/* ---- Badge ---------------------------------------------------------------- */
.json-render-badge {
display: inline-block;
padding: 4px 12px;
border-radius: 999px;
font-size: 13px;
font-weight: 500;
background-color: #e0f2fe;
color: #0369a1;
border: 1px solid #bae6fd;
}
/* ---- ListItem ------------------------------------------------------------- */
.json-render-list-item {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 12px;
border-radius: 8px;
cursor: pointer;
background-color: #f9fafb;
border: 1px solid #e5e7eb;
}
.json-render-list-item--done {
background-color: #f0fdf4;
border-color: #bbf7d0;
}
.json-render-list-item-check {
width: 18px;
height: 18px;
border-radius: 50%;
border: 2px solid #d1d5db;
background-color: transparent;
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
font-size: 11px;
color: white;
}
.json-render-list-item-check--done {
border-color: #16a34a;
background-color: #16a34a;
}
.json-render-list-item-text {
font-size: 14px;
color: #111827;
text-decoration: none;
}
.json-render-list-item-text--done {
color: #6b7280;
text-decoration: line-through;
}
/* ---- RendererBadge -------------------------------------------------------- */
.json-render-renderer-badge {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 10px 15px;
border-radius: 999px;
font-size: 12px;
font-weight: 500;
/* default colors; overridden by renderer parent class below */
background-color: #e0f2fe;
color: #0369a1;
border: 1px solid #bae6fd;
}
.json-render-renderer-dot {
width: 6px;
height: 6px;
border-radius: 50%;
display: inline-block;
/* background overridden by renderer parent class below */
background-color: #0369a1;
}
/* ---- RendererTabs --------------------------------------------------------- */
.json-render-renderer-tabs-wrapper {
display: inline-flex;
align-items: center;
gap: 8px;
margin-left: auto;
}
.json-render-renderer-tabs-label {
font-size: 13px;
color: #6b7280;
font-weight: 500;
}
.json-render-renderer-tabs {
display: inline-flex;
border-radius: 8px;
border: 1px solid #e5e7eb;
overflow: hidden;
}
.json-render-renderer-tab {
padding: 6px 16px;
border: none;
border-right: 0;
cursor: pointer;
font-size: 13px;
font-weight: 500;
background-color: white;
color: #374151;
transition: background 0.15s;
}
.json-render-renderer-tab:first-child {
border-right: 1px solid #e5e7eb;
}
/* ---- Renderer-specific overrides ----------------------------------------- */
.renderer-vue .json-render-renderer-badge {
color: #42b883;
background-color: #42b88318;
border-color: #42b88340;
}
.renderer-vue .json-render-renderer-dot {
background-color: #42b883;
}
.renderer-vue .json-render-renderer-tab--active {
background-color: #42b883;
color: white;
}
.renderer-react .json-render-renderer-badge {
color: #149eca;
background-color: #149eca18;
border-color: #149eca40;
}
.renderer-react .json-render-renderer-dot {
background-color: #149eca;
}
.renderer-react .json-render-renderer-tab--active {
background-color: #149eca;
color: white;
}
-126
View File
@@ -1,126 +0,0 @@
import type { Spec } from "@json-render/core";
export const demoSpec: Spec = {
root: "root",
state: {
renderer: "vue",
count: 0,
todos: [
{ id: 1, title: "Learn JSON Render", completed: true },
{
id: 2,
title: "Try @json-render/vue or @json-render/react",
completed: false,
},
{ id: 3, title: "Build something awesome", completed: false },
],
},
elements: {
root: {
type: "Stack",
props: { gap: 24, padding: 24, direction: "vertical" },
children: [
"demo-title",
"renderer-tabs",
"renderer-badge",
"counter-card",
"milestone-badge",
"todos-card",
],
},
"demo-title": {
type: "Text",
props: {
content: "@json-render multi-renderer demo",
size: "xl",
weight: "bold",
},
},
"renderer-badge": {
type: "RendererBadge",
props: { renderer: { $state: "/renderer" } },
},
"renderer-tabs": {
type: "RendererTabs",
props: { renderer: { $state: "/renderer" } },
on: {
pressVue: { action: "switchToVue" },
pressReact: { action: "switchToReact" },
},
},
// ---- Counter card ----
"counter-card": {
type: "Card",
props: {
title: "Counter",
subtitle: "Click the buttons to change the count",
},
children: ["counter-body"],
},
"counter-body": {
type: "Stack",
props: { gap: 12, direction: "horizontal", align: "center" },
children: [
"decrement-btn",
"counter-value",
"increment-btn",
"reset-btn",
],
},
"decrement-btn": {
type: "Button",
props: { label: "−", variant: "secondary" },
on: { press: { action: "decrement" } },
},
"counter-value": {
type: "Text",
props: {
content: { $state: "/count" },
size: "xl",
weight: "bold",
},
},
"increment-btn": {
type: "Button",
props: { label: "+", variant: "primary" },
on: { press: { action: "increment" } },
},
"reset-btn": {
type: "Button",
props: { label: "Reset", variant: "danger" },
on: { press: { action: "reset" } },
},
// ---- Milestone badge (visible only when count >= 10) ----
"milestone-badge": {
type: "Badge",
props: { label: "Milestone reached: 10!", color: "#10b981" },
visible: { $state: "/count", gte: 10 },
},
// ---- Todos card ----
"todos-card": {
type: "Card",
props: { title: "Todo List", subtitle: "Your tasks" },
children: ["todos-list"],
},
"todos-list": {
type: "Stack",
props: { gap: 8, direction: "vertical" },
repeat: { statePath: "/todos", key: "id" },
children: ["todo-item"],
},
"todo-item": {
type: "ListItem",
props: {
title: { $item: "title" },
completed: { $item: "completed" },
},
on: {
press: { action: "toggleItem", params: { index: { $index: true } } },
},
},
},
};
-19
View File
@@ -1,19 +0,0 @@
<script setup lang="ts">
import type { Spec } from "@json-render/core";
import { StateProvider } from "@json-render/vue";
import DemoRenderer from "./DemoRenderer.vue";
const props = defineProps<{
initialRenderer?: string; spec: Spec }>();
const initialState = {
...props.spec.state,
renderer: props.initialRenderer ?? "vue" };
</script>
<template>
<div :class="`renderer-${props.initialRenderer ?? 'vue'}`">
<StateProvider :initial-state="initialState">
<DemoRenderer :spec="props.spec" />
</StateProvider>
</div>
</template>
@@ -1,25 +0,0 @@
<script setup lang="ts">
import type { Spec } from "@json-render/core";
import {
ActionProvider, ValidationProvider, VisibilityProvider,
Renderer, defineRegistry, useStateStore,
} from "@json-render/vue";
import { catalog } from "./catalog";
import { components } from "./registry";
import { actionStubs, makeHandlers } from "../shared/handlers";
const props = defineProps<{ spec: Spec }>();
const { get, set } = useStateStore();
const { registry } = defineRegistry(catalog, { components, actions: actionStubs });
const handlers = makeHandlers(get, set);
</script>
<template>
<ActionProvider :handlers="handlers">
<VisibilityProvider>
<ValidationProvider>
<Renderer :spec="props.spec" :registry="registry" />
</ValidationProvider>
</VisibilityProvider>
</ActionProvider>
</template>
@@ -1,5 +0,0 @@
import { schema } from "@json-render/vue/schema";
import { catalogDef } from "../shared/catalog-def";
export const catalog = schema.createCatalog(catalogDef);
export type AppCatalog = typeof catalog;
-15
View File
@@ -1,15 +0,0 @@
import { createApp, type App } from "vue";
import type { Spec } from "@json-render/core";
import VueApp from "./App.vue";
let app: App | null = null;
export function mount(container: HTMLElement, renderer: string, spec: Spec) {
app = createApp(VueApp, { initialRenderer: renderer, spec });
app.mount(container);
}
export function unmount() {
app?.unmount();
app = null;
}
-166
View File
@@ -1,166 +0,0 @@
import { h } from "vue";
import type { Components } from "@json-render/vue";
import type { AppCatalog } from "./catalog";
export const components: Components<AppCatalog> = {
Stack: ({ props, children }) =>
h(
"div",
{
class: [
"json-render-stack",
props.direction === "horizontal" && "json-render-stack--horizontal",
props.align && `json-render-stack--align-${props.align}`,
]
.filter(Boolean)
.join(" "),
style: {
gap: props.gap ? `${props.gap}px` : undefined,
padding: props.padding ? `${props.padding}px` : undefined,
},
},
children,
),
Card: ({ props, children }) =>
h("div", { class: "json-render-card" }, [
props.title &&
h("div", { class: "json-render-card-title-wrap" }, [
h("h2", { class: "json-render-card-title" }, props.title),
]),
props.subtitle &&
h("p", { class: "json-render-card-subtitle" }, props.subtitle),
children,
]),
Text: ({ props }) =>
h(
"span",
{
class: [
"json-render-text",
props.size &&
props.size !== "md" &&
`json-render-text--${props.size}`,
props.weight &&
props.weight !== "normal" &&
`json-render-text--${props.weight}`,
]
.filter(Boolean)
.join(" "),
style: props.color ? { color: props.color } : undefined,
},
String(props.content ?? ""),
),
Button: ({ props, emit }) =>
h(
"button",
{
disabled: props.disabled,
onClick: () => emit("press"),
class: [
"json-render-button",
props.variant && `json-render-button--${props.variant}`,
]
.filter(Boolean)
.join(" "),
},
props.label,
),
Badge: ({ props }) =>
h(
"span",
{
class: "json-render-badge",
style: props.color
? {
backgroundColor: `${props.color}20`,
color: props.color,
borderColor: `${props.color}40`,
}
: undefined,
},
props.label,
),
ListItem: ({ props, emit }) =>
h(
"div",
{
onClick: () => emit("press"),
class: [
"json-render-list-item",
props.completed && "json-render-list-item--done",
]
.filter(Boolean)
.join(" "),
},
[
h(
"div",
{
class: [
"json-render-list-item-check",
props.completed && "json-render-list-item-check--done",
]
.filter(Boolean)
.join(" "),
},
props.completed ? "✓" : "",
),
h(
"span",
{
class: [
"json-render-list-item-text",
props.completed && "json-render-list-item-text--done",
]
.filter(Boolean)
.join(" "),
},
props.title,
),
],
),
RendererBadge: ({ props }) =>
h("span", { class: "json-render-renderer-badge" }, [
h("span", { class: "json-render-renderer-dot" }),
props.renderer === "vue" ? "Rendered with Vue" : "Rendered with React",
]),
RendererTabs: ({ props, emit }) =>
h("div", { class: "json-render-renderer-tabs-wrapper" }, [
h("span", { class: "json-render-renderer-tabs-label" }, "Render"),
h("div", { class: "json-render-renderer-tabs" }, [
h(
"button",
{
onClick: () => emit("pressVue"),
class: [
"json-render-renderer-tab",
props.renderer === "vue" && "json-render-renderer-tab--active",
]
.filter(Boolean)
.join(" "),
},
"Vue",
),
h(
"button",
{
onClick: () => emit("pressReact"),
class: [
"json-render-renderer-tab",
props.renderer === "react" && "json-render-renderer-tab--active",
]
.filter(Boolean)
.join(" "),
},
"React",
),
]),
]),
};
-17
View File
@@ -1,17 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"strict": true
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
}
-7
View File
@@ -1,7 +0,0 @@
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [vue(), react({ include: /\.tsx$/ })],
});
-9
View File
@@ -1,9 +0,0 @@
# example-vue
## 0.1.1
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
- @json-render/vue@0.10.0
-26
View File
@@ -1,26 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>json-render vue example</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family:
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
background: #f9fafb;
color: #111827;
min-height: 100vh;
}
</style>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
-22
View File
@@ -1,22 +0,0 @@
{
"name": "example-vue",
"version": "0.1.1",
"private": true,
"scripts": {
"dev": "portless vue.json-render vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@json-render/core": "workspace:*",
"@json-render/vue": "workspace:*",
"vue": "^3.5.0",
"zod": "^4.3.6"
},
"devDependencies": {
"@vitejs/plugin-vue": "^6.0.4",
"typescript": "^5.9.3",
"vite": "^7.3.1",
"vue-tsc": "^3.2.5"
}
}
-14
View File
@@ -1,14 +0,0 @@
<script setup lang="ts">
import { StateProvider } from "@json-render/vue";
import { demoSpec } from "./lib/spec";
import DemoRenderer from "./DemoRenderer.vue";
const initialState = demoSpec.state ?? {};
</script>
<template>
<!-- StateProvider sets up the reactive state store for the whole tree -->
<StateProvider :initial-state="initialState">
<DemoRenderer />
</StateProvider>
</template>
-68
View File
@@ -1,68 +0,0 @@
<script setup lang="ts">
import {
ActionProvider,
ValidationProvider,
VisibilityProvider,
Renderer,
defineRegistry,
useStateStore,
} from "@json-render/vue";
import { catalog } from "./lib/catalog";
import { components } from "./lib/registry";
import { demoSpec } from "./lib/spec";
// Access the state store provided by the parent StateProvider
const { get, set } = useStateStore();
// Build registry — include stub actions to satisfy catalog types.
// The actual logic runs in the handlers below, which have direct
// access to the state store.
const { registry } = defineRegistry(catalog, {
components,
actions: {
increment: async () => {},
decrement: async () => {},
reset: async () => {},
toggleItem: async () => {},
},
});
// Action handlers — close over the state store's get/set so they
// can read and write state directly without needing an external store.
const handlers = {
increment: async () => {
set("/count", Number(get("/count") || 0) + 1);
},
decrement: async () => {
set("/count", Math.max(0, Number(get("/count") || 0) - 1));
},
reset: async () => {
set("/count", 0);
},
toggleItem: async (params: Record<string, unknown>) => {
const index = params.index as number;
const todos = (
get("/todos") as Array<{
id: number;
title: string;
completed: boolean;
}>
).slice();
const item = todos[index];
if (item) {
todos[index] = { ...item, completed: !item.completed };
}
set("/todos", todos);
},
};
</script>
<template>
<ActionProvider :handlers="handlers">
<VisibilityProvider>
<ValidationProvider>
<Renderer :spec="demoSpec" :registry="registry" />
</ValidationProvider>
</VisibilityProvider>
</ActionProvider>
</template>
-92
View File
@@ -1,92 +0,0 @@
import { schema } from "@json-render/vue/schema";
import { z } from "zod";
export const catalog = schema.createCatalog({
components: {
Stack: {
props: z.object({
gap: z.number().optional(),
padding: z.number().optional(),
direction: z.enum(["vertical", "horizontal"]).optional(),
align: z.enum(["start", "center", "end"]).optional(),
}),
slots: ["default"],
description:
"Layout container that stacks children vertically or horizontally",
},
Card: {
props: z.object({
title: z.string().optional(),
subtitle: z.string().optional(),
}),
slots: ["default"],
description: "A card container with optional title and subtitle",
},
Text: {
props: z.object({
content: z.string(),
size: z.enum(["sm", "md", "lg", "xl"]).optional(),
weight: z.enum(["normal", "medium", "bold"]).optional(),
color: z.string().optional(),
}),
slots: [],
description: "Displays a text string",
},
Button: {
props: z.object({
label: z.string(),
variant: z.enum(["primary", "secondary", "danger"]).optional(),
disabled: z.boolean().optional(),
}),
slots: [],
description: "A clickable button that emits a 'press' event",
},
Badge: {
props: z.object({
label: z.string(),
color: z.string().optional(),
}),
slots: [],
description: "A small badge/tag label",
},
ListItem: {
props: z.object({
title: z.string(),
description: z.string().optional(),
completed: z.boolean().optional(),
}),
slots: [],
description: "A single item in a list",
},
Input: {
props: z.object({
value: z.string().optional(),
placeholder: z.string().optional(),
}),
slots: [],
description: "A text input field that supports two-way state binding",
},
},
actions: {
increment: {
params: z.object({}),
description: "Increment the counter by 1",
},
decrement: {
params: z.object({}),
description: "Decrement the counter by 1",
},
reset: {
params: z.object({}),
description: "Reset the counter to 0",
},
toggleItem: {
params: z.object({
index: z.number(),
}),
description: "Toggle the completed state of a todo item",
},
},
});
export type AppCatalog = typeof catalog;
-213
View File
@@ -1,213 +0,0 @@
import { h } from "vue";
import type { Components } from "@json-render/vue";
import { useBoundProp } from "@json-render/vue";
import type { AppCatalog } from "./catalog";
export const components: Components<AppCatalog> = {
Stack: ({ props, children }) => {
const isHorizontal = props.direction === "horizontal";
return h(
"div",
{
style: {
display: "flex",
flexDirection: isHorizontal ? "row" : "column",
gap: props.gap ? `${props.gap}px` : undefined,
padding: props.padding ? `${props.padding}px` : undefined,
alignItems: props.align ?? (isHorizontal ? "center" : "stretch"),
},
},
children,
);
},
Card: ({ props, children }) =>
h(
"div",
{
style: {
backgroundColor: "white",
borderRadius: "12px",
border: "1px solid #e5e7eb",
padding: "20px",
boxShadow: "0 1px 3px rgba(0,0,0,0.05)",
},
},
[
props.title &&
h("div", { style: { marginBottom: "4px" } }, [
h(
"h2",
{
style: {
fontSize: "16px",
fontWeight: "600",
color: "#111827",
margin: 0,
},
},
props.title,
),
]),
props.subtitle &&
h(
"p",
{
style: {
fontSize: "13px",
color: "#6b7280",
margin: "0 0 12px 0",
},
},
props.subtitle,
),
children,
],
),
Text: ({ props }) => {
const sizeMap: Record<string, string> = {
sm: "12px",
md: "14px",
lg: "16px",
xl: "24px",
};
const weightMap: Record<string, string> = {
normal: "400",
medium: "500",
bold: "700",
};
return h(
"span",
{
style: {
fontSize: sizeMap[props.size ?? "md"] ?? "14px",
fontWeight: weightMap[props.weight ?? "normal"] ?? "400",
color: props.color ?? "#111827",
},
},
String(props.content ?? ""),
);
},
Button: ({ props, emit }) =>
h(
"button",
{
disabled: props.disabled,
onClick: () => emit("press"),
style: {
padding: "8px 16px",
borderRadius: "8px",
border: "none",
cursor: props.disabled ? "not-allowed" : "pointer",
fontWeight: "500",
fontSize: "14px",
transition: "background 0.15s",
opacity: props.disabled ? "0.5" : "1",
backgroundColor:
props.variant === "danger"
? "#fee2e2"
: props.variant === "secondary"
? "#f3f4f6"
: "#3b82f6",
color:
props.variant === "danger"
? "#dc2626"
: props.variant === "secondary"
? "#374151"
: "white",
},
},
props.label,
),
Badge: ({ props }) =>
h(
"span",
{
style: {
display: "inline-block",
padding: "4px 12px",
borderRadius: "999px",
fontSize: "13px",
fontWeight: "500",
backgroundColor: props.color ? `${props.color}20` : "#e0f2fe",
color: props.color ?? "#0369a1",
border: `1px solid ${props.color ? `${props.color}40` : "#bae6fd"}`,
},
},
props.label,
),
Input: ({ props, bindings }) => {
const [value, setValue] = useBoundProp<string>(
props.value as string | undefined,
bindings?.value,
);
return h("input", {
value: value ?? "",
placeholder: props.placeholder as string | undefined,
onInput: (e: Event) => setValue((e.target as HTMLInputElement).value),
style: {
padding: "8px 12px",
borderRadius: "8px",
border: "1px solid #d1d5db",
fontSize: "14px",
outline: "none",
width: "100%",
boxSizing: "border-box",
},
});
},
ListItem: ({ props, emit }) =>
h(
"div",
{
onClick: () => emit("press"),
style: {
display: "flex",
alignItems: "center",
gap: "12px",
padding: "10px 12px",
borderRadius: "8px",
cursor: "pointer",
backgroundColor: props.completed ? "#f0fdf4" : "#f9fafb",
border: `1px solid ${props.completed ? "#bbf7d0" : "#e5e7eb"}`,
},
},
[
h(
"div",
{
style: {
width: "18px",
height: "18px",
borderRadius: "50%",
border: `2px solid ${props.completed ? "#16a34a" : "#d1d5db"}`,
backgroundColor: props.completed ? "#16a34a" : "transparent",
flexShrink: "0",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontSize: "11px",
color: "white",
},
},
props.completed ? "✓" : "",
),
h(
"span",
{
style: {
fontSize: "14px",
color: props.completed ? "#6b7280" : "#111827",
textDecoration: props.completed ? "line-through" : "none",
},
},
props.title,
),
],
),
};
-138
View File
@@ -1,138 +0,0 @@
import type { Spec } from "@json-render/core";
export const demoSpec: Spec = {
root: "root",
state: {
count: 0,
name: "",
todos: [
{ id: 1, title: "Learn Vue 3", completed: true },
{ id: 2, title: "Try @json-render/vue", completed: false },
{ id: 3, title: "Build something awesome", completed: false },
],
},
elements: {
root: {
type: "Stack",
props: { gap: 24, padding: 24, direction: "vertical" },
children: [
"header",
"counter-card",
"milestone-badge",
"todos-card",
"input-card",
],
},
header: {
type: "Text",
props: {
content: "@json-render/vue demo",
size: "xl",
weight: "bold",
},
},
// ---- Counter card ----
"counter-card": {
type: "Card",
props: {
title: "Counter",
subtitle: "Click the buttons to change the count",
},
children: ["counter-body"],
},
"counter-body": {
type: "Stack",
props: { gap: 12, direction: "horizontal", align: "center" },
children: [
"decrement-btn",
"counter-value",
"increment-btn",
"reset-btn",
],
},
"decrement-btn": {
type: "Button",
props: { label: "−", variant: "secondary" },
on: { press: { action: "decrement" } },
},
"counter-value": {
type: "Text",
props: {
content: { $state: "/count" },
size: "xl",
weight: "bold",
},
},
"increment-btn": {
type: "Button",
props: { label: "+", variant: "primary" },
on: { press: { action: "increment" } },
},
"reset-btn": {
type: "Button",
props: { label: "Reset", variant: "danger" },
on: { press: { action: "reset" } },
},
// ---- Milestone badge (visible only when count >= 10) ----
"milestone-badge": {
type: "Badge",
props: { label: "Milestone reached: 10!", color: "#10b981" },
visible: { $state: "/count", gte: 10 },
},
// ---- Todos card ----
"todos-card": {
type: "Card",
props: { title: "Todo List", subtitle: "Your tasks" },
children: ["todos-list"],
},
"todos-list": {
type: "Stack",
props: { gap: 8, direction: "vertical" },
repeat: { statePath: "/todos", key: "id" },
children: ["todo-item"],
},
"todo-item": {
type: "ListItem",
props: {
title: { $item: "title" },
completed: { $item: "completed" },
},
on: {
press: { action: "toggleItem", params: { index: { $index: true } } },
},
},
// ---- Bound Input card (useBoundProp demo) ----
"input-card": {
type: "Card",
props: {
title: "Bound Input",
subtitle: "Type to update state — the display text reacts in real time",
},
children: ["input-body"],
},
"input-body": {
type: "Stack",
props: { gap: 12, direction: "vertical" },
children: ["name-input", "name-display"],
},
"name-input": {
type: "Input",
props: {
value: { $bindState: "/name" },
placeholder: "Enter your name…",
},
},
"name-display": {
type: "Text",
props: {
content: { $state: "/name" },
size: "md",
color: "#6b7280",
},
},
},
};
-4
View File
@@ -1,4 +0,0 @@
import { createApp } from "vue";
import App from "./App.vue";
createApp(App).mount("#app");
-17
View File
@@ -1,17 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "preserve",
"strict": true
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
}
-6
View File
@@ -1,6 +0,0 @@
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
export default defineConfig({
plugins: [vue()],
});
-13
View File
@@ -1,18 +1,5 @@
# @json-render/codegen
## 0.10.0
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
## 0.9.1
### Patch Changes
- @json-render/core@0.9.1
## 0.9.0
### Minor Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@json-render/codegen",
"version": "0.10.0",
"version": "0.9.0",
"license": "Apache-2.0",
"description": "Utilities for generating code from json-render UI trees",
"keywords": [
-73
View File
@@ -1,78 +1,5 @@
# @json-render/core
## 0.10.0
### Minor Changes
- 9cef4e9: Dynamic forms, Vue renderer, XState Store adapter, and computed values.
### New: `@json-render/vue` Package
Vue 3 renderer for json-render. Full feature parity with `@json-render/react` including data binding, visibility conditions, actions, validation, repeat scopes, and streaming.
- `defineRegistry` — create type-safe component registries from catalogs
- `Renderer` — render specs as Vue component trees
- Providers: `StateProvider`, `ActionProvider`, `VisibilityProvider`, `ValidationProvider`
- Composables: `useStateStore`, `useStateValue`, `useStateBinding`, `useActions`, `useAction`, `useIsVisible`, `useFieldValidation`
- Streaming: `useUIStream`, `useChatUI`
- External store support via `StateStore` interface
### New: `@json-render/xstate` Package
XState Store (atom) adapter for json-render's `StateStore` interface. Wire an `@xstate/store` atom as the state backend.
- `xstateStoreStateStore({ atom })` — creates a `StateStore` from an `@xstate/store` atom
- Requires `@xstate/store` v3+
### New: `$computed` Expressions
Call registered functions from prop expressions:
- `{ "$computed": "functionName", "args": { "key": <expression> } }` — calls a named function with resolved args
- Functions registered via catalog and provided at runtime through `functions` prop on `JSONUIProvider` / `createRenderer`
- `ComputedFunction` type exported from `@json-render/core`
### New: `$template` Expressions
Interpolate state values into strings:
- `{ "$template": "Hello, ${/user/name}!" }` — replaces `${/path}` references with state values
- Missing paths resolve to empty string
### New: State Watchers
React to state changes by triggering actions:
- `watch` field on elements maps state paths to action bindings
- Fires when watched values change (not on initial render)
- Supports cascading dependencies (e.g. country → city loading)
- `watch` is a top-level field on elements (sibling of type/props/children), not inside props
- Spec validator detects and auto-fixes `watch` placed inside props
### New: Cross-Field Validation Functions
New built-in validation functions for cross-field comparisons:
- `equalTo` — alias for `matches` with clearer semantics
- `lessThan` — value must be less than another field (numbers, strings, coerced)
- `greaterThan` — value must be greater than another field
- `requiredIf` — required only when a condition field is truthy
- Validation args now resolve through `resolvePropValue` for consistent `$state` expression handling
### New: `validateForm` Action (React)
Built-in action that validates all registered form fields at once:
- Runs `validateAll()` synchronously and writes `{ valid, errors }` to state
- Default state path: `/formValidation` (configurable via `statePath` param)
- Added to React schema's built-in actions list
### Improved: shadcn/ui Validation
All form components now support validation:
- Checkbox, Radio, Switch — added `checks` and `validateOn` props
- Input, Textarea, Select — added `validateOn` prop (controls timing: change/blur/submit)
- Shared validation schemas reduce catalog definition duplication
### Improved: React Provider Tree
Reordered provider nesting so `ValidationProvider` wraps `ActionProvider`, enabling `validateForm` to access validation state. Added `useOptionalValidation` hook for non-throwing access.
## 0.9.1
## 0.9.0
### Minor Changes
-114
View File
@@ -188,22 +188,6 @@ Schema options:
| `resolvePropValue(value, ctx)` | Resolve a single prop expression |
| `resolveElementProps(props, ctx)` | Resolve all prop expressions in an element |
| `PropExpression<T>` | Type for prop values that may contain expressions |
| `ComputedFunction` | Function signature for `$computed` expressions |
| `PropResolutionContext` | Context for resolving props (includes `functions` for `$computed`) |
### Validation
| Export | Purpose |
|--------|---------|
| `check.required()` | Required validation helper |
| `check.email()` | Email validation helper |
| `check.matches(path)` | Cross-field match helper |
| `check.equalTo(path)` | Cross-field equality helper |
| `check.lessThan(path)` | Cross-field less-than helper |
| `check.greaterThan(path)` | Cross-field greater-than helper |
| `check.requiredIf(path)` | Conditional required helper |
| `builtInValidationFunctions` | All built-in validation functions |
| `runValidationCheck()` | Run a single validation check |
### User Prompt
@@ -301,7 +285,6 @@ The official adapter packages (`@json-render/redux`, `@json-render/zustand`, `@j
| `Spec` | Base spec type |
| `Catalog` | Catalog type |
| `BuiltInAction` | Built-in action type (`name` + `description`) |
| `ComputedFunction` | Function signature for `$computed` expressions |
| `VisibilityCondition` | Visibility condition type (used by `$cond`) |
| `VisibilityContext` | Context for evaluating visibility and prop expressions |
| `SpecStreamLine` | Single patch operation |
@@ -389,44 +372,6 @@ Get the current array index inside a repeat:
`$index` uses `true` as a sentinel flag because the index is a scalar value with no sub-path to navigate (unlike `$item` which needs a path).
### Template (`$template`)
Interpolate state values into strings using `${/path}` syntax:
```json
{
"label": { "$template": "Hello, ${/user/name}! You have ${/inbox/count} messages." }
}
```
Missing paths resolve to an empty string.
### Computed (`$computed`)
Call a registered function with resolved arguments:
```json
{
"text": {
"$computed": "fullName",
"args": {
"first": { "$state": "/form/firstName" },
"last": { "$state": "/form/lastName" }
}
}
}
```
Functions are registered in the catalog and provided at runtime via the `functions` prop on the renderer.
```typescript
import type { ComputedFunction } from "@json-render/core";
const functions: Record<string, ComputedFunction> = {
fullName: (args) => `${args.first} ${args.last}`,
};
```
### API
```typescript
@@ -521,65 +466,6 @@ console.log(formatSpecIssues(issues));
const fixed = autoFixSpec(spec);
```
## State Watchers
Elements can declare a `watch` field to trigger actions when state values change. `watch` is a top-level field on the element (sibling of `type`, `props`, `children`), not inside `props`.
```json
{
"type": "Select",
"props": {
"label": "Country",
"value": { "$bindState": "/form/country" },
"options": ["US", "Canada", "UK"]
},
"watch": {
"/form/country": {
"action": "loadCities",
"params": { "country": { "$state": "/form/country" } }
}
},
"children": []
}
```
Watchers only fire on value changes, not on initial render. Multiple action bindings per path execute sequentially.
## Validation
### Built-in Validation Functions
| Function | Description | Args |
|----------|-------------|------|
| `required` | Value must not be empty | — |
| `email` | Must be a valid email | — |
| `url` | Must be a valid URL | — |
| `numeric` | Must be a number | — |
| `minLength` | Minimum string length | `{ min: number }` |
| `maxLength` | Maximum string length | `{ max: number }` |
| `min` | Minimum numeric value | `{ min: number }` |
| `max` | Maximum numeric value | `{ max: number }` |
| `pattern` | Must match regex | `{ pattern: string }` |
| `matches` | Must equal another field | `{ other: { $state: "/path" } }` |
| `equalTo` | Alias for matches | `{ other: { $state: "/path" } }` |
| `lessThan` | Must be less than another field | `{ other: { $state: "/path" } }` |
| `greaterThan` | Must be greater than another field | `{ other: { $state: "/path" } }` |
| `requiredIf` | Required when condition is truthy | `{ field: { $state: "/path" } }` |
### TypeScript Helpers
```typescript
import { check } from "@json-render/core";
check.required("Field is required");
check.email("Invalid email");
check.matches("/form/password", "Passwords must match");
check.equalTo("/form/password", "Passwords must match");
check.lessThan("/form/endDate", "Must be before end date");
check.greaterThan("/form/startDate", "Must be after start date");
check.requiredIf("/form/enableNotifications", "Required when notifications enabled");
```
## Custom Schemas
json-render supports completely different spec formats for different renderers:
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@json-render/core",
"version": "0.10.0",
"version": "0.9.0",
"license": "Apache-2.0",
"description": "JSON becomes real things. Define your catalog, register your components, let AI generate.",
"keywords": [
-13
View File
@@ -1,18 +1,5 @@
# @json-render/jotai
## 0.10.0
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
## 0.9.1
### Patch Changes
- @json-render/core@0.9.1
## 0.9.0
### Minor Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@json-render/jotai",
"version": "0.10.0",
"version": "0.9.0",
"license": "Apache-2.0",
"description": "Jotai adapter for json-render StateStore",
"keywords": [
-14
View File
@@ -1,19 +1,5 @@
# @json-render/react-native
## 0.10.0
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
## 0.9.1
### Patch Changes
- b103676: Fix install failure caused by `@internal/react-state` (a private workspace package) being listed as a published dependency. The internal package is now bundled into each renderer's output at build time, so consumers no longer need to resolve it from npm.
- @json-render/core@0.9.1
## 0.9.0
### Minor Changes
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@json-render/react-native",
"version": "0.10.0",
"version": "0.9.0",
"license": "Apache-2.0",
"description": "React Native renderer for @json-render/core. JSON becomes React Native components.",
"keywords": [
@@ -56,10 +56,10 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@json-render/core": "workspace:*"
"@json-render/core": "workspace:*",
"@internal/react-state": "workspace:*"
},
"devDependencies": {
"@internal/react-state": "workspace:*",
"@internal/typescript-config": "workspace:*",
"@types/react": "19.2.3",
"react-native": "0.83.1",
+1 -2
View File
@@ -3,9 +3,8 @@ import { defineConfig } from "tsup";
export default defineConfig({
entry: ["src/index.ts", "src/schema.ts", "src/catalog.ts"],
format: ["cjs", "esm"],
dts: { resolve: ["@internal/react-state"] },
dts: true,
sourcemap: true,
clean: true,
noExternal: ["@internal/react-state"],
external: ["react", "react-native", "@json-render/core", "zod"],
});
-14
View File
@@ -1,19 +1,5 @@
# @json-render/react-pdf
## 0.10.0
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
## 0.9.1
### Patch Changes
- b103676: Fix install failure caused by `@internal/react-state` (a private workspace package) being listed as a published dependency. The internal package is now bundled into each renderer's output at build time, so consumers no longer need to resolve it from npm.
- @json-render/core@0.9.1
## 0.9.0
### Minor Changes
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@json-render/react-pdf",
"version": "0.10.0",
"version": "0.9.0",
"license": "Apache-2.0",
"description": "React PDF renderer for @json-render/core. JSON becomes PDF documents.",
"keywords": [
@@ -61,10 +61,10 @@
},
"dependencies": {
"@json-render/core": "workspace:*",
"@internal/react-state": "workspace:*",
"@react-pdf/renderer": "^4.3.2"
},
"devDependencies": {
"@internal/react-state": "workspace:*",
"@internal/typescript-config": "workspace:*",
"@types/react": "19.2.3",
"tsup": "^8.0.2",
+1 -2
View File
@@ -3,9 +3,8 @@ import { defineConfig } from "tsup";
export default defineConfig({
entry: ["src/index.ts", "src/server.ts", "src/catalog.ts", "src/render.tsx"],
format: ["cjs", "esm"],
dts: { resolve: ["@internal/react-state"] },
dts: true,
sourcemap: true,
clean: true,
noExternal: ["@internal/react-state"],
external: ["react", "@json-render/core", "@react-pdf/renderer", "zod"],
});
-13
View File
@@ -1,18 +1,5 @@
# @internal/react-state
## 0.8.3
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
## 0.8.2
### Patch Changes
- @json-render/core@0.9.1
## 0.8.1
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@internal/react-state",
"version": "0.8.3",
"version": "0.8.1",
"private": true,
"license": "Apache-2.0",
"description": "Shared React state context for json-render renderer packages",
-83
View File
@@ -1,88 +1,5 @@
# @json-render/react
## 0.10.0
### Minor Changes
- 9cef4e9: Dynamic forms, Vue renderer, XState Store adapter, and computed values.
### New: `@json-render/vue` Package
Vue 3 renderer for json-render. Full feature parity with `@json-render/react` including data binding, visibility conditions, actions, validation, repeat scopes, and streaming.
- `defineRegistry` — create type-safe component registries from catalogs
- `Renderer` — render specs as Vue component trees
- Providers: `StateProvider`, `ActionProvider`, `VisibilityProvider`, `ValidationProvider`
- Composables: `useStateStore`, `useStateValue`, `useStateBinding`, `useActions`, `useAction`, `useIsVisible`, `useFieldValidation`
- Streaming: `useUIStream`, `useChatUI`
- External store support via `StateStore` interface
### New: `@json-render/xstate` Package
XState Store (atom) adapter for json-render's `StateStore` interface. Wire an `@xstate/store` atom as the state backend.
- `xstateStoreStateStore({ atom })` — creates a `StateStore` from an `@xstate/store` atom
- Requires `@xstate/store` v3+
### New: `$computed` Expressions
Call registered functions from prop expressions:
- `{ "$computed": "functionName", "args": { "key": <expression> } }` — calls a named function with resolved args
- Functions registered via catalog and provided at runtime through `functions` prop on `JSONUIProvider` / `createRenderer`
- `ComputedFunction` type exported from `@json-render/core`
### New: `$template` Expressions
Interpolate state values into strings:
- `{ "$template": "Hello, ${/user/name}!" }` — replaces `${/path}` references with state values
- Missing paths resolve to empty string
### New: State Watchers
React to state changes by triggering actions:
- `watch` field on elements maps state paths to action bindings
- Fires when watched values change (not on initial render)
- Supports cascading dependencies (e.g. country → city loading)
- `watch` is a top-level field on elements (sibling of type/props/children), not inside props
- Spec validator detects and auto-fixes `watch` placed inside props
### New: Cross-Field Validation Functions
New built-in validation functions for cross-field comparisons:
- `equalTo` — alias for `matches` with clearer semantics
- `lessThan` — value must be less than another field (numbers, strings, coerced)
- `greaterThan` — value must be greater than another field
- `requiredIf` — required only when a condition field is truthy
- Validation args now resolve through `resolvePropValue` for consistent `$state` expression handling
### New: `validateForm` Action (React)
Built-in action that validates all registered form fields at once:
- Runs `validateAll()` synchronously and writes `{ valid, errors }` to state
- Default state path: `/formValidation` (configurable via `statePath` param)
- Added to React schema's built-in actions list
### Improved: shadcn/ui Validation
All form components now support validation:
- Checkbox, Radio, Switch — added `checks` and `validateOn` props
- Input, Textarea, Select — added `validateOn` prop (controls timing: change/blur/submit)
- Shared validation schemas reduce catalog definition duplication
### Improved: React Provider Tree
Reordered provider nesting so `ValidationProvider` wraps `ActionProvider`, enabling `validateForm` to access validation state. Added `useOptionalValidation` hook for non-throwing access.
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
## 0.9.1
### Patch Changes
- b103676: Fix install failure caused by `@internal/react-state` (a private workspace package) being listed as a published dependency. The internal package is now bundled into each renderer's output at build time, so consumers no longer need to resolve it from npm.
- @json-render/core@0.9.1
## 0.9.0
### Minor Changes
+2 -72
View File
@@ -261,7 +261,6 @@ const { errors, validate } = useFieldValidation("/form/email", {
| `useActions()` | Access action context |
| `useAction(name)` | Get a single action dispatch function |
| `useFieldValidation(path, config)` | Field validation state |
| `useOptionalValidation()` | Non-throwing validation context (returns `null` if no provider) |
| `useUIStream(options)` | Stream specs from an API endpoint |
## Visibility Conditions
@@ -325,60 +324,11 @@ Any prop value can use data-driven expressions that resolve at render time. The
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]`.
### `$template` and `$computed`
```json
{
"label": { "$template": "Hello, ${/user/name}!" },
"fullName": {
"$computed": "fullName",
"args": {
"first": { "$state": "/form/firstName" },
"last": { "$state": "/form/lastName" }
}
}
}
```
Register functions via the `functions` prop on `JSONUIProvider` or `createRenderer`:
```tsx
<JSONUIProvider
spec={spec}
catalog={catalog}
functions={{ fullName: (args) => `${args.first} ${args.last}` }}
>
```
See [@json-render/core](../core/README.md) for full expression syntax.
## State Watchers
Elements can declare a `watch` field to trigger actions when state values change:
```json
{
"type": "Select",
"props": {
"label": "Country",
"value": { "$bindState": "/form/country" },
"options": ["US", "Canada", "UK"]
},
"watch": {
"/form/country": {
"action": "loadCities",
"params": { "country": { "$state": "/form/country" } }
}
},
"children": []
}
```
`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.
## Built-in Actions
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`:
The `setState`, `pushState`, and `removeState` 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`. They update the state model, which triggers re-evaluation of visibility conditions and dynamic prop expressions:
```json
{
@@ -394,26 +344,6 @@ The `setState`, `pushState`, `removeState`, and `validateForm` actions are built
}
```
### `validateForm`
Validate all registered form fields at once and write the result to state:
```json
{
"type": "Button",
"props": { "label": "Submit" },
"on": {
"press": [
{ "action": "validateForm", "params": { "statePath": "/formResult" } },
{ "action": "submitForm" }
]
},
"children": []
}
```
Writes `{ valid: boolean, errors: Record<string, string[]> }` to the specified state path (defaults to `/formValidation`).
## Component Props
When using `defineRegistry`, components receive these props:
@@ -521,7 +451,7 @@ function App() {
|--------|---------|
| `defineRegistry` | Create a type-safe component registry from a catalog |
| `Renderer` | Render a spec using a registry |
| `schema` | Element tree schema (includes built-in actions: `setState`, `pushState`, `removeState`, `validateForm`) |
| `schema` | Element tree schema (includes built-in actions: `setState`, `pushState`, `removeState`) |
| `useStateStore` | Access state context |
| `useStateValue` | Get single value from state |
| `useBoundProp` | Two-way binding for `$bindState`/`$bindItem` expressions |
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@json-render/react",
"version": "0.10.0",
"version": "0.9.0",
"license": "Apache-2.0",
"description": "React renderer for @json-render/core. JSON becomes React components.",
"keywords": [
@@ -50,10 +50,10 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@json-render/core": "workspace:*"
"@json-render/core": "workspace:*",
"@internal/react-state": "workspace:*"
},
"devDependencies": {
"@internal/react-state": "workspace:*",
"@internal/typescript-config": "workspace:*",
"@types/react": "19.2.3",
"tsup": "^8.0.2",
+1 -7
View File
@@ -251,15 +251,9 @@ export function ActionProvider({
return;
}
const valid = validateAll();
const errors: Record<string, string[]> = {};
for (const [path, fs] of Object.entries(validation.fieldStates)) {
if (fs.result && !fs.result.valid) {
errors[path] = fs.result.errors;
}
}
const statePath =
(resolved.params?.statePath as string) || "/formValidation";
set(statePath, { valid, errors });
set(statePath, { valid });
return;
}
+19 -31
View File
@@ -3,7 +3,6 @@
import React, {
createContext,
useContext,
useRef,
useState,
useCallback,
useMemo,
@@ -135,9 +134,6 @@ export function ValidationProvider({
const [fieldStates, setFieldStates] = useState<
Record<string, FieldValidationState>
>({});
// Mutable mirror of fieldStates for synchronous reads (e.g. reading errors
// immediately after validateAll() before React flushes the batched setState).
const fieldStatesRef = useRef<Record<string, FieldValidationState>>({});
const [fieldConfigs, setFieldConfigs] = useState<
Record<string, ValidationConfig>
>({});
@@ -179,16 +175,14 @@ export function ValidationProvider({
customFunctions,
});
const newFieldState: FieldValidationState = {
touched: fieldStatesRef.current[path]?.touched ?? true,
validated: true,
result,
};
fieldStatesRef.current = {
...fieldStatesRef.current,
[path]: newFieldState,
};
setFieldStates(fieldStatesRef.current);
setFieldStates((prev) => ({
...prev,
[path]: {
touched: prev[path]?.touched ?? true,
validated: true,
result,
},
}));
return result;
},
@@ -196,22 +190,22 @@ export function ValidationProvider({
);
const touch = useCallback((path: string) => {
fieldStatesRef.current = {
...fieldStatesRef.current,
setFieldStates((prev) => ({
...prev,
[path]: {
...fieldStatesRef.current[path],
...prev[path],
touched: true,
validated: fieldStatesRef.current[path]?.validated ?? false,
result: fieldStatesRef.current[path]?.result ?? null,
validated: prev[path]?.validated ?? false,
result: prev[path]?.result ?? null,
},
};
setFieldStates(fieldStatesRef.current);
}));
}, []);
const clear = useCallback((path: string) => {
const { [path]: _, ...rest } = fieldStatesRef.current;
fieldStatesRef.current = rest;
setFieldStates(rest);
setFieldStates((prev) => {
const { [path]: _, ...rest } = prev;
return rest;
});
}, []);
const validateAll = useCallback(() => {
@@ -230,11 +224,7 @@ export function ValidationProvider({
const value = useMemo<ValidationContextValue>(
() => ({
customFunctions,
// Getter returns the mutable ref so callers that read fieldStates
// synchronously after validateAll() see the latest values.
get fieldStates() {
return fieldStatesRef.current;
},
fieldStates,
validate,
touch,
clear,
@@ -243,8 +233,6 @@ export function ValidationProvider({
}),
[
customFunctions,
// fieldStates (React state) stays in deps so the context value object
// is recreated on re-render, triggering downstream consumers.
fieldStates,
validate,
touch,
+3 -6
View File
@@ -546,10 +546,7 @@ describe("validateForm action", () => {
});
const state = getState();
expect(state.result).toEqual({
valid: false,
errors: { "/form/email": ["Email is required"] },
});
expect(state.result).toEqual({ valid: false });
});
it("writes { valid: true } when all fields pass validation", async () => {
@@ -604,7 +601,7 @@ describe("validateForm action", () => {
});
const state = getState();
expect(state.result).toEqual({ valid: true, errors: {} });
expect(state.result).toEqual({ valid: true });
});
it("defaults to /formValidation when no statePath is provided", async () => {
@@ -654,7 +651,7 @@ describe("validateForm action", () => {
});
const state = getState();
expect(state.formValidation).toEqual({ valid: true, errors: {} });
expect(state.formValidation).toEqual({ valid: true });
});
});
+1 -1
View File
@@ -70,7 +70,7 @@ export const schema = defineSchema(
{
name: "validateForm",
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[]> }.",
"Validate all registered form fields and write the result to state. Params: { statePath?: string }. Defaults to /formValidation. Result: { valid: boolean }.",
},
],
defaultRules: [
+1 -2
View File
@@ -3,9 +3,8 @@ import { defineConfig } from "tsup";
export default defineConfig({
entry: ["src/index.ts", "src/schema.ts"],
format: ["cjs", "esm"],
dts: { resolve: ["@internal/react-state"] },
dts: true,
sourcemap: true,
clean: true,
noExternal: ["@internal/react-state"],
external: ["react", "react-dom", "@json-render/core"],
});
-13
View File
@@ -1,18 +1,5 @@
# @json-render/redux
## 0.10.0
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
## 0.9.1
### Patch Changes
- @json-render/core@0.9.1
## 0.9.0
### Minor Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@json-render/redux",
"version": "0.10.0",
"version": "0.9.0",
"license": "Apache-2.0",
"description": "Redux adapter for json-render StateStore",
"keywords": [
-13
View File
@@ -1,18 +1,5 @@
# @json-render/remotion
## 0.10.0
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
## 0.9.1
### Patch Changes
- @json-render/core@0.9.1
## 0.9.0
### Minor Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@json-render/remotion",
"version": "0.10.0",
"version": "0.9.0",
"license": "Apache-2.0",
"description": "Remotion renderer for @json-render/core. JSON becomes video compositions.",
"keywords": [
-85
View File
@@ -1,90 +1,5 @@
# @json-render/shadcn
## 0.10.0
### Minor Changes
- 9cef4e9: Dynamic forms, Vue renderer, XState Store adapter, and computed values.
### New: `@json-render/vue` Package
Vue 3 renderer for json-render. Full feature parity with `@json-render/react` including data binding, visibility conditions, actions, validation, repeat scopes, and streaming.
- `defineRegistry` — create type-safe component registries from catalogs
- `Renderer` — render specs as Vue component trees
- Providers: `StateProvider`, `ActionProvider`, `VisibilityProvider`, `ValidationProvider`
- Composables: `useStateStore`, `useStateValue`, `useStateBinding`, `useActions`, `useAction`, `useIsVisible`, `useFieldValidation`
- Streaming: `useUIStream`, `useChatUI`
- External store support via `StateStore` interface
### New: `@json-render/xstate` Package
XState Store (atom) adapter for json-render's `StateStore` interface. Wire an `@xstate/store` atom as the state backend.
- `xstateStoreStateStore({ atom })` — creates a `StateStore` from an `@xstate/store` atom
- Requires `@xstate/store` v3+
### New: `$computed` Expressions
Call registered functions from prop expressions:
- `{ "$computed": "functionName", "args": { "key": <expression> } }` — calls a named function with resolved args
- Functions registered via catalog and provided at runtime through `functions` prop on `JSONUIProvider` / `createRenderer`
- `ComputedFunction` type exported from `@json-render/core`
### New: `$template` Expressions
Interpolate state values into strings:
- `{ "$template": "Hello, ${/user/name}!" }` — replaces `${/path}` references with state values
- Missing paths resolve to empty string
### New: State Watchers
React to state changes by triggering actions:
- `watch` field on elements maps state paths to action bindings
- Fires when watched values change (not on initial render)
- Supports cascading dependencies (e.g. country → city loading)
- `watch` is a top-level field on elements (sibling of type/props/children), not inside props
- Spec validator detects and auto-fixes `watch` placed inside props
### New: Cross-Field Validation Functions
New built-in validation functions for cross-field comparisons:
- `equalTo` — alias for `matches` with clearer semantics
- `lessThan` — value must be less than another field (numbers, strings, coerced)
- `greaterThan` — value must be greater than another field
- `requiredIf` — required only when a condition field is truthy
- Validation args now resolve through `resolvePropValue` for consistent `$state` expression handling
### New: `validateForm` Action (React)
Built-in action that validates all registered form fields at once:
- Runs `validateAll()` synchronously and writes `{ valid, errors }` to state
- Default state path: `/formValidation` (configurable via `statePath` param)
- Added to React schema's built-in actions list
### Improved: shadcn/ui Validation
All form components now support validation:
- Checkbox, Radio, Switch — added `checks` and `validateOn` props
- Input, Textarea, Select — added `validateOn` prop (controls timing: change/blur/submit)
- Shared validation schemas reduce catalog definition duplication
### Improved: React Provider Tree
Reordered provider nesting so `ValidationProvider` wraps `ActionProvider`, enabling `validateForm` to access validation state. Added `useOptionalValidation` hook for non-throwing access.
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
- @json-render/react@0.10.0
## 0.9.1
### Patch Changes
- Updated dependencies [b103676]
- @json-render/react@0.9.1
- @json-render/core@0.9.1
## 0.9.0
### Minor Changes
+7 -18
View File
@@ -167,12 +167,12 @@ const { registry } = defineRegistry(catalog, {
|-----------|-------------|
| `Button` | Clickable button with variants |
| `Link` | Anchor link |
| `Input` | Text input with label, validation, and `validateOn` timing |
| `Textarea` | Multi-line text input with validation and `validateOn` |
| `Select` | Dropdown select with validation and `validateOn` |
| `Checkbox` | Checkbox input with validation and `validateOn` |
| `Radio` | Radio button group with validation and `validateOn` |
| `Switch` | Toggle switch with validation and `validateOn` |
| `Input` | Text input with label and validation |
| `Textarea` | Multi-line text input |
| `Select` | Dropdown select |
| `Checkbox` | Checkbox input |
| `Radio` | Radio button group |
| `Switch` | Toggle switch |
| `Slider` | Range slider |
| `Toggle` | Toggle button |
| `ToggleGroup` | Group of toggle buttons |
@@ -180,24 +180,13 @@ const { registry } = defineRegistry(catalog, {
## Built-in Actions
State actions (`setState`, `pushState`, `removeState`, `validateForm`) are built into the `@json-render/react` schema and handled automatically by `ActionProvider`. They are included in prompts without needing to be declared in your catalog.
State actions (`setState`, `pushState`, `removeState`) are built into the `@json-render/react` schema and handled automatically by `ActionProvider`. They are included in prompts without needing to be declared in your catalog.
| Action | Description |
|--------|-------------|
| `setState` | Set a value at a state path |
| `pushState` | Push a value onto an array in state |
| `removeState` | Remove an item from an array in state |
| `validateForm` | Validate all fields and write result to state |
### Validation Timing (`validateOn`)
All form components support the `validateOn` prop to control when validation runs:
| Value | Description | Default For |
|-------|-------------|-------------|
| `"change"` | Validate on every input change | Select, Checkbox, Radio, Switch |
| `"blur"` | Validate when field loses focus | Input, Textarea |
| `"submit"` | Validate only on form submission | — |
## Exports
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@json-render/shadcn",
"version": "0.10.0",
"version": "0.9.0",
"license": "Apache-2.0",
"description": "shadcn/ui component library for @json-render/core. JSON becomes beautiful Tailwind-styled React components.",
"keywords": [
-77
View File
@@ -1,77 +0,0 @@
# @json-render/vue
## 0.10.0
### Minor Changes
- 9cef4e9: Dynamic forms, Vue renderer, XState Store adapter, and computed values.
### New: `@json-render/vue` Package
Vue 3 renderer for json-render. Full feature parity with `@json-render/react` including data binding, visibility conditions, actions, validation, repeat scopes, and streaming.
- `defineRegistry` — create type-safe component registries from catalogs
- `Renderer` — render specs as Vue component trees
- Providers: `StateProvider`, `ActionProvider`, `VisibilityProvider`, `ValidationProvider`
- Composables: `useStateStore`, `useStateValue`, `useStateBinding`, `useActions`, `useAction`, `useIsVisible`, `useFieldValidation`
- Streaming: `useUIStream`, `useChatUI`
- External store support via `StateStore` interface
### New: `@json-render/xstate` Package
XState Store (atom) adapter for json-render's `StateStore` interface. Wire an `@xstate/store` atom as the state backend.
- `xstateStoreStateStore({ atom })` — creates a `StateStore` from an `@xstate/store` atom
- Requires `@xstate/store` v3+
### New: `$computed` Expressions
Call registered functions from prop expressions:
- `{ "$computed": "functionName", "args": { "key": <expression> } }` — calls a named function with resolved args
- Functions registered via catalog and provided at runtime through `functions` prop on `JSONUIProvider` / `createRenderer`
- `ComputedFunction` type exported from `@json-render/core`
### New: `$template` Expressions
Interpolate state values into strings:
- `{ "$template": "Hello, ${/user/name}!" }` — replaces `${/path}` references with state values
- Missing paths resolve to empty string
### New: State Watchers
React to state changes by triggering actions:
- `watch` field on elements maps state paths to action bindings
- Fires when watched values change (not on initial render)
- Supports cascading dependencies (e.g. country → city loading)
- `watch` is a top-level field on elements (sibling of type/props/children), not inside props
- Spec validator detects and auto-fixes `watch` placed inside props
### New: Cross-Field Validation Functions
New built-in validation functions for cross-field comparisons:
- `equalTo` — alias for `matches` with clearer semantics
- `lessThan` — value must be less than another field (numbers, strings, coerced)
- `greaterThan` — value must be greater than another field
- `requiredIf` — required only when a condition field is truthy
- Validation args now resolve through `resolvePropValue` for consistent `$state` expression handling
### New: `validateForm` Action (React)
Built-in action that validates all registered form fields at once:
- Runs `validateAll()` synchronously and writes `{ valid, errors }` to state
- Default state path: `/formValidation` (configurable via `statePath` param)
- Added to React schema's built-in actions list
### Improved: shadcn/ui Validation
All form components now support validation:
- Checkbox, Radio, Switch — added `checks` and `validateOn` props
- Input, Textarea, Select — added `validateOn` prop (controls timing: change/blur/submit)
- Shared validation schemas reduce catalog definition duplication
### Improved: React Provider Tree
Reordered provider nesting so `ValidationProvider` wraps `ActionProvider`, enabling `validateForm` to access validation state. Added `useOptionalValidation` hook for non-throwing access.
### Patch Changes
- Updated dependencies [9cef4e9]
- @json-render/core@0.10.0
-496
View File
@@ -1,496 +0,0 @@
# @json-render/vue
Vue 3 renderer for json-render. Turn JSON specs into Vue components with data binding, visibility, and actions.
## Installation
```bash
npm install @json-render/vue @json-render/core zod
```
Peer dependencies: `vue ^3.5.0` and `zod ^4.0.0`.
## Quick Start
### 1. Create a Catalog
```typescript
import { defineCatalog } from "@json-render/core";
import { schema } from "@json-render/vue/schema";
import { z } from "zod";
export const catalog = defineCatalog(schema, {
components: {
Card: {
props: z.object({
title: z.string(),
description: z.string().nullable(),
}),
description: "A card container",
},
Button: {
props: z.object({
label: z.string(),
action: z.string(),
}),
description: "A clickable button",
},
Input: {
props: z.object({
value: z.union([z.string(), z.record(z.unknown())]).nullable(),
label: z.string(),
placeholder: z.string().nullable(),
}),
description: "Text input field with optional value binding",
},
},
actions: {
submit: { description: "Submit the form" },
cancel: { description: "Cancel and close" },
},
});
```
### 2. Define Component Implementations
Components are written using Vue's `h()` render function. `children` is a `VNode | VNode[]` — pass it directly to your container element.
`defineRegistry` conditionally requires the `actions` field only when the catalog declares actions. Catalogs with `actions: {}` can omit it entirely.
```typescript
import { h } from "vue";
import { defineRegistry } from "@json-render/vue";
import { catalog } from "./catalog";
export const { registry } = defineRegistry(catalog, {
components: {
Card: ({ props, children }) =>
h("div", { class: "card" }, [
h("h3", null, props.title),
props.description ? h("p", null, props.description) : null,
children,
]),
Button: ({ props, emit }) =>
h("button", { onClick: () => emit("press") }, props.label),
Input: ({ props, bindings }) => {
// Use bindings?.value with a watcher to implement two-way binding
return h("label", null, [
props.label,
h("input", {
placeholder: props.placeholder ?? "",
value: props.value ?? "",
}),
]);
},
},
// actions stubs are required when the catalog declares actions:
actions: {
submit: async () => {},
cancel: async () => {},
},
});
```
> **Tip:** Use `useBoundProp(props.value, bindings?.value)` for two-way binding, or handle the `bindings` object directly in your component.
### 3. Render Specs
```vue
<script setup lang="ts">
import { StateProvider, ActionProvider, Renderer } from "@json-render/vue";
import { registry } from "./registry";
const spec = { /* ... */ };
function handleSubmit(params) {
console.log("Submit", params);
}
</script>
<template>
<StateProvider :initial-state="{ form: { name: '' } }">
<ActionProvider :handlers="{ submit: handleSubmit }">
<Renderer :spec="spec" :registry="registry" />
</ActionProvider>
</StateProvider>
</template>
```
## Spec Format
The Vue renderer uses the same flat element map format as the React renderer:
```typescript
interface Spec {
root: string; // Key of the root element
elements: Record<string, UIElement>; // Flat map of elements by key
state?: Record<string, unknown>; // Optional initial state
}
interface UIElement {
type: string; // Component name from catalog
props: Record<string, unknown>; // Component props
children?: string[]; // Keys of child elements
visible?: VisibilityCondition; // Visibility condition
}
```
Example spec:
```json
{
"root": "card-1",
"elements": {
"card-1": {
"type": "Card",
"props": { "title": "Welcome" },
"children": ["input-1", "btn-1"]
},
"input-1": {
"type": "Input",
"props": {
"value": { "$bindState": "/form/name" },
"label": "Name",
"placeholder": "Enter name"
}
},
"btn-1": {
"type": "Button",
"props": { "label": "Submit" },
"children": []
}
}
}
```
## Providers
### StateProvider
Share data across components with JSON Pointer paths:
```vue
<StateProvider :initial-state="{ user: { name: 'John' } }">
<!-- children -->
</StateProvider>
```
```typescript
// In composables:
const { state, get, set } = useStateStore();
const name = get("/user/name"); // "John"
set("/user/age", 25);
// state is a ShallowRef<StateModel> — access with state.value
console.log(state.value);
```
#### External Store (Controlled Mode)
Pass a `StateStore` to bypass the internal state and wire json-render to any state management library (Pinia, VueUse, etc.):
```typescript
import { createStateStore, type StateStore } from "@json-render/vue";
// Option 1: Use the built-in store outside of Vue
const store = createStateStore({ count: 0 });
```
```vue
<StateProvider :store="store">
<!-- children -->
</StateProvider>
```
```typescript
// Mutate from anywhere — Vue will re-render automatically:
store.set("/count", 1);
// Option 2: Implement the StateStore interface with your own backend
const piniaStore: StateStore = {
get: (path) => getByPath(myStore.$state, path),
set: (path, value) => myStore.$patch(/* ... */),
update: (updates) => myStore.$patch(/* ... */),
getSnapshot: () => myStore.$state,
subscribe: (listener) => myStore.$subscribe(listener),
};
```
When `store` is provided, `initialState` and `onStateChange` are ignored.
### ActionProvider
Handle actions from components:
```vue
<ActionProvider :handlers="{ submit: handleSubmit, cancel: handleCancel }">
<!-- children -->
</ActionProvider>
```
### VisibilityProvider
Control element visibility based on data:
```vue
<VisibilityProvider>
<!-- children -->
</VisibilityProvider>
```
```json
{
"type": "Alert",
"props": { "message": "Error!" },
"visible": { "$state": "/form/hasError" }
}
```
### ValidationProvider
Add field validation:
```vue
<ValidationProvider>
<!-- children -->
</ValidationProvider>
```
```typescript
// Use validation composable:
const { errors, validate } = useFieldValidation("/form/email", {
checks: [
{ type: "required", message: "Email required" },
{ type: "email", message: "Invalid email" },
],
});
```
## Composables
| Composable | Purpose |
|------------|---------|
| `useStateStore()` | Access state context (`state` as `ShallowRef`, `get`, `set`, `update`) |
| `useStateValue(path)` | Get single value from state |
| `useStateBinding(path)` | Two-way data binding (deprecated — use `$bindState` instead) |
| `useIsVisible(condition)` | Check if a visibility condition is met |
| `useActions()` | Access action context |
| `useAction(binding)` | Get a single action dispatch function |
| `useFieldValidation(path, config)` | Field validation state |
> **Note:** `useStateStore().state` returns a `ShallowRef<StateModel>` — use `state.value` to access the underlying object. This differs from the React renderer where `state` is a plain object.
## Visibility Conditions
```typescript
// Truthiness check
{ "$state": "/user/isAdmin" }
// Auth state (use state path)
{ "$state": "/auth/isSignedIn" }
// Comparisons (flat style)
{ "$state": "/status", "eq": "active" }
{ "$state": "/count", "gt": 10 }
// Negation
{ "$state": "/maintenance", "not": true }
// Multiple conditions (implicit AND)
[
{ "$state": "/feature/enabled" },
{ "$state": "/maintenance", "not": true }
]
// Always / never
true // always visible
false // never visible
```
TypeScript helpers from `@json-render/core`:
```typescript
import { visibility } from "@json-render/core";
visibility.when("/path") // { $state: "/path" }
visibility.unless("/path") // { $state: "/path", not: true }
visibility.eq("/path", val) // { $state: "/path", eq: val }
visibility.neq("/path", val) // { $state: "/path", neq: val }
visibility.and(cond1, cond2) // { $and: [cond1, cond2] }
visibility.always // true
visibility.never // false
```
## Dynamic Prop Expressions
Any prop value can use data-driven expressions that resolve at render time. The renderer resolves these transparently before passing props to components.
```json
{
"type": "Badge",
"props": {
"label": { "$state": "/user/role" },
"color": {
"$cond": { "$state": "/user/role", "eq": "admin" },
"$then": "red",
"$else": "gray"
}
}
}
```
For two-way binding, use `{ "$bindState": "/path" }` on the natural value prop. Inside repeat scopes, use `{ "$bindItem": "field" }` instead. Components receive resolved `bindings` with the state path for each bound prop.
See [@json-render/core](../core/README.md) for full expression syntax.
## Built-in Actions
The `setState`, `pushState`, `removeState`, and `validateForm` actions are built into the Vue schema and handled automatically by `ActionProvider`. They are injected into AI prompts without needing to be declared in your catalog's `actions`. They update the state model, which triggers re-evaluation of visibility conditions and dynamic prop expressions:
```json
{
"type": "Button",
"props": { "label": "Switch Tab" },
"on": {
"press": {
"action": "setState",
"params": { "statePath": "/activeTab", "value": "settings" }
}
},
"children": []
}
```
## Component Props
When using `defineRegistry`, components receive these props via their render function:
```typescript
import type { VNode } from "vue";
interface ComponentContext<P> {
props: P; // Typed props from the catalog (expressions resolved)
children?: VNode | VNode[]; // Rendered children (for container components)
emit: (event: string) => void; // Emit a named event (always defined)
on: (event: string) => EventHandle; // Get event handle with metadata
loading?: boolean; // Whether the parent is loading
bindings?: Record<string, string>; // State paths for $bindState/$bindItem expressions
}
interface EventHandle {
emit: () => void; // Fire the event
shouldPreventDefault: boolean; // Whether any binding requested preventDefault
bound: boolean; // Whether any handler is bound
}
```
Use `emit("press")` for simple event firing. Use `on("click")` when you need to check metadata like `shouldPreventDefault` or `bound`:
```typescript
Link: ({ props, on }) => {
const click = on("click");
return h("a", {
href: props.href,
onClick: (e: MouseEvent) => {
if (click.shouldPreventDefault) e.preventDefault();
click.emit();
},
}, props.label);
},
```
### `BaseComponentProps`
For building reusable component libraries that are not tied to a specific catalog, use the catalog-agnostic `BaseComponentProps` type:
```typescript
import type { BaseComponentProps } from "@json-render/vue";
const Card = ({ props, children }: BaseComponentProps<{ title?: string }>) =>
h("div", null, [props.title, children]);
```
## Generate AI Prompts
```typescript
const systemPrompt = catalog.prompt();
// Returns detailed prompt with component/action descriptions
```
## Full Example
```typescript
import { h } from "vue";
import { defineCatalog } from "@json-render/core";
import { schema } from "@json-render/vue/schema";
import { defineRegistry, Renderer, StateProvider } from "@json-render/vue";
import { z } from "zod";
const catalog = defineCatalog(schema, {
components: {
Greeting: {
props: z.object({ name: z.string() }),
description: "Displays a greeting",
},
},
actions: {},
});
const { registry } = defineRegistry(catalog, {
components: {
Greeting: ({ props }) => h("h1", null, `Hello, ${props.name}!`),
},
});
const spec = {
root: "greeting-1",
elements: {
"greeting-1": {
type: "Greeting",
props: { name: "World" },
children: [],
},
},
};
// In your App.vue:
// <StateProvider>
// <Renderer :spec="spec" :registry="registry" />
// </StateProvider>
```
## Key Exports
| Export | Purpose |
|--------|---------|
| `defineRegistry` | Create a type-safe component registry from a catalog |
| `Renderer` | Render a spec using a registry |
| `schema` | Element tree schema (includes built-in actions: `setState`, `pushState`, `removeState`) |
| `useStateStore` | Access state context (`state` is `ShallowRef<StateModel>`) |
| `useStateValue` | Get single value from state |
| `useActions` | Access actions context |
| `useAction` | Get a single action dispatch function |
| `createStateStore` | Create a framework-agnostic in-memory `StateStore` |
### Types
| Export | Purpose |
|--------|---------|
| `ComponentContext` | Typed component render function context (catalog-aware) |
| `BaseComponentProps` | Catalog-agnostic base type for reusable component libraries |
| `EventHandle` | Event handle with `emit()`, `shouldPreventDefault`, `bound` |
| `ActionProviderProps` | Props for `ActionProvider` |
| `ValidationProviderProps` | Props for `ValidationProvider` |
| `ComponentFn` | Component render function type |
| `SetState` | State setter type |
| `StateModel` | State model type |
| `StateStore` | Interface for plugging in external state management |
## Differences from `@json-render/react`
| API | React | Vue | Note |
|-----|-------|-----|------|
| `useStateStore().state` | `StateModel` | `ShallowRef<StateModel>` | Vue reactivity; use `state.value` |
| `children` type | `React.ReactNode` | `VNode \| VNode[]` | Platform-specific |
| `useBoundProp` | exported | exported | Same API; returns `[value, setValue]` |
| Streaming hooks | `useUIStream`, `useChatUI` | `useUIStream`, `useChatUI` | Same API; returns Vue `Ref` values |
-66
View File
@@ -1,66 +0,0 @@
{
"name": "@json-render/vue",
"version": "0.10.0",
"license": "Apache-2.0",
"description": "Vue renderer for @json-render/core. JSON becomes Vue components.",
"keywords": [
"json",
"ui",
"vue",
"ai",
"generative-ui",
"llm",
"renderer",
"streaming",
"components"
],
"repository": {
"type": "git",
"url": "git+https://github.com/vercel-labs/json-render.git",
"directory": "packages/vue"
},
"homepage": "https://github.com/vercel-labs/json-render#readme",
"bugs": {
"url": "https://github.com/vercel-labs/json-render/issues"
},
"publishConfig": {
"access": "public"
},
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
"./schema": {
"types": "./dist/schema.d.ts",
"import": "./dist/schema.mjs",
"require": "./dist/schema.js"
}
},
"files": [
"dist"
],
"scripts": {
"build": "tsup",
"dev": "tsup --watch",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@json-render/core": "workspace:*"
},
"devDependencies": {
"@internal/typescript-config": "workspace:*",
"@vue/test-utils": "^2.4.6",
"tsup": "^8.0.2",
"typescript": "^5.4.5",
"vue": "^3.5.0"
},
"peerDependencies": {
"vue": "^3.5.0",
"zod": "^4.0.0"
}
}
-152
View File
@@ -1,152 +0,0 @@
import type { VNode } from "vue";
import type {
Catalog,
InferCatalogComponents,
InferCatalogActions,
InferComponentProps,
InferActionParams,
StateModel,
} from "@json-render/core";
export type { StateModel };
// =============================================================================
// State Types
// =============================================================================
/**
* State setter function for updating application state
*/
export type SetState = (
updater: (prev: Record<string, unknown>) => Record<string, unknown>,
) => void;
// =============================================================================
// Component Types
// =============================================================================
/**
* Handle returned by the `on()` function for a specific event.
* Provides metadata about the event binding and a method to fire it.
*
* @example
* ```ts
* const press = on("press");
* if (press.shouldPreventDefault) e.preventDefault();
* press.emit();
* ```
*/
export interface EventHandle {
/** Fire the event (resolve action bindings) */
emit: () => void;
/** Whether any binding requested preventDefault */
shouldPreventDefault: boolean;
/** Whether any handler is bound to this event */
bound: boolean;
}
/**
* Catalog-agnostic base type for component render function arguments.
* Use this when building reusable component libraries that are not tied to a specific catalog.
*
* @example
* ```ts
* const Card = ({ props, children }: BaseComponentProps<{ title?: string }>) =>
* h('div', null, [props.title, children])
* ```
*/
export interface BaseComponentProps<P = Record<string, unknown>> {
props: P;
/** Rendered children (from the default slot) */
children?: VNode | VNode[];
/** Simple event emitter (shorthand). Fires the event and returns void. */
emit: (event: string) => void;
/** Get an event handle with metadata. Use when you need shouldPreventDefault or bound checks. */
on: (event: string) => EventHandle;
/**
* Two-way binding paths resolved from `$bindState` / `$bindItem` expressions.
* Maps prop name → absolute state path for write-back.
*/
bindings?: Record<string, string>;
loading?: boolean;
}
/**
* Context passed to component render functions
* @example
* const Button: ComponentFn<typeof catalog, 'Button'> = (ctx) => {
* return h('button', { onClick: () => ctx.emit("press") }, ctx.props.label)
* }
*/
export interface ComponentContext<
C extends Catalog,
K extends keyof InferCatalogComponents<C>,
> extends BaseComponentProps<InferComponentProps<C, K>> {}
/**
* Component render function type for Vue
* @example
* const Button: ComponentFn<typeof catalog, 'Button'> = ({ props, emit }) =>
* h('button', { onClick: () => emit("press") }, props.label)
*/
export type ComponentFn<
C extends Catalog,
K extends keyof InferCatalogComponents<C>,
> = (ctx: ComponentContext<C, K>) => VNode | VNode[] | null | string;
/**
* Registry of all component render functions for a catalog
* @example
* const components: Components<typeof myCatalog> = {
* Button: ({ props }) => h('button', null, props.label),
* Input: ({ props }) => h('input', { placeholder: props.placeholder }),
* };
*/
export type Components<C extends Catalog> = {
[K in keyof InferCatalogComponents<C>]: ComponentFn<C, K>;
};
// =============================================================================
// Action Types
// =============================================================================
/**
* Action handler function type
* @example
* const viewCustomers: ActionFn<typeof catalog, 'viewCustomers'> = async (params, setState) => {
* const data = await fetch('/api/customers');
* setState(prev => ({ ...prev, customers: data }));
* };
*/
export type ActionFn<
C extends Catalog,
K extends keyof InferCatalogActions<C>,
> = (
params: InferActionParams<C, K> | undefined,
setState: SetState,
state: StateModel,
) => Promise<void>;
/**
* Registry of all action handlers for a catalog
* @example
* const actions: Actions<typeof myCatalog> = {
* viewCustomers: async (params, setState) => { ... },
* createCustomer: async (params, setState) => { ... },
* };
*/
export type Actions<C extends Catalog> = {
[K in keyof InferCatalogActions<C>]: ActionFn<C, K>;
};
/**
* True when the catalog declares at least one action, false otherwise.
* Used by defineRegistry to conditionally require the `actions` field.
*/
export type CatalogHasActions<C extends Catalog> = [
InferCatalogActions<C>,
] extends [never]
? false
: [keyof InferCatalogActions<C>] extends [never]
? false
: true;
@@ -1,106 +0,0 @@
import { describe, it, expect, vi } from "vitest";
import { defineComponent, h, type Component } from "vue";
import { mount } from "@vue/test-utils";
import { StateProvider, useStateStore } from "./state";
import { ActionProvider, useActions, useAction } from "./actions";
/** Mount StateProvider → ActionProvider with a child that captures context. */
function withProviders<T>(
composable: () => T,
handlers: Record<
string,
(params: Record<string, unknown>) => Promise<void>
> = {},
initialState: Record<string, unknown> = {},
): { result: T } {
let result!: T;
const Child = defineComponent({
setup() {
result = composable();
return () => h("div");
},
});
mount(StateProvider as Component, {
props: { initialState } as any,
slots: {
default: () =>
h(ActionProvider as Component, { handlers } as any, {
default: () => h(Child),
}),
},
});
return { result };
}
describe("ActionProvider — provide/inject", () => {
it("useActions() throws outside a provider", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
expect(() => useActions()).toThrow(
"useActions must be used within an ActionProvider",
);
warn.mockRestore();
});
});
describe("ActionProvider — custom handler dispatch", () => {
it("calling execute invokes the registered handler", async () => {
const handler = vi.fn().mockResolvedValue(undefined);
const { result } = withProviders(() => useActions(), { myAction: handler });
await result.execute({ action: "myAction", params: { x: 1 } });
expect(handler).toHaveBeenCalledOnce();
});
it("handler receives the resolved params", async () => {
const handler = vi.fn().mockResolvedValue(undefined);
const { result } = withProviders(() => useActions(), { myAction: handler });
await result.execute({ action: "myAction", params: { x: 1, y: "hello" } });
expect(handler).toHaveBeenCalledWith({ x: 1, y: "hello" });
});
it("console.warn is called for unknown actions", async () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const { result } = withProviders(() => useActions());
await result.execute({ action: "unknownAction" });
expect(warn).toHaveBeenCalledWith(expect.stringContaining("unknownAction"));
warn.mockRestore();
});
});
describe("ActionProvider — built-in setState integration", () => {
it("executing setState updates state via the provider chain", async () => {
let stateCtx!: ReturnType<typeof useStateStore>;
let actionsCtx!: ReturnType<typeof useActions>;
const Child = defineComponent({
setup() {
stateCtx = useStateStore();
actionsCtx = useActions();
return () => h("div");
},
});
mount(StateProvider as Component, {
props: { initialState: { v: 0 } } as any,
slots: {
default: () =>
h(ActionProvider as Component, null, {
default: () => h(Child),
}),
},
});
await actionsCtx.execute({
action: "setState",
params: { statePath: "/v", value: 42 },
});
expect(stateCtx.state.value).toEqual({ v: 42 });
});
});
describe("useAction", () => {
it("returns { execute, isLoading: false } before execution", () => {
const { result } = withProviders(() => useAction({ action: "myAction" }));
expect(typeof result.execute).toBe("function");
expect(result.isLoading.value).toBe(false);
});
});
-487
View File
@@ -1,487 +0,0 @@
import {
computed,
defineComponent,
h,
inject,
provide,
ref,
watch,
type ComputedRef,
type PropType,
} from "vue";
import {
resolveAction,
executeAction,
type ActionBinding,
type ActionHandler,
type ActionConfirm,
type ResolvedAction,
} from "@json-render/core";
import { useStateStore } from "./state";
import { useOptionalValidation } from "./validation";
/**
* Generate a unique ID for use with the "$id" token.
*/
let idCounter = 0;
function generateUniqueId(): string {
idCounter += 1;
return `${Date.now()}-${idCounter}`;
}
/**
* Deep-resolve dynamic value references within an object.
*
* Supported tokens:
* - `{ $state: "/statePath" }` - read a value from state
* - `"$id"` (string) or `{ "$id": true }` - generate a unique ID
*/
function deepResolveValue(
value: unknown,
get: (path: string) => unknown,
): unknown {
if (value === null || value === undefined) return value;
if (value === "$id") {
return generateUniqueId();
}
if (typeof value === "object" && !Array.isArray(value)) {
const obj = value as Record<string, unknown>;
const keys = Object.keys(obj);
if (keys.length === 1 && typeof obj.$state === "string") {
return get(obj.$state as string);
}
if (keys.length === 1 && "$id" in obj) {
return generateUniqueId();
}
}
if (Array.isArray(value)) {
return value.map((item) => deepResolveValue(item, get));
}
if (typeof value === "object") {
const resolved: Record<string, unknown> = {};
for (const [key, val] of Object.entries(value as Record<string, unknown>)) {
resolved[key] = deepResolveValue(val, get);
}
return resolved;
}
return value;
}
/**
* Pending confirmation state
*/
export interface PendingConfirmation {
action: ResolvedAction;
handler: ActionHandler;
resolve: () => void;
reject: () => void;
}
/**
* Action context value
*/
export interface ActionContextValue {
handlers: Record<string, ActionHandler>;
loadingActions: Set<string>;
pendingConfirmation: PendingConfirmation | null;
execute: (binding: ActionBinding) => Promise<void>;
confirm: () => void;
cancel: () => void;
registerHandler: (name: string, handler: ActionHandler) => void;
}
const ACTIONS_KEY = Symbol("json-render:actions");
export interface ActionProviderProps {
handlers?: Record<string, ActionHandler>;
navigate?: (path: string) => void;
}
/**
* Provider for action execution
*/
export const ActionProvider = defineComponent({
name: "ActionProvider",
props: {
handlers: {
type: Object as PropType<Record<string, ActionHandler>>,
default: () => ({}),
},
navigate: {
type: Function as PropType<(path: string) => void>,
default: undefined,
},
},
setup(props, { slots }) {
const { get, set, getSnapshot } = useStateStore();
const validation = useOptionalValidation();
const handlers = ref<Record<string, ActionHandler>>(props.handlers ?? {});
const loadingActions = ref<Set<string>>(new Set());
const pendingConfirmation = ref<PendingConfirmation | null>(null);
// Sync handlers when prop changes
watch(
() => props.handlers,
(newHandlers) => {
if (newHandlers) handlers.value = newHandlers;
},
);
const registerHandler = (name: string, handler: ActionHandler) => {
handlers.value = { ...handlers.value, [name]: handler };
};
const execute = async (binding: ActionBinding): Promise<void> => {
const resolved = resolveAction(binding, getSnapshot());
// Built-in: setState
if (resolved.action === "setState" && resolved.params) {
const statePath = resolved.params.statePath as string;
const value = resolved.params.value;
if (statePath) {
set(statePath, value);
}
return;
}
// Built-in: pushState
if (resolved.action === "pushState" && resolved.params) {
const statePath = resolved.params.statePath as string;
const rawValue = resolved.params.value;
if (statePath) {
const resolvedValue = deepResolveValue(rawValue, get);
const arr = (get(statePath) as unknown[] | undefined) ?? [];
set(statePath, [...arr, resolvedValue]);
const clearStatePath = resolved.params.clearStatePath as
| string
| undefined;
if (clearStatePath) {
set(clearStatePath, "");
}
}
return;
}
// Built-in: removeState
if (resolved.action === "removeState" && resolved.params) {
const statePath = resolved.params.statePath as string;
const index = resolved.params.index as number;
if (statePath !== undefined && index !== undefined) {
const arr = (get(statePath) as unknown[] | undefined) ?? [];
set(
statePath,
arr.filter((_, i) => i !== index),
);
}
return;
}
// Built-in: validateForm — triggers validateAll and writes result to state
if (resolved.action === "validateForm") {
const validateAll = validation?.validateAll;
if (!validateAll) {
console.warn(
"validateForm action was dispatched but no ValidationProvider is connected. " +
"Ensure ValidationProvider is rendered inside the provider tree.",
);
return;
}
const valid = validateAll();
const errors: Record<string, string[]> = {};
for (const [path, fs] of Object.entries(validation.fieldStates)) {
if (fs.result && !fs.result.valid) {
errors[path] = fs.result.errors;
}
}
const statePath =
(resolved.params?.statePath as string) || "/formValidation";
set(statePath, { valid, errors });
return;
}
// Built-in: push (navigation)
if (resolved.action === "push" && resolved.params) {
const screen = resolved.params.screen as string;
if (screen) {
const currentScreen = get("/currentScreen") as string | undefined;
const navStack = (get("/navStack") as string[] | undefined) ?? [];
if (currentScreen) {
set("/navStack", [...navStack, currentScreen]);
} else {
set("/navStack", [...navStack, ""]);
}
set("/currentScreen", screen);
}
return;
}
// Built-in: pop (navigation)
if (resolved.action === "pop") {
const navStack = (get("/navStack") as string[] | undefined) ?? [];
if (navStack.length > 0) {
const previousScreen = navStack[navStack.length - 1];
set("/navStack", navStack.slice(0, -1));
if (previousScreen) {
set("/currentScreen", previousScreen);
} else {
set("/currentScreen", undefined);
}
}
return;
}
const handler = handlers.value[resolved.action];
if (!handler) {
console.warn(`No handler registered for action: ${resolved.action}`);
return;
}
// If confirmation is required, show dialog first
if (resolved.confirm) {
await new Promise<void>((resolve, reject) => {
pendingConfirmation.value = {
action: resolved,
handler,
resolve: () => {
pendingConfirmation.value = null;
resolve();
},
reject: () => {
pendingConfirmation.value = null;
reject(new Error("Action cancelled"));
},
};
});
const addLoading = new Set(loadingActions.value);
addLoading.add(resolved.action);
loadingActions.value = addLoading;
try {
await executeAction({
action: resolved,
handler,
setState: set,
navigate: props.navigate,
executeAction: async (name) => {
const subBinding: ActionBinding = { action: name };
await execute(subBinding);
},
});
} finally {
const removeLoading = new Set(loadingActions.value);
removeLoading.delete(resolved.action);
loadingActions.value = removeLoading;
}
return;
}
// Execute immediately
const addLoading = new Set(loadingActions.value);
addLoading.add(resolved.action);
loadingActions.value = addLoading;
try {
await executeAction({
action: resolved,
handler,
setState: set,
navigate: props.navigate,
executeAction: async (name) => {
const subBinding: ActionBinding = { action: name };
await execute(subBinding);
},
});
} finally {
const removeLoading = new Set(loadingActions.value);
removeLoading.delete(resolved.action);
loadingActions.value = removeLoading;
}
};
const confirm = () => pendingConfirmation.value?.resolve();
const cancel = () => pendingConfirmation.value?.reject();
provide<ActionContextValue>(ACTIONS_KEY, {
get handlers() {
return handlers.value;
},
get loadingActions() {
return loadingActions.value;
},
get pendingConfirmation() {
return pendingConfirmation.value;
},
execute,
confirm,
cancel,
registerHandler,
});
return () => slots.default?.();
},
});
/**
* Composable to access action context
*/
export function useActions(): ActionContextValue {
const ctx = inject<ActionContextValue>(ACTIONS_KEY);
if (!ctx) {
throw new Error("useActions must be used within an ActionProvider");
}
return ctx;
}
/**
* Composable to execute an action binding
*/
export function useAction(binding: ActionBinding): {
execute: () => Promise<void>;
isLoading: ComputedRef<boolean>;
} {
const ctx = useActions();
return {
execute: () => ctx.execute(binding),
isLoading: computed(() => ctx.loadingActions.has(binding.action)),
};
}
// =============================================================================
// ConfirmDialog component
// =============================================================================
/**
* Props for ConfirmDialog component
*/
export interface ConfirmDialogProps {
confirm: ActionConfirm;
onConfirm: () => void;
onCancel: () => void;
}
/**
* Default confirmation dialog component
*/
export const ConfirmDialog = defineComponent({
name: "ConfirmDialog",
props: {
confirm: {
type: Object as PropType<ActionConfirm>,
required: true,
},
onConfirm: {
type: Function as PropType<() => void>,
required: true,
},
onCancel: {
type: Function as PropType<() => void>,
required: true,
},
},
setup(props) {
return () => {
const isDanger = props.confirm.variant === "danger";
return h(
"div",
{
style: {
position: "fixed",
inset: "0",
backgroundColor: "rgba(0, 0, 0, 0.5)",
display: "flex",
alignItems: "center",
justifyContent: "center",
zIndex: "50",
},
onClick: props.onCancel,
},
[
h(
"div",
{
style: {
backgroundColor: "white",
borderRadius: "8px",
padding: "24px",
maxWidth: "400px",
width: "100%",
boxShadow: "0 20px 25px -5px rgba(0, 0, 0, 0.1)",
},
onClick: (e: MouseEvent) => e.stopPropagation(),
},
[
h(
"h3",
{
style: {
margin: "0 0 8px 0",
fontSize: "18px",
fontWeight: "600",
},
},
props.confirm.title,
),
h(
"p",
{
style: { margin: "0 0 24px 0", color: "#6b7280" },
},
props.confirm.message,
),
h(
"div",
{
style: {
display: "flex",
gap: "12px",
justifyContent: "flex-end",
},
},
[
h(
"button",
{
style: {
padding: "8px 16px",
borderRadius: "6px",
border: "1px solid #d1d5db",
backgroundColor: "white",
cursor: "pointer",
},
onClick: props.onCancel,
},
props.confirm.cancelLabel ?? "Cancel",
),
h(
"button",
{
style: {
padding: "8px 16px",
borderRadius: "6px",
border: "none",
backgroundColor: isDanger ? "#dc2626" : "#3b82f6",
color: "white",
cursor: "pointer",
},
onClick: props.onConfirm,
},
props.confirm.confirmLabel ?? "Confirm",
),
],
),
],
),
],
);
};
},
});
@@ -1,51 +0,0 @@
import { defineComponent, inject, provide, type PropType } from "vue";
/**
* Repeat scope value provided to child elements inside a repeated element.
*/
export interface RepeatScopeValue {
/** The current array item object */
item: unknown;
/** Index of the current item in the array */
index: number;
/** Absolute state path to the current array item (e.g. "/todos/0") — used for statePath two-way binding */
basePath: string;
}
const REPEAT_SCOPE_KEY = Symbol("json-render:repeat-scope");
/**
* Provides repeat scope to child elements so $item and $index expressions resolve correctly.
*/
export const RepeatScopeProvider = defineComponent({
name: "RepeatScopeProvider",
props: {
item: {
required: true,
},
index: {
type: Number,
required: true,
},
basePath: {
type: String as PropType<string>,
required: true,
},
},
setup(props, { slots }) {
provide(REPEAT_SCOPE_KEY, props as RepeatScopeValue);
return () => slots.default?.();
},
});
/**
* Read the current repeat scope (or null if not inside a repeated element).
*/
export function useRepeatScope(): RepeatScopeValue | null {
return (
inject<RepeatScopeValue>(
REPEAT_SCOPE_KEY,
null as unknown as RepeatScopeValue,
) ?? null
);
}
-139
View File
@@ -1,139 +0,0 @@
import { describe, it, expect, vi } from "vitest";
import { defineComponent, h, type Component } from "vue";
import { mount } from "@vue/test-utils";
import { createStateStore } from "@json-render/core";
import { StateProvider, useStateStore } from "./state";
/** Mount a StateProvider with a child that captures the injected context. */
function withProvider<T>(
composable: () => T,
props: Record<string, unknown> = {},
): { result: T } {
let result!: T;
const Child = defineComponent({
setup() {
result = composable();
return () => h("div");
},
});
mount(StateProvider as Component, {
props: props as any,
slots: { default: () => h(Child) },
});
return { result };
}
describe("StateProvider — provide/inject", () => {
it("useStateStore() throws outside a provider", () => {
// inject() returns undefined outside of component setup; our guard throws
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
expect(() => useStateStore()).toThrow(
"useStateStore must be used within a StateProvider",
);
warn.mockRestore();
});
it("child receives the context from StateProvider", () => {
const { result } = withProvider(() => useStateStore());
expect(result).toBeDefined();
expect(result.state).toBeDefined();
expect(typeof result.get).toBe("function");
expect(typeof result.set).toBe("function");
expect(typeof result.update).toBe("function");
});
it("state.value is a plain object (not a wrapper type)", () => {
const { result } = withProvider(() => useStateStore(), {
initialState: { x: 1 },
});
expect(result.state.value).toEqual({ x: 1 });
// Should be a plain object, not a Vue Proxy of a ShallowRef wrapper
expect(typeof result.state.value).toBe("object");
});
});
describe("StateProvider (uncontrolled) — reactivity", () => {
it("state.value reflects initialState on mount", () => {
const { result } = withProvider(() => useStateStore(), {
initialState: { count: 5 },
});
expect(result.state.value).toEqual({ count: 5 });
});
it("after set(), state.value is updated synchronously", () => {
const { result } = withProvider(() => useStateStore(), {
initialState: { x: 0 },
});
result.set("/x", 42);
expect(result.state.value).toEqual({ x: 42 });
});
it("after update(), all paths are reflected in state.value", () => {
const { result } = withProvider(() => useStateStore(), {
initialState: {},
});
result.update({ "/a": 1, "/b": "hello" });
expect(result.state.value).toEqual({ a: 1, b: "hello" });
});
it("onStateChange is fired with the changes array on set", () => {
const onChange = vi.fn();
const { result } = withProvider(() => useStateStore(), {
initialState: {},
onStateChange: onChange,
});
result.set("/name", "Alice");
expect(onChange).toHaveBeenCalledOnce();
expect(onChange).toHaveBeenCalledWith([{ path: "/name", value: "Alice" }]);
});
it("onStateChange is fired once with all changed entries on update", () => {
const onChange = vi.fn();
const { result } = withProvider(() => useStateStore(), {
initialState: {},
onStateChange: onChange,
});
result.update({ "/a": 1, "/b": 2 });
expect(onChange).toHaveBeenCalledOnce();
const [changes] = onChange.mock.calls[0]!;
expect(changes).toEqual(
expect.arrayContaining([
{ path: "/a", value: 1 },
{ path: "/b", value: 2 },
]),
);
});
});
describe("StateProvider (controlled mode)", () => {
it("state.value reads from the external store snapshot", () => {
const store = createStateStore({ x: 10 });
const { result } = withProvider(() => useStateStore(), { store });
expect(result.state.value).toEqual({ x: 10 });
});
it("set() writes through to the external store", () => {
const store = createStateStore({ x: 0 });
const { result } = withProvider(() => useStateStore(), { store });
result.set("/x", 99);
expect(store.getSnapshot()).toEqual({ x: 99 });
});
it("external store mutation triggers state.value update", () => {
const store = createStateStore({ x: 0 });
const { result } = withProvider(() => useStateStore(), { store });
store.set("/x", 99);
expect(result.state.value).toEqual({ x: 99 });
});
it("onStateChange is NOT called in controlled mode", () => {
const store = createStateStore({ x: 0 });
const onChange = vi.fn();
const { result } = withProvider(() => useStateStore(), {
store,
onStateChange: onChange,
});
result.set("/x", 99);
expect(onChange).not.toHaveBeenCalled();
});
});
-216
View File
@@ -1,216 +0,0 @@
import {
computed,
defineComponent,
inject,
onUnmounted,
provide,
ref,
shallowRef,
watch,
type ComputedRef,
type PropType,
type ShallowRef,
} from "vue";
import {
createStateStore,
getByPath,
type StateModel,
type StateStore,
} from "@json-render/core";
import { flattenToPointers } from "@json-render/core/store-utils";
/**
* State context value
*/
export interface StateContextValue {
/** Reactive state snapshot — use state.value in reactive contexts */
state: ShallowRef<StateModel>;
/** Get a value by path */
get: (path: string) => unknown;
/** Set a value by path */
set: (path: string, value: unknown) => void;
/** Update multiple values at once */
update: (updates: Record<string, unknown>) => void;
/** Return the live state snapshot from the underlying store (not through Vue reactivity). */
getSnapshot: () => StateModel;
}
const STATE_KEY = Symbol("json-render:state");
/**
* Props for StateProvider
*/
export interface StateProviderProps {
/**
* External store that owns the state. When provided, the provider operates
* in **controlled mode** — `initialState` and `onStateChange` are ignored
* and the store is the single source of truth.
*/
store?: StateStore;
/** Initial state model (used only in uncontrolled mode) */
initialState?: StateModel;
/**
* Callback when state changes (used only in uncontrolled mode).
* Called once per `set` or `update` with all changed entries.
*/
onStateChange?: (changes: Array<{ path: string; value: unknown }>) => void;
}
/**
* Provider for state model context.
*
* Supports two modes:
* - **Controlled**: pass a `store` prop (e.g. backed by Redux / Zustand).
* - **Uncontrolled** (default): omit `store` and optionally pass
* `initialState` / `onStateChange`.
*/
export const StateProvider = defineComponent({
name: "StateProvider",
props: {
store: {
type: Object as PropType<StateStore>,
default: undefined,
},
initialState: {
type: Object as PropType<StateModel>,
default: undefined,
},
onStateChange: {
type: Function as PropType<
(changes: Array<{ path: string; value: unknown }>) => void
>,
default: undefined,
},
},
setup(props, { slots }) {
const isControlled = !!props.store;
// Use external store (controlled) or create internal store (uncontrolled)
const internalStore = !isControlled
? createStateStore(props.initialState ?? {})
: null;
const store: StateStore = props.store ?? internalStore!;
const state = shallowRef<StateModel>(store.getSnapshot());
const unsubscribe = store.subscribe(() => {
state.value = store.getSnapshot();
});
onUnmounted(unsubscribe);
// Sync external initialState changes (uncontrolled mode only)
if (!isControlled) {
let prevFlat: Record<string, unknown> =
props.initialState && Object.keys(props.initialState).length > 0
? flattenToPointers(props.initialState)
: {};
watch(
() => props.initialState,
(newInitialState) => {
if (!newInitialState) return;
const nextFlat =
Object.keys(newInitialState).length > 0
? flattenToPointers(newInitialState)
: {};
const allKeys = new Set([
...Object.keys(prevFlat),
...Object.keys(nextFlat),
]);
const updates: Record<string, unknown> = {};
for (const key of allKeys) {
if (prevFlat[key] !== nextFlat[key]) {
updates[key] = key in nextFlat ? nextFlat[key] : undefined;
}
}
prevFlat = nextFlat;
if (Object.keys(updates).length > 0) {
store.update(updates);
}
},
);
}
// Keep onStateChange in a ref so it always reads the latest callback
const onStateChangeRef = ref(props.onStateChange);
watch(
() => props.onStateChange,
(fn) => {
onStateChangeRef.value = fn;
},
);
const get = (path: string) => store.get(path);
const getSnapshot = () => store.getSnapshot();
const set = (path: string, value: unknown) => {
const prev = store.getSnapshot();
store.set(path, value);
if (!isControlled && store.getSnapshot() !== prev) {
onStateChangeRef.value?.([{ path, value }]);
}
};
const update = (updates: Record<string, unknown>) => {
const prev = store.getSnapshot();
store.update(updates);
if (!isControlled && store.getSnapshot() !== prev) {
const changes: Array<{ path: string; value: unknown }> = [];
for (const [path, value] of Object.entries(updates)) {
if (getByPath(prev, path) !== value) {
changes.push({ path, value });
}
}
if (changes.length > 0) {
onStateChangeRef.value?.(changes);
}
}
};
provide<StateContextValue>(STATE_KEY, {
state,
get,
set,
update,
getSnapshot,
});
return () => slots.default?.();
},
});
/**
* Composable to access the state context
*/
export function useStateStore(): StateContextValue {
const ctx = inject<StateContextValue>(STATE_KEY);
if (!ctx) {
throw new Error("useStateStore must be used within a StateProvider");
}
return ctx;
}
/**
* Composable to get a value from the state model (reactive)
*/
export function useStateValue<T>(path: string): ComputedRef<T | undefined> {
const { state } = useStateStore();
return computed(() => getByPath(state.value, path) as T | undefined);
}
/**
* Composable to get and set a value from the state model by path.
*
* This is the path-based variant for use in arbitrary composables. For
* registry components that receive `bindings` from the renderer, prefer
* `useBoundProp` which reads the already-resolved prop value and writes back
* to the bound path.
*/
export function useStateBinding<T>(
path: string,
): [ComputedRef<T | undefined>, (value: T) => void] {
const { state, set } = useStateStore();
const value = computed(() => getByPath(state.value, path) as T | undefined);
const setValue = (newValue: T) => set(path, newValue);
return [value, setValue];
}
@@ -1,209 +0,0 @@
import { describe, it, expect, vi } from "vitest";
import { defineComponent, h, type Component } from "vue";
import { mount } from "@vue/test-utils";
import { StateProvider } from "./state";
import {
ValidationProvider,
useOptionalValidation,
useValidation,
useFieldValidation,
} from "./validation";
/** Mount StateProvider → ValidationProvider with a child that captures context. */
function withProviders<T>(
composable: () => T,
initialState: Record<string, unknown> = {},
): { result: T } {
let result!: T;
const Child = defineComponent({
setup() {
result = composable();
return () => h("div");
},
});
mount(StateProvider as Component, {
props: { initialState } as any,
slots: {
default: () =>
h(ValidationProvider as Component, null, {
default: () => h(Child),
}),
},
});
return { result };
}
/** Mount only inside StateProvider (no ValidationProvider) */
function withStateOnly<T>(composable: () => T): { result: T } {
let result!: T;
const Child = defineComponent({
setup() {
result = composable();
return () => h("div");
},
});
mount(StateProvider as Component, {
props: { initialState: {} } as any,
slots: { default: () => h(Child) },
});
return { result };
}
describe("ValidationProvider — provide/inject", () => {
it("useValidation() throws outside a provider", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
expect(() => useValidation()).toThrow(
"useValidation must be used within a ValidationProvider",
);
warn.mockRestore();
});
});
describe("useOptionalValidation", () => {
it("returns null outside a ValidationProvider", () => {
const { result } = withStateOnly(() => useOptionalValidation());
expect(result).toBeNull();
});
it("returns context inside a ValidationProvider", () => {
const { result } = withProviders(() => useOptionalValidation());
expect(result).not.toBeNull();
expect(typeof result!.validate).toBe("function");
expect(typeof result!.validateAll).toBe("function");
});
});
describe("useFieldValidation — lifecycle", () => {
it("after validate(), isValid and errors reflect the result", () => {
const { result } = withProviders(
() =>
useFieldValidation("/name", {
checks: [{ type: "required", message: "Name is required" }],
}),
{ name: "" },
);
const validationResult = result.validate();
expect(validationResult.valid).toBe(false);
expect(validationResult.errors).toContain("Name is required");
});
it("after validate() with valid value, isValid is true", () => {
const { result } = withProviders(
() =>
useFieldValidation("/name", {
checks: [{ type: "required", message: "Name is required" }],
}),
{ name: "Alice" },
);
const validationResult = result.validate();
expect(validationResult.valid).toBe(true);
expect(validationResult.errors).toHaveLength(0);
});
it("touch() sets touched: true in the validation context", () => {
let validationCtx!: ReturnType<typeof useValidation>;
let fieldCtx!: ReturnType<typeof useFieldValidation>;
const Child = defineComponent({
setup() {
validationCtx = useValidation();
fieldCtx = useFieldValidation("/email");
return () => h("div");
},
});
mount(StateProvider as Component, {
props: { initialState: {} } as any,
slots: {
default: () =>
h(ValidationProvider as Component, null, {
default: () => h(Child),
}),
},
});
fieldCtx.touch();
expect(validationCtx.fieldStates["/email"]?.touched).toBe(true);
});
it("clear() resets the field state from the validation context", () => {
let validationCtx!: ReturnType<typeof useValidation>;
let fieldCtx!: ReturnType<typeof useFieldValidation>;
const Child = defineComponent({
setup() {
validationCtx = useValidation();
fieldCtx = useFieldValidation("/email", {
checks: [{ type: "required", message: "Required" }],
});
return () => h("div");
},
});
mount(StateProvider as Component, {
props: { initialState: { email: "" } } as any,
slots: {
default: () =>
h(ValidationProvider as Component, null, {
default: () => h(Child),
}),
},
});
fieldCtx.validate(); // populate fieldStates
fieldCtx.clear();
expect(validationCtx.fieldStates["/email"]).toBeUndefined();
});
it("validateAll() returns true when all registered fields pass", () => {
let validationCtx!: ReturnType<typeof useValidation>;
const Child = defineComponent({
setup() {
validationCtx = useValidation();
useFieldValidation("/name", {
checks: [{ type: "required", message: "Required" }],
});
return () => h("div");
},
});
mount(StateProvider as Component, {
props: { initialState: { name: "Alice" } } as any,
slots: {
default: () =>
h(ValidationProvider as Component, null, {
default: () => h(Child),
}),
},
});
expect(validationCtx.validateAll()).toBe(true);
});
it("validateAll() returns false when any field fails", () => {
let validationCtx!: ReturnType<typeof useValidation>;
const Child = defineComponent({
setup() {
validationCtx = useValidation();
useFieldValidation("/name", {
checks: [{ type: "required", message: "Required" }],
});
return () => h("div");
},
});
mount(StateProvider as Component, {
props: { initialState: { name: "" } } as any,
slots: {
default: () =>
h(ValidationProvider as Component, null, {
default: () => h(Child),
}),
},
});
expect(validationCtx.validateAll()).toBe(false);
});
});
-267
View File
@@ -1,267 +0,0 @@
import {
computed,
defineComponent,
inject,
onMounted,
onUnmounted,
provide,
ref,
type ComputedRef,
type PropType,
} from "vue";
import {
runValidation,
type ValidationConfig,
type ValidationFunction,
type ValidationResult,
} from "@json-render/core";
import { useStateStore } from "./state";
/**
* Field validation state
*/
export interface FieldValidationState {
touched: boolean;
validated: boolean;
result: ValidationResult | null;
}
/**
* Validation context value
*/
export interface ValidationContextValue {
customFunctions: Record<string, ValidationFunction>;
fieldStates: Record<string, FieldValidationState>;
validate: (path: string, config: ValidationConfig) => ValidationResult;
touch: (path: string) => void;
clear: (path: string) => void;
validateAll: () => boolean;
registerField: (path: string, config: ValidationConfig) => void;
}
const VALIDATION_KEY = Symbol("json-render:validation");
export interface ValidationProviderProps {
customFunctions?: Record<string, ValidationFunction>;
}
/**
* Compare two args records shallowly.
*/
function dynamicArgsEqual(
a: Record<string, unknown> | undefined,
b: Record<string, unknown> | undefined,
): boolean {
if (a === b) return true;
if (!a || !b) return false;
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if (keysA.length !== keysB.length) return false;
for (const key of keysA) {
const va = a[key];
const vb = b[key];
if (va === vb) continue;
if (
typeof va === "object" &&
va !== null &&
typeof vb === "object" &&
vb !== null
) {
const sa = (va as Record<string, unknown>).$state;
const sb = (vb as Record<string, unknown>).$state;
if (typeof sa === "string" && sa === sb) continue;
}
return false;
}
return true;
}
/**
* Structural equality check for ValidationConfig.
*/
function validationConfigEqual(
a: ValidationConfig,
b: ValidationConfig,
): boolean {
if (a === b) return true;
if (a.validateOn !== b.validateOn) return false;
const ac = a.checks ?? [];
const bc = b.checks ?? [];
if (ac.length !== bc.length) return false;
for (let i = 0; i < ac.length; i++) {
const ca = ac[i]!;
const cb = bc[i]!;
if (ca.type !== cb.type) return false;
if (ca.message !== cb.message) return false;
if (!dynamicArgsEqual(ca.args, cb.args)) return false;
}
return true;
}
/**
* Provider for validation
*/
export const ValidationProvider = defineComponent({
name: "ValidationProvider",
props: {
customFunctions: {
type: Object as PropType<Record<string, ValidationFunction>>,
default: () => ({}),
},
},
setup(props, { slots }) {
const { state } = useStateStore();
const fieldStates = ref<Record<string, FieldValidationState>>({});
const fieldConfigs = ref<Record<string, ValidationConfig>>({});
const registerField = (path: string, config: ValidationConfig) => {
const existing = fieldConfigs.value[path];
if (existing && validationConfigEqual(existing, config)) return;
fieldConfigs.value = { ...fieldConfigs.value, [path]: config };
};
const validate = (
path: string,
config: ValidationConfig,
): ValidationResult => {
const currentState = state.value;
const segments = path.split("/").filter(Boolean);
let value: unknown = currentState;
for (const seg of segments) {
if (value != null && typeof value === "object") {
value = (value as Record<string, unknown>)[seg];
} else {
value = undefined;
break;
}
}
const result = runValidation(config, {
value,
stateModel: currentState,
customFunctions: props.customFunctions,
});
fieldStates.value = {
...fieldStates.value,
[path]: {
touched: fieldStates.value[path]?.touched ?? true,
validated: true,
result,
},
};
return result;
};
const touch = (path: string) => {
fieldStates.value = {
...fieldStates.value,
[path]: {
...fieldStates.value[path],
touched: true,
validated: fieldStates.value[path]?.validated ?? false,
result: fieldStates.value[path]?.result ?? null,
},
};
};
const clear = (path: string) => {
const { [path]: _, ...rest } = fieldStates.value;
fieldStates.value = rest;
};
const validateAll = (): boolean => {
let allValid = true;
for (const [path, config] of Object.entries(fieldConfigs.value)) {
const result = validate(path, config);
if (!result.valid) {
allValid = false;
}
}
return allValid;
};
provide<ValidationContextValue>(VALIDATION_KEY, {
get customFunctions() {
return props.customFunctions;
},
get fieldStates() {
return fieldStates.value;
},
validate,
touch,
clear,
validateAll,
registerField,
});
return () => slots.default?.();
},
});
/**
* Composable to access validation context (or null if not inside a ValidationProvider).
* Useful for components that optionally participate in form validation.
*/
export function useOptionalValidation(): ValidationContextValue | null {
return (
inject<ValidationContextValue>(
VALIDATION_KEY,
null as unknown as ValidationContextValue,
) ?? null
);
}
/**
* Composable to access validation context
*/
export function useValidation(): ValidationContextValue {
const ctx = inject<ValidationContextValue>(VALIDATION_KEY);
if (!ctx) {
throw new Error("useValidation must be used within a ValidationProvider");
}
return ctx;
}
/**
* Composable to get validation state for a field
*/
export function useFieldValidation(
path: string,
config?: ValidationConfig,
): {
state: ComputedRef<FieldValidationState>;
validate: () => ValidationResult;
touch: () => void;
clear: () => void;
errors: ComputedRef<string[]>;
isValid: ComputedRef<boolean>;
} {
const ctx = useValidation();
onMounted(() => {
if (path && config) {
ctx.registerField(path, config);
}
});
onUnmounted(() => {
ctx.clear(path);
});
const defaultState: FieldValidationState = {
touched: false,
validated: false,
result: null,
};
return {
state: computed(() => ctx.fieldStates[path] ?? defaultState),
validate: () => ctx.validate(path, config ?? { checks: [] }),
touch: () => ctx.touch(path),
clear: () => ctx.clear(path),
errors: computed(() => ctx.fieldStates[path]?.result?.errors ?? []),
isValid: computed(() => ctx.fieldStates[path]?.result?.valid ?? true),
};
}
@@ -1,97 +0,0 @@
import { describe, it, expect, vi } from "vitest";
import { defineComponent, h, type Component, type ComputedRef } from "vue";
import { mount } from "@vue/test-utils";
import { StateProvider, useStateStore } from "./state";
import { VisibilityProvider, useVisibility, useIsVisible } from "./visibility";
/** Mount StateProvider → VisibilityProvider with a child that captures context. */
function withProviders<T>(
composable: () => T,
initialState: Record<string, unknown> = {},
): { result: T } {
let result!: T;
const Child = defineComponent({
setup() {
result = composable();
return () => h("div");
},
});
mount(StateProvider as Component, {
props: { initialState } as any,
slots: {
default: () =>
h(VisibilityProvider as Component, null, {
default: () => h(Child),
}),
},
});
return { result };
}
describe("VisibilityProvider — provide/inject", () => {
it("useVisibility() throws outside a VisibilityProvider", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
expect(() => useVisibility()).toThrow(
"useVisibility must be used within a VisibilityProvider",
);
warn.mockRestore();
});
it("useVisibility() returns a context with isVisible and ctx", () => {
const { result } = withProviders(() => useVisibility());
expect(typeof result.isVisible).toBe("function");
expect(result.ctx).toBeDefined();
expect(result.ctx.value).toBeDefined();
});
});
describe("useIsVisible — state integration", () => {
it("undefined condition returns true", () => {
const { result } = withProviders(() => useVisibility());
expect(result.isVisible(undefined)).toBe(true);
});
it("{ $state: '/flag' } returns true when state flag is truthy", () => {
const { result } = withProviders(() => useVisibility(), { flag: true });
expect(result.isVisible({ $state: "/flag" })).toBe(true);
});
it("{ $state: '/flag' } returns false when state flag is falsy", () => {
const { result } = withProviders(() => useVisibility(), { flag: false });
expect(result.isVisible({ $state: "/flag" })).toBe(false);
});
it("ctx is a ComputedRef whose .value reflects current state", () => {
const { result } = withProviders(() => useVisibility(), { count: 3 });
expect(result.ctx.value.stateModel).toEqual({ count: 3 });
});
});
describe("useIsVisible — reactivity", () => {
it("returns a ComputedRef<boolean> that updates when state changes", () => {
let storeCtx!: ReturnType<typeof useStateStore>;
let isVisible!: ComputedRef<boolean>;
const Child = defineComponent({
setup() {
storeCtx = useStateStore();
isVisible = useIsVisible({ $state: "/flag" });
return () => h("div");
},
});
mount(StateProvider as Component, {
props: { initialState: { flag: false } } as any,
slots: {
default: () =>
h(VisibilityProvider as Component, null, {
default: () => h(Child),
}),
},
});
expect(isVisible.value).toBe(false);
storeCtx.set("/flag", true);
expect(isVisible.value).toBe(true);
});
});
@@ -1,68 +0,0 @@
import {
computed,
defineComponent,
inject,
provide,
type ComputedRef,
} from "vue";
import {
evaluateVisibility,
type VisibilityCondition,
type VisibilityContext as CoreVisibilityContext,
} from "@json-render/core";
import { useStateStore } from "./state";
/**
* Visibility context value
*/
export interface VisibilityContextValue {
/** Evaluate a visibility condition */
isVisible: (condition: VisibilityCondition | undefined) => boolean;
/** The underlying visibility context (reactive) */
ctx: ComputedRef<CoreVisibilityContext>;
}
const VISIBILITY_KEY = Symbol("json-render:visibility");
/**
* Provider for visibility evaluation
*/
export const VisibilityProvider = defineComponent({
name: "VisibilityProvider",
setup(_, { slots }) {
const { state } = useStateStore();
const ctx = computed<CoreVisibilityContext>(() => ({
stateModel: state.value,
}));
const isVisible = (condition: VisibilityCondition | undefined): boolean =>
evaluateVisibility(condition, ctx.value);
provide<VisibilityContextValue>(VISIBILITY_KEY, { isVisible, ctx });
return () => slots.default?.();
},
});
/**
* Composable to access visibility evaluation
*/
export function useVisibility(): VisibilityContextValue {
const ctx = inject<VisibilityContextValue>(VISIBILITY_KEY);
if (!ctx) {
throw new Error("useVisibility must be used within a VisibilityProvider");
}
return ctx;
}
/**
* Composable to check if a condition is visible. Returns a reactive
* `ComputedRef<boolean>` so the result updates whenever state changes.
*/
export function useIsVisible(
condition: VisibilityCondition | undefined,
): ComputedRef<boolean> {
const { ctx } = useVisibility();
return computed(() => evaluateVisibility(condition, ctx.value));
}
-482
View File
@@ -1,482 +0,0 @@
import { describe, it, expect, vi } from "vitest";
import { defineComponent, h, nextTick, type Component } from "vue";
import { mount } from "@vue/test-utils";
import type { Spec } from "@json-render/core";
import { StateProvider, useStateStore } from "./composables/state";
import { VisibilityProvider } from "./composables/visibility";
import { ActionProvider } from "./composables/actions";
import { ValidationProvider } from "./composables/validation";
import { useFieldValidation } from "./composables/validation";
import { useBoundProp } from "./hooks";
import {
Renderer,
JSONUIProvider,
type ComponentRegistry,
type ComponentRenderProps,
} from "./renderer";
// =============================================================================
// Stub components
// =============================================================================
const Button = defineComponent({
name: "Button",
props: {
element: { type: Object, required: true },
emit: { type: Function, required: true },
on: { type: Function, required: true },
bindings: { type: Object, default: undefined },
loading: { type: Boolean, default: undefined },
},
setup(props) {
return () =>
h(
"button",
{ "data-testid": "btn", onClick: () => props.emit("press") },
String((props.element as any).props?.label ?? ""),
);
},
});
const Text = defineComponent({
name: "Text",
props: {
element: { type: Object, required: true },
emit: { type: Function, required: true },
on: { type: Function, required: true },
bindings: { type: Object, default: undefined },
loading: { type: Boolean, default: undefined },
},
setup(props) {
return () => {
const value = (props.element as any).props?.text;
return h(
"span",
{ "data-testid": "text" },
value == null
? ""
: typeof value === "string"
? value
: JSON.stringify(value),
);
};
},
});
const Stack = defineComponent({
name: "Stack",
props: {
element: { type: Object, required: true },
emit: { type: Function, required: true },
on: { type: Function, required: true },
bindings: { type: Object, default: undefined },
loading: { type: Boolean, default: undefined },
},
setup(_props, { slots }) {
return () => h("div", { "data-testid": "stack" }, slots.default?.());
},
});
const InputField = defineComponent({
name: "InputField",
props: {
element: { type: Object, required: true },
emit: { type: Function, required: true },
on: { type: Function, required: true },
bindings: { type: Object, default: undefined },
loading: { type: Boolean, default: undefined },
},
setup(props) {
const elProps = (props.element as any).props ?? {};
const bindingPath = (props.bindings as Record<string, string>)?.value;
const [boundValue, setBoundValue] = useBoundProp<string>(
elProps.value as string | undefined,
bindingPath,
);
const hasValidation = !!(bindingPath && elProps.checks?.length);
const config = hasValidation ? { checks: elProps.checks ?? [] } : undefined;
const { errors } = useFieldValidation(bindingPath ?? "", config);
return () =>
h("div", null, [
elProps.label ? h("label", null, elProps.label) : null,
h("input", {
"data-testid": "input",
value: boundValue ?? "",
onInput: (e: Event) =>
setBoundValue((e.target as HTMLInputElement).value),
}),
errors.value.length > 0
? h("span", { "data-testid": "input-error" }, errors.value[0])
: null,
]);
},
});
const Select = defineComponent({
name: "Select",
props: {
element: { type: Object, required: true },
emit: { type: Function, required: true },
on: { type: Function, required: true },
bindings: { type: Object, default: undefined },
loading: { type: Boolean, default: undefined },
},
setup(props) {
const elProps = (props.element as any).props ?? {};
const bindingPath = (props.bindings as Record<string, string>)?.value;
const [boundValue] = useBoundProp<string>(
elProps.value as string | undefined,
bindingPath,
);
return () => h("span", { "data-testid": "select-value" }, boundValue ?? "");
},
});
const registry: ComponentRegistry = {
Button: Button as unknown as Component,
Text: Text as unknown as Component,
Input: InputField as unknown as Component,
Select: Select as unknown as Component,
Stack: Stack as unknown as Component,
};
// State probe to read state from tests
const StateProbe = defineComponent({
name: "StateProbe",
setup() {
const { state } = useStateStore();
return () =>
h("pre", { "data-testid": "state-probe" }, JSON.stringify(state.value));
},
});
function getState(wrapper: ReturnType<typeof mount>): Record<string, unknown> {
return JSON.parse(wrapper.find("[data-testid='state-probe']").text());
}
// =============================================================================
// Mount helper
// =============================================================================
function mountWithProviders(
spec: Spec,
opts: {
functions?: Record<string, (args: Record<string, unknown>) => unknown>;
handlers?: Record<
string,
(params: Record<string, unknown>) => Promise<void> | void
>;
initialState?: Record<string, unknown>;
} = {},
) {
return mount(JSONUIProvider as Component, {
props: {
registry,
initialState: opts.initialState ?? spec.state ?? {},
functions: opts.functions,
handlers: opts.handlers,
} as any,
slots: {
default: () => [h(Renderer, { spec, registry }), h(StateProbe)],
},
});
}
// =============================================================================
// $computed expressions in rendering
// =============================================================================
describe("$computed expressions in rendering", () => {
it("resolves a $computed prop using provided functions", () => {
const spec: Spec = {
state: { first: "Jane", last: "Doe" },
root: "main",
elements: {
main: {
type: "Text",
props: {
text: {
$computed: "fullName",
args: {
first: { $state: "/first" },
last: { $state: "/last" },
},
},
},
children: [],
},
},
};
const functions = {
fullName: (args: Record<string, unknown>) => `${args.first} ${args.last}`,
};
const wrapper = mountWithProviders(spec, { functions });
expect(wrapper.find("[data-testid='text']").text()).toBe("Jane Doe");
});
it("renders gracefully when functions prop is omitted", () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const spec: Spec = {
state: {},
root: "main",
elements: {
main: {
type: "Text",
props: {
text: { $computed: "missing" },
},
children: [],
},
},
};
const wrapper = mountWithProviders(spec);
expect(wrapper.find("[data-testid='text']").text()).toBe("");
warnSpy.mockRestore();
});
});
// =============================================================================
// Watchers
// =============================================================================
describe("watchers (watch field)", () => {
it("does not fire on initial render, fires when watched state changes", async () => {
const loadCities = vi.fn();
const spec: Spec = {
state: { form: { country: "" }, citiesLoaded: false },
root: "wrapper",
elements: {
wrapper: {
type: "Stack",
props: {},
children: ["btn", "watcher"],
},
btn: {
type: "Button",
props: { label: "Set Country" },
on: {
press: [
{
action: "setState",
params: { statePath: "/form/country", value: "US" },
},
],
},
children: [],
},
watcher: {
type: "Select",
props: { value: { $state: "/form/country" } },
watch: {
"/form/country": {
action: "loadCities",
params: { country: { $state: "/form/country" } },
},
},
children: [],
},
},
};
const wrapper = mountWithProviders(spec, { handlers: { loadCities } });
expect(loadCities).not.toHaveBeenCalled();
await wrapper.find("[data-testid='btn']").trigger("click");
await nextTick();
await nextTick();
expect(loadCities).toHaveBeenCalledTimes(1);
expect(loadCities).toHaveBeenCalledWith(
expect.objectContaining({ country: "US" }),
);
});
it("fires multiple action bindings on the same watch path", async () => {
const action1 = vi.fn();
const action2 = vi.fn();
const spec: Spec = {
state: { value: "a" },
root: "wrapper",
elements: {
wrapper: {
type: "Stack",
props: {},
children: ["btn", "watcher"],
},
btn: {
type: "Button",
props: { label: "Change" },
on: {
press: [
{
action: "setState",
params: { statePath: "/value", value: "b" },
},
],
},
children: [],
},
watcher: {
type: "Text",
props: { text: { $state: "/value" } },
watch: {
"/value": [{ action: "action1" }, { action: "action2" }],
},
children: [],
},
},
};
const wrapper = mountWithProviders(spec, {
handlers: { action1, action2 },
});
await wrapper.find("[data-testid='btn']").trigger("click");
await nextTick();
await nextTick();
expect(action1).toHaveBeenCalledTimes(1);
expect(action2).toHaveBeenCalledTimes(1);
});
});
// =============================================================================
// validateForm action
// =============================================================================
describe("validateForm action", () => {
it("writes { valid: false, errors } when a required field is empty", async () => {
const spec: Spec = {
state: { form: { email: "" }, result: null },
root: "wrapper",
elements: {
wrapper: {
type: "Stack",
props: {},
children: ["emailInput", "submitBtn"],
},
emailInput: {
type: "Input",
props: {
label: "Email",
value: { $bindState: "/form/email" },
checks: [{ type: "required", message: "Email is required" }],
},
children: [],
},
submitBtn: {
type: "Button",
props: { label: "Submit" },
on: {
press: [
{
action: "validateForm",
params: { statePath: "/result" },
},
],
},
children: [],
},
},
};
const wrapper = mountWithProviders(spec);
await wrapper.find("[data-testid='btn']").trigger("click");
await nextTick();
const state = getState(wrapper);
expect(state.result).toEqual({
valid: false,
errors: { "/form/email": ["Email is required"] },
});
});
it("writes { valid: true, errors: {} } when all fields pass validation", async () => {
const spec: Spec = {
state: { form: { email: "test@example.com" }, result: null },
root: "wrapper",
elements: {
wrapper: {
type: "Stack",
props: {},
children: ["emailInput", "submitBtn"],
},
emailInput: {
type: "Input",
props: {
label: "Email",
value: { $bindState: "/form/email" },
checks: [{ type: "required", message: "Email is required" }],
},
children: [],
},
submitBtn: {
type: "Button",
props: { label: "Submit" },
on: {
press: [
{
action: "validateForm",
params: { statePath: "/result" },
},
],
},
children: [],
},
},
};
const wrapper = mountWithProviders(spec);
await wrapper.find("[data-testid='btn']").trigger("click");
await nextTick();
const state = getState(wrapper);
expect(state.result).toEqual({ valid: true, errors: {} });
});
it("defaults to /formValidation when no statePath is provided", async () => {
const spec: Spec = {
state: { form: { name: "filled" } },
root: "wrapper",
elements: {
wrapper: {
type: "Stack",
props: {},
children: ["nameInput", "submitBtn"],
},
nameInput: {
type: "Input",
props: {
label: "Name",
value: { $bindState: "/form/name" },
checks: [{ type: "required", message: "Required" }],
},
children: [],
},
submitBtn: {
type: "Button",
props: { label: "Submit" },
on: {
press: [{ action: "validateForm" }],
},
children: [],
},
},
};
const wrapper = mountWithProviders(spec);
await wrapper.find("[data-testid='btn']").trigger("click");
await nextTick();
const state = getState(wrapper);
expect(state.formValidation).toEqual({ valid: true, errors: {} });
});
});

Some files were not shown because too many files have changed in this diff Show More