From 04287ac4334390a8ce3de23c778d1c73668986ec Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sun, 18 Oct 2026 06:31:36 +0000 Subject: [PATCH] feat(web): SchemaForm, a form generated from a JSON Schema with a {{ }} variable picker The studio's action cards and the canvas's action node settings render an action's params from the actions catalog's JSON Schema: text, template, number, choice, toggle, list and JSON fields, labels and hints from the schema, a variable picker on {{ and a preview line per field. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01AjJqXgjj1cNdKGRQbX5frb --- .../__tests__/schema-form.test.tsx | 180 ++++++++++++ .../components/forms/schema-form.tsx | 273 ++++++++++++++++++ .../components/forms/schema-model.ts | 140 +++++++++ 3 files changed, 593 insertions(+) create mode 100644 nextjs-frontend/__tests__/schema-form.test.tsx create mode 100644 nextjs-frontend/components/forms/schema-form.tsx create mode 100644 nextjs-frontend/components/forms/schema-model.ts diff --git a/nextjs-frontend/__tests__/schema-form.test.tsx b/nextjs-frontend/__tests__/schema-form.test.tsx new file mode 100644 index 000000000..08a42fb65 --- /dev/null +++ b/nextjs-frontend/__tests__/schema-form.test.tsx @@ -0,0 +1,180 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import "@testing-library/jest-dom"; +import { useState } from "react"; + +import { SchemaForm, type Variable } from "@/components/forms/schema-form"; +import { + fieldProblem, + fieldsOf, + fromText, + insertVariable, + openVariable, + toText, + type JsonSchema, +} from "@/components/forms/schema-model"; + +// the shapes of the actions catalog's params (GET /api/v1/automations/actions) +const notify: JsonSchema = { + type: "object", + properties: { + to: { + type: "string", + title: "To", + default: "me", + maxLength: 200, + description: "me, target: or gateway:", + }, + text: { type: "string", title: "Message", maxLength: 4000 }, + link: { type: "string", title: "Link", maxLength: 2000 }, + }, +}; +const mixed: JsonSchema = { + type: "object", + properties: { + method: { type: "string", title: "Method", enum: ["GET", "POST", "PUT"], default: "GET" }, + collection: { type: "integer", title: "Collection" }, + propose_only: { type: "boolean", title: "Only propose its changes", default: false }, + tools: { type: "array", title: "Tools", items: { type: "string" } }, + headers: { type: "object", title: "Headers", default: {} }, + asset: { title: "Asset", default: "{{ event.object.id }}" }, + prompt: { type: "string", title: "Prompt", format: "prompt" }, + }, +}; + +describe("schema fields", () => { + it("gives each property the control its type needs", () => { + const fs = fieldsOf(mixed, ["collection"]); + expect(fs.map((f) => [f.key, f.kind, f.required])).toEqual([ + ["method", "choice", false], + ["collection", "number", true], + ["propose_only", "toggle", false], + ["tools", "list", false], + ["headers", "json", false], + ["asset", "any", false], + ["prompt", "long", false], + ]); + expect(fieldsOf(notify).map((f) => f.kind)).toEqual(["text", "long", "long"]); + expect(fs[0]).toMatchObject({ label: "Method", options: ["GET", "POST", "PUT"], default: "GET", template: false }); + }); + + it("reads what's typed as the value, templates standing for any type", () => { + const [, collection, , tools, headers, asset] = fieldsOf(mixed); + expect(fromText(collection, "12")).toBe(12); + expect(fromText(collection, "{{ vars.box }}")).toBe("{{ vars.box }}"); + expect(fromText(collection, "")).toBeUndefined(); + expect(fromText(tools, "search\n\nweb_fetch ")).toEqual(["search", "web_fetch"]); + expect(fromText(headers, '{"X-Key": "a"}')).toEqual({ "X-Key": "a" }); + expect(fromText(asset, "7")).toBe(7); + expect(fromText(asset, "lens:recording/7")).toBe("lens:recording/7"); + expect(toText(tools, ["a", "b"])).toBe("a\nb"); + expect(toText(headers, { a: 1 })).toBe('{\n "a": 1\n}'); + }); + + it("says what's wrong with a value", () => { + const [method, collection, , , headers] = fieldsOf(mixed, ["collection"]); + expect(fieldProblem(collection, undefined)).toBe("Fill in Collection."); + expect(fieldProblem(collection, "abc")).toBe("A number, or a {{ }} template."); + expect(fieldProblem(collection, "{{ vars.box }}")).toBe(""); + expect(fieldProblem(headers, "{bad")).toMatch(/object in JSON/); + expect(fieldProblem(method, "DELETE")).toBe("One of GET, POST, PUT."); + expect(fieldProblem(method, undefined)).toBe(""); + }); + + it("finds the {{ being typed and puts a variable in its place", () => { + expect(openVariable("Hi {{ eve", 9)).toEqual({ start: 3, query: "eve" }); + expect(openVariable("Hi {{ event }} there", 20)).toBeNull(); + expect(insertVariable("Hi {{ eve", 9, "event.summary")).toEqual({ text: "Hi {{ event.summary }}", caret: 22 }); + expect(insertVariable("Hi {{ eve }}!", 9, "event.summary").text).toBe("Hi {{ event.summary }}!"); + }); +}); + +const vars: Variable[] = [ + { path: "event.summary", label: "What happened" }, + { path: "event.actor.name", label: "Who" }, + { path: "now", label: "The time" }, +]; + +function Harness({ schema, required, spy }: { schema: JsonSchema; required?: string[]; spy: jest.Mock }) { + const [v, setV] = useState>({}); + return ( + { + spy(x); + setV(x); + }} + variables={vars} + preview={(k, x) => `preview of ${k}: ${String(x)}`} + /> + ); +} + +describe("SchemaForm", () => { + it("labels fields from the schema and fills the value in as you type", () => { + const spy = jest.fn(); + render(); + expect(screen.getByLabelText(/^To/)).toHaveAttribute("placeholder", "me"); + expect(screen.getByText("me, target: or gateway:")).toBeInTheDocument(); + fireEvent.change(screen.getByLabelText(/^Message/), { target: { value: "School wrote" } }); + expect(spy).toHaveBeenLastCalledWith({ text: "School wrote" }); + expect(screen.getByText("preview of text: School wrote")).toBeInTheDocument(); + fireEvent.change(screen.getByLabelText(/^Message/), { target: { value: "" } }); + expect(spy).toHaveBeenLastCalledWith({}); + }); + + it("sets numbers, choices, toggles and lists as their types", () => { + const spy = jest.fn(); + render(); + fireEvent.change(screen.getByLabelText(/^Collection/), { target: { value: "4" } }); + fireEvent.change(screen.getByLabelText(/^Method/), { target: { value: "POST" } }); + fireEvent.click(screen.getByRole("checkbox", { name: "Only propose its changes" })); + fireEvent.change(screen.getByLabelText(/Tools/), { target: { value: "search\nweb" } }); + expect(spy).toHaveBeenLastCalledWith({ + collection: 4, + method: "POST", + propose_only: true, + tools: ["search", "web"], + }); + fireEvent.change(screen.getByLabelText(/^Collection/), { target: { value: "four" } }); + fireEvent.blur(screen.getByLabelText(/^Collection/)); + expect(screen.getByRole("alert")).toHaveTextContent("A number, or a {{ }} template."); + }); + + it("opens the variable picker on {{ and puts the pick in with Enter", () => { + const spy = jest.fn(); + render(); + const box = screen.getByLabelText(/^Message/) as HTMLTextAreaElement; + fireEvent.change(box, { target: { value: "From {{ ev", selectionStart: 10 } }); + const list = screen.getByRole("listbox", { name: "Variables" }); + expect(list.querySelectorAll("[role=option]")).toHaveLength(2); + fireEvent.keyDown(box, { key: "ArrowDown" }); + expect(screen.getAllByRole("option")[1]).toHaveAttribute("aria-selected", "true"); + fireEvent.keyDown(box, { key: "Enter" }); + expect(spy).toHaveBeenLastCalledWith({ text: "From {{ event.actor.name }}" }); + expect(screen.queryByRole("listbox")).toBeNull(); + }); + + it("closes the picker with Esc, and a click picks too", () => { + const spy = jest.fn(); + render(); + const box = screen.getByLabelText(/^Message/); + fireEvent.change(box, { target: { value: "{{", selectionStart: 2 } }); + expect(screen.getAllByRole("option")).toHaveLength(3); + fireEvent.keyDown(box, { key: "Escape" }); + expect(screen.queryByRole("listbox")).toBeNull(); + fireEvent.change(box, { target: { value: "At {{ no", selectionStart: 8 } }); + fireEvent.mouseDown(screen.getByRole("option", { name: /The time/ })); + expect(spy).toHaveBeenLastCalledWith({ text: "At {{ now }}" }); + }); + + it("shows the API's problems next to their fields, and says when there's nothing to set", () => { + const { rerender } = render( + {}} errors={{ text: "notify needs Message (text)" }} />, + ); + expect(screen.getByRole("alert")).toHaveTextContent("notify needs Message (text)"); + rerender( {}} />); + expect(screen.getByText("Nothing to set.")).toBeInTheDocument(); + }); +}); diff --git a/nextjs-frontend/components/forms/schema-form.tsx b/nextjs-frontend/components/forms/schema-form.tsx new file mode 100644 index 000000000..bec485242 --- /dev/null +++ b/nextjs-frontend/components/forms/schema-form.tsx @@ -0,0 +1,273 @@ +"use client"; + +/** + * A form generated from a JSON Schema object: text, template, number, choice, toggle, list and JSON fields, with the + * schema's titles as labels and its descriptions as hints. Typing `{{` in a field that takes a template opens the + * variable picker when `variables` are given; `preview` puts a line under a field (what its template gives). + */ +import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react"; + +import { Checkbox, Field, Input, Select, Textarea } from "@/components/ui/field"; +import { cn } from "@/lib/utils"; + +import { + fieldProblem, + fieldsOf, + fromText, + insertVariable, + openVariable, + setValue, + toText, + type JsonSchema, + type SchemaField, +} from "./schema-model"; + +export type Variable = { path: string; label?: string; group?: string }; + +export function SchemaForm({ + schema, + required, + value, + onChange, + variables, + preview, + errors, + idPrefix, + className, +}: { + schema: JsonSchema | undefined; + required?: string[]; + value: Record; + onChange: (v: Record) => void; + variables?: Variable[]; + preview?: (key: string, v: unknown) => ReactNode; + /** Problems by field key, from the API. */ + errors?: Record; + idPrefix?: string; + className?: string; +}) { + const fields = useMemo(() => fieldsOf(schema, required), [schema, required]); + const auto = useId(); + const prefix = idPrefix ?? auto; + if (!fields.length) return

Nothing to set.

; + return ( +
+ {fields.map((f) => ( + onChange(setValue(value, f.key, v))} + variables={f.template ? variables : undefined} + preview={preview} + error={errors?.[f.key]} + /> + ))} +
+ ); +} + +function SchemaInput({ + id, + field: f, + value, + onChange, + variables, + preview, + error, +}: { + id: string; + field: SchemaField; + value: unknown; + onChange: (v: unknown) => void; + variables?: Variable[]; + preview?: (key: string, v: unknown) => ReactNode; + error?: string; +}) { + const [text, setText] = useState(() => toText(f, value)); + const [touched, setTouched] = useState(false); + // a value set from outside (a draft filled in, undo) shows; what's being typed stays as typed + useEffect(() => { + if (JSON.stringify(fromText(f, text)) !== JSON.stringify(value)) setText(toText(f, value)); + }, [value]); + const problem = error || (touched ? fieldProblem(f, fromText(f, text)) : ""); + const placeholder = f.default !== undefined ? toText(f, f.default) : undefined; + const hint = ( + <> + {f.help} + {preview && value !== undefined && {preview(f.key, value)}} + + ); + if (f.kind === "toggle") + return ( +
+ onChange(v)} + label={f.label} + /> + {f.help &&

{f.help}

} +
+ ); + return ( + + {({ id: fid, describedBy, invalid }) => + f.kind === "choice" ? ( +