mirror of
https://github.com/vercel-labs/json-render.git
synced 2026-10-02 12:00:58 +08:00
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc2a696a50 | ||
|
|
c2600d7390 | ||
|
|
3709614de0 | ||
|
|
3ad3818811 | ||
|
|
535f414eb4 | ||
|
|
e11d2d0e63 | ||
|
|
6c7164342a | ||
|
|
ea3326046f | ||
|
|
a4d033cf04 | ||
|
|
ea4b361b9f | ||
|
|
0f6798b193 | ||
|
|
9f58a3cade | ||
|
|
9d3dfc8917 |
@@ -53,6 +53,27 @@ jobs:
|
||||
run: pnpm turbo run build --filter='./packages/*'
|
||||
- run: pnpm test
|
||||
|
||||
docs:
|
||||
name: Docs (${{ matrix.environment }})
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
environment: [production, preview]
|
||||
env:
|
||||
VERCEL_ENV: ${{ matrix.environment }}
|
||||
DOCS_EXPECT_NOINDEX: ${{ matrix.environment == 'preview' && '1' || '0' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: .node-version
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm turbo run build --filter='web^...'
|
||||
- run: pnpm --filter web build
|
||||
- run: pnpm --filter web test:routes
|
||||
|
||||
typecheck:
|
||||
name: Type Check
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -66,6 +66,8 @@ Do **not** add `--port` flags -- portless handles port assignment automatically.
|
||||
## Workflow
|
||||
|
||||
- Run `pnpm type-check` after each turn to ensure type safety
|
||||
- Documentation lives in `apps/web/content/docs/` and uses Geistdocs frontmatter. Keep public `/docs` URLs, heading IDs, `lib/page-titles.ts`, `lib/docs-navigation.ts`, and the content `meta.json` files in sync.
|
||||
- For docs routing or infrastructure changes, run `pnpm turbo run build --filter='web^...'`, `pnpm --filter web build`, and `pnpm --filter web test:routes`. Existing-page source and Markdown parity are covered by `apps/web/tests/fixtures/docs-baseline.json`; update fixtures only when intentionally changing the documented content.
|
||||
- When making user-facing changes (new packages, API changes, new features, renamed exports, changed behavior), update the relevant documentation:
|
||||
- Package `README.md` files in `packages/*/README.md`
|
||||
- Root `README.md` (if packages table, install commands, or examples are affected)
|
||||
@@ -90,7 +92,7 @@ When asked to prepare a release (e.g. "prepare v0.17.0"):
|
||||
5. **Fill documentation gaps** — every public package should have:
|
||||
- A row in the root `README.md` packages table
|
||||
- A renderer section in the root `README.md` (if it's a renderer)
|
||||
- An API reference page at `apps/web/app/(main)/docs/api/<name>/page.mdx`
|
||||
- An API reference page at `apps/web/content/docs/api/<name>.mdx`
|
||||
- An entry in `apps/web/lib/page-titles.ts` and `apps/web/lib/docs-navigation.ts`
|
||||
- An entry in the docs-chat system prompt (`apps/web/app/api/docs-chat/route.ts`)
|
||||
- A skill at `skills/<name>/SKILL.md`
|
||||
|
||||
+50
-2
@@ -1,8 +1,57 @@
|
||||
# Changelog
|
||||
|
||||
## 0.21.0
|
||||
|
||||
<!-- release:start -->
|
||||
|
||||
### New Features
|
||||
|
||||
- **TanStack Start renderer:** Added `@json-render/tanstack-start` for JSON-defined applications with file-based routes, reusable layouts, SSR loaders, head metadata, prerender paths, client navigation, and route fallbacks (#334)
|
||||
- **Experimental Jev composition:** Added `experimental_composeSpec` and `experimental_createEvaluator` to compose validated specs from app-owned candidates, plus a Jev model option and iterative composition editing in the playground
|
||||
|
||||
### Improvements
|
||||
|
||||
- **Vue named slots:** Vue registries now support catalog-declared named slots alongside the default `children` slot (#323)
|
||||
- **React streaming stability:** Stabilized streamed React renders and added coverage for incomplete streamed props and nested prop identities (#325)
|
||||
- **Documentation and project status:** Expanded renderer, Jev, and package documentation and added Labs status badges to the project README
|
||||
|
||||
### Contributors
|
||||
|
||||
- @ctate
|
||||
- @Railly
|
||||
<!-- release:end -->
|
||||
|
||||
## 0.20.0
|
||||
|
||||
### New Features
|
||||
|
||||
- **Named slots for React:** Components can declare named slots such as `header` and `footer`, while `children` remains the default slot. Slots are preserved through validation, streaming, nested conversion, code export, playground views, and Devtools navigation (#320). Built from the original contribution by @wotnak in #105
|
||||
- **Nested repeats:** `repeat.statePath` now accepts item-relative paths such as `{ "$item": "employees" }`, enabling nested data rendering across React, React Native, React Email, React PDF, Image, Ink, Solid, Svelte, and Vue (#319). Built from the original contribution by @tmchow in #256
|
||||
- **Harness chat example:** Added a complete Next.js example using the AI SDK 7 harness adapter, agent delegation, sandbox transport, and json-render components (#302)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- **Chained action params:** Named `onSuccess` and `onError` actions now receive their configured `params` across core and all renderer bridges (#307)
|
||||
- **Consistent optional visibility:** Element `visible` fields now remain optional across Zod 4 versions, while prompts explicitly require `children` arrays for every element (#299)
|
||||
- **Spec validation and autofix:** Dangling child references are pruned, malformed visibility conditions are reported, and repeated items can be filtered safely (#300)
|
||||
|
||||
### Improvements
|
||||
|
||||
- **Release toolchain hardening:** The workspace now requires Node.js 24 and pnpm 11, enforces package engine checks, and applies a minimum package release age (#293)
|
||||
|
||||
### Breaking Changes
|
||||
|
||||
- Custom renderer bridges that implement the core `executeAction` callback must now accept an `ActionBinding` instead of a bare action name. This exposes chained action params to custom integrations at compile time (#307)
|
||||
|
||||
### Contributors
|
||||
|
||||
- @ctate
|
||||
- @Railly
|
||||
- @tmchow
|
||||
- @wotnak
|
||||
|
||||
## 0.19.0
|
||||
|
||||
<!-- release:start -->
|
||||
### New Features
|
||||
|
||||
- **Custom directives API** — `@json-render/core` now supports custom directives via `defineDirective`, letting you declare new JSON shapes (like `$format`, `$math`) that resolve to computed values at render time. Directives compose naturally — nest `$format` over `$math` over `$state` and they resolve inside-out. All four renderers (React, Vue, Svelte, Solid) have built-in directive resolution (#279)
|
||||
@@ -15,7 +64,6 @@
|
||||
### Contributors
|
||||
|
||||
- @ctate
|
||||
<!-- release:end -->
|
||||
|
||||
## 0.18.0
|
||||
|
||||
|
||||
@@ -4,6 +4,13 @@
|
||||
|
||||
Generate dynamic, personalized UIs from prompts without sacrificing reliability. Predefined components and actions for safe, predictable output.
|
||||
|
||||
<p>
|
||||
<a href="https://vercel.com/labs#labs-products"><img alt="Vercel Labs Product" src="https://img.shields.io/badge/LABS-PRODUCT-0a0a0a.svg?style=for-the-badge&logo=Vercel&labelColor=000000" height="28"></a>
|
||||
<a href="https://www.npmjs.com/package/@json-render/core"><img alt="npm version: @json-render/core" src="https://img.shields.io/npm/v/%40json-render%2Fcore.svg?style=for-the-badge&labelColor=000000" height="28"></a>
|
||||
<a href="https://github.com/vercel-labs/json-render/blob/main/LICENSE"><img alt="License: Apache-2.0" src="https://img.shields.io/github/license/vercel-labs/json-render.svg?style=for-the-badge&labelColor=000000" height="28"></a>
|
||||
<a href="https://www.npmjs.com/package/@json-render/core"><img alt="npm downloads per month: @json-render/core" src="https://img.shields.io/npm/dm/%40json-render%2Fcore.svg?style=for-the-badge&labelColor=000000&label=npm%20downloads" height="28"></a>
|
||||
</p>
|
||||
|
||||
```bash
|
||||
# for React
|
||||
npm install @json-render/core @json-render/react
|
||||
@@ -131,6 +138,7 @@ function Dashboard({ spec }) {
|
||||
| `@json-render/react-three-fiber` | React Three Fiber renderer for 3D scenes (20 built-in components, including GaussianSplat) |
|
||||
| `@json-render/react-native` | React Native renderer with standard mobile components |
|
||||
| `@json-render/next` | Next.js renderer — JSON becomes full apps with routes, layouts, SSR |
|
||||
| `@json-render/tanstack-start` | TanStack Start renderer — full apps with routes, layouts, SSR, and head metadata |
|
||||
| `@json-render/remotion` | Remotion video renderer, timeline schema |
|
||||
| `@json-render/react-pdf` | React PDF renderer for generating PDF documents from specs |
|
||||
| `@json-render/react-email` | React Email renderer for HTML/plain-text emails from specs |
|
||||
@@ -536,6 +544,54 @@ const app = createNextApp({ spec });
|
||||
// </NextAppProvider>
|
||||
```
|
||||
|
||||
### TanStack Start (Full Apps)
|
||||
|
||||
```tsx
|
||||
import { createFileRoute, notFound } from "@tanstack/react-router";
|
||||
import {
|
||||
PageRenderer,
|
||||
StartErrorBoundary,
|
||||
StartLoading,
|
||||
StartNotFound,
|
||||
type StartAppSpec,
|
||||
} from "@json-render/tanstack-start";
|
||||
import { createStartApp } from "@json-render/tanstack-start/server";
|
||||
|
||||
const spec: StartAppSpec = {
|
||||
metadata: { title: { default: "My App", template: "%s | My App" } },
|
||||
routes: {
|
||||
"/": {
|
||||
metadata: { title: "Home" },
|
||||
page: {
|
||||
root: "hero",
|
||||
elements: {
|
||||
hero: { type: "Card", props: { title: "Welcome" }, children: [] },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const { getPageData, getHead } = createStartApp({ spec });
|
||||
|
||||
export const Route = createFileRoute("/$")({
|
||||
loader: async ({ location }) => {
|
||||
const data = await getPageData({ pathname: location.pathname });
|
||||
if (!data) throw notFound();
|
||||
return data;
|
||||
},
|
||||
head: ({ match }) => getHead({ pathname: match.pathname }),
|
||||
component: () => <PageRenderer {...Route.useLoaderData()} />,
|
||||
pendingComponent: StartLoading,
|
||||
errorComponent: StartErrorBoundary,
|
||||
notFoundComponent: StartNotFound,
|
||||
});
|
||||
```
|
||||
|
||||
Wrap the root route's outlet with `<StartAppProvider spec={spec}>` so route
|
||||
fallback components can resolve the current route. Pass named `$computed`
|
||||
implementations through its `functions` prop.
|
||||
|
||||
### shadcn-svelte (Svelte)
|
||||
|
||||
```typescript
|
||||
@@ -752,6 +808,7 @@ pnpm dev
|
||||
- http://react-email-demo.json-render.localhost:1355 - React Email Example
|
||||
- http://remotion-demo.json-render.localhost:1355 - Remotion Video Example
|
||||
- Chat Example: run `pnpm dev` in `examples/chat`
|
||||
- [Experimental Jev composition](https://json-render.dev/docs/jev): use `experimental_composeSpec` and `experimental_createEvaluator` from core with your own catalog, or select **Jev (Experimental)** in `/playground`. Unreleased; source-build instructions are in the guide.
|
||||
- Svelte Example: run `pnpm dev` in `examples/svelte` or `examples/svelte-chat`
|
||||
- Vue Example: run `pnpm dev` in `examples/vue`
|
||||
- Vite Renderers (React + Vue + Svelte + Solid): run `pnpm dev` in `examples/vite-renderers`
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
# For local development, get your key from https://vercel.com/ai-gateway
|
||||
AI_GATEWAY_API_KEY=
|
||||
|
||||
# Dedicated AI Gateway key for the experimental Jev playground option
|
||||
# Required locally and on Vercel; no fallback to AI_GATEWAY_API_KEY
|
||||
JEV_AI_GATEWAY_API_KEY=
|
||||
|
||||
# AI Model Configuration
|
||||
# Override the default model used for UI generation
|
||||
# Default: anthropic/claude-haiku-4.5
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/.source/
|
||||
/out/
|
||||
|
||||
# production
|
||||
|
||||
@@ -16,6 +16,10 @@ bun dev
|
||||
|
||||
Open [http://json-render.localhost:1355](http://json-render.localhost:1355) with your browser to see the result.
|
||||
|
||||
## Jev composition experiment
|
||||
|
||||
The **default / jev** toggle in `/playground` includes an experimental Jev option; hover or focus its info icon segment for details. It is a reference consumer of core's reusable `experimental_composeSpec` and `experimental_createEvaluator` APIs. It lets Jev compose and edit UI trees from the playground's component catalog and allowed action bindings through Vercel AI Gateway. Set `JEV_AI_GATEWAY_API_KEY` on the server for Jev; the default model uses `AI_GATEWAY_API_KEY`. Follow-ups use the selected version as `initialSpec` and can add, replace, remove, or move elements; earlier versions remain unchanged. It uses the same prompt input, version history, spec/stream inspectors, and functional preview as the default model. The shared `/api/generate` endpoint streams spec patches and decision metadata. See [setup, architecture, and limits](lib/jev/README.md).
|
||||
|
||||
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
|
||||
|
||||
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load Inter, a custom Google Font.
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import { DocsMobileNav } from "@/components/docs-mobile-nav";
|
||||
import { DocsSidebar } from "@/components/docs-sidebar";
|
||||
import { CopyPageButton } from "@/components/copy-page-button";
|
||||
import { TableOfContents } from "@/components/table-of-contents";
|
||||
|
||||
export default function DocsLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<DocsMobileNav />
|
||||
<div className="max-w-7xl mx-auto px-6 py-8 lg:py-12 flex gap-12">
|
||||
{/* Sidebar */}
|
||||
<aside className="w-48 shrink-0 hidden lg:block sticky top-28 h-[calc(100vh-7rem)] overflow-y-auto">
|
||||
<DocsSidebar />
|
||||
</aside>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 min-w-0 max-w-2xl pb-20">
|
||||
<div className="flex justify-end mb-4">
|
||||
<CopyPageButton />
|
||||
</div>
|
||||
<article>{children}</article>
|
||||
</div>
|
||||
|
||||
{/* On this page */}
|
||||
<aside className="w-44 shrink-0 hidden xl:block sticky top-28 h-[calc(100vh-7rem)] overflow-y-auto">
|
||||
<TableOfContents />
|
||||
</aside>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { pageMetadata } from "@/lib/page-metadata";
|
||||
|
||||
export const metadata = pageMetadata("examples");
|
||||
|
||||
export default function ExamplesLayout({ children }: { children: ReactNode }) {
|
||||
return children;
|
||||
}
|
||||
@@ -1,17 +1,7 @@
|
||||
import { Header } from "@/components/header";
|
||||
import { getStarCount } from "@/lib/github";
|
||||
|
||||
export default async function MainLayout({
|
||||
export default function MainLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const stars = await getStarCount();
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col">
|
||||
<Header stars={stars} />
|
||||
<main className="flex-1">{children}</main>
|
||||
</div>
|
||||
);
|
||||
return <main className="min-h-[calc(100dvh-4rem)]">{children}</main>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { MobileDocsBar } from "@vercel/geistdocs/mobile-docs-bar";
|
||||
import { createDocsPage } from "@vercel/geistdocs/pages/docs";
|
||||
import { notFound } from "next/navigation";
|
||||
import { GenerationModesDiagram } from "@/components/generation-modes-diagram";
|
||||
import { PackageInstall } from "@/components/package-install";
|
||||
import { isSafePathSegments } from "@/lib/docs-source";
|
||||
import { config } from "@/lib/geistdocs/config";
|
||||
import { geistdocsSource } from "@/lib/geistdocs/source";
|
||||
import { pageMetadata } from "@/lib/page-metadata";
|
||||
|
||||
type PageProps = { params: Promise<{ lang: string; slug?: string[] }> };
|
||||
|
||||
async function validate(params: PageProps["params"]) {
|
||||
const resolved = await params;
|
||||
if (resolved.lang !== "en" || !isSafePathSegments(resolved.slug ?? []))
|
||||
notFound();
|
||||
try {
|
||||
if (!geistdocsSource.source.getPage(resolved.slug, resolved.lang))
|
||||
notFound();
|
||||
} catch (error) {
|
||||
if (error instanceof URIError) notFound();
|
||||
throw error;
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
const docsPage = createDocsPage({
|
||||
config,
|
||||
source: geistdocsSource,
|
||||
mdx: { GenerationModesDiagram, PackageInstall },
|
||||
renderTop: ({ data }) => <MobileDocsBar toc={data.toc} />,
|
||||
});
|
||||
|
||||
export default async function Page({ params }: PageProps) {
|
||||
return <docsPage.Page params={Promise.resolve(await validate(params))} />;
|
||||
}
|
||||
|
||||
export async function generateMetadata({ params }: PageProps) {
|
||||
const { slug = [] } = await validate(params);
|
||||
return pageMetadata(["docs", ...slug].join("/"));
|
||||
}
|
||||
|
||||
export const generateStaticParams = docsPage.generateStaticParams;
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { notFound } from "next/navigation";
|
||||
import { GeistdocsDocsLayout } from "@vercel/geistdocs/layout";
|
||||
import { config } from "@/lib/geistdocs/config";
|
||||
import { geistdocsSource } from "@/lib/geistdocs/source";
|
||||
|
||||
export default async function DocsLayout({
|
||||
children,
|
||||
params,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
params: Promise<{ lang: string }>;
|
||||
}) {
|
||||
const { lang } = await params;
|
||||
if (lang !== "en") notFound();
|
||||
return (
|
||||
<GeistdocsDocsLayout
|
||||
config={config}
|
||||
tree={geistdocsSource.source.getPageTree(lang)}
|
||||
containerProps={{ className: "mx-auto max-w-[1448px]" }}
|
||||
>
|
||||
{children}
|
||||
</GeistdocsDocsLayout>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +1,8 @@
|
||||
import { readFile } from "fs/promises";
|
||||
import { join } from "path";
|
||||
import { convertToModelMessages, stepCountIs, streamText } from "ai";
|
||||
import type { ModelMessage, UIMessage } from "ai";
|
||||
import { createBashTool } from "bash-tool";
|
||||
import { headers } from "next/headers";
|
||||
import { allDocsPages } from "@/lib/docs-navigation";
|
||||
import { mdxToCleanMarkdown } from "@/lib/mdx-to-markdown";
|
||||
import { loadAllDocsSources } from "@/lib/docs-source";
|
||||
import { minuteRateLimit, dailyRateLimit } from "@/lib/rate-limit";
|
||||
|
||||
export const maxDuration = 60;
|
||||
@@ -16,8 +13,10 @@ const SYSTEM_PROMPT = `You are a helpful documentation assistant for json-render
|
||||
|
||||
GitHub repository: https://github.com/vercel-labs/json-render
|
||||
Documentation: https://json-render.dev/docs
|
||||
npm packages: @json-render/core, @json-render/react, @json-render/next, @json-render/ink, @json-render/vue, @json-render/svelte, @json-render/solid, @json-render/shadcn, @json-render/shadcn-svelte, @json-render/react-three-fiber, @json-render/react-native, @json-render/react-email, @json-render/react-pdf, @json-render/image, @json-render/remotion, @json-render/directives, @json-render/codegen, @json-render/devtools, @json-render/devtools-react, @json-render/devtools-vue, @json-render/devtools-svelte, @json-render/devtools-solid, @json-render/mcp, @json-render/redux, @json-render/zustand, @json-render/jotai, @json-render/xstate, @json-render/yaml
|
||||
Skills: json-render ships AI agent skills that teach coding agents how to use each package. Install with "npx skills add vercel-labs/json-render --skill <name>". Available skills: core, react, next, ink, react-pdf, react-email, react-native, shadcn, shadcn-svelte, react-three-fiber, image, remotion, vue, svelte, solid, directives, codegen, devtools, mcp, redux, zustand, jotai, xstate, yaml. See /docs/skills for details.
|
||||
npm packages: @json-render/core, @json-render/react, @json-render/next, @json-render/tanstack-start, @json-render/ink, @json-render/vue, @json-render/svelte, @json-render/solid, @json-render/shadcn, @json-render/shadcn-svelte, @json-render/react-three-fiber, @json-render/react-native, @json-render/react-email, @json-render/react-pdf, @json-render/image, @json-render/remotion, @json-render/directives, @json-render/codegen, @json-render/devtools, @json-render/devtools-react, @json-render/devtools-vue, @json-render/devtools-svelte, @json-render/devtools-solid, @json-render/mcp, @json-render/redux, @json-render/zustand, @json-render/jotai, @json-render/xstate, @json-render/yaml
|
||||
Skills: json-render ships AI agent skills that teach coding agents how to use each package. Install with "npx skills add vercel-labs/json-render --skill <name>". Available skills: core, react, next, tanstack-start, ink, react-pdf, react-email, react-native, shadcn, shadcn-svelte, react-three-fiber, image, remotion, vue, svelte, solid, directives, codegen, devtools, devtools-react, devtools-vue, devtools-svelte, devtools-solid, mcp, redux, zustand, jotai, xstate, yaml. See /docs/skills for details.
|
||||
|
||||
Experimental Jev composition: core exports experimental_composeSpec and experimental_createEvaluator for app-owned catalogs/candidates through Vercel AI Gateway. See /docs/jev for availability, source-build setup, and limits; do not assume the currently published npm version includes it.
|
||||
|
||||
You have access to the full json-render documentation via the bash and readFile tools. The docs are available as markdown files in the /workspace/docs/ directory.
|
||||
|
||||
@@ -32,37 +31,13 @@ When answering questions:
|
||||
- Do NOT use emojis in your responses`;
|
||||
|
||||
async function loadDocsFiles(): Promise<Record<string, string>> {
|
||||
const files: Record<string, string> = {};
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
allDocsPages.map(async (page) => {
|
||||
const slug =
|
||||
page.href === "/docs" ? "" : page.href.replace(/^\/docs\/?/, "");
|
||||
const filePath = slug
|
||||
? join(
|
||||
process.cwd(),
|
||||
"app",
|
||||
"(main)",
|
||||
"docs",
|
||||
...slug.split("/"),
|
||||
"page.mdx",
|
||||
)
|
||||
: join(process.cwd(), "app", "(main)", "docs", "page.mdx");
|
||||
|
||||
const raw = await readFile(filePath, "utf-8");
|
||||
const md = mdxToCleanMarkdown(raw);
|
||||
const fileName = slug ? `/docs/${slug}.md` : "/docs/index.md";
|
||||
return { fileName, md };
|
||||
}),
|
||||
const pages = await loadAllDocsSources();
|
||||
return Object.fromEntries(
|
||||
pages.map((page) => [
|
||||
page.href === "/docs" ? "/docs/index.md" : `${page.href}.md`,
|
||||
page.markdown,
|
||||
]),
|
||||
);
|
||||
|
||||
for (const result of results) {
|
||||
if (result.status === "fulfilled") {
|
||||
files[result.value.fileName] = result.value.md;
|
||||
}
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
function addCacheControl(messages: ModelMessage[]): ModelMessage[] {
|
||||
|
||||
@@ -1,55 +1,25 @@
|
||||
import { readFile } from "fs/promises";
|
||||
import { join } from "path";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { mdxToCleanMarkdown } from "@/lib/mdx-to-markdown";
|
||||
import { loadDocsSource } from "@/lib/docs-source";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const docPath = searchParams.get("path");
|
||||
|
||||
if (!docPath) {
|
||||
const docPath = req.nextUrl.searchParams.get("path");
|
||||
if (!docPath)
|
||||
return NextResponse.json(
|
||||
{ error: "Missing ?path= parameter" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// Sanitize path: only allow docs paths, no traversal
|
||||
const normalized = docPath
|
||||
.replace(/^\//, "")
|
||||
.replace(/\.\./g, "")
|
||||
.replace(/[^a-zA-Z0-9/-]/g, "");
|
||||
|
||||
if (!normalized.startsWith("docs")) {
|
||||
const path = docPath.startsWith("/") ? docPath : `/${docPath}`;
|
||||
if (!/^\/docs(?:\/[a-zA-Z0-9_-]+)*\/?$/.test(path)) {
|
||||
return NextResponse.json({ error: "Invalid path" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Map URL path to file path
|
||||
// /docs -> /app/(main)/docs/page.mdx
|
||||
// /docs/installation -> /app/(main)/docs/installation/page.mdx
|
||||
const slug = normalized === "docs" ? "" : normalized.replace(/^docs\/?/, "");
|
||||
const filePath = slug
|
||||
? join(
|
||||
process.cwd(),
|
||||
"app",
|
||||
"(main)",
|
||||
"docs",
|
||||
...slug.split("/"),
|
||||
"page.mdx",
|
||||
)
|
||||
: join(process.cwd(), "app", "(main)", "docs", "page.mdx");
|
||||
|
||||
try {
|
||||
const raw = await readFile(filePath, "utf-8");
|
||||
const markdown = mdxToCleanMarkdown(raw);
|
||||
|
||||
return new NextResponse(markdown, {
|
||||
headers: {
|
||||
"Content-Type": "text/markdown; charset=utf-8",
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
const page = await loadDocsSource(path);
|
||||
if (!page)
|
||||
return NextResponse.json({ error: "Page not found" }, { status: 404 });
|
||||
}
|
||||
return new NextResponse(page.markdown, {
|
||||
headers: {
|
||||
"Content-Type": "text/markdown; charset=utf-8",
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
Link: `<${page.canonicalUrl}>; rel="canonical"`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { loadDocsSource, isSafePathSegments } from "@/lib/docs-source";
|
||||
import { applyDocsResponseHeaders } from "@/lib/docs-response-headers";
|
||||
|
||||
export async function GET(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ slug?: string[] }> },
|
||||
) {
|
||||
const { slug = [] } = await params;
|
||||
const path = `/docs${slug.length ? `/${slug.join("/")}` : ""}`;
|
||||
const page = isSafePathSegments(slug) ? await loadDocsSource(path) : null;
|
||||
const headers = new Headers({
|
||||
"Content-Type": "text/markdown; charset=utf-8",
|
||||
});
|
||||
applyDocsResponseHeaders(headers);
|
||||
if (page) headers.set("Link", `<${page.canonicalUrl}>; rel="canonical"`);
|
||||
return new Response(
|
||||
page?.markdown ??
|
||||
"# Page Not Found\n\nSee [the documentation index](/llms.txt).\n",
|
||||
{ status: page ? 200 : 404, headers },
|
||||
);
|
||||
}
|
||||
@@ -10,8 +10,9 @@ import { yamlPrompt } from "@json-render/yaml";
|
||||
import { stringify as yamlStringify } from "yaml";
|
||||
import { minuteRateLimit, dailyRateLimit } from "@/lib/rate-limit";
|
||||
import { playgroundCatalog } from "@/lib/render/catalog";
|
||||
import { createCompositionResponse } from "@/lib/jev/response";
|
||||
|
||||
export const maxDuration = 30;
|
||||
export const maxDuration = 60;
|
||||
|
||||
const PLAYGROUND_RULES = [
|
||||
"NEVER use viewport height classes (min-h-screen, h-screen) - the UI renders inside a fixed-size container.",
|
||||
@@ -92,7 +93,9 @@ export async function POST(req: Request) {
|
||||
);
|
||||
}
|
||||
|
||||
const { prompt, context, format, editModes } = await req.json();
|
||||
const { prompt, context, format, editModes, model } = await req.json();
|
||||
if (model === "typesafe-ai/jev")
|
||||
return createCompositionResponse(req, prompt, context?.previousSpec);
|
||||
const isYaml = format === "yaml";
|
||||
|
||||
const systemPrompt = getSystemPrompt(isYaml, editModes);
|
||||
@@ -107,6 +110,7 @@ export async function POST(req: Request) {
|
||||
|
||||
const result = streamText({
|
||||
model: process.env.AI_GATEWAY_MODEL || DEFAULT_MODEL,
|
||||
abortSignal: req.signal,
|
||||
system: [
|
||||
{
|
||||
role: "system",
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { createMcpRoute } from "@vercel/geistdocs/routes/mcp";
|
||||
import { config } from "@/lib/geistdocs/config";
|
||||
import { GET as search } from "../search/route";
|
||||
|
||||
const handler = createMcpRoute({ config, search });
|
||||
|
||||
export { handler as GET, handler as POST };
|
||||
@@ -1,7 +1,13 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getSearchIndex } from "@/lib/search-index";
|
||||
import { createSearchRoute } from "@vercel/geistdocs/routes/search";
|
||||
import { geistdocsSource } from "@/lib/geistdocs/source";
|
||||
import { config } from "@/lib/geistdocs/config";
|
||||
|
||||
const docsSearch = createSearchRoute({ config, source: geistdocsSource });
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
if (req.nextUrl.searchParams.has("query")) return docsSearch(req);
|
||||
const q = req.nextUrl.searchParams.get("q")?.trim().toLowerCase();
|
||||
|
||||
if (!q) {
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@import "@vercel/geistdocs/styles.css";
|
||||
|
||||
@theme {
|
||||
--breakpoint-sm: 40rem;
|
||||
--breakpoint-md: 48rem;
|
||||
--breakpoint-lg: 64rem;
|
||||
--breakpoint-xl: 80rem;
|
||||
--breakpoint-2xl: 96rem;
|
||||
}
|
||||
|
||||
@source "../node_modules/streamdown/dist/index.js";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
@custom-variant dark (&:is(.dark-theme *));
|
||||
|
||||
:root {
|
||||
--radius: 0.5rem;
|
||||
@@ -31,7 +38,7 @@
|
||||
--chat-bg: oklch(0.95 0 0);
|
||||
}
|
||||
|
||||
.dark {
|
||||
.dark-theme {
|
||||
--ds-gray-500: oklch(0.39 0 0);
|
||||
/* Monochrome dark theme */
|
||||
--background: oklch(0.0 0 0);
|
||||
@@ -189,9 +196,31 @@ article table {
|
||||
background-color: var(--shiki-light-bg) !important;
|
||||
}
|
||||
|
||||
.dark .shiki,
|
||||
.dark .shiki span {
|
||||
.dark-theme .shiki,
|
||||
.dark-theme .shiki span {
|
||||
color: var(--shiki-dark) !important;
|
||||
background-color: var(--shiki-dark-bg) !important;
|
||||
}
|
||||
|
||||
@container (width < 1200px) {
|
||||
#nd-page { @apply px-6 pt-6; }
|
||||
#nd-page > [data-mobile-docs-bar],
|
||||
#nd-page > div:has([data-mobile-toc-trigger]) { display: flex; }
|
||||
#nd-page [data-mobile-toc-trigger] { width: 44px; height: 44px; }
|
||||
#nd-page > div:has(> h1) { padding-inline-end: 3.5rem; }
|
||||
#nd-page > div:has(> h1) + div,
|
||||
#nd-page > div:has(> h1) + p + div { margin-top: 0; }
|
||||
}
|
||||
|
||||
@container (961px <= width < 1200px) {
|
||||
#nd-page > [data-mobile-docs-bar] { display: none; }
|
||||
}
|
||||
|
||||
header .pointer-events-none.opacity-0 {
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
#nd-page div:has(> [aria-live="polite"]) > div > .max-sm\:hidden {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
|
||||
+31
-6
@@ -3,11 +3,16 @@ import localFont from "next/font/local";
|
||||
import { GeistPixelSquare } from "geist/font/pixel";
|
||||
import "./globals.css";
|
||||
import { ThemeProvider } from "@/components/theme-provider";
|
||||
import { DocsProvider } from "@/components/geistdocs-provider";
|
||||
import { Navbar } from "@vercel/geistdocs/navbar";
|
||||
import { Footer } from "@vercel/geistdocs/footer";
|
||||
import { config } from "@/lib/geistdocs/config";
|
||||
import { DocsChat } from "@/components/docs-chat";
|
||||
import { Analytics } from "@vercel/analytics/next";
|
||||
import { SpeedInsights } from "@vercel/speed-insights/next";
|
||||
import { PAGE_TITLES } from "@/lib/page-titles";
|
||||
import { cookies } from "next/headers";
|
||||
import { isPreview, siteUrl, siteDescription } from "@/lib/site";
|
||||
|
||||
const geistSans = localFont({
|
||||
src: "./fonts/GeistVF.woff",
|
||||
@@ -19,7 +24,8 @@ const geistMono = localFont({
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
metadataBase: new URL("https://json-render.dev"),
|
||||
metadataBase: new URL(siteUrl),
|
||||
alternates: { canonical: "/" },
|
||||
title: {
|
||||
default: `json-render | ${PAGE_TITLES[""]}`,
|
||||
template: "%s | json-render",
|
||||
@@ -64,8 +70,8 @@ export const metadata: Metadata = {
|
||||
images: ["/og"],
|
||||
},
|
||||
robots: {
|
||||
index: true,
|
||||
follow: true,
|
||||
index: !isPreview,
|
||||
follow: !isPreview,
|
||||
},
|
||||
icons: {
|
||||
icon: "/favicon.ico",
|
||||
@@ -79,15 +85,30 @@ export default async function RootLayout({
|
||||
}>) {
|
||||
const cookieStore = await cookies();
|
||||
const chatOpen = cookieStore.get("docs-chat-open")?.value === "true";
|
||||
const chatWidth = Number(cookieStore.get("docs-chat-width")?.value) || 400;
|
||||
const chatWidth = Math.min(
|
||||
700,
|
||||
Math.max(300, Number(cookieStore.get("docs-chat-width")?.value) || 400),
|
||||
);
|
||||
|
||||
return (
|
||||
<html lang="en" suppressHydrationWarning>
|
||||
<head>
|
||||
<script
|
||||
type="application/ld+json"
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: JSON.stringify({
|
||||
"@context": "https://schema.org",
|
||||
"@type": "WebSite",
|
||||
name: "json-render",
|
||||
url: siteUrl,
|
||||
description: siteDescription,
|
||||
}),
|
||||
}}
|
||||
/>
|
||||
{chatOpen && (
|
||||
<style
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `@media(min-width:640px){body{padding-right:${chatWidth}px}}`,
|
||||
__html: `@media(min-width:640px){body{padding-right:min(${chatWidth}px, calc(100vw - 320px))}}`,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
@@ -96,7 +117,11 @@ export default async function RootLayout({
|
||||
className={`${geistSans.variable} ${geistMono.variable} ${GeistPixelSquare.variable}`}
|
||||
>
|
||||
<ThemeProvider>
|
||||
{children}
|
||||
<DocsProvider>
|
||||
<Navbar config={config} />
|
||||
{children}
|
||||
<Footer />
|
||||
</DocsProvider>
|
||||
<DocsChat defaultOpen={chatOpen} defaultWidth={chatWidth} />
|
||||
</ThemeProvider>
|
||||
<Analytics />
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { loadAllDocsSources } from "@/lib/docs-source";
|
||||
import { siteDescription, siteUrl } from "@/lib/site";
|
||||
|
||||
export async function GET() {
|
||||
const pages = await loadAllDocsSources();
|
||||
const body = `# json-render\n\n${siteDescription}\n\n## Documentation\n\n${pages.map((page) => `- [${page.title}](${siteUrl}${page.markdownUrl})`).join("\n")}\n`;
|
||||
return new Response(body, {
|
||||
headers: { "Content-Type": "text/plain; charset=utf-8" },
|
||||
});
|
||||
}
|
||||
@@ -3,5 +3,9 @@ export default function PlaygroundLayout({
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return <div className="h-dvh flex flex-col overflow-hidden">{children}</div>;
|
||||
return (
|
||||
<main className="h-[calc(100dvh-4rem)] flex flex-col overflow-hidden">
|
||||
{children}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { MetadataRoute } from "next";
|
||||
import { isPreview, siteUrl } from "@/lib/site";
|
||||
|
||||
export default function robots(): MetadataRoute.Robots {
|
||||
return {
|
||||
rules: isPreview
|
||||
? { userAgent: "*", disallow: "/" }
|
||||
: { userAgent: "*", allow: "/" },
|
||||
sitemap: `${siteUrl}/sitemap.xml`,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { docsPages } from "@/lib/docs-source";
|
||||
|
||||
export function GET() {
|
||||
return new Response(
|
||||
`# json-render documentation\n\n${docsPages.map((page) => `- [${page.title}](${page.href})`).join("\n")}\n`,
|
||||
{
|
||||
headers: { "Content-Type": "text/markdown; charset=utf-8" },
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { MetadataRoute } from "next";
|
||||
import { PAGE_TITLES } from "@/lib/page-titles";
|
||||
import { siteUrl } from "@/lib/site";
|
||||
|
||||
export default function sitemap(): MetadataRoute.Sitemap {
|
||||
return Object.keys(PAGE_TITLES).map((slug) => ({
|
||||
url: `${siteUrl}/${slug}`,
|
||||
}));
|
||||
}
|
||||
@@ -195,6 +195,15 @@ function specToNested(spec: Spec): Record<string, unknown> {
|
||||
node.children = el.children.map(resolve);
|
||||
}
|
||||
|
||||
if (el.slots && Object.keys(el.slots).length > 0) {
|
||||
node.slots = Object.fromEntries(
|
||||
Object.entries(el.slots).map(([slotName, childKeys]) => [
|
||||
slotName,
|
||||
childKeys.map(resolve),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
@@ -393,21 +402,45 @@ export function Demo({
|
||||
|
||||
const propsStr = serializeProps(propsObj);
|
||||
const hasChildren = element.children && element.children.length > 0;
|
||||
const hasSlots = element.slots && Object.keys(element.slots).length > 0;
|
||||
|
||||
if (!hasChildren) {
|
||||
if (!hasChildren && !hasSlots) {
|
||||
return propsStr
|
||||
? `${spaces}<${componentName} ${propsStr} />`
|
||||
: `${spaces}<${componentName} />`;
|
||||
}
|
||||
|
||||
const lines: string[] = [];
|
||||
lines.push(
|
||||
propsStr
|
||||
? `${spaces}<${componentName} ${propsStr}>`
|
||||
: `${spaces}<${componentName}>`,
|
||||
);
|
||||
if (hasSlots) {
|
||||
lines.push(`${spaces}<${componentName}`);
|
||||
if (propsStr) {
|
||||
lines.push(`${spaces} ${propsStr}`);
|
||||
}
|
||||
for (const [slotName, childKeys] of Object.entries(element.slots!)) {
|
||||
const slotChildren = childKeys
|
||||
.map((childKey) => generateJSX(childKey, indent + 2))
|
||||
.filter(Boolean);
|
||||
if (slotChildren.length === 0) continue;
|
||||
lines.push(`${spaces} ${slotName}={`);
|
||||
if (slotChildren.length > 1) {
|
||||
lines.push(`${spaces} <>`);
|
||||
}
|
||||
lines.push(...slotChildren);
|
||||
if (slotChildren.length > 1) {
|
||||
lines.push(`${spaces} </>`);
|
||||
}
|
||||
lines.push(`${spaces} }`);
|
||||
}
|
||||
lines.push(`${spaces}>`);
|
||||
} else {
|
||||
lines.push(
|
||||
propsStr
|
||||
? `${spaces}<${componentName} ${propsStr}>`
|
||||
: `${spaces}<${componentName}>`,
|
||||
);
|
||||
}
|
||||
|
||||
for (const childKey of element.children!) {
|
||||
for (const childKey of element.children ?? []) {
|
||||
lines.push(generateJSX(childKey, indent + 1));
|
||||
}
|
||||
|
||||
|
||||
@@ -141,6 +141,7 @@ export function DocsChat({
|
||||
);
|
||||
const messagesScrollRef = useRef<HTMLDivElement>(null);
|
||||
const inputRef = useRef<HTMLTextAreaElement>(null);
|
||||
const launcherRef = useRef<HTMLButtonElement>(null);
|
||||
const restoredRef = useRef(false);
|
||||
const isDraggingRef = useRef(false);
|
||||
|
||||
@@ -173,13 +174,51 @@ export function DocsChat({
|
||||
}
|
||||
}, [open, hasMounted]);
|
||||
|
||||
useEffect(() => {
|
||||
const launcher = launcherRef.current;
|
||||
if (!hasMounted || open || !launcher) return;
|
||||
const footer = document.querySelector("footer");
|
||||
let frame = 0;
|
||||
const update = () => {
|
||||
frame = 0;
|
||||
const rect = document
|
||||
.querySelector("footer fieldset")
|
||||
?.getBoundingClientRect();
|
||||
const overlap =
|
||||
rect && rect.width > 0 && rect.bottom > 0
|
||||
? Math.max(0, innerHeight - rect.top)
|
||||
: 0;
|
||||
launcher.style.setProperty("--chat-launcher-bottom", `${24 + overlap}px`);
|
||||
};
|
||||
const schedule = () => {
|
||||
if (!frame) frame = requestAnimationFrame(update);
|
||||
};
|
||||
const resize = new ResizeObserver(schedule);
|
||||
resize.observe(document.body);
|
||||
const mutation = new MutationObserver(schedule);
|
||||
if (footer) {
|
||||
resize.observe(footer);
|
||||
mutation.observe(footer, { childList: true, subtree: true });
|
||||
}
|
||||
window.addEventListener("scroll", schedule, { passive: true });
|
||||
window.addEventListener("resize", schedule);
|
||||
update();
|
||||
return () => {
|
||||
cancelAnimationFrame(frame);
|
||||
resize.disconnect();
|
||||
mutation.disconnect();
|
||||
window.removeEventListener("scroll", schedule);
|
||||
window.removeEventListener("resize", schedule);
|
||||
};
|
||||
}, [hasMounted, open]);
|
||||
|
||||
// Push page content on desktop when pane is open.
|
||||
// Use padding on body so the page scrollbar stays at the viewport edge (behind the sidebar)
|
||||
// instead of appearing right next to the sidebar's scrollbar.
|
||||
useEffect(() => {
|
||||
const body = document.body;
|
||||
if (isDesktop && open) {
|
||||
body.style.paddingRight = `${desktopWidth}px`;
|
||||
body.style.paddingRight = `min(${desktopWidth}px, calc(100vw - 320px))`;
|
||||
if (!isDraggingRef.current) {
|
||||
body.style.transition = "padding-right 150ms ease";
|
||||
}
|
||||
@@ -273,7 +312,13 @@ export function DocsChat({
|
||||
return !prev;
|
||||
});
|
||||
}
|
||||
if (e.key === "Escape" && open && isDesktop) {
|
||||
if (
|
||||
e.key === "Escape" &&
|
||||
open &&
|
||||
(isDesktop ||
|
||||
(e.target instanceof Element &&
|
||||
e.target.closest("#json-render-chat-mobile")))
|
||||
) {
|
||||
setOpen(false);
|
||||
}
|
||||
};
|
||||
@@ -459,6 +504,7 @@ export function DocsChat({
|
||||
rows={1}
|
||||
enterKeyHint="send"
|
||||
placeholder="Ask a question..."
|
||||
aria-label="Ask a question"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
@@ -496,12 +542,19 @@ export function DocsChat({
|
||||
{/* Ask AI trigger button */}
|
||||
{!open && (
|
||||
<button
|
||||
ref={launcherRef}
|
||||
data-docs-chat-launcher
|
||||
onClick={() => setOpen(true)}
|
||||
className="fixed z-50 bottom-4 left-1/2 -translate-x-1/2 sm:left-auto sm:translate-x-0 sm:right-4 flex items-center gap-2 px-4 py-2 rounded-lg border border-primary bg-primary text-primary-foreground shadow-lg hover:bg-primary/90 transition-colors text-sm font-medium"
|
||||
className="fixed z-30 bottom-[calc(1rem+env(safe-area-inset-bottom))] left-1/2 -translate-x-1/2 min-[640px]:left-auto min-[640px]:translate-x-0 min-[640px]:right-6 min-[640px]:bottom-[var(--chat-launcher-bottom,24px)] flex h-10 items-center gap-2 px-4 py-2 rounded-lg border border-primary bg-primary text-primary-foreground shadow-lg hover:bg-primary/90 transition-colors text-sm font-medium"
|
||||
aria-label="Ask AI"
|
||||
aria-expanded={open}
|
||||
aria-controls={
|
||||
isDesktop ? "json-render-chat-desktop" : "json-render-chat-mobile"
|
||||
}
|
||||
aria-keyshortcuts="Meta+I Control+I"
|
||||
>
|
||||
Ask AI
|
||||
<kbd className="hidden sm:inline-flex items-center gap-0.5 text-xs opacity-60 font-mono">
|
||||
<kbd className="hidden min-[640px]:inline-flex items-center gap-0.5 text-xs opacity-60 font-mono">
|
||||
<span>⌘</span>I
|
||||
</kbd>
|
||||
</button>
|
||||
@@ -509,9 +562,11 @@ export function DocsChat({
|
||||
|
||||
{/* Desktop: resizable side pane — always rendered, hidden on mobile via CSS */}
|
||||
<aside
|
||||
id="json-render-chat-desktop"
|
||||
inert={!open || !isDesktop}
|
||||
className={`hidden sm:flex fixed top-0 right-0 bottom-0 z-40 border-l bg-background transition-transform duration-150 ease-in-out ${open ? "translate-x-0" : "translate-x-full"}`}
|
||||
style={{ width: desktopWidth }}
|
||||
aria-hidden={!open}
|
||||
style={{ width: `min(${desktopWidth}px, calc(100vw - 320px))` }}
|
||||
aria-hidden={!open || !isDesktop}
|
||||
>
|
||||
{/* Resize handle */}
|
||||
<div
|
||||
@@ -525,6 +580,8 @@ export function DocsChat({
|
||||
{hasMounted && !isDesktop && (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetContent
|
||||
id="json-render-chat-mobile"
|
||||
aria-describedby={undefined}
|
||||
side="right"
|
||||
overlayClassName="!bg-background"
|
||||
className="!inset-0 !w-full !h-full !max-w-none p-0 flex flex-col"
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { GeistdocsProvider } from "@vercel/geistdocs/layout";
|
||||
import type { ReactNode } from "react";
|
||||
import { config } from "@/lib/geistdocs/config";
|
||||
|
||||
export function DocsProvider({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<GeistdocsProvider config={config} lang="en">
|
||||
{children}
|
||||
</GeistdocsProvider>
|
||||
);
|
||||
}
|
||||
@@ -11,6 +11,8 @@ import {
|
||||
usePlaygroundStream,
|
||||
type StreamFormat,
|
||||
type TokenUsage,
|
||||
type PlaygroundModel,
|
||||
type CompositionSummary,
|
||||
} from "@/lib/use-playground-stream";
|
||||
import {
|
||||
ResizablePanelGroup,
|
||||
@@ -20,7 +22,13 @@ import {
|
||||
import { CodeBlock } from "./code-block";
|
||||
import { CopyButton } from "./copy-button";
|
||||
import { Toaster } from "./ui/sonner";
|
||||
import { Header } from "./header";
|
||||
import { InfoIcon } from "lucide-react";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "./ui/tooltip";
|
||||
import { Sheet, SheetContent, SheetTitle } from "./ui/sheet";
|
||||
import { JsonEditor } from "@visual-json/react";
|
||||
import type { JsonValue } from "@visual-json/react";
|
||||
@@ -43,7 +51,10 @@ interface Version {
|
||||
id: string;
|
||||
prompt: string;
|
||||
tree: Spec | null;
|
||||
status: "generating" | "complete" | "error";
|
||||
status: "generating" | "complete" | "error" | "partial" | "unavailable";
|
||||
model: PlaygroundModel;
|
||||
composition: CompositionSummary | null;
|
||||
message?: string;
|
||||
usage: TokenUsage | null;
|
||||
rawLines: string[];
|
||||
format: StreamFormat;
|
||||
@@ -54,7 +65,97 @@ function formatTokens(n: number): string {
|
||||
return String(n);
|
||||
}
|
||||
|
||||
function ModelToggle({
|
||||
model,
|
||||
onChange,
|
||||
disabled,
|
||||
}: {
|
||||
model: PlaygroundModel;
|
||||
onChange: (model: PlaygroundModel) => void;
|
||||
disabled: boolean;
|
||||
}) {
|
||||
return (
|
||||
<TooltipProvider delayDuration={200}>
|
||||
<div
|
||||
role="group"
|
||||
aria-label="Model"
|
||||
className="flex shrink-0 items-center rounded border border-border text-[10px] font-mono overflow-hidden"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Default model"
|
||||
aria-pressed={model === "default"}
|
||||
disabled={disabled}
|
||||
onClick={() => onChange("default")}
|
||||
className={`px-1.5 py-0.5 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset disabled:opacity-50 ${
|
||||
model === "default"
|
||||
? "bg-muted text-foreground"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
default
|
||||
</button>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Jev (experimental)"
|
||||
aria-pressed={model === "typesafe-ai/jev"}
|
||||
disabled={disabled}
|
||||
onClick={() => onChange("typesafe-ai/jev")}
|
||||
className={`flex items-center gap-1 px-1.5 py-0.5 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset disabled:opacity-50 ${
|
||||
model === "typesafe-ai/jev"
|
||||
? "bg-muted text-foreground"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
jev
|
||||
<InfoIcon className="size-2.5" aria-hidden="true" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="top"
|
||||
align="start"
|
||||
sideOffset={6}
|
||||
className="max-w-64 space-y-1"
|
||||
>
|
||||
<p className="font-medium">Experimental</p>
|
||||
<p>
|
||||
Jev composes and edits UI from prepared fields, data, and actions.
|
||||
Results may be incomplete.
|
||||
</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function VersionDetails({ version }: { version: Version }) {
|
||||
return (
|
||||
<>
|
||||
<div className="mt-1 ml-6 text-[10px] font-mono text-muted-foreground/60">
|
||||
{version.model === "typesafe-ai/jev"
|
||||
? "Jev · Experimental"
|
||||
: "Default model"}
|
||||
{version.composition &&
|
||||
` · ${(version.composition.elapsedMs / 1000).toFixed(2)} s · ${version.composition.calls} calls`}
|
||||
{version.status === "partial" && " · partial"}
|
||||
{version.status === "unavailable" && " · unavailable"}
|
||||
</div>
|
||||
{version.message && (
|
||||
<p className="mt-1 ml-6 text-xs text-muted-foreground">
|
||||
{version.message}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function PlaygroundControls({
|
||||
model,
|
||||
setModel,
|
||||
disabled,
|
||||
format,
|
||||
setFormat,
|
||||
editModes,
|
||||
@@ -62,6 +163,9 @@ function PlaygroundControls({
|
||||
showClear,
|
||||
onClear,
|
||||
}: {
|
||||
model: PlaygroundModel;
|
||||
setModel: (model: PlaygroundModel) => void;
|
||||
disabled: boolean;
|
||||
format: StreamFormat;
|
||||
setFormat: (f: StreamFormat) => void;
|
||||
editModes: EditMode[];
|
||||
@@ -70,46 +174,53 @@ function PlaygroundControls({
|
||||
onClear: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex items-center rounded border border-border text-[10px] font-mono overflow-hidden">
|
||||
{(["jsonl", "yaml"] as const).map((f) => (
|
||||
<button
|
||||
key={f}
|
||||
onClick={() => setFormat(f)}
|
||||
className={`px-1.5 py-0.5 transition-colors ${
|
||||
format === f
|
||||
? "bg-muted text-foreground"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
{f}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-center rounded border border-border text-[10px] font-mono overflow-hidden">
|
||||
{(["patch", "merge", "diff"] as const).map((m) => (
|
||||
<button
|
||||
key={m}
|
||||
onClick={() => {
|
||||
setEditModes((prev) =>
|
||||
prev.includes(m)
|
||||
? prev.length > 1
|
||||
? prev.filter((x) => x !== m)
|
||||
: prev
|
||||
: [...prev, m],
|
||||
);
|
||||
}}
|
||||
className={`px-1.5 py-0.5 transition-colors ${
|
||||
editModes.includes(m)
|
||||
? "bg-muted text-foreground"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
{m}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{showClear && (
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-2">
|
||||
<ModelToggle model={model} onChange={setModel} disabled={disabled} />
|
||||
{model !== "typesafe-ai/jev" && (
|
||||
<>
|
||||
<div className="flex shrink-0 items-center rounded border border-border text-[10px] font-mono overflow-hidden">
|
||||
{(["jsonl", "yaml"] as const).map((f) => (
|
||||
<button
|
||||
key={f}
|
||||
disabled={disabled}
|
||||
onClick={() => setFormat(f)}
|
||||
className={`px-1.5 py-0.5 transition-colors ${
|
||||
format === f
|
||||
? "bg-muted text-foreground"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
{f}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center rounded border border-border text-[10px] font-mono overflow-hidden">
|
||||
{(["patch", "merge", "diff"] as const).map((m) => (
|
||||
<button
|
||||
key={m}
|
||||
disabled={disabled}
|
||||
onClick={() => {
|
||||
setEditModes((prev) =>
|
||||
prev.includes(m)
|
||||
? prev.length > 1
|
||||
? prev.filter((x) => x !== m)
|
||||
: prev
|
||||
: [...prev, m],
|
||||
);
|
||||
}}
|
||||
className={`px-1.5 py-0.5 transition-colors ${
|
||||
editModes.includes(m)
|
||||
? "bg-muted text-foreground"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
{m}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{showClear && !disabled && (
|
||||
<button
|
||||
onClick={onClear}
|
||||
className="text-xs text-muted-foreground hover:text-foreground transition-colors"
|
||||
@@ -152,6 +263,15 @@ function specToNested(spec: Spec): Record<string, unknown> {
|
||||
node.children = el.children.map(resolve);
|
||||
}
|
||||
|
||||
if (el.slots && Object.keys(el.slots).length > 0) {
|
||||
node.slots = Object.fromEntries(
|
||||
Object.entries(el.slots).map(([slotName, childKeys]) => [
|
||||
slotName,
|
||||
childKeys.map(resolve),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
@@ -173,6 +293,33 @@ const EXAMPLE_PROMPTS = [
|
||||
"Make a contact form",
|
||||
];
|
||||
|
||||
const JEV_EXAMPLE_PROMPTS = [
|
||||
{
|
||||
label: "Create a login form",
|
||||
prompt:
|
||||
'Create a login card titled "Sign in" with email, password, remember me, and a sign in button.',
|
||||
},
|
||||
{
|
||||
label: "Create account settings",
|
||||
prompt:
|
||||
'Create an account settings card titled "Preferences" with full name, email, an email notifications switch, save and reset buttons side by side, and visible save status.',
|
||||
},
|
||||
{
|
||||
label: "Design a user profile card",
|
||||
prompt: "Design a user profile card",
|
||||
},
|
||||
{
|
||||
label: "Build a sales dashboard",
|
||||
prompt:
|
||||
'Build a sales dashboard: heading "Sales overview", revenue, orders and new customers metrics in a three-column grid, then a weekly revenue chart and an order-status table.',
|
||||
},
|
||||
{
|
||||
label: "Make a contact form",
|
||||
prompt:
|
||||
'Create a contact card titled "Contact us" with full name, email, topic, a message box, and a send message button.',
|
||||
},
|
||||
];
|
||||
|
||||
export function Playground() {
|
||||
const [versions, setVersions] = useState<Version[]>([]);
|
||||
const [selectedVersionId, setSelectedVersionId] = useState<string | null>(
|
||||
@@ -186,12 +333,23 @@ export function Playground() {
|
||||
const [renderView, setRenderView] = useState<RenderView>("preview");
|
||||
const [mobileView, setMobileView] = useState<MobileView>("preview");
|
||||
const [versionsSheetOpen, setVersionsSheetOpen] = useState(false);
|
||||
const [format, setFormat] = useState<StreamFormat>("jsonl");
|
||||
const [preferredFormat, setFormat] = useState<StreamFormat>("jsonl");
|
||||
const [model, setModel] = useState<PlaygroundModel>("default");
|
||||
const format = model === "typesafe-ai/jev" ? "jsonl" : preferredFormat;
|
||||
const examplePrompts =
|
||||
model === "typesafe-ai/jev"
|
||||
? JEV_EXAMPLE_PROMPTS
|
||||
: EXAMPLE_PROMPTS.map((prompt) => ({ label: prompt, prompt }));
|
||||
const [editModes, setEditModes] = useState<EditMode[]>(["patch"]);
|
||||
const inputRef = useRef<HTMLTextAreaElement>(null);
|
||||
const mobileInputRef = useRef<HTMLTextAreaElement>(null);
|
||||
const versionsEndRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const input = inputRef.current;
|
||||
if (input?.getClientRects().length) input.focus({ preventScroll: true });
|
||||
}, []);
|
||||
|
||||
// Track the currently generating version ID
|
||||
const generatingVersionIdRef = useRef<string | null>(null);
|
||||
|
||||
@@ -202,25 +360,20 @@ export function Playground() {
|
||||
spec: apiSpec,
|
||||
isStreaming,
|
||||
usage: streamUsage,
|
||||
composition: streamComposition,
|
||||
error: streamError,
|
||||
rawLines: streamRawLines,
|
||||
send,
|
||||
clear,
|
||||
stop,
|
||||
} = usePlaygroundStream({
|
||||
api: "/api/generate",
|
||||
model,
|
||||
format,
|
||||
editModes,
|
||||
onError: (err: Error) => {
|
||||
console.error("Generation error:", err);
|
||||
toast.error(err.message || "Generation failed. Please try again.");
|
||||
if (generatingVersionIdRef.current) {
|
||||
const erroredVersionId = generatingVersionIdRef.current;
|
||||
setVersions((prev) =>
|
||||
prev.map((v) =>
|
||||
v.id === erroredVersionId ? { ...v, status: "error" as const } : v,
|
||||
),
|
||||
);
|
||||
generatingVersionIdRef.current = null;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -247,27 +400,17 @@ export function Playground() {
|
||||
: (selectedVersion?.rawLines ?? []);
|
||||
|
||||
// Keep the ref updated with the current tree for use in handleSubmit
|
||||
if (
|
||||
currentTree &&
|
||||
currentTree.root &&
|
||||
Object.keys(currentTree.elements).length > 0
|
||||
) {
|
||||
currentTreeRef.current = currentTree;
|
||||
}
|
||||
currentTreeRef.current = currentTree?.root ? currentTree : null;
|
||||
|
||||
// Scroll to bottom when versions change
|
||||
useEffect(() => {
|
||||
versionsEndRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||
const container = versionsEndRef.current?.parentElement;
|
||||
container?.scrollTo({ top: container.scrollHeight, behavior: "smooth" });
|
||||
}, [versions]);
|
||||
|
||||
// Update version when streaming completes
|
||||
useEffect(() => {
|
||||
if (
|
||||
!isStreaming &&
|
||||
apiSpec &&
|
||||
apiSpec.root &&
|
||||
generatingVersionIdRef.current
|
||||
) {
|
||||
if (!isStreaming && generatingVersionIdRef.current) {
|
||||
const completedVersionId = generatingVersionIdRef.current;
|
||||
setVersions((prev) =>
|
||||
prev.map((v) =>
|
||||
@@ -275,7 +418,23 @@ export function Playground() {
|
||||
? {
|
||||
...v,
|
||||
tree: apiSpec,
|
||||
status: "complete" as const,
|
||||
status: streamError
|
||||
? apiSpec?.root
|
||||
? ("partial" as const)
|
||||
: ("error" as const)
|
||||
: streamComposition?.stopReason === "limit"
|
||||
? ("partial" as const)
|
||||
: streamComposition?.stopReason === "unavailable"
|
||||
? ("unavailable" as const)
|
||||
: ("complete" as const),
|
||||
message:
|
||||
streamError?.message ??
|
||||
(streamComposition?.stopReason === "limit"
|
||||
? "Composition limit reached. The preview is partial."
|
||||
: streamComposition?.stopReason === "unavailable"
|
||||
? "This request needs content or capabilities outside the prepared options."
|
||||
: undefined),
|
||||
composition: streamComposition,
|
||||
usage: streamUsage,
|
||||
rawLines: streamRawLines,
|
||||
}
|
||||
@@ -284,10 +443,18 @@ export function Playground() {
|
||||
);
|
||||
generatingVersionIdRef.current = null;
|
||||
}
|
||||
}, [isStreaming, apiSpec, streamUsage, streamRawLines]);
|
||||
}, [
|
||||
isStreaming,
|
||||
apiSpec,
|
||||
streamUsage,
|
||||
streamRawLines,
|
||||
streamComposition,
|
||||
streamError,
|
||||
]);
|
||||
|
||||
const handleSubmit = useCallback(async () => {
|
||||
if (!inputValue.trim() || isStreaming) return;
|
||||
if (!inputValue.trim() || isStreaming || generatingVersionIdRef.current)
|
||||
return;
|
||||
|
||||
const newVersionId = Date.now().toString();
|
||||
const newVersion: Version = {
|
||||
@@ -298,6 +465,8 @@ export function Playground() {
|
||||
usage: null,
|
||||
rawLines: [],
|
||||
format,
|
||||
model,
|
||||
composition: null,
|
||||
};
|
||||
|
||||
generatingVersionIdRef.current = newVersionId;
|
||||
@@ -307,7 +476,7 @@ export function Playground() {
|
||||
|
||||
// Pass the current tree as context so the API can iterate on it
|
||||
await send(inputValue.trim(), { previousSpec: currentTreeRef.current });
|
||||
}, [inputValue, isStreaming, send, format]);
|
||||
}, [inputValue, isStreaming, send, format, model]);
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: React.KeyboardEvent) => {
|
||||
@@ -373,21 +542,45 @@ export function Playground() {
|
||||
|
||||
const propsStr = serializeProps(propsObj);
|
||||
const hasChildren = element.children && element.children.length > 0;
|
||||
const hasSlots = element.slots && Object.keys(element.slots).length > 0;
|
||||
|
||||
if (!hasChildren) {
|
||||
if (!hasChildren && !hasSlots) {
|
||||
return propsStr
|
||||
? `${spaces}<${componentName} ${propsStr} />`
|
||||
: `${spaces}<${componentName} />`;
|
||||
}
|
||||
|
||||
const lines: string[] = [];
|
||||
lines.push(
|
||||
propsStr
|
||||
? `${spaces}<${componentName} ${propsStr}>`
|
||||
: `${spaces}<${componentName}>`,
|
||||
);
|
||||
if (hasSlots) {
|
||||
lines.push(`${spaces}<${componentName}`);
|
||||
if (propsStr) {
|
||||
lines.push(`${spaces} ${propsStr}`);
|
||||
}
|
||||
for (const [slotName, childKeys] of Object.entries(element.slots!)) {
|
||||
const slotChildren = childKeys
|
||||
.map((childKey) => generateJSX(childKey, indent + 2))
|
||||
.filter(Boolean);
|
||||
if (slotChildren.length === 0) continue;
|
||||
lines.push(`${spaces} ${slotName}={`);
|
||||
if (slotChildren.length > 1) {
|
||||
lines.push(`${spaces} <>`);
|
||||
}
|
||||
lines.push(...slotChildren);
|
||||
if (slotChildren.length > 1) {
|
||||
lines.push(`${spaces} </>`);
|
||||
}
|
||||
lines.push(`${spaces} }`);
|
||||
}
|
||||
lines.push(`${spaces}>`);
|
||||
} else {
|
||||
lines.push(
|
||||
propsStr
|
||||
? `${spaces}<${componentName} ${propsStr}>`
|
||||
: `${spaces}<${componentName}>`,
|
||||
);
|
||||
}
|
||||
|
||||
for (const childKey of element.children!) {
|
||||
for (const childKey of element.children ?? []) {
|
||||
lines.push(generateJSX(childKey, indent + 1));
|
||||
}
|
||||
|
||||
@@ -434,10 +627,12 @@ ${jsx}
|
||||
{versions.length === 0 ? (
|
||||
<div className="flex-1 flex flex-col items-center justify-center text-center px-4">
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
Describe what you want to build, then iterate on it.
|
||||
{model === "typesafe-ai/jev"
|
||||
? "Describe a UI to compose from the prepared options."
|
||||
: "Describe what you want to build, then iterate on it."}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2 justify-center">
|
||||
{EXAMPLE_PROMPTS.map((prompt) => (
|
||||
{examplePrompts.map(({ label, prompt }) => (
|
||||
<button
|
||||
key={prompt}
|
||||
onMouseDown={(e) => {
|
||||
@@ -460,7 +655,7 @@ ${jsx}
|
||||
}}
|
||||
className="text-xs px-2 py-1 rounded border border-border text-muted-foreground hover:text-foreground hover:border-foreground/30 transition-colors"
|
||||
>
|
||||
{prompt}
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
@@ -490,6 +685,7 @@ ${jsx}
|
||||
<span className="text-xs text-red-500 shrink-0">failed</span>
|
||||
)}
|
||||
</div>
|
||||
<VersionDetails version={version} />
|
||||
{version.usage && (
|
||||
<div className="mt-1 ml-6">
|
||||
<span className="text-[10px] font-mono text-muted-foreground/60">
|
||||
@@ -513,7 +709,10 @@ ${jsx}
|
||||
onMouseDown={(e) => {
|
||||
// Focus textarea unless clicking a button or the textarea itself
|
||||
const target = e.target as HTMLElement;
|
||||
if (!target.closest("button") && target.tagName !== "TEXTAREA") {
|
||||
if (
|
||||
!target.closest("button, a, [role=combobox]") &&
|
||||
target.tagName !== "TEXTAREA"
|
||||
) {
|
||||
e.preventDefault();
|
||||
inputRef.current?.focus();
|
||||
}
|
||||
@@ -525,12 +724,15 @@ ${jsx}
|
||||
onChange={(e) => setInputValue(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Describe changes..."
|
||||
maxLength={model === "typesafe-ai/jev" ? 1000 : undefined}
|
||||
className="w-full bg-background text-base sm:text-sm resize-none outline-none placeholder:text-muted-foreground/50"
|
||||
rows={2}
|
||||
autoFocus
|
||||
/>
|
||||
<div className="flex justify-between items-center mt-2">
|
||||
<div className="flex justify-between items-end gap-2 mt-2">
|
||||
<PlaygroundControls
|
||||
model={model}
|
||||
setModel={setModel}
|
||||
disabled={isStreaming}
|
||||
format={format}
|
||||
setFormat={setFormat}
|
||||
editModes={editModes}
|
||||
@@ -539,13 +741,15 @@ ${jsx}
|
||||
onClear={() => {
|
||||
setVersions([]);
|
||||
setSelectedVersionId(null);
|
||||
generatingVersionIdRef.current = null;
|
||||
currentTreeRef.current = null;
|
||||
clear();
|
||||
}}
|
||||
/>
|
||||
{isStreaming ? (
|
||||
<button
|
||||
onClick={() => clear()}
|
||||
className="w-7 h-7 rounded-full bg-primary text-primary-foreground flex items-center justify-center hover:bg-primary/90 transition-colors"
|
||||
onClick={stop}
|
||||
className="w-7 h-7 shrink-0 rounded-full bg-primary text-primary-foreground flex items-center justify-center hover:bg-primary/90 transition-colors"
|
||||
aria-label="Stop"
|
||||
>
|
||||
<svg
|
||||
@@ -562,7 +766,7 @@ ${jsx}
|
||||
<button
|
||||
onClick={handleSubmit}
|
||||
disabled={!inputValue.trim()}
|
||||
className="w-7 h-7 rounded-full bg-primary text-primary-foreground flex items-center justify-center hover:bg-primary/90 transition-colors disabled:opacity-30"
|
||||
className="w-7 h-7 shrink-0 rounded-full bg-primary text-primary-foreground flex items-center justify-center hover:bg-primary/90 transition-colors disabled:opacity-30"
|
||||
aria-label="Send"
|
||||
>
|
||||
<svg
|
||||
@@ -835,8 +1039,12 @@ ${jsx}
|
||||
<div className="flex-1 overflow-auto">
|
||||
{renderView === "preview" ? (
|
||||
currentTree && currentTree.root ? (
|
||||
<div className="w-full min-h-full flex items-center justify-center p-6">
|
||||
<div
|
||||
className="w-full min-h-full flex items-center justify-center p-6"
|
||||
inert={isStreaming}
|
||||
>
|
||||
<PlaygroundRenderer
|
||||
key={selectedVersionId}
|
||||
spec={currentTree}
|
||||
data={currentTree.state}
|
||||
loading={isStreaming}
|
||||
@@ -863,8 +1071,6 @@ ${jsx}
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
<Header />
|
||||
|
||||
{/* Desktop: 3-pane resizable layout */}
|
||||
<div className="hidden lg:flex flex-1 min-h-0">
|
||||
<ResizablePanelGroup className="flex-1">
|
||||
@@ -1115,8 +1321,12 @@ ${jsx}
|
||||
/>
|
||||
) : mobileView === "preview" ? (
|
||||
currentTree && currentTree.root ? (
|
||||
<div className="w-full min-h-full flex items-center justify-center p-6">
|
||||
<div
|
||||
className="w-full min-h-full flex items-center justify-center p-6"
|
||||
inert={isStreaming}
|
||||
>
|
||||
<PlaygroundRenderer
|
||||
key={selectedVersionId}
|
||||
spec={currentTree}
|
||||
data={currentTree.state}
|
||||
loading={isStreaming}
|
||||
@@ -1131,10 +1341,12 @@ ${jsx}
|
||||
) : (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
Describe what you want to build, then iterate on it.
|
||||
{model === "typesafe-ai/jev"
|
||||
? "Describe a UI to compose from the prepared options."
|
||||
: "Describe what you want to build, then iterate on it."}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2 justify-center">
|
||||
{EXAMPLE_PROMPTS.map((prompt) => (
|
||||
{examplePrompts.map(({ label, prompt }) => (
|
||||
<button
|
||||
key={prompt}
|
||||
onMouseDown={(e) => {
|
||||
@@ -1148,7 +1360,7 @@ ${jsx}
|
||||
}}
|
||||
className="text-xs px-2 py-1 rounded border border-border text-muted-foreground hover:text-foreground hover:border-foreground/30 transition-colors"
|
||||
>
|
||||
{prompt}
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
@@ -1169,10 +1381,13 @@ ${jsx}
|
||||
|
||||
{/* Prompt input pinned to bottom */}
|
||||
<div
|
||||
className="border-t border-border p-3 shrink-0 cursor-text"
|
||||
className="border-t border-border p-3 pb-16 shrink-0 cursor-text"
|
||||
onMouseDown={(e) => {
|
||||
const target = e.target as HTMLElement;
|
||||
if (!target.closest("button") && target.tagName !== "TEXTAREA") {
|
||||
if (
|
||||
!target.closest("button, a, [role=combobox]") &&
|
||||
target.tagName !== "TEXTAREA"
|
||||
) {
|
||||
e.preventDefault();
|
||||
mobileInputRef.current?.focus();
|
||||
}
|
||||
@@ -1184,11 +1399,15 @@ ${jsx}
|
||||
onChange={(e) => setInputValue(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Describe changes..."
|
||||
maxLength={model === "typesafe-ai/jev" ? 1000 : undefined}
|
||||
className="w-full bg-background text-base resize-none outline-none placeholder:text-muted-foreground/50"
|
||||
rows={2}
|
||||
/>
|
||||
<div className="flex justify-between items-center mt-2">
|
||||
<div className="flex justify-between items-end gap-2 mt-2">
|
||||
<PlaygroundControls
|
||||
model={model}
|
||||
setModel={setModel}
|
||||
disabled={isStreaming}
|
||||
format={format}
|
||||
setFormat={setFormat}
|
||||
editModes={editModes}
|
||||
@@ -1197,13 +1416,15 @@ ${jsx}
|
||||
onClear={() => {
|
||||
setVersions([]);
|
||||
setSelectedVersionId(null);
|
||||
generatingVersionIdRef.current = null;
|
||||
currentTreeRef.current = null;
|
||||
clear();
|
||||
}}
|
||||
/>
|
||||
{isStreaming ? (
|
||||
<button
|
||||
onClick={() => clear()}
|
||||
className="w-7 h-7 rounded-full bg-primary text-primary-foreground flex items-center justify-center hover:bg-primary/90 transition-colors"
|
||||
onClick={stop}
|
||||
className="w-7 h-7 shrink-0 rounded-full bg-primary text-primary-foreground flex items-center justify-center hover:bg-primary/90 transition-colors"
|
||||
aria-label="Stop"
|
||||
>
|
||||
<svg
|
||||
@@ -1220,7 +1441,7 @@ ${jsx}
|
||||
<button
|
||||
onClick={handleSubmit}
|
||||
disabled={!inputValue.trim()}
|
||||
className="w-7 h-7 rounded-full bg-primary text-primary-foreground flex items-center justify-center hover:bg-primary/90 transition-colors disabled:opacity-30"
|
||||
className="w-7 h-7 shrink-0 rounded-full bg-primary text-primary-foreground flex items-center justify-center hover:bg-primary/90 transition-colors disabled:opacity-30"
|
||||
aria-label="Send"
|
||||
>
|
||||
<svg
|
||||
@@ -1275,6 +1496,7 @@ ${jsx}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<VersionDetails version={version} />
|
||||
{version.usage && (
|
||||
<div className="mt-1 ml-6">
|
||||
<span className="text-[10px] font-mono text-muted-foreground/60">
|
||||
|
||||
@@ -6,6 +6,7 @@ export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<NextThemesProvider
|
||||
attribute="class"
|
||||
value={{ dark: "dark-theme", light: "light-theme" }}
|
||||
defaultTheme="dark"
|
||||
enableSystem
|
||||
disableTransitionOnChange
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/a2ui")
|
||||
|
||||
# A2UI Integration
|
||||
---
|
||||
title: "A2UI Integration"
|
||||
---
|
||||
|
||||
Use `@json-render/core` to support [A2UI](https://a2ui.org) natively.
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/adaptive-cards")
|
||||
|
||||
# Adaptive Cards Integration
|
||||
---
|
||||
title: "Adaptive Cards Integration"
|
||||
---
|
||||
|
||||
Use json-render to render [Microsoft Adaptive Cards](https://adaptivecards.io) natively.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/ag-ui")
|
||||
|
||||
# AG-UI Integration
|
||||
---
|
||||
title: "AG-UI Integration"
|
||||
---
|
||||
|
||||
Use json-render to support [AG-UI](https://docs.copilotkit.ai/ag-ui) (Agent User Interaction Protocol) from CopilotKit.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/ai-sdk")
|
||||
|
||||
# AI SDK Integration
|
||||
---
|
||||
title: "AI SDK Integration"
|
||||
---
|
||||
|
||||
Use json-render with the [Vercel AI SDK](https://sdk.vercel.ai) for seamless streaming. json-render supports two modes: **Standalone** (standalone UI) and **Inline** (UI embedded in conversation). See [Generation Modes](/docs/generation-modes) for a detailed comparison.
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/codegen")
|
||||
|
||||
# @json-render/codegen
|
||||
---
|
||||
title: "@json-render/codegen"
|
||||
---
|
||||
|
||||
Utilities for generating code from UI trees.
|
||||
|
||||
@@ -1,10 +1,97 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/core")
|
||||
|
||||
# @json-render/core
|
||||
---
|
||||
title: "@json-render/core"
|
||||
---
|
||||
|
||||
Core types, schemas, and utilities.
|
||||
|
||||
## experimental_composeSpec
|
||||
|
||||
**Experimental, unreleased:** may change in any release. Pin exact versions when published; see [source-build setup and the full Jev guide](/docs/jev).
|
||||
|
||||
```typescript
|
||||
import {
|
||||
experimental_composeSpec,
|
||||
type Experimental_CompositionCandidate,
|
||||
type Experimental_CompositionEvaluator,
|
||||
type Experimental_CompositionEvent,
|
||||
} from "@json-render/core";
|
||||
|
||||
const events = experimental_composeSpec({
|
||||
catalog, // Standard flat Spec catalog
|
||||
candidates, // App-owned atomic elements
|
||||
prompt, // User request
|
||||
evaluate, // Experimental_CompositionEvaluator
|
||||
initialState: {}, // Included in spec; not sent to evaluator
|
||||
initialSpec, // Optional selected version to edit; never mutated
|
||||
elementDescriptions: {}, // Optional descriptions of existing element IDs
|
||||
context: {}, // Explicitly shared evaluator context
|
||||
strategy: "batch", // Default for new trees; edits are sequential
|
||||
maxElements: 32, // Batched creation only, includes the root
|
||||
maxSteps: 32, // Evaluation calls, including terminal decisions
|
||||
maxDepth: 8, // Root depth is one
|
||||
signal, // AbortSignal, optional
|
||||
instructions: { root: "", next: "", parent: "" }, // Appended guidance
|
||||
});
|
||||
```
|
||||
|
||||
A candidate has `id`, `description`, `element`, optional `root` (default true), `maxUses` (default one), and `resource` (mutually exclusive variants). IDs start with a letter and contain only letters, digits, underscores, and hyphens. IDs must be unique; `finish` and `unavailable` are reserved. Elements accept `type`, `props`, optional `on`, and `visible`. The composer supplies children and named slots.
|
||||
|
||||
Events are full detached snapshots. A `step` contains `spec` and `step`; `complete` contains nullable `spec`, `steps`, `elapsedMs`, nullable `inputTokens`, and `stopReason` (`finish`, `limit`, or `unavailable`). Each trace step contains `index`, `choice`, `description`, nullable `parent`/`slot`, nullable `confidence`/`parentConfidence`, `elapsedMs`, and nullable `inputTokens`. Batched steps also contain `answers`, keyed by question name, with each selected `choice` and optional confidence. Each trace represents one evaluation: batched timing and usage are counted once, not once per answer. Indexes start at zero. Completion is not a guarantee of semantic correctness.
|
||||
|
||||
### Batched creation
|
||||
|
||||
With no `initialSpec`, `strategy: "batch"` is the default. The first evaluation selects the root and required components together. Shared `resource` variants use one exclusive choice; reusable recipes use bounded counts that include the root when applicable. Root selection takes precedence over speculative membership for the same recipe/resource. The first snapshot includes all selected elements in catalog order under the root's default slot, or its first declared slot when there is no default.
|
||||
|
||||
A second evaluation selects parents and sibling positions from the actual selected set. Equal positions retain catalog order. The combined tree must pass catalog, slot, depth, and tree validation before publication; a cycle or invalid layout throws and preserves the first snapshot as partial output. A single root or one child in a single slot needs no layout call. No separate finish call is made.
|
||||
|
||||
`maxElements` limits batched creation, including the root. A truncated selection, insufficient depth for selected content, or a call budget that prevents required layout returns `limit`. Use `strategy: "sequential"` for one-operation-at-a-time creation. Edits always use the sequential protocol.
|
||||
|
||||
Invalid configuration, out-of-set decisions, provider failures, and aborts throw. Previous snapshots remain usable as partial UI. Stopping iteration prevents further evaluation calls. A supplied signal also stops waiting for an evaluator that ignores cancellation; that evaluator must honor the signal to stop its underlying work.
|
||||
|
||||
### Custom evaluators
|
||||
|
||||
The composer is provider independent. An evaluator receives `state`, `questions`, and `signal`, then returns a selected criteria key for each question:
|
||||
|
||||
```typescript
|
||||
const evaluate: Experimental_CompositionEvaluator = async ({ state, questions, signal }) => {
|
||||
// Your adapter calls a decision model with this request.
|
||||
const result = await yourEvaluator({ state, questions, signal });
|
||||
return {
|
||||
answers: result.answers, // { [questionName]: { choice: "offered_key", confidence: 0.9 } }
|
||||
usage: { inputTokens: result.inputTokens }, // Optional
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
Questions are records of `type: "choice"`, `instructions`, and `criteria` (choice key to description). Return an answer for every question and treat question/choice keys as opaque. Batched creation sends `root` and `select_*` questions, then `parent_*` and `order_*` questions. Sequential creation and edits use `next` to select an operation, `finish`, or `unavailable`, with `parent` when several attachment points exist. Existing adapters that only implement `next`/`parent` must opt into `strategy: "sequential"`. Confidence must be in [0, 1] when provided; input tokens must be a nonnegative integer.
|
||||
|
||||
State contains `user_request` and explicit app `context`, plus capabilities/guidance during batched selection, `selected_elements` during layout, or `already_built` during sequential composition. Candidate descriptions and instructions are shared; raw state/props/binding values are not automatically included. See [validation and v1 limits](/docs/jev#validation-and-v1-limits).
|
||||
|
||||
### Follow-up edits
|
||||
|
||||
Pass `initialSpec` to edit an existing version. The composer validates and clones it, preserving unchanged elements, IDs, action bindings, and state. `initialState` explicitly overrides `initialSpec.state` when provided. Optional `elementDescriptions` maps existing IDs to descriptions shared with the evaluator; matching candidates supply the default description, otherwise only the component type is shared.
|
||||
|
||||
Editing adds bounded operations: replace an element with an offered recipe, remove a non-root subtree, and move/reorder a subtree to an allowed slot/position. Replacements preserve children and are offered only when the new component can contain them. Moves cannot create cycles or exceed the depth limit. Seed specs with cycles, shared children, missing references, unreachable nodes, or unsupported expressions are rejected before evaluation.
|
||||
|
||||
The `next` question offers opaque operation keys as well as candidate IDs. For replacement or movement, the following evaluation selects a recipe or destination, also through `next`. Both calls count toward `maxSteps`; the first emits an unchanged snapshot with its decision trace. `changes_made` supplies the edit trace alongside `already_built`. A budget limit, unavailable result, or cancellation may leave a selected edit unapplied. Existing elements exactly matching a recipe count toward `maxUses` and `resource`; removing/replacing them releases those limits.
|
||||
|
||||
## experimental_createEvaluator
|
||||
|
||||
**Experimental:** creates a server-side evaluator using Vercel AI Gateway's experimental v4 evaluation transport. No AI SDK dependency or provider constructor is required.
|
||||
|
||||
```typescript
|
||||
import { experimental_createEvaluator } from "@json-render/core";
|
||||
|
||||
const evaluate = experimental_createEvaluator({
|
||||
apiKey: process.env.AI_GATEWAY_API_KEY!, // Required; keep server-side
|
||||
model: "typesafe-ai/jev", // Required, plain Gateway evaluation model ID
|
||||
timeoutMs: 10_000, // Default, per evaluation
|
||||
fetch: globalThis.fetch, // Optional transport override
|
||||
});
|
||||
```
|
||||
|
||||
The factory uses model-neutral naming and requires an explicit model. Jev is the current tested example; other models must support the Gateway choice-evaluation protocol. When using Jev, the Gateway team must permit TypeSafe AI. The adapter reports HTTP status on failure and rejects malformed/unoffered decisions. For Jev, it normalizes TypeSafe's native confidence rather than treating option probability as confidence. Confidence from other provider metadata is not yet normalized. Missing confidence and usage remain unknown. It does not retry automatically or estimate cost.
|
||||
|
||||
## defineCatalog
|
||||
|
||||
Creates a type-safe catalog definition with schema validation.
|
||||
@@ -339,17 +426,18 @@ setSpec({ ...applySpecPatch(spec, patch) });
|
||||
|
||||
### nestedToFlat
|
||||
|
||||
Convert a nested element tree (with inline children) into the flat `Spec` format:
|
||||
Convert a nested element tree (with inline children and named slots) into the flat `Spec` format:
|
||||
|
||||
```typescript
|
||||
import { nestedToFlat } from '@json-render/core';
|
||||
|
||||
const flat = nestedToFlat({
|
||||
type: "Card",
|
||||
props: { title: "Hello" },
|
||||
children: [
|
||||
{ type: "Text", props: { content: "World" }, children: [] }
|
||||
],
|
||||
type: "Layout",
|
||||
props: {},
|
||||
children: [{ type: "Text", props: { content: "Main" }, children: [] }],
|
||||
slots: {
|
||||
header: [{ type: "Heading", props: { text: "Header" }, children: [] }],
|
||||
},
|
||||
});
|
||||
// { root: "el-0", elements: { "el-0": ..., "el-1": ... } }
|
||||
```
|
||||
@@ -462,14 +550,19 @@ const name2 = resolveDynamicValue({ $state: "/user/name" }, state); // "Alice"
|
||||
|
||||
### findFormValue
|
||||
|
||||
Read a value from resolved action parameters or state. A parameter value is literal, including strings with dots such as emails, URLs, and versions. Lookup order: a defined direct parameter, a parameter key ending in `.<fieldName>`, a matching flat state key, then a slash-delimited path in nested state.
|
||||
|
||||
```typescript
|
||||
import { findFormValue } from '@json-render/core';
|
||||
|
||||
// Find form values regardless of path format
|
||||
// Checks: params.name, params["form.name"], state["form.name"], state.form.name
|
||||
const value = findFormValue("name", params, state);
|
||||
findFormValue("email", { email: "john.doe@example.com" }, {});
|
||||
findFormValue("email", { "form.email": "john.doe@example.com" }, {});
|
||||
findFormValue("email", {}, { "form.email": "john.doe@example.com" });
|
||||
findFormValue("/form/email", {}, { form: { email: "john.doe@example.com" } });
|
||||
```
|
||||
|
||||
For action bindings, use `{ $state: "/form/email" }` to read nested state: the action resolver passes the resulting value to the handler. A raw string like `"form.email"` in parameters is not a state reference. A bare `"email"` field name does not search `state.form.email`.
|
||||
|
||||
## buildUserPrompt
|
||||
|
||||
Build structured user prompts for AI generation, with support for refinement and state context.
|
||||
@@ -648,9 +741,10 @@ interface UIElement {
|
||||
type: string;
|
||||
props: Record<string, unknown>;
|
||||
children?: string[]; // Keys of child elements
|
||||
slots?: Record<string, string[]>; // Named slots mapped to child keys
|
||||
visible?: VisibilityCondition;
|
||||
on?: Record<string, ActionBinding | ActionBinding[]>; // Event bindings
|
||||
repeat?: { statePath: string; key?: string }; // Repeat for arrays
|
||||
repeat?: { statePath: string | { $item: string }; key?: string }; // Repeat for arrays
|
||||
}
|
||||
```
|
||||
|
||||
@@ -666,7 +760,7 @@ interface Spec {
|
||||
}
|
||||
```
|
||||
|
||||
Elements are stored as a flat map with string keys. The tree structure is built by following the `children` arrays.
|
||||
Elements are stored as a flat map with string keys. The tree structure is built by following `children` and named `slots` references.
|
||||
|
||||
### ActionBinding
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/devtools-react")
|
||||
|
||||
# @json-render/devtools-react
|
||||
---
|
||||
title: "@json-render/devtools-react"
|
||||
---
|
||||
|
||||
React adapter for the json-render devtools. Drop-in `<JsonRenderDevtools />` component.
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/devtools-solid")
|
||||
|
||||
# @json-render/devtools-solid
|
||||
---
|
||||
title: "@json-render/devtools-solid"
|
||||
---
|
||||
|
||||
SolidJS adapter for the json-render devtools. Drop-in `<JsonRenderDevtools />` component.
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/devtools-svelte")
|
||||
|
||||
# @json-render/devtools-svelte
|
||||
---
|
||||
title: "@json-render/devtools-svelte"
|
||||
---
|
||||
|
||||
Svelte adapter for the json-render devtools. Drop-in `<JsonRenderDevtools />` component.
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/devtools-vue")
|
||||
|
||||
# @json-render/devtools-vue
|
||||
---
|
||||
title: "@json-render/devtools-vue"
|
||||
---
|
||||
|
||||
Vue adapter for the json-render devtools. Drop-in `<JsonRenderDevtools />` component.
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/devtools")
|
||||
|
||||
# @json-render/devtools
|
||||
---
|
||||
title: "@json-render/devtools"
|
||||
---
|
||||
|
||||
Framework-agnostic core for the json-render devtools — vanilla TS panel UI, event store, DOM picker, and stream tap utilities. Every framework-specific adapter package depends on this.
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/directives")
|
||||
|
||||
# @json-render/directives
|
||||
---
|
||||
title: "@json-render/directives"
|
||||
---
|
||||
|
||||
Pre-built custom directives for `@json-render/core`. Drop them into your catalog and renderer to add formatting, math, string manipulation, and i18n.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/image")
|
||||
|
||||
# @json-render/image
|
||||
---
|
||||
title: "@json-render/image"
|
||||
---
|
||||
|
||||
Image renderer. Turn JSON specs into SVG and PNG images using [Satori](https://github.com/vercel/satori).
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/ink")
|
||||
|
||||
# @json-render/ink
|
||||
---
|
||||
title: "@json-render/ink"
|
||||
---
|
||||
|
||||
Terminal renderer for [Ink](https://github.com/vadimdemedes/ink) with multiple standard components, providers, hooks, and streaming support.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/jotai")
|
||||
|
||||
# @json-render/jotai
|
||||
---
|
||||
title: "@json-render/jotai"
|
||||
---
|
||||
|
||||
Jotai adapter for json-render's `StateStore` interface.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/mcp")
|
||||
|
||||
# @json-render/mcp
|
||||
---
|
||||
title: "@json-render/mcp"
|
||||
---
|
||||
|
||||
MCP Apps integration for json-render. Serve json-render UIs as interactive [MCP Apps](https://modelcontextprotocol.io/docs/extensions/apps) inside Claude, ChatGPT, Cursor, VS Code, and other MCP-capable clients.
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"title": "API Reference",
|
||||
"pages": [
|
||||
"core",
|
||||
"react",
|
||||
"next",
|
||||
"tanstack-start",
|
||||
"react-pdf",
|
||||
"react-email",
|
||||
"shadcn",
|
||||
"shadcn-svelte",
|
||||
"react-native",
|
||||
"image",
|
||||
"remotion",
|
||||
"ink",
|
||||
"vue",
|
||||
"svelte",
|
||||
"solid",
|
||||
"react-three-fiber",
|
||||
"directives",
|
||||
"codegen",
|
||||
"devtools",
|
||||
"devtools-react",
|
||||
"devtools-vue",
|
||||
"devtools-svelte",
|
||||
"devtools-solid",
|
||||
"mcp",
|
||||
"redux",
|
||||
"zustand",
|
||||
"jotai",
|
||||
"xstate",
|
||||
"yaml"
|
||||
]
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/next")
|
||||
|
||||
# @json-render/next
|
||||
---
|
||||
title: "@json-render/next"
|
||||
---
|
||||
|
||||
Next.js renderer. JSON becomes full Next.js applications with routes, layouts, metadata, and SSR.
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/react-email")
|
||||
|
||||
# @json-render/react-email
|
||||
---
|
||||
title: "@json-render/react-email"
|
||||
---
|
||||
|
||||
React Email renderer. Turn JSON specs into HTML or plain-text emails using `@react-email/components` and `@react-email/render`.
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/react-native")
|
||||
|
||||
# @json-render/react-native
|
||||
---
|
||||
title: "@json-render/react-native"
|
||||
---
|
||||
|
||||
React Native renderer with standard components, providers, and hooks.
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/react-pdf")
|
||||
|
||||
# @json-render/react-pdf
|
||||
---
|
||||
title: "@json-render/react-pdf"
|
||||
---
|
||||
|
||||
PDF document renderer. Turn JSON specs into PDFs using `@react-pdf/renderer`.
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/react-three-fiber")
|
||||
|
||||
# @json-render/react-three-fiber
|
||||
---
|
||||
title: "@json-render/react-three-fiber"
|
||||
---
|
||||
|
||||
React Three Fiber renderer for json-render. 20 built-in 3D components for meshes, lights, models, gaussian splats, environments, text, cameras, and controls.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/react")
|
||||
|
||||
# @json-render/react
|
||||
---
|
||||
title: "@json-render/react"
|
||||
---
|
||||
|
||||
React components, providers, and hooks.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/redux")
|
||||
|
||||
# @json-render/redux
|
||||
---
|
||||
title: "@json-render/redux"
|
||||
---
|
||||
|
||||
Redux / Redux Toolkit adapter for json-render's `StateStore` interface.
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/remotion")
|
||||
|
||||
# @json-render/remotion
|
||||
---
|
||||
title: "@json-render/remotion"
|
||||
---
|
||||
|
||||
Remotion video renderer. Turn JSON timeline specs into video compositions.
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/shadcn-svelte")
|
||||
|
||||
# @json-render/shadcn-svelte
|
||||
---
|
||||
title: "@json-render/shadcn-svelte"
|
||||
---
|
||||
|
||||
Pre-built [shadcn-svelte](https://www.shadcn-svelte.com/) components for json-render. 36 components built on Svelte 5 + Tailwind CSS, ready to use with `defineCatalog` and `defineRegistry`.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/shadcn")
|
||||
|
||||
# @json-render/shadcn
|
||||
---
|
||||
title: "@json-render/shadcn"
|
||||
---
|
||||
|
||||
Pre-built [shadcn/ui](https://ui.shadcn.com/) components for json-render. 36 components built on Radix UI + Tailwind CSS, ready to use with `defineCatalog` and `defineRegistry`.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata";
|
||||
export const metadata = pageMetadata("docs/api/solid");
|
||||
|
||||
# @json-render/solid
|
||||
---
|
||||
title: "@json-render/solid"
|
||||
---
|
||||
|
||||
SolidJS components, providers, and hooks for rendering json-render specs.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/svelte")
|
||||
|
||||
# @json-render/svelte
|
||||
---
|
||||
title: "@json-render/svelte"
|
||||
---
|
||||
|
||||
Svelte 5 components, providers, and helpers for rendering json-render specs.
|
||||
|
||||
@@ -0,0 +1,391 @@
|
||||
---
|
||||
title: "@json-render/tanstack-start"
|
||||
---
|
||||
|
||||
TanStack Start renderer for JSON-defined applications with routes, layouts,
|
||||
head metadata, SSR loaders, prerender paths, and client navigation.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @json-render/core @json-render/react @json-render/tanstack-start
|
||||
```
|
||||
|
||||
## schema
|
||||
|
||||
Use the Start application schema to generate full multi-page specs.
|
||||
|
||||
```typescript
|
||||
import { defineCatalog } from "@json-render/core";
|
||||
import {
|
||||
schema,
|
||||
startComponentDefinitions,
|
||||
} from "@json-render/tanstack-start/server";
|
||||
import { z } from "zod";
|
||||
|
||||
const catalog = defineCatalog(schema, {
|
||||
components: {
|
||||
...startComponentDefinitions,
|
||||
Card: {
|
||||
props: z.object({ title: z.string() }),
|
||||
description: "Card container",
|
||||
},
|
||||
NavBar: {
|
||||
props: z.object({}),
|
||||
slots: ["default"],
|
||||
description: "Application navigation",
|
||||
},
|
||||
},
|
||||
actions: {},
|
||||
});
|
||||
```
|
||||
|
||||
The generation prompt teaches TanStack Router's `$param` and `$` splat route
|
||||
syntax, reusable layouts, escaped JSON Patch route keys, and the built-in
|
||||
`Slot`, `Link`, and `navigate` capabilities.
|
||||
|
||||
Include `startComponentDefinitions` in the catalog so generated `Slot` and
|
||||
`Link` elements pass validation. `PageRenderer` supplies their React
|
||||
implementations automatically.
|
||||
|
||||
## createStartApp
|
||||
|
||||
Create helpers for a TanStack Start splat route.
|
||||
|
||||
```typescript
|
||||
import { createStartApp } from "@json-render/tanstack-start/server";
|
||||
|
||||
export const { getPageData, getHead, getStaticPaths } = createStartApp({
|
||||
spec,
|
||||
loaders: {
|
||||
post: async ({ slug }) => ({
|
||||
post: await getPost(slug as string),
|
||||
}),
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Options
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Option</th>
|
||||
<th>Type</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>
|
||||
<code>spec</code>
|
||||
</td>
|
||||
<td>
|
||||
<code>
|
||||
{"StartAppSpec | (() => StartAppSpec | Promise<StartAppSpec>)"}
|
||||
</code>
|
||||
</td>
|
||||
<td>A static application spec or an async spec factory</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>loaders</code>
|
||||
</td>
|
||||
<td>
|
||||
<code>{"Record<string, LoaderFn>"}</code>
|
||||
</td>
|
||||
<td>Named data loaders referenced by route specs</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
### Returns
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Helper</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>
|
||||
<code>getPageData</code>
|
||||
</td>
|
||||
<td>
|
||||
Matches a pathname, runs its loader, and returns serializable page and
|
||||
layout data
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>getHead</code>
|
||||
</td>
|
||||
<td>
|
||||
Returns TanStack Router <code>meta</code> and <code>links</code>{" "}
|
||||
descriptors
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>getStaticPaths</code>
|
||||
</td>
|
||||
<td>Returns concrete paths for TanStack Start prerendering</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
State is merged in this order: application state, layout state, page state,
|
||||
then loader data. Later sources override earlier values.
|
||||
|
||||
## StartAppSpec
|
||||
|
||||
```typescript
|
||||
interface StartAppSpec {
|
||||
metadata?: StartMetadata;
|
||||
routes: Record<string, StartRouteSpec>;
|
||||
layouts?: Record<string, Spec>;
|
||||
state?: Record<string, unknown>;
|
||||
}
|
||||
```
|
||||
|
||||
Each route requires a `page` spec and can select a layout, metadata, a named
|
||||
loader, loading/error/not-found specs, and static parameters.
|
||||
|
||||
### Route Patterns
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Pattern</th>
|
||||
<th>Example</th>
|
||||
<th>Params</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>
|
||||
<code>/</code>
|
||||
</td>
|
||||
<td>
|
||||
<code>/</code>
|
||||
</td>
|
||||
<td>
|
||||
<code>{"{}"}</code>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>/about</code>
|
||||
</td>
|
||||
<td>
|
||||
<code>/about</code>
|
||||
</td>
|
||||
<td>
|
||||
<code>{"{}"}</code>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>{"/blog/$slug"}</code>
|
||||
</td>
|
||||
<td>
|
||||
<code>/blog/hello</code>
|
||||
</td>
|
||||
<td>
|
||||
<code>{'{ slug: "hello" }'}</code>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>{"/docs/$"}</code>
|
||||
</td>
|
||||
<td>
|
||||
<code>/docs/guides/intro</code>
|
||||
</td>
|
||||
<td>
|
||||
<code>{'{ _splat: "guides/intro" }'}</code>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
Loader parameters are URL-decoded before they reach named loaders. Splat
|
||||
content is a slash-delimited string under `_splat`. Parameter values supplied
|
||||
through `staticParams` are URL-encoded in the paths returned by
|
||||
`getStaticPaths()`.
|
||||
|
||||
Route matching treats trailing slashes as optional and accepts both encoded and
|
||||
decoded pathname representations. This keeps loader data and route metadata in
|
||||
sync for static paths containing spaces or non-ASCII characters.
|
||||
|
||||
For prerendered dynamic routes, provide `staticParams`:
|
||||
|
||||
```typescript
|
||||
routes: {
|
||||
'/blog/$slug': {
|
||||
page,
|
||||
staticParams: [{ slug: 'hello' }, { slug: 'world' }],
|
||||
},
|
||||
'/docs/$': {
|
||||
page: docsPage,
|
||||
staticParams: [{ _splat: 'guides/intro' }],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Map `getStaticPaths()` into TanStack Start's top-level `pages` configuration:
|
||||
|
||||
```typescript
|
||||
const pages = (await getStaticPaths()).map((path) => ({ path }));
|
||||
```
|
||||
|
||||
## TanStack Route Setup
|
||||
|
||||
Wire the helpers to a file-based `$` splat route:
|
||||
|
||||
```tsx
|
||||
// src/routes/$.tsx
|
||||
import { createFileRoute, notFound } from "@tanstack/react-router";
|
||||
import {
|
||||
PageRenderer,
|
||||
StartErrorBoundary,
|
||||
StartLoading,
|
||||
StartNotFound,
|
||||
} from "@json-render/tanstack-start";
|
||||
import { getHead, getPageData } from "@/lib/json-app";
|
||||
|
||||
export const Route = createFileRoute("/$")({
|
||||
loader: async ({ location }) => {
|
||||
const data = await getPageData({ pathname: location.pathname });
|
||||
if (!data) throw notFound();
|
||||
return data;
|
||||
},
|
||||
head: ({ match }) => getHead({ pathname: match.pathname }),
|
||||
component: Page,
|
||||
pendingComponent: StartLoading,
|
||||
errorComponent: StartErrorBoundary,
|
||||
notFoundComponent: StartNotFound,
|
||||
});
|
||||
|
||||
function Page() {
|
||||
return <PageRenderer {...Route.useLoaderData()} />;
|
||||
}
|
||||
```
|
||||
|
||||
TanStack Router loaders are isomorphic. When a spec factory or named loader
|
||||
uses database clients, credentials, or server-only imports, invoke
|
||||
`getPageData` and `getHead` inside a TanStack Start `createServerFn` and call
|
||||
that server function from the route loader.
|
||||
|
||||
## StartAppProvider
|
||||
|
||||
Provide component implementations and action handlers around the root
|
||||
`Outlet`. Render `HeadContent` for route metadata.
|
||||
|
||||
```tsx
|
||||
import {
|
||||
createRootRoute,
|
||||
HeadContent,
|
||||
Outlet,
|
||||
Scripts,
|
||||
} from "@tanstack/react-router";
|
||||
import { StartAppProvider } from "@json-render/tanstack-start";
|
||||
import { spec } from "@/lib/spec";
|
||||
|
||||
export const Route = createRootRoute({
|
||||
component: () => (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<HeadContent />
|
||||
</head>
|
||||
<body>
|
||||
<StartAppProvider
|
||||
registry={registry}
|
||||
handlers={handlers}
|
||||
spec={spec}
|
||||
>
|
||||
<Outlet />
|
||||
</StartAppProvider>
|
||||
<Scripts />
|
||||
</body>
|
||||
</html>
|
||||
),
|
||||
});
|
||||
```
|
||||
|
||||
Passing `spec` lets `StartLoading`, `StartErrorBoundary`, and `StartNotFound`
|
||||
automatically select the matched route's fallback specs. Their explicit
|
||||
`loadingSpec`, `errorSpec`, and `notFoundSpec` props take precedence. For a
|
||||
server-only application spec, omit `spec` and pass client-safe fallback specs
|
||||
explicitly.
|
||||
|
||||
Pass named functions through `functions` when props use `$computed`:
|
||||
|
||||
```tsx
|
||||
<StartAppProvider
|
||||
registry={registry}
|
||||
spec={spec}
|
||||
functions={{ uppercase: ({ value }) => String(value).toUpperCase() }}
|
||||
>
|
||||
<Outlet />
|
||||
</StartAppProvider>
|
||||
```
|
||||
|
||||
## Built-ins
|
||||
|
||||
- `Slot` inserts page content into a JSON-defined layout.
|
||||
- `Link` wraps TanStack Router's `Link`; generated specs use an `href` prop.
|
||||
- `navigate` performs client-side navigation from action bindings.
|
||||
- `StartLoading`, `StartErrorBoundary`, and `StartNotFound` resolve the matched
|
||||
route's fallback specs when they are used as TanStack Router boundary
|
||||
components and the provider receives `spec`.
|
||||
|
||||
The default `StartErrorBoundary` fallback invalidates the router and reruns the
|
||||
failed loader when the user selects **Try again**.
|
||||
|
||||
`Slot` and `Link` are automatically added to the page registry.
|
||||
|
||||
## Server Utilities
|
||||
|
||||
```typescript
|
||||
import {
|
||||
collectStaticPaths,
|
||||
matchRoute,
|
||||
metadataToHead,
|
||||
resolveMetadata,
|
||||
splatToPath,
|
||||
} from "@json-render/tanstack-start/server";
|
||||
```
|
||||
|
||||
## Entry Points
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Import</th>
|
||||
<th>Contents</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>
|
||||
<code>@json-render/tanstack-start</code>
|
||||
</td>
|
||||
<td>Provider, page renderer, Link, and route fallback components</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>@json-render/tanstack-start/server</code>
|
||||
</td>
|
||||
<td>App factory, schema, matcher, metadata, and prerender helpers</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<code>@json-render/tanstack-start/catalog</code>
|
||||
</td>
|
||||
<td>Server-safe definitions for built-in Slot and Link components</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/vue")
|
||||
|
||||
# @json-render/vue
|
||||
---
|
||||
title: "@json-render/vue"
|
||||
---
|
||||
|
||||
Vue 3 components, providers, and composables.
|
||||
|
||||
@@ -95,7 +94,7 @@ store.set("/count", 1);
|
||||
|
||||
## defineRegistry
|
||||
|
||||
Create a type-safe component registry from a catalog. Components receive `props`, `children`, `emit`, `on`, and `loading` with catalog-inferred types.
|
||||
Create a type-safe component registry from a catalog. Components receive `props`, `children`, `slots`, `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.
|
||||
|
||||
@@ -105,8 +104,12 @@ import { defineRegistry } from "@json-render/vue";
|
||||
|
||||
const { registry } = defineRegistry(catalog, {
|
||||
components: {
|
||||
Card: ({ props, children }) =>
|
||||
h("div", { class: "card" }, [h("h3", null, props.title), children]),
|
||||
Layout: ({ slots }) =>
|
||||
h("div", { class: "layout" }, [
|
||||
h("header", null, slots.header?.()),
|
||||
h("main", null, slots.default?.()),
|
||||
h("footer", null, slots.footer?.()),
|
||||
]),
|
||||
Button: ({ props, emit }) =>
|
||||
h("button", { onClick: () => emit("press") }, props.label),
|
||||
},
|
||||
@@ -136,11 +139,12 @@ const { registry } = defineRegistry(catalog, {
|
||||
### Component Props (via defineRegistry)
|
||||
|
||||
```typescript
|
||||
import type { VNode } from "vue";
|
||||
import type { Slots, VNode } from "vue";
|
||||
|
||||
interface ComponentContext<P> {
|
||||
props: P; // Typed props from catalog
|
||||
children?: VNode | VNode[]; // Rendered children (for container components)
|
||||
slots: Slots; // Vue-native slot functions
|
||||
emit: (event: string) => void; // Emit a named event (always defined)
|
||||
on: (event: string) => EventHandle; // Get event handle with metadata
|
||||
loading?: boolean;
|
||||
@@ -154,6 +158,22 @@ interface EventHandle {
|
||||
}
|
||||
```
|
||||
|
||||
Use `children` for the default slot. For other slots declared by the catalog, add a top-level `slots` map to the spec element:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "Layout",
|
||||
"props": {},
|
||||
"children": ["main-content"],
|
||||
"slots": {
|
||||
"header": ["page-heading"],
|
||||
"footer": ["page-actions"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The component renders these regions with Vue's native slot functions: `slots.header?.()`, `slots.footer?.()`, and so on. `slots.default?.()` renders the spec's `children`; `children` is a convenience alias for that rendered result. In the JSON spec, keep default content in `children` rather than adding a `default` entry to `slots`.
|
||||
|
||||
Use `emit("press")` for simple event firing. Use `on("click")` when you need metadata like `shouldPreventDefault`:
|
||||
|
||||
```typescript
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/xstate")
|
||||
|
||||
# @json-render/xstate
|
||||
---
|
||||
title: "@json-render/xstate"
|
||||
---
|
||||
|
||||
[XState Store](https://stately.ai/docs/xstate-store) adapter for json-render's `StateStore` interface.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/yaml")
|
||||
|
||||
# @json-render/yaml
|
||||
---
|
||||
title: "@json-render/yaml"
|
||||
---
|
||||
|
||||
YAML wire format for json-render. Progressive rendering and surgical edits via streaming YAML.
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/api/zustand")
|
||||
|
||||
# @json-render/zustand
|
||||
---
|
||||
title: "@json-render/zustand"
|
||||
---
|
||||
|
||||
Zustand adapter for json-render's `StateStore` interface.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/catalog")
|
||||
|
||||
# Catalog
|
||||
---
|
||||
title: "Catalog"
|
||||
---
|
||||
|
||||
The catalog defines what AI can generate. It's your guardrail.
|
||||
|
||||
@@ -18,9 +17,9 @@ A catalog is the vocabulary for your UI. While the [schema](/docs/schemas) defin
|
||||
`defineCatalog` is from `@json-render/core`. The `schema` import comes from your platform package (`@json-render/react` or `@json-render/react-native`) and defines the element structure the catalog targets. The catalog definition itself is framework-agnostic.
|
||||
|
||||
```typescript
|
||||
import { defineCatalog } from '@json-render/core';
|
||||
import { schema } from '@json-render/react/schema'; // or '@json-render/react-native/schema'
|
||||
import { z } from 'zod';
|
||||
import { defineCatalog } from "@json-render/core";
|
||||
import { schema } from "@json-render/react/schema"; // or '@json-render/react-native/schema'
|
||||
import { z } from "zod";
|
||||
|
||||
const catalog = defineCatalog(schema, {
|
||||
components: {
|
||||
@@ -29,35 +28,35 @@ const catalog = defineCatalog(schema, {
|
||||
props: z.object({
|
||||
title: z.string(),
|
||||
description: z.string().nullable(),
|
||||
padding: z.enum(['sm', 'md', 'lg']).nullable(),
|
||||
padding: z.enum(["sm", "md", "lg"]).nullable(),
|
||||
}),
|
||||
slots: ["default"], // Can contain other components
|
||||
description: "Container card for grouping content",
|
||||
},
|
||||
|
||||
|
||||
Metric: {
|
||||
props: z.object({
|
||||
label: z.string(),
|
||||
value: z.union([z.string(), z.number()]),
|
||||
format: z.enum(['currency', 'percent', 'number']),
|
||||
format: z.enum(["currency", "percent", "number"]),
|
||||
}),
|
||||
description: "Display a single metric value",
|
||||
},
|
||||
},
|
||||
|
||||
|
||||
actions: {
|
||||
submit_form: {
|
||||
params: z.object({
|
||||
formId: z.string(),
|
||||
}),
|
||||
description: 'Submit a form',
|
||||
description: "Submit a form",
|
||||
},
|
||||
|
||||
|
||||
export_data: {
|
||||
params: z.object({
|
||||
format: z.enum(['csv', 'pdf', 'json']),
|
||||
format: z.enum(["csv", "pdf", "json"]),
|
||||
}),
|
||||
description: 'Export data in various formats',
|
||||
description: "Export data in various formats",
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -70,12 +69,22 @@ Each component in the catalog has:
|
||||
```typescript
|
||||
{
|
||||
props: z.object({...}), // Zod schema for props (use .nullable() for optional)
|
||||
slots?: string[], // Named slots for children (e.g., ["default"])
|
||||
slots?: string[], // Available slots (e.g., ["default", "header", "footer"])
|
||||
description?: string, // Help AI understand when to use it
|
||||
}
|
||||
```
|
||||
|
||||
Use `slots: ["default"]` for components that can contain children. The slot name corresponds to where child elements are rendered.
|
||||
Use `"default"` for regular children. Add named slots when a component places content in multiple regions:
|
||||
|
||||
```typescript
|
||||
Layout: {
|
||||
props: z.object({}),
|
||||
slots: ["default", "header", "footer"],
|
||||
description: "Page layout with header, content, and footer regions",
|
||||
}
|
||||
```
|
||||
|
||||
React specs use `children` for the default slot and a `slots` object for the other names.
|
||||
|
||||
## Generating AI Prompts
|
||||
|
||||
@@ -1,10 +1,101 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/changelog")
|
||||
|
||||
# Changelog
|
||||
---
|
||||
title: "Changelog"
|
||||
---
|
||||
|
||||
Notable changes and updates to json-render.
|
||||
|
||||
## v0.21.0
|
||||
|
||||
September 18, 2026
|
||||
|
||||
### New: TanStack Start Renderer
|
||||
|
||||
Added `@json-render/tanstack-start` for JSON-defined applications with file-based routes, reusable layouts, SSR loaders, head metadata, prerender paths, client navigation, and route fallbacks.
|
||||
|
||||
See the [TanStack Start API reference](/docs/api/tanstack-start) for setup and route configuration.
|
||||
|
||||
### New: Experimental Jev Composition
|
||||
|
||||
Added `experimental_composeSpec` and `experimental_createEvaluator` to `@json-render/core`. Apps can provide their own catalogs and bounded component candidates, then stream validated compositions through an evaluation model. The playground now includes a Jev model option and supports iterative composition edits.
|
||||
|
||||
These APIs are experimental and may change in any release. See the [Jev guide](/docs/jev) for the source-build workflow, examples, and current limitations.
|
||||
|
||||
### Improved: Vue Named Slots
|
||||
|
||||
Vue registries now support catalog-declared named slots alongside the default `children` slot.
|
||||
|
||||
### Fixed: React Streaming Stability
|
||||
|
||||
Stabilized streamed React renders and added coverage for incomplete streamed props and nested prop identities.
|
||||
|
||||
---
|
||||
|
||||
## v0.20.0
|
||||
|
||||
August 15, 2026
|
||||
|
||||
### New: Named Slots for React
|
||||
|
||||
React components can now declare named slots such as `header` and `footer`, while `children` remains the default slot. Named slots are preserved through validation, streaming, nested conversion, code export, playground views, and Devtools navigation.
|
||||
|
||||
This work builds on the original named slots contribution by @wotnak.
|
||||
|
||||
```tsx
|
||||
const catalog = defineCatalog(schema, {
|
||||
components: {
|
||||
Layout: {
|
||||
props: z.object({}),
|
||||
slots: ["default", "header", "footer"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const { registry } = defineRegistry(catalog, {
|
||||
components: {
|
||||
Layout: ({ children, slots }) => (
|
||||
<section>
|
||||
<header>{slots?.header}</header>
|
||||
<main>{children}</main>
|
||||
<footer>{slots?.footer}</footer>
|
||||
</section>
|
||||
),
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### New: Nested Repeats
|
||||
|
||||
`repeat.statePath` now accepts item-relative paths such as `{ "$item": "employees" }`. Nested data can be rendered across React, React Native, React Email, React PDF, Image, Ink, Solid, Svelte, and Vue.
|
||||
|
||||
This work builds on the original nested repeats contribution by @tmchow.
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "Table",
|
||||
"repeat": { "statePath": { "$item": "employees" }, "key": "id" },
|
||||
"children": ["employee-row"],
|
||||
"props": {}
|
||||
}
|
||||
```
|
||||
|
||||
### New: Harness Chat Example
|
||||
|
||||
Added a complete Next.js example using the AI SDK 7 harness adapter, agent delegation, sandbox transport, and json-render components.
|
||||
|
||||
### Fixed: Chained Action Params
|
||||
|
||||
Named `onSuccess` and `onError` actions now receive their configured `params` across core and all renderer bridges. Custom renderer bridges must now accept an `ActionBinding` in the core `executeAction` callback instead of a bare action name.
|
||||
|
||||
### Improved: Spec Validation and Compatibility
|
||||
|
||||
Element visibility remains optional across Zod 4 versions. Autofix now prunes dangling child references, validation reports malformed visibility conditions, and repeated items can be filtered safely.
|
||||
|
||||
### Improved: Release Toolchain
|
||||
|
||||
The workspace now requires Node.js 24 and pnpm 11, enforces package engine checks, and applies a minimum package release age.
|
||||
|
||||
---
|
||||
|
||||
## v0.19.0
|
||||
|
||||
May 6, 2026
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/code-export")
|
||||
|
||||
# Code Export
|
||||
---
|
||||
title: "Code Export"
|
||||
---
|
||||
|
||||
Export generated UI as standalone code for your framework.
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/computed-values")
|
||||
|
||||
# Computed Values
|
||||
---
|
||||
title: "Computed Values"
|
||||
---
|
||||
|
||||
Derive dynamic prop values using registered functions or string templates.
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/custom-schema")
|
||||
|
||||
# Custom Schema & Renderer
|
||||
---
|
||||
title: "Custom Schema & Renderer"
|
||||
---
|
||||
|
||||
Build your own schema and renderer with `@json-render/core`.
|
||||
|
||||
+4
-5
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/data-binding")
|
||||
|
||||
# Data Binding
|
||||
---
|
||||
title: "Data Binding"
|
||||
---
|
||||
|
||||
Connect UI elements to dynamic data using expressions in your JSON specs.
|
||||
|
||||
@@ -126,7 +125,7 @@ The `repeat` field on an element renders its children once per item in a state a
|
||||
}
|
||||
```
|
||||
|
||||
- `repeat.statePath` — JSON Pointer to the state array
|
||||
- `repeat.statePath`: root JSON Pointer to the state array, or `{ "$item": "field" }` for an array on the enclosing repeat item
|
||||
- `repeat.key` — field name on each item to use as a stable key for rendering
|
||||
|
||||
Inside `todo-item`, `{ "$item": "title" }` reads the `title` field from whichever array item is currently being rendered. `{ "$index": true }` would return `0` for the first item, `1` for the second, and so on.
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/devtools")
|
||||
|
||||
# Devtools
|
||||
---
|
||||
title: "Devtools"
|
||||
---
|
||||
|
||||
A drop-in inspector panel for any json-render app. See the spec tree, edit state inline, watch dispatched actions, follow stream patches live, browse your catalog, and pick DOM elements to map them back to spec keys.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/directives")
|
||||
|
||||
# Directives
|
||||
---
|
||||
title: "Directives"
|
||||
---
|
||||
|
||||
Extend the spec language with custom `$`-prefixed dynamic values. Directives let you add formatting, math, string manipulation, i18n, and any other transformation without modifying core.
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/generation-modes")
|
||||
|
||||
# Generation Modes
|
||||
---
|
||||
title: "Generation Modes"
|
||||
---
|
||||
|
||||
json-render supports two modes for AI-generated UI: **Standalone mode** for standalone UI and **Inline mode** for inline UI within a conversation.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs")
|
||||
|
||||
# Introduction
|
||||
---
|
||||
title: "Introduction"
|
||||
---
|
||||
|
||||
json-render is a framework for **Generative UI** — AI-generated interfaces that are safe, predictable, and render natively on any platform.
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/installation")
|
||||
|
||||
# Installation
|
||||
---
|
||||
title: "Installation"
|
||||
---
|
||||
|
||||
Install the core package plus your renderer of choice.
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
---
|
||||
title: "Jev (Experimental)"
|
||||
---
|
||||
**Experimental:** `experimental_composeSpec` and `experimental_createEvaluator` are reusable APIs in `@json-render/core`. Like AI SDK's experimental APIs, names prefixed with `experimental_` or `Experimental_` may change in any release. Pin exact package versions (no `^` or `~`) and review release notes before upgrading.
|
||||
|
||||
**Availability:** these APIs are unreleased. You can try the source build below before they appear in a published npm version.
|
||||
|
||||
Open the [playground](/playground), select **jev** in the **default / jev** toggle, and send a request. Hover or focus the Jev option with its info icon for details about the experiment. Or use your own catalog in your app. [Share feedback](https://github.com/vercel-labs/json-render/issues/new) with your catalog, candidates, request, resulting spec, and expected behavior. Remove private data from reproductions.
|
||||
|
||||
## Why use it?
|
||||
|
||||
The public API is model-neutral: `experimental_createEvaluator` takes an explicit Gateway evaluation model ID. Jev is the current tested example.
|
||||
|
||||
Jev is a decision model from TypeSafe AI. It chooses among discrete options instead of writing free-form text. json-render turns those choices into a normal flat `Spec`, which your existing renderer, component registry, and action handlers can use.
|
||||
|
||||
Your app supplies atomic element candidates: component names, concrete props, state bindings, and allowed action bindings. Jev selects which to include, their order, and their placement. The platform controls the available capabilities and design system. The composer never executes actions.
|
||||
|
||||
New trees use batched composition by default. One evaluation selects the root and required components together, and immediately emits a validated preview containing content. A second evaluation arranges the selected elements when needed. This avoids one network round trip per component. The first preview uses catalog order and the root's default (or first declared) slot; the final layout can move elements. Root selection takes precedence over speculative membership for the same recipe/resource, and equal sibling positions retain catalog order. Inconsistent combined layouts throw, retaining the first preview as partial output. Set `strategy: "sequential"` for one-operation-at-a-time creation; follow-up edits remain sequential.
|
||||
|
||||
A catalog alone is not enough for Jev: open-ended string props and data still need values. Build candidates from your records, localized copy, form definitions, or prepared content. Jev cannot invent missing prose or data.
|
||||
|
||||
UI composition and data can stay separate: bind candidate props to `initialState` with `$state`, or construct candidates from the current records for each request. Jev chooses the component tree, grouping, and order; no complete page template is required. Each candidate is a configured component instance, so the model can only select the chart types, field configurations, and layout variants you offer. For example, supplying a revenue BarGraph alone does not let it choose a LineGraph; supply both candidates with a shared `resource` to offer that choice.
|
||||
|
||||
## Try it in your app
|
||||
|
||||
From a checkout containing this feature, build and pack core:
|
||||
|
||||
```sh
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm --filter @json-render/core build
|
||||
pnpm --filter @json-render/core pack --pack-destination /tmp/json-render-preview
|
||||
```
|
||||
|
||||
Install the resulting `.tgz` file in your app with `pnpm add /absolute/path/to/the-file.tgz`. Keep your renderer and other json-render packages on the same version as the checkout. Source builds are for evaluation; the package version alone does not identify the experimental revision, so record the checkout commit in feedback.
|
||||
|
||||
### Define the catalog and candidates
|
||||
|
||||
This example uses the React schema. The composer supports catalogs using the standard flat `Spec` format, including named slots. It does not support arbitrary custom spec formats.
|
||||
|
||||
```typescript
|
||||
// catalog.ts
|
||||
import { defineCatalog } from "@json-render/core";
|
||||
import { schema } from "@json-render/react/schema";
|
||||
import { z } from "zod";
|
||||
|
||||
export const catalog = defineCatalog(schema, {
|
||||
components: {
|
||||
Panel: { props: z.object({ title: z.string() }), slots: ["default"] },
|
||||
Input: { props: z.object({ label: z.string(), value: z.string() }) },
|
||||
Button: { props: z.object({ label: z.string() }), events: ["press"] },
|
||||
},
|
||||
actions: {
|
||||
savePreferences: { params: z.object({ name: z.string() }) },
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
```typescript
|
||||
// candidates.ts
|
||||
import type { Experimental_CompositionCandidate } from "@json-render/core";
|
||||
|
||||
export const candidates = [
|
||||
{
|
||||
id: "preferences",
|
||||
description: "Account preferences panel",
|
||||
element: { type: "Panel", props: { title: "Account preferences" } },
|
||||
},
|
||||
{
|
||||
id: "name",
|
||||
description: "Editable name field",
|
||||
root: false,
|
||||
element: {
|
||||
type: "Input",
|
||||
props: { label: "Name", value: { $bindState: "/name" } },
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "save",
|
||||
description: "Save preferences using the current name",
|
||||
root: false,
|
||||
element: {
|
||||
type: "Button",
|
||||
props: { label: "Save" },
|
||||
on: { press: { action: "savePreferences", params: { name: { $state: "/name" } } } },
|
||||
},
|
||||
},
|
||||
] satisfies Experimental_CompositionCandidate[];
|
||||
```
|
||||
|
||||
### Compose on the server
|
||||
|
||||
Set `AI_GATEWAY_API_KEY` in your server environment. Your Gateway team must allow the `typesafe-ai` provider. A separate TypeSafe key is not required. Keep the evaluator and credentials on the server.
|
||||
|
||||
```typescript
|
||||
// Server only
|
||||
import { experimental_composeSpec, experimental_createEvaluator } from "@json-render/core";
|
||||
import { catalog } from "./catalog";
|
||||
import { candidates } from "./candidates";
|
||||
|
||||
const evaluate = experimental_createEvaluator({
|
||||
model: "typesafe-ai/jev",
|
||||
apiKey: process.env.AI_GATEWAY_API_KEY!,
|
||||
});
|
||||
|
||||
for await (const event of experimental_composeSpec({
|
||||
catalog,
|
||||
candidates,
|
||||
prompt: "Create account preferences with a name field and Save button",
|
||||
initialState: { name: "" },
|
||||
evaluate,
|
||||
maxSteps: 12,
|
||||
maxElements: 24,
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
})) {
|
||||
// Send snapshots to your client and render using your existing registry.
|
||||
if (event.type === "step") console.log(event.spec);
|
||||
else console.log(event.stopReason, event.spec);
|
||||
}
|
||||
```
|
||||
|
||||
The adapter uses the plain model ID `typesafe-ai/jev` and Gateway's experimental v4 evaluation endpoint. It has no AI SDK dependency. The default timeout is 10 seconds per evaluation; use `signal` for an overall deadline. See the [core API reference](/docs/api/core#experimental_composespec) for all options.
|
||||
|
||||
### Iterate on a version
|
||||
|
||||
Pass the selected version as `initialSpec` with the next request:
|
||||
|
||||
```typescript
|
||||
for await (const event of experimental_composeSpec({
|
||||
catalog,
|
||||
candidates,
|
||||
initialSpec: selectedSpec,
|
||||
prompt: "Remove the Save button",
|
||||
evaluate,
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
})) {
|
||||
if (event.spec) updatePreview(event.spec);
|
||||
}
|
||||
```
|
||||
|
||||
Edits can add candidates, replace element recipes, remove non-root subtrees, and move/reorder subtrees. Replacements keep the element's ID, position, and compatible children. Unchanged content, bindings, and state are preserved; the input spec is never mutated. Omit `initialSpec` to start a new composition.
|
||||
|
||||
Existing elements use matching candidate descriptions; you can supply `elementDescriptions` keyed by element ID to identify other content. Raw props and state are not shared automatically. Seed specs must be valid trees within the supported catalog and expression subset. Replacement and move operations take two evaluations: select the element, then the recipe or destination. Both count toward the request budget.
|
||||
|
||||
### Render and handle actions
|
||||
|
||||
Send `step` events over your app's streaming transport and update the preview with `event.spec`. These are full snapshots, not SpecStream patches. Register `Panel`, `Input`, and `Button` in your existing registry, implement `Input` with `useBoundProp`, and bind the `savePreferences` action to your app's handler. See [the React quickstart](/docs/quick-start) and [state binding](/docs/data-binding).
|
||||
|
||||
Initialize your renderer's state from `spec.state`. Keep user interaction disabled while composing so incoming snapshots do not compete with edits. Registering an action does not make it safe to execute with arbitrary values: authorize and validate requests in your handler as usual.
|
||||
|
||||
On `complete`, inspect `stopReason`: `finish` means composition finished; `unavailable` means the evaluator could not fulfill the request; `limit` means a call, element, or depth budget prevented completion. A complete event can contain a partial spec, or `null` when no root was added. Completion is not a correctness guarantee. Errors and cancellation throw; retain the last snapshot and label it incomplete. Each batched trace is one evaluation (`select` or `layout`), with the individual choices in `step.answers` and usage/timing counted once.
|
||||
|
||||
The playground is a reference implementation: [candidates and server wrapper](https://github.com/vercel-labs/json-render/tree/main/apps/web/lib/jev), [streaming route](https://github.com/vercel-labs/json-render/blob/main/apps/web/app/api/generate/route.ts), and [client](https://github.com/vercel-labs/json-render/blob/main/apps/web/components/playground.tsx).
|
||||
|
||||
## Validation and v1 limits
|
||||
|
||||
- Candidate props and action parameters are validated against their catalog schemas using `initialState`, or `initialSpec.state` when editing without an explicit override. Expressions remain intact in the returned spec. Supply valid initial values; schema defaults and transforms are not applied to recipes.
|
||||
- V1 supports literal values, `$state`, `$bindState`, and state-based visibility. Repeats, watches, computed expressions, templates, conditional props, and custom directives are not supported. Candidate recipes remain atomic; use `initialSpec` for an existing tree.
|
||||
- Events must be declared by the component. Actions must be in the catalog or the schema's built-in action list. Built-ins without a parameter schema receive name validation only. Success/error callbacks must reference catalog actions.
|
||||
- Runtime state can change after composition. The composer cannot validate future values or authorize a later action invocation.
|
||||
- The default budget is 32 evaluations, with at most 32 elements in batched creation; default maximum depth is eight. Batching needs at most two evaluations and no separate finish decision. Each candidate is used at most once unless `maxUses` is set. `root: false` excludes it from root selection. A shared `resource` makes candidate variants mutually exclusive.
|
||||
- Named slots come from the catalog. Jev selects an existing parent/slot; the composer creates the edge and validates structural integrity before yielding. It does not guarantee an ideal layout or semantic completeness.
|
||||
- The evaluator receives the prompt, candidate descriptions, construction instructions, tree topology, and explicit `context`. Initial state, raw props, and binding values are not sent automatically. Put the information needed to choose candidates in their descriptions.
|
||||
- Confidence and input usage may be unknown. Confidence is not a calibrated quality threshold. The reusable API does not assume model prices.
|
||||
|
||||
## Playground capabilities
|
||||
|
||||
To self-host the playground, set `JEV_AI_GATEWAY_API_KEY` on the server for Jev. The default model uses `AI_GATEWAY_API_KEY`; Jev requires its own key and does not fall back to that variable. This is a playground convention: the reusable evaluator accepts whichever server-side key your app passes as `apiKey`.
|
||||
|
||||
The playground offers 17 component types with prepared account/contact fields, validation rules, synthetic profile and commerce data, and local Save/Reset/Submit actions. Profile choices include an avatar, display name, role, bio, email, location, and membership badge, bound to the supplied record. A title in double quotes becomes an extra Heading candidate. Values entered in the rendered preview stay in the browser.
|
||||
|
||||
Select **jev**, choose **Create account settings**, and send the request. Edit the fields and press **Save changes**. The status changes locally; **Reset** restores the form. Login/contact submission validates inputs and shows a demo toast. The demo does not authenticate users, send messages, or save business records.
|
||||
|
||||
Both model options edit the selected version. Try `Design a user profile card`, then `Remove the bio` or `Make the avatar smaller`. After generating settings with Jev, try `Remove the email notifications switch`, `Change the heading to "Account settings"`, or `Move the email field above the name field`. Select any earlier version to branch from it; Clear starts fresh. New text still needs a prepared candidate or a quoted heading. The playground shares existing display labels and matching candidate descriptions to identify edit targets, but does not send entered form values or raw state to Jev. Specs using unsupported expressions cannot be edited by Jev.
|
||||
|
||||
For a dashboard, try `Generate a sales dashboard with an orders table at the top, then revenue, orders and new customers metrics in a row, then a weekly revenue chart.` Section order is a model decision, and follow-ups can move the table or chart. Name the sections you need: a vague request such as `Generate a dashboard with the table at the top` can produce only a table. A valid finished spec does not guarantee that the model inferred all the intended content.
|
||||
|
||||
The stream tab shows spec patches and decision metadata, and version history labels partial or unavailable results. Requests retain the selected version until edits arrive, including when an edit is unavailable or interrupted.
|
||||
|
||||
The playground limits batched creation to 14 elements and runs to 14 evaluations, depth four, and 55 seconds overall, and accepts selected specs with up to 100 elements. Its endpoint uses the web app's minute and daily rate limiters. Self-hosted deployments need `KV_REST_API_URL` and `KV_REST_API_TOKEN` to enable those rate limits.
|
||||
|
||||
References: [Jev on Gateway](https://vercel.com/ai-gateway/models/jev), [AI SDK experimental versioning](https://ai-sdk.dev/docs/migration-guides/versioning), [Jev's documented limits](https://docs.typesafe.ai/model-jaggedness/jev-1.13).
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"title": "Documentation",
|
||||
"pages": [
|
||||
"---Getting Started---",
|
||||
"index",
|
||||
"installation",
|
||||
"quick-start",
|
||||
"skills",
|
||||
"migration",
|
||||
"changelog",
|
||||
"---Core---",
|
||||
"specs",
|
||||
"schemas",
|
||||
"catalog",
|
||||
"data-binding",
|
||||
"computed-values",
|
||||
"visibility",
|
||||
"watchers",
|
||||
"validation",
|
||||
"directives",
|
||||
"---Rendering---",
|
||||
"renderers",
|
||||
"registry",
|
||||
"streaming",
|
||||
"generation-modes",
|
||||
"---Examples---",
|
||||
"[Browse All Examples](/examples)",
|
||||
"---Guides---",
|
||||
"custom-schema",
|
||||
"code-export",
|
||||
"devtools",
|
||||
"---Experimental---",
|
||||
"jev",
|
||||
"---Integrations---",
|
||||
"ai-sdk",
|
||||
"a2ui",
|
||||
"adaptive-cards",
|
||||
"ag-ui",
|
||||
"openapi",
|
||||
"api"
|
||||
]
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/migration")
|
||||
|
||||
# Migration Guide
|
||||
---
|
||||
title: "Migration Guide"
|
||||
---
|
||||
|
||||
This guide covers breaking changes introduced in v0.6.0 and how to update your code.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/openapi")
|
||||
|
||||
# OpenAPI Integration
|
||||
---
|
||||
title: "OpenAPI Integration"
|
||||
---
|
||||
|
||||
Use json-render to generate dynamic forms and UIs from [OpenAPI/Swagger](https://swagger.io/specification/) schemas.
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/quick-start")
|
||||
|
||||
# Quick Start
|
||||
---
|
||||
title: "Quick Start"
|
||||
---
|
||||
|
||||
Get up and running with json-render in 5 minutes.
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/registry")
|
||||
---
|
||||
title: "Registry"
|
||||
---
|
||||
|
||||
# Registry
|
||||
|
||||
A registry maps your [catalog](/docs/catalog) definitions to platform-specific implementations. The catalog defines *what* AI can generate — the registry provides the *how*.
|
||||
A registry maps your [catalog](/docs/catalog) definitions to platform-specific implementations. The catalog defines _what_ AI can generate; the registry provides the _how_.
|
||||
|
||||
What a registry contains depends on the schema you use. Each package defines its own schema, which determines the shape of both the catalog and the registry.
|
||||
|
||||
@@ -19,8 +18,8 @@ What a registry contains depends on the schema you use. Each package defines its
|
||||
Use `defineRegistry` to create a type-safe registry from your catalog. Pass your components, actions, or both:
|
||||
|
||||
```tsx
|
||||
import { defineRegistry } from '@json-render/react';
|
||||
import { myCatalog } from './catalog';
|
||||
import { defineRegistry } from "@json-render/react";
|
||||
import { myCatalog } from "./catalog";
|
||||
|
||||
export const { registry, handlers, executeAction } = defineRegistry(myCatalog, {
|
||||
components: {
|
||||
@@ -33,16 +32,14 @@ export const { registry, handlers, executeAction } = defineRegistry(myCatalog, {
|
||||
),
|
||||
|
||||
Button: ({ props, emit }) => (
|
||||
<button onClick={() => emit("press")}>
|
||||
{props.label}
|
||||
</button>
|
||||
<button onClick={() => emit("press")}>{props.label}</button>
|
||||
),
|
||||
},
|
||||
|
||||
actions: {
|
||||
submit_form: async (params, setState) => {
|
||||
const res = await fetch('/api/submit', {
|
||||
method: 'POST',
|
||||
const res = await fetch("/api/submit", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(params),
|
||||
});
|
||||
const result = await res.json();
|
||||
@@ -69,23 +66,36 @@ Each component receives a `ComponentContext` object:
|
||||
|
||||
```typescript
|
||||
interface ComponentContext {
|
||||
props: T; // Type-safe props from your catalog
|
||||
children?: React.ReactNode; // Rendered children (for slot components)
|
||||
emit: (event: string) => void; // Emit a named event (always defined)
|
||||
on: (event: string) => EventHandle; // Get event handle with metadata
|
||||
loading?: boolean; // Whether the renderer is in a loading state
|
||||
bindings?: Record<string, string>; // State paths from $bindState/$bindItem expressions
|
||||
props: T; // Type-safe props from your catalog
|
||||
children?: React.ReactNode; // Rendered children (for slot components)
|
||||
slots?: Record<string, React.ReactNode>; // Rendered named slots
|
||||
emit: (event: string) => void; // Emit a named event (always defined)
|
||||
on: (event: string) => EventHandle; // Get event handle with metadata
|
||||
loading?: boolean; // Whether the renderer is in a loading state
|
||||
bindings?: Record<string, string>; // State paths from $bindState/$bindItem expressions
|
||||
}
|
||||
|
||||
interface EventHandle {
|
||||
emit: () => void; // Fire the event
|
||||
emit: () => void; // Fire the event
|
||||
shouldPreventDefault: boolean; // Whether any binding requested preventDefault
|
||||
bound: boolean; // Whether any handler is bound
|
||||
bound: boolean; // Whether any handler is bound
|
||||
}
|
||||
```
|
||||
|
||||
Props are automatically inferred from your catalog, so `props.title` is typed as `string` if your catalog defines it that way.
|
||||
|
||||
For components with named slots, read the default content from `children` and other regions from `slots`:
|
||||
|
||||
```tsx
|
||||
Layout: ({ children, slots }) => (
|
||||
<div>
|
||||
<header>{slots?.header}</header>
|
||||
<main>{children}</main>
|
||||
<footer>{slots?.footer}</footer>
|
||||
</div>
|
||||
),
|
||||
```
|
||||
|
||||
Use `emit("press")` for simple event firing. Use `on("click")` when you need to inspect event metadata:
|
||||
|
||||
```tsx
|
||||
@@ -128,27 +138,29 @@ TextInput: ({ props, bindings }) => {
|
||||
|
||||
### Action Handlers
|
||||
|
||||
Instead of AI generating arbitrary code, it declares *intent* by name. Your application provides the implementation. This is a core guardrail.
|
||||
Instead of AI generating arbitrary code, it declares _intent_ by name. Your application provides the implementation. This is a core guardrail.
|
||||
|
||||
Actions are declared in your [catalog](/docs/catalog). The `@json-render/react` schema supports an `actions` key where you define what operations AI can trigger:
|
||||
|
||||
```typescript
|
||||
import { defineCatalog } from '@json-render/core';
|
||||
import { schema } from '@json-render/react/schema';
|
||||
import { z } from 'zod';
|
||||
import { defineCatalog } from "@json-render/core";
|
||||
import { schema } from "@json-render/react/schema";
|
||||
import { z } from "zod";
|
||||
|
||||
const catalog = defineCatalog(schema, {
|
||||
components: { /* ... */ },
|
||||
components: {
|
||||
/* ... */
|
||||
},
|
||||
actions: {
|
||||
submit_form: {
|
||||
params: z.object({
|
||||
formId: z.string(),
|
||||
}),
|
||||
description: 'Submit a form',
|
||||
description: "Submit a form",
|
||||
},
|
||||
export_data: {
|
||||
params: z.object({
|
||||
format: z.enum(['csv', 'pdf', 'json']),
|
||||
format: z.enum(["csv", "pdf", "json"]),
|
||||
}),
|
||||
},
|
||||
navigate: {
|
||||
@@ -166,8 +178,8 @@ Action handlers receive `(params, setState, state)` and are defined inside `defi
|
||||
export const { handlers, executeAction } = defineRegistry(catalog, {
|
||||
actions: {
|
||||
submit_form: async (params, setState) => {
|
||||
const response = await fetch('/api/submit', {
|
||||
method: 'POST',
|
||||
const response = await fetch("/api/submit", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ formId: params.formId }),
|
||||
});
|
||||
const result = await response.json();
|
||||
@@ -219,14 +231,14 @@ For read-only state access (e.g. displaying a value from state), use `$state` ex
|
||||
Wire everything together with providers and the `<Renderer />` component:
|
||||
|
||||
```tsx
|
||||
import { useMemo, useRef } from 'react';
|
||||
import { useMemo, useRef } from "react";
|
||||
import {
|
||||
Renderer,
|
||||
StateProvider,
|
||||
VisibilityProvider,
|
||||
ActionProvider,
|
||||
} from '@json-render/react';
|
||||
import { registry, handlers } from './registry';
|
||||
} from "@json-render/react";
|
||||
import { registry, handlers } from "./registry";
|
||||
|
||||
function App({ spec, state, setState }) {
|
||||
const stateRef = useRef(state);
|
||||
@@ -235,7 +247,11 @@ function App({ spec, state, setState }) {
|
||||
setStateRef.current = setState;
|
||||
|
||||
const actionHandlers = useMemo(
|
||||
() => handlers(() => setStateRef.current, () => stateRef.current),
|
||||
() =>
|
||||
handlers(
|
||||
() => setStateRef.current,
|
||||
() => stateRef.current,
|
||||
),
|
||||
[],
|
||||
);
|
||||
|
||||
@@ -256,8 +272,8 @@ function App({ spec, state, setState }) {
|
||||
`@json-render/react-native` uses the same `defineRegistry` API. The only difference is that components return React Native elements instead of HTML:
|
||||
|
||||
```tsx
|
||||
import { defineRegistry } from '@json-render/react-native';
|
||||
import { View, Text, Pressable } from 'react-native';
|
||||
import { defineRegistry } from "@json-render/react-native";
|
||||
import { View, Text, Pressable } from "react-native";
|
||||
|
||||
export const { registry } = defineRegistry(catalog, {
|
||||
components: {
|
||||
@@ -284,14 +300,14 @@ See the [@json-render/react-native API reference](/docs/api/react-native) for th
|
||||
`@json-render/react-email` uses `defineRegistry` like React and React Native. Components render to React Email primitives (`@react-email/components`). Use `renderToHtml` or `renderToPlainText` for server-side email output:
|
||||
|
||||
```tsx
|
||||
import { defineRegistry } from '@json-render/react-email';
|
||||
import { renderToHtml } from '@json-render/react-email';
|
||||
import { Body, Container, Heading, Text } from '@react-email/components';
|
||||
import { defineRegistry } from "@json-render/react-email";
|
||||
import { renderToHtml } from "@json-render/react-email";
|
||||
import { Body, Container, Heading, Text } from "@react-email/components";
|
||||
|
||||
export const { registry } = defineRegistry(catalog, {
|
||||
components: {
|
||||
Card: ({ props, children }) => (
|
||||
<Container style={{ padding: 16, backgroundColor: '#fff' }}>
|
||||
<Container style={{ padding: 16, backgroundColor: "#fff" }}>
|
||||
<Heading>{props.title}</Heading>
|
||||
{children}
|
||||
</Container>
|
||||
@@ -309,10 +325,10 @@ See the [@json-render/react-email API reference](/docs/api/react-email) for the
|
||||
`@json-render/remotion` takes a different approach. Instead of `defineRegistry`, it uses a plain component registry with built-in standard components for video production:
|
||||
|
||||
```tsx
|
||||
import { Renderer, standardComponents } from '@json-render/remotion';
|
||||
import { Renderer, standardComponents } from "@json-render/remotion";
|
||||
|
||||
// Use the standard components directly
|
||||
<Renderer spec={timelineSpec} components={standardComponents} />
|
||||
<Renderer spec={timelineSpec} components={standardComponents} />;
|
||||
|
||||
// Or extend with your own
|
||||
const components = {
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata";
|
||||
export const metadata = pageMetadata("docs/renderers");
|
||||
|
||||
# Renderers
|
||||
---
|
||||
title: "Renderers"
|
||||
---
|
||||
|
||||
json-render supports multiple output targets. Each renderer takes the same core concept -- a JSON spec constrained to a catalog -- and renders it natively on a different platform or into a different format.
|
||||
|
||||
@@ -62,6 +61,15 @@ All renderers share the same workflow:
|
||||
</td>
|
||||
<td>Native mobile views</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>TanStack Start</td>
|
||||
<td>
|
||||
<code>@json-render/tanstack-start</code>
|
||||
</td>
|
||||
<td>
|
||||
Full React applications with routes, layouts, SSR, and head metadata
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Image</td>
|
||||
<td>
|
||||
@@ -213,6 +221,32 @@ const { registry } = defineRegistry(catalog, { components: {} });
|
||||
|
||||
See the [@json-render/react-native API reference](/docs/api/react-native) for details.
|
||||
|
||||
## TanStack Start
|
||||
|
||||
Define complete TanStack Start applications with route specs, reusable layouts,
|
||||
loader-backed state, head metadata, and prerender paths. The integration uses
|
||||
the React renderer for each page and TanStack Router for navigation.
|
||||
|
||||
```tsx
|
||||
import { createFileRoute, notFound } from "@tanstack/react-router";
|
||||
import { PageRenderer } from "@json-render/tanstack-start";
|
||||
import { createStartApp } from "@json-render/tanstack-start/server";
|
||||
|
||||
const { getPageData, getHead } = createStartApp({ spec });
|
||||
|
||||
export const Route = createFileRoute("/$")({
|
||||
loader: async ({ location }) => {
|
||||
const data = await getPageData({ pathname: location.pathname });
|
||||
if (!data) throw notFound();
|
||||
return data;
|
||||
},
|
||||
head: ({ match }) => getHead({ pathname: match.pathname }),
|
||||
component: () => <PageRenderer {...Route.useLoaderData()} />,
|
||||
});
|
||||
```
|
||||
|
||||
See the [@json-render/tanstack-start API reference](/docs/api/tanstack-start) for details.
|
||||
|
||||
## Image
|
||||
|
||||
Generate SVG and PNG images from JSON specs using Satori. Ideal for OG images, social cards, and banners.
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/schemas")
|
||||
|
||||
# Schemas
|
||||
---
|
||||
title: "Schemas"
|
||||
---
|
||||
|
||||
Schemas define the structure and validation rules for your UI specs.
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata";
|
||||
|
||||
export const metadata = pageMetadata("docs/skills");
|
||||
|
||||
# Skills
|
||||
---
|
||||
title: "Skills"
|
||||
---
|
||||
|
||||
json-render ships with skills that teach AI coding agents how to use each package. Install a skill and your agent in Cursor, Claude Code, or Codex can generate json-render UIs without manual guidance.
|
||||
|
||||
@@ -10,6 +8,12 @@ json-render ships with skills that teach AI coding agents how to use each packag
|
||||
|
||||
- **core** — Core schemas, catalogs, and AI prompt generation.
|
||||
- **react** — React renderer that turns JSON specs into React component trees.
|
||||
- **tanstack-start** — Full TanStack Start applications with routes, layouts, SSR loaders, and head metadata.
|
||||
- **devtools** — Framework-agnostic inspector panel for specs, state, actions, streams, catalogs, and DOM picking.
|
||||
- **devtools-react** — React adapter for the json-render devtools panel.
|
||||
- **devtools-vue** — Vue adapter for the json-render devtools panel.
|
||||
- **devtools-svelte** — Svelte adapter for the json-render devtools panel.
|
||||
- **devtools-solid** — SolidJS adapter for the json-render devtools panel.
|
||||
- **react-pdf** — PDF renderer using `@react-pdf/renderer`.
|
||||
- **react-email** — Email renderer that produces HTML or plain-text emails.
|
||||
- **react-native** — React Native renderer for native mobile UIs.
|
||||
@@ -31,6 +35,12 @@ json-render ships with skills that teach AI coding agents how to use each packag
|
||||
```bash
|
||||
npx skills add vercel-labs/json-render --skill core
|
||||
npx skills add vercel-labs/json-render --skill react
|
||||
npx skills add vercel-labs/json-render --skill tanstack-start
|
||||
npx skills add vercel-labs/json-render --skill devtools
|
||||
npx skills add vercel-labs/json-render --skill devtools-react
|
||||
npx skills add vercel-labs/json-render --skill devtools-vue
|
||||
npx skills add vercel-labs/json-render --skill devtools-svelte
|
||||
npx skills add vercel-labs/json-render --skill devtools-solid
|
||||
npx skills add vercel-labs/json-render --skill react-pdf
|
||||
npx skills add vercel-labs/json-render --skill react-email
|
||||
npx skills add vercel-labs/json-render --skill react-native
|
||||
@@ -58,6 +68,30 @@ The foundational skill. Teaches agents how to define catalogs, create schemas, b
|
||||
|
||||
Teaches agents how to render JSON specs as React component trees using `JsonRender`, `JsonRenderClient`, and `useJsonRender`. Covers custom component registries, client-side interactivity, state management, and streaming integration.
|
||||
|
||||
## tanstack-start
|
||||
|
||||
Teaches agents how to build JSON-defined TanStack Start applications with splat routes, reusable layouts, SSR-safe loaders, head metadata, prerender paths, and client navigation.
|
||||
|
||||
## devtools
|
||||
|
||||
Teaches agents how to add and configure the framework-agnostic json-render devtools panel, including spec inspection, state editing, action and stream timelines, catalog browsing, and DOM picking.
|
||||
|
||||
## devtools-react
|
||||
|
||||
Teaches agents how to mount and control `@json-render/devtools-react` inside a React json-render provider, including the imperative devtools hook.
|
||||
|
||||
## devtools-vue
|
||||
|
||||
Teaches agents how to mount and configure `@json-render/devtools-vue` inside a Vue json-render provider.
|
||||
|
||||
## devtools-svelte
|
||||
|
||||
Teaches agents how to mount and configure `@json-render/devtools-svelte` inside a Svelte 5 json-render provider.
|
||||
|
||||
## devtools-solid
|
||||
|
||||
Teaches agents how to mount and configure `@json-render/devtools-solid` inside a SolidJS json-render provider.
|
||||
|
||||
## react-pdf
|
||||
|
||||
Teaches agents how to generate PDFs from JSON specs using `@react-pdf/renderer`. Covers the PDF-specific component registry, page layout, and styling.
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/specs")
|
||||
|
||||
# Specs
|
||||
---
|
||||
title: "Specs"
|
||||
---
|
||||
|
||||
A spec is a JSON document that describes your UI.
|
||||
|
||||
@@ -60,7 +59,10 @@ A more complex spec with multiple nested elements:
|
||||
},
|
||||
"avatar-1": {
|
||||
"type": "Avatar",
|
||||
"props": { "src": { "$state": "/user/avatar" }, "alt": { "$state": "/user/name" } },
|
||||
"props": {
|
||||
"src": { "$state": "/user/avatar" },
|
||||
"alt": { "$state": "/user/name" }
|
||||
},
|
||||
"children": []
|
||||
},
|
||||
"stack-1": {
|
||||
@@ -102,7 +104,10 @@ A high-level spec using semantic blocks for page layouts:
|
||||
},
|
||||
"header": {
|
||||
"type": "Header",
|
||||
"props": { "logo": "/logo.svg", "navItems": ["Products", "Pricing", "Docs"] },
|
||||
"props": {
|
||||
"logo": "/logo.svg",
|
||||
"navItems": ["Products", "Pricing", "Docs"]
|
||||
},
|
||||
"children": []
|
||||
},
|
||||
"hero": {
|
||||
@@ -122,22 +127,37 @@ A high-level spec using semantic blocks for page layouts:
|
||||
},
|
||||
"feature-1": {
|
||||
"type": "Feature",
|
||||
"props": { "icon": "zap", "title": "Fast", "description": "Render UIs in milliseconds" },
|
||||
"props": {
|
||||
"icon": "zap",
|
||||
"title": "Fast",
|
||||
"description": "Render UIs in milliseconds"
|
||||
},
|
||||
"children": []
|
||||
},
|
||||
"feature-2": {
|
||||
"type": "Feature",
|
||||
"props": { "icon": "shield", "title": "Secure", "description": "Validate all specs against your catalog" },
|
||||
"props": {
|
||||
"icon": "shield",
|
||||
"title": "Secure",
|
||||
"description": "Validate all specs against your catalog"
|
||||
},
|
||||
"children": []
|
||||
},
|
||||
"feature-3": {
|
||||
"type": "Feature",
|
||||
"props": { "icon": "sparkles", "title": "AI-Ready", "description": "Generate prompts from your catalog" },
|
||||
"props": {
|
||||
"icon": "sparkles",
|
||||
"title": "AI-Ready",
|
||||
"description": "Generate prompts from your catalog"
|
||||
},
|
||||
"children": []
|
||||
},
|
||||
"footer": {
|
||||
"type": "Footer",
|
||||
"props": { "copyright": "2025 Acme Inc", "links": ["Privacy", "Terms", "Contact"] },
|
||||
"props": {
|
||||
"copyright": "2025 Acme Inc",
|
||||
"links": ["Privacy", "Terms", "Contact"]
|
||||
},
|
||||
"children": []
|
||||
}
|
||||
}
|
||||
@@ -174,13 +194,18 @@ Each element in the map has a consistent shape:
|
||||
{
|
||||
"type": "ComponentName",
|
||||
"props": { "label": "Hello" },
|
||||
"children": ["child-1", "child-2"]
|
||||
"children": ["child-1", "child-2"],
|
||||
"slots": {
|
||||
"header": ["heading-1"],
|
||||
"footer": ["actions-1"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `type` — Component type from your catalog
|
||||
- `props` — Component properties
|
||||
- `children` — Array of child element keys
|
||||
- `slots`: Optional map of named slots to child element keys. Use `children` for the default slot. Named slot rendering is supported by `@json-render/react` and `@json-render/vue`.
|
||||
|
||||
### Dynamic Data
|
||||
|
||||
@@ -225,12 +250,12 @@ Control when elements appear using the `visible` property:
|
||||
Use `validateSpec` from `@json-render/core` to check a spec for structural issues:
|
||||
|
||||
```typescript
|
||||
import { validateSpec } from '@json-render/core';
|
||||
import { validateSpec } from "@json-render/core";
|
||||
|
||||
const result = validateSpec(spec);
|
||||
|
||||
if (!result.valid) {
|
||||
console.error('Invalid spec:', result.issues);
|
||||
console.error("Invalid spec:", result.issues);
|
||||
}
|
||||
```
|
||||
|
||||
@@ -239,8 +264,12 @@ if (!result.valid) {
|
||||
With `@json-render/react`, wrap the `Renderer` in providers to supply state and visibility:
|
||||
|
||||
```tsx
|
||||
import { Renderer, StateProvider, VisibilityProvider } from '@json-render/react';
|
||||
import { registry } from './registry';
|
||||
import {
|
||||
Renderer,
|
||||
StateProvider,
|
||||
VisibilityProvider,
|
||||
} from "@json-render/react";
|
||||
import { registry } from "./registry";
|
||||
|
||||
function MyApp({ spec, initialState }) {
|
||||
return (
|
||||
@@ -260,20 +289,14 @@ See the [@json-render/react API reference](/docs/api/react) for full provider an
|
||||
With `@json-render/react`, use the `useUIStream` hook to stream specs incrementally:
|
||||
|
||||
```tsx
|
||||
import { useUIStream } from '@json-render/react';
|
||||
import { useUIStream } from "@json-render/react";
|
||||
|
||||
function GenerativeUI() {
|
||||
const { spec, isStreaming } = useUIStream({
|
||||
api: '/api/generate',
|
||||
api: "/api/generate",
|
||||
});
|
||||
|
||||
return (
|
||||
<Renderer
|
||||
spec={spec}
|
||||
registry={registry}
|
||||
loading={isStreaming}
|
||||
/>
|
||||
);
|
||||
return <Renderer spec={spec} registry={registry} loading={isStreaming} />;
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/streaming")
|
||||
|
||||
# Streaming
|
||||
---
|
||||
title: "Streaming"
|
||||
---
|
||||
|
||||
Progressively render UI as AI generates it.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/validation")
|
||||
|
||||
# Validation
|
||||
---
|
||||
title: "Validation"
|
||||
---
|
||||
|
||||
Validate form inputs with built-in and custom functions.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/visibility")
|
||||
|
||||
# Visibility
|
||||
---
|
||||
title: "Visibility"
|
||||
---
|
||||
|
||||
Conditionally show or hide components based on state values and logic.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { pageMetadata } from "@/lib/page-metadata"
|
||||
export const metadata = pageMetadata("docs/watchers")
|
||||
|
||||
# Watchers
|
||||
---
|
||||
title: "Watchers"
|
||||
---
|
||||
|
||||
React to state changes by triggering actions when watched paths update.
|
||||
|
||||
@@ -2,6 +2,7 @@ import { nextJsConfig } from "@internal/eslint-config/next-js";
|
||||
|
||||
/** @type {import("eslint").Linter.Config[]} */
|
||||
export default [
|
||||
{ ignores: [".source/**"] },
|
||||
...nextJsConfig,
|
||||
{
|
||||
rules: {
|
||||
|
||||
@@ -60,6 +60,7 @@ export const docsNavigation: NavSection[] = [
|
||||
title: "Integrations",
|
||||
items: [
|
||||
{ title: "AI SDK", href: "/docs/ai-sdk" },
|
||||
{ title: "Jev (Experimental)", href: "/docs/jev" },
|
||||
{ title: "A2UI", href: "/docs/a2ui" },
|
||||
{ title: "Adaptive Cards", href: "/docs/adaptive-cards" },
|
||||
{ title: "AG-UI", href: "/docs/ag-ui" },
|
||||
@@ -72,6 +73,10 @@ export const docsNavigation: NavSection[] = [
|
||||
{ title: "@json-render/core", href: "/docs/api/core" },
|
||||
{ title: "@json-render/react", href: "/docs/api/react" },
|
||||
{ title: "@json-render/next", href: "/docs/api/next" },
|
||||
{
|
||||
title: "@json-render/tanstack-start",
|
||||
href: "/docs/api/tanstack-start",
|
||||
},
|
||||
{ title: "@json-render/react-pdf", href: "/docs/api/react-pdf" },
|
||||
{ title: "@json-render/react-email", href: "/docs/api/react-email" },
|
||||
{ title: "@json-render/shadcn", href: "/docs/api/shadcn" },
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
const negotiationHeaders = [
|
||||
"Accept",
|
||||
"User-Agent",
|
||||
"Signature-Agent",
|
||||
"Sec-Fetch-Mode",
|
||||
"Sec-Fetch-Dest",
|
||||
"RSC",
|
||||
"Next-Router-Prefetch",
|
||||
"Next-Router-Segment-Prefetch",
|
||||
"Purpose",
|
||||
"Sec-Purpose",
|
||||
];
|
||||
|
||||
export function applyDocsResponseHeaders(headers: Headers) {
|
||||
const tokens = new Map<string, string>();
|
||||
for (const token of [
|
||||
...(headers.get("Vary") ?? "").split(/\s*,\s*/),
|
||||
...negotiationHeaders,
|
||||
]) {
|
||||
if (token) tokens.set(token.toLowerCase(), token);
|
||||
}
|
||||
headers.set("Vary", [...tokens.values()].join(", "));
|
||||
headers.set("Cache-Control", "private, no-store");
|
||||
headers.set("CDN-Cache-Control", "no-store");
|
||||
headers.set("Vercel-CDN-Cache-Control", "no-store");
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { parse } from "yaml";
|
||||
import { allDocsPages } from "./docs-navigation";
|
||||
import { mdxToCleanMarkdown } from "./mdx-to-markdown";
|
||||
import { siteUrl } from "./site";
|
||||
|
||||
export const docsPages = allDocsPages.filter(
|
||||
(page) => page.href === "/docs" || page.href.startsWith("/docs/"),
|
||||
);
|
||||
const inventory = new Map(docsPages.map((page) => [page.href, page]));
|
||||
const pending = new Map<string, Promise<DocsSource>>();
|
||||
|
||||
export type DocsSource = {
|
||||
href: string;
|
||||
title: string;
|
||||
markdown: string;
|
||||
markdownUrl: string;
|
||||
canonicalUrl: string;
|
||||
};
|
||||
|
||||
export function isSafePathSegments(segments: readonly string[]) {
|
||||
return segments.every(
|
||||
(part) =>
|
||||
part.length > 0 &&
|
||||
part !== "." &&
|
||||
part !== ".." &&
|
||||
!part.includes("/") &&
|
||||
!part.includes("\\"),
|
||||
);
|
||||
}
|
||||
|
||||
export function loadDocsSource(pathname: string): Promise<DocsSource> | null {
|
||||
const href = pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
|
||||
if (!inventory.has(href)) return null;
|
||||
let result = pending.get(href);
|
||||
if (!result) {
|
||||
const slug = href === "/docs" ? "index" : href.slice("/docs/".length);
|
||||
result = readFile(
|
||||
join(process.cwd(), "content", "docs", `${slug}.mdx`),
|
||||
"utf8",
|
||||
).then((raw) => {
|
||||
const frontmatter = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/);
|
||||
if (!frontmatter) throw new Error(`Missing frontmatter for ${href}`);
|
||||
const metadata = parse(frontmatter[1] ?? "") as {
|
||||
title?: unknown;
|
||||
} | null;
|
||||
if (typeof metadata?.title !== "string")
|
||||
throw new Error(`Missing title for ${href}`);
|
||||
const title = metadata.title;
|
||||
return {
|
||||
href,
|
||||
title,
|
||||
markdown: mdxToCleanMarkdown(
|
||||
`# ${title}\n${raw.slice(frontmatter[0].length)}`,
|
||||
),
|
||||
markdownUrl: `${href}.md`,
|
||||
canonicalUrl: `${siteUrl}${href}`,
|
||||
};
|
||||
});
|
||||
pending.set(href, result);
|
||||
result.catch(() => pending.delete(href));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function loadAllDocsSources() {
|
||||
return Promise.all(docsPages.map((page) => loadDocsSource(page.href)!));
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { defineConfig } from "@vercel/geistdocs/config";
|
||||
import { siteUrl } from "@/lib/site";
|
||||
|
||||
export const config = defineConfig({
|
||||
title: "json-render",
|
||||
siteUrl,
|
||||
defaultLanguage: "en",
|
||||
logo: <span className="font-medium">json-render</span>,
|
||||
navbarActiveProduct: "json-render",
|
||||
navbarBrand: "labs",
|
||||
github: {
|
||||
owner: "vercel-labs",
|
||||
repo: "json-render",
|
||||
branch: "main",
|
||||
editPath: "apps/web/content/docs",
|
||||
},
|
||||
content: [
|
||||
{ id: "docs", label: "Documentation", dir: "content/docs", route: "/docs" },
|
||||
],
|
||||
nav: [
|
||||
{ label: "Docs", href: "/docs" },
|
||||
{ label: "Playground", href: "/playground" },
|
||||
{ label: "Examples", href: "/examples" },
|
||||
],
|
||||
ai: { enabled: false },
|
||||
feedback: { enabled: false },
|
||||
language: { enabled: false },
|
||||
pageActions: { askAI: false, openInChat: false },
|
||||
webmcp: { enabled: true },
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import {
|
||||
createSource,
|
||||
type GeistdocsSourceBundle,
|
||||
} from "@vercel/geistdocs/source";
|
||||
import { docs } from "@/.source/server";
|
||||
import { loadDocsSource } from "@/lib/docs-source";
|
||||
import { config } from "./config";
|
||||
|
||||
const bundle = createSource({ docs, config, baseUrl: "/docs" });
|
||||
|
||||
export const geistdocsSource: GeistdocsSourceBundle = {
|
||||
...bundle,
|
||||
async getPageMarkdown(page) {
|
||||
const source = await loadDocsSource(
|
||||
`/docs${page.slugs.length ? `/${page.slugs.join("/")}` : ""}`,
|
||||
);
|
||||
if (!source) throw new Error(`Documentation source not found: ${page.url}`);
|
||||
return source.markdown;
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,78 @@
|
||||
# Jev composing catalog UI
|
||||
|
||||
Open **`/playground`** and select **jev** in the **default / jev** toggle. Hover or focus the Jev option with its info icon to read its experimental status. This experiment uses Jev through Vercel AI Gateway to compose a tree and edit it in follow-up requests. It renders with the **actual playground catalog and registry**, including the existing shadcn components, state bindings, validation, and action handlers.
|
||||
|
||||
## Run
|
||||
|
||||
Set `JEV_AI_GATEWAY_API_KEY` in `apps/web/.env.local` or the server environment. The playground uses this dedicated Gateway key for Jev; the default model continues to use `AI_GATEWAY_API_KEY`. Jev does not fall back to the default model's key. The Gateway team must permit the `typesafe-ai` provider. No separate TypeSafe API key is required.
|
||||
|
||||
From the repository root:
|
||||
|
||||
```sh
|
||||
pnpm --filter web dev
|
||||
```
|
||||
|
||||
Use the portless URL printed by the command, followed by `/playground`. With the HTTPS proxy enabled this is `https://json-render.localhost/playground`.
|
||||
|
||||
Select Jev, choose Create account settings, and send the request. Edit the name, switch notifications on, click Save changes, and then Reset. The action handlers run only on user interaction. Form submission validates and shows a toast; it does not authenticate a user or send a message. All business data is synthetic.
|
||||
|
||||
## How Jev produces a spec
|
||||
|
||||
Jev exposes Choice, Boolean, and Score outputs. It does not produce free-form JSON or prose. We express new UI construction as two batches of finite choices:
|
||||
|
||||
1. Offer the root and independent component membership questions in one evaluation. Exclusive resource variants share a question; reusable recipes get bounded counts. Candidate values include state/action bindings owned by the app.
|
||||
2. Assemble and validate the selected content, then stream a preview immediately. This preview uses catalog order and the root's default slot. Root selection takes precedence over speculative membership for the same recipe/resource.
|
||||
3. Ask final parent slots and sibling positions in a second evaluation against the actual selected set. Validate the combined tree, including depth and cycles, before streaming it. Equal positions retain catalog order. A single root or one child in a single slot needs no second call. No separate finish call is needed.
|
||||
4. On follow-ups, use the selected spec with the sequential edit protocol: add, replace, remove, or move/reorder. Replacements and moves select a target, then choose a valid recipe or destination in a second evaluation. Preserve unchanged elements and earlier versions.
|
||||
5. Each trace represents one evaluation. Batched traces use `select`/`layout` with the independent decisions in `answers`; timing and usage are counted once per call. Provider errors or invalid combined layouts preserve the last valid preview and report failure.
|
||||
|
||||
There are **no complete UI templates** and no generative-model calls. The example prompt buttons only populate the request text. Jev chooses which elements to include, their order, grouping, and which offered action bindings to use. The registry owns appearance and behavior.
|
||||
|
||||
Batching avoids a network round trip per component. Jev does not author the serialized JSON; code assembles it from the choices. The public API also supports `strategy: "sequential"` for one-operation-at-a-time creation and existing custom evaluators.
|
||||
|
||||
## What the platform must supply
|
||||
|
||||
A component catalog bounds component names, props, and events, but string and array props still have open-ended values. This example closes that remaining space with platform-owned content and binding recipes:
|
||||
|
||||
- 17 component types from the playground catalog: Card, Stack, Grid, Heading, Avatar, Badge, Input, Textarea, Select, Checkbox, Switch, Button, Text, Metric, BarGraph, Table, and Separator.
|
||||
- Form fields, validation rules, labels, synthetic profile and commerce data, and two allowed catalog actions (`formSubmit` and `setState`). Profile choices include an avatar, display name, role, bio, email, location, and membership badge, bound to the supplied record.
|
||||
- Several useful values for layout props and button labels. Quoted titles in the request are copied into additional Heading choices.
|
||||
|
||||
These are **atomic element candidates**, not page templates. A host application could build them from its actual data schema, records, localized copy, and permitted operations. This example supplies those values in `grammar.ts`; apps supply their own candidates to the reusable core API. Repeating the same field in multiple forms and arbitrary new text/data are not supported.
|
||||
|
||||
Each candidate also fixes a component configuration. The prepared revenue BarGraph can be selected and moved, but choosing a LineGraph requires another candidate. Apps can bind props to their live state or build candidates per request; data need not be hardcoded. Jev determines the tree, grouping, and section order within those offered configurations.
|
||||
|
||||
## Limits
|
||||
|
||||
The composer validates tree structure and candidate values; it does not guarantee that Jev chose the right UI. Root selection, grouping, and deciding when to stop require planning, which is a documented weakness of Jev. Confidence is displayed without a quality gate: multiple layout choices may be reasonable, and a universal threshold has not been calibrated.
|
||||
|
||||
Name required sections explicitly. For example, request an orders table at the top, revenue/orders/customer metrics in a row, then a weekly revenue chart. The shorter request "a dashboard with the table at the top" can select only a table. Follow-up requests can move an existing table without reconstructing its data.
|
||||
|
||||
The code bounds new batches to 14 elements, each request to 14 evaluation calls, nesting depth four, ten seconds per provider request, and 55 seconds overall. The selected seed may contain up to 100 elements. A limit, cancellation, or error retains the current preview and labels it partial. The shared endpoint uses the web app's request rate limiters. Both models edit the selected version; Clear starts fresh. The stream tab exposes construction decisions alongside spec patches. Provider calls and spec assembly never execute the selected UI actions.
|
||||
|
||||
Try `Design a user profile card`, then `Remove the bio` or `Make the avatar smaller`. For settings, try `Remove the email notifications switch`, `Change the heading to "Account settings"`, or `Move the email field above the name field`. The server shares existing display labels and matching candidate descriptions to identify edit targets, without sharing raw state or entered field values. Existing specs must use the supported expression subset and form a valid tree. Edits retain state from the selected spec, as in the default model flow; interactive preview state is not saved into version history.
|
||||
|
||||
|
||||
## Transport and files
|
||||
|
||||
The server uses Gateway's experimental v4 evaluation transport with model `typesafe-ai/jev`. This was verified against `@ai-sdk/gateway@4.0.85`. Native fetch avoids upgrading the workspace's AI SDK 6 dependencies or bypassing its minimum release age. The protocol can change; migrate to the eligible AI SDK evaluation API with a plain model string when appropriate.
|
||||
|
||||
- `grammar.ts`: playground-owned values and atomic candidates.
|
||||
- `packages/core/src/experimental-compose.ts`: public provider-independent composer.
|
||||
- `packages/core/src/experimental-composition-batch.ts`: parallel membership and layout decisions for new trees.
|
||||
- `packages/core/src/experimental-composition-tree.ts`: internal seed validation and tree edit helpers.
|
||||
- `packages/core/src/experimental-evaluator.ts`: public Gateway evaluator adapter.
|
||||
- `compose.ts`: public API consumer with playground instructions and cost display.
|
||||
- `../../app/api/generate/route.ts`: shared rate-limited endpoint, dispatching the selected model.
|
||||
- `response.ts`: adapts composition snapshots into the playground's JSONL spec patches and decision metadata.
|
||||
- `../../components/playground.tsx`: shared model toggle, experimental info tooltip, prompt, version history, live preview, and inspectors.
|
||||
- `compose.test.ts`: structure, action boundaries, unknown usage, cancellation, and limits.
|
||||
|
||||
```sh
|
||||
pnpm exec vitest run packages/core/src/experimental-compose.test.ts packages/core/src/experimental-evaluator.test.ts apps/web/lib/jev/compose.test.ts
|
||||
pnpm type-check
|
||||
```
|
||||
|
||||
References: [Jev on Gateway](https://vercel.com/ai-gateway/models/jev), [AI SDK evaluation](https://ai-sdk.dev/docs/ai-sdk-core/evaluation), [Jev's documented limits](https://docs.typesafe.ai/model-jaggedness/jev-1.13).
|
||||
|
||||
For app integration and source-build installation, see the [Jev guide](https://json-render.dev/docs/jev). The `experimental_` APIs may change in any release; pin exact versions.
|
||||
@@ -0,0 +1,306 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { composeUI, type CompositionEvent, type Evaluate } from "./compose";
|
||||
import { buildCandidates, MAX_ELEMENTS } from "./grammar";
|
||||
|
||||
function scripted(
|
||||
choices: { next: string; parent?: string }[],
|
||||
usage: number | undefined = 100,
|
||||
): Evaluate {
|
||||
let index = 0;
|
||||
return async ({ questions, state }) => {
|
||||
if (
|
||||
questions.root ||
|
||||
Object.keys(questions).some((name) => name.startsWith("order_"))
|
||||
) {
|
||||
const candidates = buildCandidates(String(state.user_request));
|
||||
const selected = state.selected_elements as
|
||||
| { id: string; content: string }[]
|
||||
| undefined;
|
||||
const idFor = (candidateId: string) =>
|
||||
selected?.find(
|
||||
(element) =>
|
||||
element.content ===
|
||||
candidates.find((c) => c.id === candidateId)?.description,
|
||||
)?.id;
|
||||
const answers = Object.fromEntries(
|
||||
Object.entries(questions).map(([name, question]) => {
|
||||
let choice: string;
|
||||
if (name === "root") choice = choices[0]!.next;
|
||||
else if (name.startsWith("select_")) {
|
||||
if (Object.hasOwn(question.criteria, "0")) {
|
||||
const candidate = candidates.find((c) =>
|
||||
question.instructions.includes(c.description),
|
||||
)!;
|
||||
choice = String(
|
||||
choices.filter((c) => c.next === candidate.id).length,
|
||||
);
|
||||
} else {
|
||||
choice =
|
||||
choices
|
||||
.map((c) => `use:${c.next}`)
|
||||
.find((key) => Object.hasOwn(question.criteria, key)) ??
|
||||
"omit";
|
||||
}
|
||||
} else {
|
||||
const id = name.replace(/^(parent|order)_/, "");
|
||||
const element = selected!.find((e) => e.id === id)!;
|
||||
const candidate = candidates.find(
|
||||
(c) => c.description === element.content,
|
||||
)!;
|
||||
const at = choices.findIndex((c) => c.next === candidate.id);
|
||||
const fixture = choices[at]!;
|
||||
if (name.startsWith("order_")) choice = String(at);
|
||||
else if (fixture.parent?.startsWith("node_")) {
|
||||
const originalParent =
|
||||
choices[Number(fixture.parent.slice(5))]!.next;
|
||||
choice = `${idFor(originalParent)}:default`;
|
||||
} else choice = fixture.parent ?? "node_0:default";
|
||||
}
|
||||
return [name, { choice, confidence: 0.9 }];
|
||||
}),
|
||||
);
|
||||
return { answers, usage: { inputTokens: usage } };
|
||||
}
|
||||
const selected = choices[index++];
|
||||
if (!selected) throw new Error("Unexpected extra model call");
|
||||
const answers = Object.fromEntries(
|
||||
Object.keys(questions).map((name) => [
|
||||
name,
|
||||
{
|
||||
confidence: 0.9,
|
||||
choice: selected[name as keyof typeof selected]!,
|
||||
},
|
||||
]),
|
||||
);
|
||||
return {
|
||||
answers,
|
||||
usage: { inputTokens: usage },
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
async function collect(
|
||||
evaluate: Evaluate,
|
||||
signal = new AbortController().signal,
|
||||
) {
|
||||
const events: CompositionEvent[] = [];
|
||||
for await (const event of composeUI(
|
||||
'Create settings titled "Preferences".',
|
||||
signal,
|
||||
evaluate,
|
||||
))
|
||||
events.push(event);
|
||||
return events;
|
||||
}
|
||||
|
||||
describe("Jev catalog composition", () => {
|
||||
it("composes profile display content and identifies bound content for follow-up edits", async () => {
|
||||
const events: CompositionEvent[] = [];
|
||||
for await (const event of composeUI(
|
||||
"Design a user profile card",
|
||||
new AbortController().signal,
|
||||
scripted([
|
||||
{ next: "card" },
|
||||
{ next: "profile_avatar_lg" },
|
||||
{ next: "profile_name" },
|
||||
{ next: "profile_role" },
|
||||
{ next: "profile_bio" },
|
||||
{ next: "finish" },
|
||||
]),
|
||||
))
|
||||
events.push(event);
|
||||
const first = events.at(-1)!;
|
||||
if (first.type !== "complete") throw new Error("Missing profile spec");
|
||||
const initialSpec = first.spec!;
|
||||
expect(
|
||||
Object.values(initialSpec.elements).map((element) => element.type),
|
||||
).toEqual(["Card", "Avatar", "Heading", "Text", "Text"]);
|
||||
expect(initialSpec.elements.node_2!.props.text).toEqual({
|
||||
$state: "/profile/name",
|
||||
});
|
||||
expect(initialSpec.state?.profile).toMatchObject({ name: "Maya Chen" });
|
||||
|
||||
// Editing must identify a bound Text by its meaning without sending its value.
|
||||
initialSpec.state!.profile = {
|
||||
...(initialSpec.state!.profile as Record<string, unknown>),
|
||||
bio: "Private profile biography",
|
||||
};
|
||||
const before = structuredClone(initialSpec);
|
||||
const choose = scripted([{ next: "remove:node_4" }, { next: "finish" }]);
|
||||
let calls = 0;
|
||||
for await (const event of composeUI(
|
||||
"Remove the bio",
|
||||
new AbortController().signal,
|
||||
async (request) => {
|
||||
if (calls++ === 0) {
|
||||
expect(request.questions.next!.criteria["remove:node_4"]).toContain(
|
||||
"biography",
|
||||
);
|
||||
expect(request.questions.next!.criteria["remove:node_3"]).toContain(
|
||||
"job title or role",
|
||||
);
|
||||
}
|
||||
expect(JSON.stringify(request)).not.toContain(
|
||||
"Private profile biography",
|
||||
);
|
||||
return choose(request);
|
||||
},
|
||||
initialSpec,
|
||||
))
|
||||
events.push(event);
|
||||
const edited = events.at(-1)!;
|
||||
if (edited.type !== "complete") throw new Error("Missing edited profile");
|
||||
expect(edited.spec!.elements).not.toHaveProperty("node_4");
|
||||
expect(edited.spec!.elements.node_3).toEqual(initialSpec.elements.node_3);
|
||||
expect(edited.spec!.state).toEqual(initialSpec.state);
|
||||
expect(initialSpec).toEqual(before);
|
||||
});
|
||||
|
||||
it("supports follow-up removal and replacement while preserving the selected version", async () => {
|
||||
const first = (
|
||||
await collect(
|
||||
scripted([
|
||||
{ next: "card" },
|
||||
{ next: "heading_7" },
|
||||
{ next: "input_email" },
|
||||
{ next: "notifications_switch" },
|
||||
{ next: "finish" },
|
||||
]),
|
||||
)
|
||||
).at(-1)!;
|
||||
if (first.type !== "complete") throw new Error("Missing completed spec");
|
||||
const initialSpec = first.spec!;
|
||||
const before = structuredClone(initialSpec);
|
||||
const events: CompositionEvent[] = [];
|
||||
for await (const event of composeUI(
|
||||
'Remove email notifications and change the heading to "Contact us".',
|
||||
new AbortController().signal,
|
||||
scripted([
|
||||
{ next: "remove:node_3" },
|
||||
{ next: "replace:node_1" },
|
||||
{ next: "heading_1" },
|
||||
{ next: "finish" },
|
||||
]),
|
||||
initialSpec,
|
||||
))
|
||||
events.push(event);
|
||||
const last = events.at(-1)!;
|
||||
if (last.type !== "complete") throw new Error("Missing edited spec");
|
||||
expect(last.spec!.elements.node_1!.props.text).toBe("Contact us");
|
||||
expect(last.spec!.elements).not.toHaveProperty("node_3");
|
||||
expect(last.spec!.elements.node_2).toEqual(initialSpec.elements.node_2);
|
||||
expect(initialSpec).toEqual(before);
|
||||
});
|
||||
|
||||
it("composes a new nested tree with state bindings and catalog actions", async () => {
|
||||
const events = await collect(
|
||||
scripted([
|
||||
{ next: "card" },
|
||||
{ next: "input_email" },
|
||||
{ next: "stack_horizontal" },
|
||||
{ next: "save", parent: "node_2" },
|
||||
{ next: "reset", parent: "node_2" },
|
||||
{ next: "status", parent: "node_0" },
|
||||
{ next: "finish", parent: "node_0" },
|
||||
]),
|
||||
);
|
||||
const result = events.at(-1)!;
|
||||
expect(result.type).toBe("complete");
|
||||
if (result.type !== "complete") throw new Error("Missing final result");
|
||||
expect(result.stopReason).toBe("finish");
|
||||
expect(result.spec?.elements.node_0?.children).toEqual([
|
||||
"node_2",
|
||||
"node_1",
|
||||
"node_5",
|
||||
]);
|
||||
expect(result.spec?.elements.node_1?.children).toEqual([
|
||||
"node_3",
|
||||
"node_4",
|
||||
]);
|
||||
expect(result.spec?.elements.node_2?.props.value).toEqual({
|
||||
$bindState: "/form/email",
|
||||
});
|
||||
expect(result.spec?.elements.node_3?.on?.press).toEqual({
|
||||
action: "setState",
|
||||
params: { statePath: "/status", value: "Changes saved locally." },
|
||||
});
|
||||
expect(result.inputTokens).toBe(200);
|
||||
expect(result.steps).toHaveLength(2);
|
||||
// Streamed snapshots stay immutable as later elements are appended.
|
||||
const first = events[0]!;
|
||||
expect(first.type === "step" && Object.keys(first.spec.elements)).toEqual([
|
||||
"node_0",
|
||||
"node_1",
|
||||
"node_2",
|
||||
"node_3",
|
||||
"node_4",
|
||||
"node_5",
|
||||
]);
|
||||
});
|
||||
|
||||
it("cannot accept an arbitrary component, path, or nonexistent parent from the model", async () => {
|
||||
await expect(
|
||||
collect(scripted([{ next: "execute_shell" }])),
|
||||
).rejects.toThrow("outside the permitted");
|
||||
await expect(
|
||||
collect(
|
||||
scripted([
|
||||
{ next: "card" },
|
||||
{ next: "stack_horizontal" },
|
||||
{ next: "save", parent: "/secrets" },
|
||||
]),
|
||||
),
|
||||
).rejects.toThrow("outside the permitted");
|
||||
});
|
||||
|
||||
it("supplies literal quoted text as a value, never as executable structure", () => {
|
||||
const text = "<script>alert(1)</script>";
|
||||
const candidates = buildCandidates(`Title the UI "${text}".`);
|
||||
expect(
|
||||
candidates.find((c) => c.element.props.text === text)?.element.type,
|
||||
).toBe("Heading");
|
||||
});
|
||||
|
||||
it("reports unavailable capability without producing a misleading empty UI", async () => {
|
||||
const events = await collect(scripted([{ next: "unavailable" }]));
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]).toMatchObject({
|
||||
type: "complete",
|
||||
spec: null,
|
||||
stopReason: "unavailable",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves unknown usage and stops at the configured call budget", async () => {
|
||||
const events = await collect(
|
||||
scripted([{ next: "card" }, { next: "finish" }], undefined),
|
||||
);
|
||||
// Explicitly remove usage to exercise the missing-usage path.
|
||||
const missingUsage: Evaluate = async (request) => {
|
||||
const result = await scripted([{ next: "unavailable" }])(request);
|
||||
return { ...result, usage: undefined };
|
||||
};
|
||||
expect((await collect(missingUsage)).at(-1)).toMatchObject({
|
||||
inputTokens: null,
|
||||
estimatedCostUsd: null,
|
||||
});
|
||||
expect(events.at(-1)?.type).toBe("complete");
|
||||
const choices = [
|
||||
{ next: "card" },
|
||||
...Array.from({ length: MAX_ELEMENTS }, () => ({
|
||||
next: "separator",
|
||||
})),
|
||||
];
|
||||
const limited = (await collect(scripted(choices))).at(-1);
|
||||
expect(limited).toMatchObject({ type: "complete", stopReason: "limit" });
|
||||
if (limited?.type === "complete")
|
||||
expect(Object.keys(limited.spec!.elements)).toHaveLength(MAX_ELEMENTS);
|
||||
});
|
||||
|
||||
it("honors cancellation before making another provider request", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
await expect(collect(scripted([]), controller.signal)).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import {
|
||||
experimental_composeSpec,
|
||||
experimental_createEvaluator,
|
||||
type Experimental_CompositionEvaluator,
|
||||
type Experimental_CompositionEvent,
|
||||
type Experimental_CompositionStep,
|
||||
type Spec,
|
||||
} from "@json-render/core";
|
||||
import { playgroundCatalog } from "../render/catalog";
|
||||
import { buildCandidates, MAX_ELEMENTS, platformState } from "./grammar";
|
||||
|
||||
export type Evaluate = Experimental_CompositionEvaluator;
|
||||
export type TraceStep = Experimental_CompositionStep;
|
||||
export type CompositionEvent =
|
||||
| Extract<Experimental_CompositionEvent, { type: "step" }>
|
||||
| (Extract<Experimental_CompositionEvent, { type: "complete" }> & {
|
||||
estimatedCostUsd: number | null;
|
||||
})
|
||||
| { type: "error"; message: string };
|
||||
|
||||
/** The playground supplies its own content and recipes to the public API. */
|
||||
export async function* composeUI(
|
||||
prompt: string,
|
||||
signal: AbortSignal,
|
||||
evaluate: Evaluate = experimental_createEvaluator({
|
||||
model: "typesafe-ai/jev",
|
||||
apiKey: process.env.JEV_AI_GATEWAY_API_KEY ?? "",
|
||||
}),
|
||||
initialSpec?: Spec,
|
||||
): AsyncGenerator<CompositionEvent> {
|
||||
for await (const event of experimental_composeSpec({
|
||||
catalog: playgroundCatalog,
|
||||
candidates: buildCandidates(prompt),
|
||||
initialSpec,
|
||||
initialState: { ...platformState, ...initialSpec?.state },
|
||||
// Share display copy needed to identify an existing element, never field
|
||||
// values, raw binding recipes, action params, or renderer state.
|
||||
elementDescriptions:
|
||||
initialSpec &&
|
||||
Object.fromEntries(
|
||||
Object.entries(initialSpec.elements).flatMap(([id, element]) => {
|
||||
const labels = [
|
||||
"title",
|
||||
"text",
|
||||
"label",
|
||||
"name",
|
||||
"direction",
|
||||
].flatMap((key) =>
|
||||
typeof element.props[key] === "string"
|
||||
? [`${key}: ${JSON.stringify(element.props[key])}`]
|
||||
: [],
|
||||
);
|
||||
// Let the composer use the matching candidate's description for
|
||||
// bound content, so edits can distinguish e.g. profile bio and email.
|
||||
return labels.length
|
||||
? [[id, [element.type, ...labels].join("; ")]]
|
||||
: [];
|
||||
}),
|
||||
),
|
||||
prompt,
|
||||
signal,
|
||||
evaluate,
|
||||
maxSteps: MAX_ELEMENTS,
|
||||
maxElements: MAX_ELEMENTS,
|
||||
maxDepth: 4,
|
||||
context: {
|
||||
platform:
|
||||
"Available: a synthetic user profile (avatar, display name, role, biography, email, location, membership badge); account/contact fields (name, email, password, message, topic, remember-me, notifications); form submit/save/reset demo actions; synthetic sales revenue, orders, customers, a weekly revenue chart, and order-status table. Quoted titles may be copied from the request. Actions run on later user interaction. Submission is a validation/toast demo, not an authentication or messaging service.",
|
||||
},
|
||||
instructions: {
|
||||
root: "Use Card for a compact form or profile card. Use vertical Stack for a page with a heading and several sections, including a dashboard containing a metric row followed by charts or tables. Use Grid as root only when the entire page is one uniform grid of peers.",
|
||||
next: "Include a Grid or horizontal Stack for a requested side-by-side group. Include only requested content or conventional essentials (login needs email, password, and submit; a profile card displays avatar, name, role, and bio). Use display elements for viewing data and form fields when the user asks to enter or edit data. Prefer a compact tree. Do not include an extra vertical Stack inside a Card unless an explicit subgroup needs it.",
|
||||
parent:
|
||||
"Never put headings or form fields inside a horizontal button row. Choose the root for a new top-level section.",
|
||||
},
|
||||
})) {
|
||||
if (event.type === "complete") {
|
||||
yield {
|
||||
...event,
|
||||
estimatedCostUsd:
|
||||
event.inputTokens === null ? null : (event.inputTokens * 0.042) / 1e6,
|
||||
};
|
||||
} else yield event;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
import type {
|
||||
Experimental_CompositionCandidate,
|
||||
UIElement,
|
||||
} from "@json-render/core";
|
||||
|
||||
export const MAX_ELEMENTS = 14;
|
||||
export type Candidate = Experimental_CompositionCandidate;
|
||||
|
||||
const fieldValues = {
|
||||
name: "",
|
||||
email: "",
|
||||
password: "",
|
||||
message: "",
|
||||
topic: "General",
|
||||
notifications: false,
|
||||
remember: false,
|
||||
};
|
||||
export const platformState = {
|
||||
form: fieldValues,
|
||||
status: "No changes saved yet.",
|
||||
profile: {
|
||||
name: "Maya Chen",
|
||||
role: "Product designer",
|
||||
bio: "Designing thoughtful tools that make everyday work simpler.",
|
||||
email: "maya@example.com",
|
||||
location: "Portland, OR",
|
||||
membership: "Pro member",
|
||||
},
|
||||
};
|
||||
|
||||
/** Prop values are platform content, never model-invented strings or code. */
|
||||
export function buildCandidates(prompt: string): Candidate[] {
|
||||
const candidates: Candidate[] = [];
|
||||
function add(
|
||||
id: string,
|
||||
description: string,
|
||||
type: string,
|
||||
props: Record<string, unknown>,
|
||||
resource?: string,
|
||||
on?: UIElement["on"],
|
||||
) {
|
||||
candidates.push({
|
||||
id,
|
||||
description,
|
||||
resource,
|
||||
root: ["card", "stack_vertical", "grid_two", "grid_three"].includes(id),
|
||||
maxUses: ["Card", "Stack", "Grid", "Separator"].includes(type)
|
||||
? MAX_ELEMENTS
|
||||
: 1,
|
||||
element: { type, props, ...(on ? { on } : {}) },
|
||||
});
|
||||
}
|
||||
add(
|
||||
"card",
|
||||
"Card: a bordered container for a compact form or related content.",
|
||||
"Card",
|
||||
{ title: null, description: null, maxWidth: "md", centered: true },
|
||||
);
|
||||
add(
|
||||
"stack_vertical",
|
||||
"Stack: vertical layout for a page or section.",
|
||||
"Stack",
|
||||
{ direction: "vertical", gap: "md", align: "stretch", justify: "start" },
|
||||
);
|
||||
add(
|
||||
"stack_horizontal",
|
||||
"Stack: horizontal row for two or more explicitly requested side-by-side elements, such as Save and Reset buttons. Not needed for a single button or an ordinary vertical form.",
|
||||
"Stack",
|
||||
{ direction: "horizontal", gap: "sm", align: "center", justify: "start" },
|
||||
);
|
||||
add("grid_two", "Grid: two equal columns for side-by-side content.", "Grid", {
|
||||
columns: 2,
|
||||
gap: "md",
|
||||
});
|
||||
add(
|
||||
"grid_three",
|
||||
"Grid: three equal columns, e.g. a row of metrics.",
|
||||
"Grid",
|
||||
{ columns: 3, gap: "md" },
|
||||
);
|
||||
|
||||
const titles = [
|
||||
"Sign in",
|
||||
"Contact us",
|
||||
"Account settings",
|
||||
"Sales overview",
|
||||
"Customer overview",
|
||||
"Create account",
|
||||
"Support request",
|
||||
];
|
||||
// Quoted labels are copied from the request; Jev can select them without generating text.
|
||||
const quoted = [...prompt.matchAll(/["“]([^"”\n]{1,80})["”]/g)].map(
|
||||
(match) => match[1]!,
|
||||
);
|
||||
for (const [index, text] of [...new Set([...titles, ...quoted])]
|
||||
.slice(0, 12)
|
||||
.entries()) {
|
||||
add(
|
||||
`heading_${index}`,
|
||||
`Heading with the exact text ${JSON.stringify(text)}. Include only when this is the requested title or heading; quoted field values and biography text are not headings.`,
|
||||
"Heading",
|
||||
{ text, level: "h2" },
|
||||
`text:${text}`,
|
||||
);
|
||||
}
|
||||
for (const size of ["lg", "md", "sm"] as const) {
|
||||
add(
|
||||
`profile_avatar_${size}`,
|
||||
`Avatar: ${size === "lg" ? "large" : size === "md" ? "medium" : "small"} profile avatar with initials from the user's name. Use large for a profile card unless another size is requested.`,
|
||||
"Avatar",
|
||||
{ src: null, name: { $state: "/profile/name" }, size },
|
||||
"data:profile_avatar",
|
||||
);
|
||||
}
|
||||
add(
|
||||
"profile_name",
|
||||
"Heading: display the user's profile name as read-only text.",
|
||||
"Heading",
|
||||
{ text: { $state: "/profile/name" }, level: "h2" },
|
||||
"data:profile_name",
|
||||
);
|
||||
for (const [field, description, variant] of [
|
||||
["role", "job title or role", "lead"],
|
||||
["bio", "short biography or about text", "body"],
|
||||
["email", "email address", "muted"],
|
||||
["location", "location", "muted"],
|
||||
] as const) {
|
||||
add(
|
||||
`profile_${field}`,
|
||||
`Text: display the user's profile ${description} as read-only text.`,
|
||||
"Text",
|
||||
{ text: { $state: `/profile/${field}` }, variant },
|
||||
`data:profile_${field}`,
|
||||
);
|
||||
}
|
||||
add(
|
||||
"profile_membership",
|
||||
"Badge: display the user's profile membership status.",
|
||||
"Badge",
|
||||
{ text: { $state: "/profile/membership" }, variant: "default" },
|
||||
"data:profile_membership",
|
||||
);
|
||||
for (const [name, label, type] of [
|
||||
["name", "Full name", "text"],
|
||||
["email", "Email", "email"],
|
||||
["password", "Password", "password"],
|
||||
] as const) {
|
||||
add(
|
||||
`input_${name}`,
|
||||
`Input: editable ${label.toLowerCase()} field. ${name === "password" ? "For sign-in or account creation." : ""}`,
|
||||
"Input",
|
||||
{
|
||||
name,
|
||||
label,
|
||||
type,
|
||||
placeholder: null,
|
||||
value: { $bindState: `/form/${name}` },
|
||||
checks: [
|
||||
{ type: "required", message: `${label} is required.` },
|
||||
...(type === "email"
|
||||
? [{ type: "email", message: "Enter a valid email address." }]
|
||||
: []),
|
||||
],
|
||||
},
|
||||
`field:${name}`,
|
||||
);
|
||||
}
|
||||
add(
|
||||
"message",
|
||||
"Textarea: editable multi-line message or support inquiry.",
|
||||
"Textarea",
|
||||
{
|
||||
name: "message",
|
||||
label: "Message",
|
||||
placeholder: null,
|
||||
rows: 4,
|
||||
value: { $bindState: "/form/message" },
|
||||
checks: [{ type: "required", message: "Enter a message." }],
|
||||
},
|
||||
"field:message",
|
||||
);
|
||||
add(
|
||||
"topic",
|
||||
"Select: choose a contact topic from General, Billing, Technical.",
|
||||
"Select",
|
||||
{
|
||||
name: "topic",
|
||||
label: "Topic",
|
||||
options: ["General", "Billing", "Technical"],
|
||||
placeholder: null,
|
||||
value: { $bindState: "/form/topic" },
|
||||
checks: null,
|
||||
},
|
||||
"field:topic",
|
||||
);
|
||||
add(
|
||||
"remember",
|
||||
"Checkbox: remember me when signing in.",
|
||||
"Checkbox",
|
||||
{
|
||||
name: "remember",
|
||||
label: "Remember me",
|
||||
checked: { $bindState: "/form/remember" },
|
||||
},
|
||||
"field:remember",
|
||||
);
|
||||
add(
|
||||
"notifications_switch",
|
||||
"Switch: enable email notifications in account settings.",
|
||||
"Switch",
|
||||
{
|
||||
name: "notifications",
|
||||
label: "Email notifications",
|
||||
checked: { $bindState: "/form/notifications" },
|
||||
},
|
||||
"field:notifications",
|
||||
);
|
||||
add(
|
||||
"notifications_checkbox",
|
||||
"Checkbox: enable email notifications, if a checkbox is requested.",
|
||||
"Checkbox",
|
||||
{
|
||||
name: "notifications",
|
||||
label: "Email notifications",
|
||||
checked: { $bindState: "/form/notifications" },
|
||||
},
|
||||
"field:notifications",
|
||||
);
|
||||
|
||||
const submitLabels = ["Sign in", "Create account", "Send message", "Submit"];
|
||||
for (const [index, label] of submitLabels.entries()) {
|
||||
add(
|
||||
`submit_${index}`,
|
||||
`Button labeled ${JSON.stringify(label)}. Bind press to the catalog's formSubmit action, which validates inputs and shows a demo toast.`,
|
||||
"Button",
|
||||
{ label, variant: "primary", disabled: false },
|
||||
"action:submit",
|
||||
{ press: { action: "formSubmit", params: { formName: "jev-form" } } },
|
||||
);
|
||||
}
|
||||
add(
|
||||
"save",
|
||||
"Button: Save changes. Bind press to setState to update the visible saved-status text. Local demo only.",
|
||||
"Button",
|
||||
{ label: "Save changes", variant: "primary", disabled: false },
|
||||
"action:save",
|
||||
{
|
||||
press: {
|
||||
action: "setState",
|
||||
params: { statePath: "/status", value: "Changes saved locally." },
|
||||
},
|
||||
},
|
||||
);
|
||||
add(
|
||||
"reset",
|
||||
"Button: Reset. Bind press to setState to restore all form fields to their initial values.",
|
||||
"Button",
|
||||
{ label: "Reset", variant: "outline", disabled: false },
|
||||
"action:reset",
|
||||
{
|
||||
press: {
|
||||
action: "setState",
|
||||
params: { statePath: "/form", value: structuredClone(fieldValues) },
|
||||
},
|
||||
},
|
||||
);
|
||||
add(
|
||||
"status",
|
||||
"Text: live save status, bound to /status. Include alongside Save changes.",
|
||||
"Text",
|
||||
{ text: { $state: "/status" }, variant: "muted" },
|
||||
"data:status",
|
||||
);
|
||||
add(
|
||||
"revenue",
|
||||
"Metric: total sales revenue, $48,250, up 12.8%. Synthetic platform data.",
|
||||
"Metric",
|
||||
{
|
||||
label: "Revenue",
|
||||
value: "48,250",
|
||||
prefix: "$",
|
||||
suffix: null,
|
||||
change: "+12.8%",
|
||||
changeType: "positive",
|
||||
},
|
||||
"data:revenue",
|
||||
);
|
||||
add(
|
||||
"orders",
|
||||
"Metric: 384 orders, up 8.2%. Synthetic platform data.",
|
||||
"Metric",
|
||||
{
|
||||
label: "Orders",
|
||||
value: "384",
|
||||
prefix: null,
|
||||
suffix: null,
|
||||
change: "+8.2%",
|
||||
changeType: "positive",
|
||||
},
|
||||
"data:orders",
|
||||
);
|
||||
add(
|
||||
"customers",
|
||||
"Metric: 125 new customers, up 14.4%. Synthetic platform data.",
|
||||
"Metric",
|
||||
{
|
||||
label: "New customers",
|
||||
value: "125",
|
||||
prefix: null,
|
||||
suffix: null,
|
||||
change: "+14.4%",
|
||||
changeType: "positive",
|
||||
},
|
||||
"data:customers",
|
||||
);
|
||||
add(
|
||||
"sales_chart",
|
||||
"BarGraph: weekly revenue chart (Week 1–4). Synthetic platform data.",
|
||||
"BarGraph",
|
||||
{
|
||||
title: "Weekly revenue",
|
||||
data: [
|
||||
{ label: "Week 1", value: 9200 },
|
||||
{ label: "Week 2", value: 11400 },
|
||||
{ label: "Week 3", value: 12650 },
|
||||
{ label: "Week 4", value: 15000 },
|
||||
],
|
||||
},
|
||||
"data:sales_chart",
|
||||
);
|
||||
add(
|
||||
"orders_table",
|
||||
"Table: order-status breakdown with Fulfilled, Processing, and Returned counts. Synthetic platform data.",
|
||||
"Table",
|
||||
{
|
||||
columns: ["Status", "Orders"],
|
||||
rows: [
|
||||
["Fulfilled", "312"],
|
||||
["Processing", "54"],
|
||||
["Returned", "18"],
|
||||
],
|
||||
caption: "Synthetic order data",
|
||||
},
|
||||
"data:orders_table",
|
||||
);
|
||||
add(
|
||||
"separator",
|
||||
"Separator: horizontal dividing line, only when requested.",
|
||||
"Separator",
|
||||
{ orientation: "horizontal" },
|
||||
);
|
||||
return candidates;
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// @vitest-environment node
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { type JsonPatch, type Spec } from "@json-render/core";
|
||||
import { applySpecPatch } from "../spec-patch";
|
||||
import { createCompositionResponse } from "./response";
|
||||
import { composeUI } from "./compose";
|
||||
|
||||
vi.mock("./compose", () => ({ composeUI: vi.fn() }));
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
describe("playground composition response", () => {
|
||||
it("passes the selected spec to the composer and streams patches relative to it", async () => {
|
||||
vi.stubEnv("AI_GATEWAY_API_KEY", "");
|
||||
vi.stubEnv("JEV_AI_GATEWAY_API_KEY", "test");
|
||||
const initialSpec: Spec = {
|
||||
root: "card",
|
||||
elements: {
|
||||
card: { type: "Card", props: { title: "Before" }, children: [] },
|
||||
},
|
||||
state: { saved: true },
|
||||
};
|
||||
const spec = structuredClone(initialSpec);
|
||||
spec.elements.card!.props.title = "After";
|
||||
vi.mocked(composeUI).mockImplementation(async function* () {
|
||||
yield {
|
||||
type: "complete",
|
||||
spec,
|
||||
steps: [],
|
||||
stopReason: "finish",
|
||||
elapsedMs: 1,
|
||||
inputTokens: null,
|
||||
estimatedCostUsd: null,
|
||||
};
|
||||
});
|
||||
const response = createCompositionResponse(
|
||||
new Request("https://example.com/api/generate"),
|
||||
"Rename it",
|
||||
initialSpec,
|
||||
);
|
||||
const lines = (await response.text())
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => JSON.parse(line));
|
||||
expect(vi.mocked(composeUI).mock.calls[0]![3]).toEqual(initialSpec);
|
||||
const patches = lines.filter((line) => line.op);
|
||||
expect(patches).toEqual([
|
||||
{ op: "replace", path: "/elements/card/props/title", value: "After" },
|
||||
]);
|
||||
expect(
|
||||
patches.reduce(
|
||||
(value, patch) => applySpecPatch(value, patch),
|
||||
structuredClone(initialSpec),
|
||||
),
|
||||
).toEqual(spec);
|
||||
expect(initialSpec.elements.card!.props.title).toBe("Before");
|
||||
});
|
||||
|
||||
it("adapts snapshots to the existing patch stream, including the final decision", async () => {
|
||||
vi.stubEnv("JEV_AI_GATEWAY_API_KEY", "test");
|
||||
const spec: Spec = {
|
||||
root: "card",
|
||||
elements: { card: { type: "Card", props: {}, children: [] } },
|
||||
state: { name: "" },
|
||||
};
|
||||
const step = {
|
||||
index: 0,
|
||||
choice: "card",
|
||||
description: "Card",
|
||||
parent: null,
|
||||
slot: null,
|
||||
confidence: null,
|
||||
parentConfidence: null,
|
||||
elapsedMs: 10,
|
||||
inputTokens: null,
|
||||
};
|
||||
vi.mocked(composeUI).mockImplementation(async function* () {
|
||||
yield { type: "step", spec, step };
|
||||
yield {
|
||||
type: "complete",
|
||||
spec,
|
||||
steps: [step, { ...step, index: 1, choice: "finish" }],
|
||||
stopReason: "finish",
|
||||
elapsedMs: 20,
|
||||
inputTokens: null,
|
||||
estimatedCostUsd: null,
|
||||
};
|
||||
});
|
||||
const response = createCompositionResponse(
|
||||
new Request("https://example.com/api/generate"),
|
||||
"Create a card",
|
||||
);
|
||||
const lines = (await response.text())
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => JSON.parse(line));
|
||||
let actual: Spec = { root: "", elements: {} };
|
||||
for (const line of lines)
|
||||
if (line.op) actual = applySpecPatch(actual, line as JsonPatch);
|
||||
expect(actual).toEqual(spec);
|
||||
expect(
|
||||
lines
|
||||
.filter((line) => line.__meta === "decision")
|
||||
.map((line) => line.choice),
|
||||
).toEqual(["card", "finish"]);
|
||||
expect(lines.at(-1)).toMatchObject({
|
||||
__meta: "composition",
|
||||
stopReason: "finish",
|
||||
calls: 2,
|
||||
inputTokens: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("retains unavailable outcomes and sends failures in the shared protocol", async () => {
|
||||
vi.stubEnv("JEV_AI_GATEWAY_API_KEY", "test");
|
||||
vi.mocked(composeUI).mockImplementation(async function* () {
|
||||
yield {
|
||||
type: "complete",
|
||||
spec: null,
|
||||
steps: [],
|
||||
stopReason: "unavailable",
|
||||
elapsedMs: 1,
|
||||
inputTokens: null,
|
||||
estimatedCostUsd: null,
|
||||
};
|
||||
});
|
||||
const request = new Request("https://example.com/api/generate");
|
||||
expect(
|
||||
await createCompositionResponse(request, "Unavailable request").text(),
|
||||
).toContain('"stopReason":"unavailable"');
|
||||
vi.mocked(composeUI).mockImplementation(async function* () {
|
||||
yield { type: "error", message: "Provider failed" };
|
||||
});
|
||||
expect(
|
||||
await createCompositionResponse(request, "Create a form").text(),
|
||||
).toContain('"__meta":"error"');
|
||||
});
|
||||
|
||||
it("validates requests before starting the model", async () => {
|
||||
const request = new Request("https://example.com/api/generate");
|
||||
expect(createCompositionResponse(request, " ").status).toBe(400);
|
||||
expect(
|
||||
createCompositionResponse(request, "Edit", {
|
||||
root: "card",
|
||||
elements: { card: null },
|
||||
}).status,
|
||||
).toBe(400);
|
||||
vi.stubEnv("AI_GATEWAY_API_KEY", "default-model-key");
|
||||
vi.stubEnv("JEV_AI_GATEWAY_API_KEY", "");
|
||||
expect(createCompositionResponse(request, "Create a form").status).toBe(
|
||||
503,
|
||||
);
|
||||
expect(composeUI).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user