From 1521d5557f7beb91dd34b1d5a15bd842c5c3704b Mon Sep 17 00:00:00 2001 From: ArizmendiWan <2311602492@qq.com> Date: Tue, 24 Nov 2026 00:51:54 -0600 Subject: [PATCH 1/6] Support configurable section templates with schema-driven forms Let template authors declare configuration and port schemas, bind operation fields to template properties, and configure each section instance independently. Use React JSONSchema Form for schema authoring and data entry, including inline titles for alternatives. Signed-off-by: ArizmendiWan <2311602492@qq.com> --- Cargo.toml | 2 + diagram-editor/dist.hash | 2 +- .../frontend/api.preprocessed.schema.json | 46 +- diagram-editor/frontend/command-panel.tsx | 58 +- diagram-editor/frontend/diagram-editor.tsx | 20 +- .../frontend/diagram-side-panel.tsx | 39 +- diagram-editor/frontend/editor-mode.tsx | 5 + .../frontend/forms/node-form.test.tsx | 164 +-- diagram-editor/frontend/forms/node-form.tsx | 18 +- .../frontend/forms/operation-config-form.tsx | 191 +++ .../frontend/forms/schema-config-form.tsx | 1153 +++++++---------- .../frontend/forms/schema-editor.tsx | 610 +++++++++ .../script-environment-workspace.test.tsx | 25 +- .../forms/script-environment-workspace.tsx | 32 +- .../script-environments/python-form.test.tsx | 8 +- .../forms/script-environments/python-form.tsx | 110 +- diagram-editor/frontend/forms/script-form.tsx | 54 +- .../frontend/forms/section-form.tsx | 106 +- .../frontend/forms/template-panel.tsx | 116 ++ diagram-editor/frontend/nodes/create-node.ts | 8 +- .../frontend/nodes/section-node.tsx | 4 +- .../frontend/templates-provider.tsx | 15 + .../frontend/transient-editor-drafts.tsx | 15 +- diagram-editor/frontend/types/api.d.ts | 28 + .../frontend/utils/compatibility.ts | 8 +- .../frontend/utils/export-diagram.ts | 14 +- diagram-editor/frontend/utils/load-diagram.ts | 32 +- diagram-editor/jest-setup.ts | 6 + diagram-editor/jest.config.js | 4 + diagram-editor/package.json | 7 +- diagram-editor/server/api/executor.rs | 115 +- diagram-editor/wasm/src/executor.rs | 2 + diagram.schema.json | 53 +- handbook/src/diagram-section-templates.md | 20 +- pnpm-lock.yaml | 176 ++- src/diagram/node_schema.rs | 12 +- src/diagram/registration.rs | 45 + src/diagram/script_schema.rs | 15 +- src/diagram/section_schema.rs | 152 ++- 39 files changed, 2352 insertions(+), 1138 deletions(-) create mode 100644 diagram-editor/frontend/forms/operation-config-form.tsx create mode 100644 diagram-editor/frontend/forms/schema-editor.tsx create mode 100644 diagram-editor/frontend/forms/template-panel.tsx diff --git a/Cargo.toml b/Cargo.toml index 192635ca..f1ff3f0b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -114,6 +114,7 @@ serde_json = { workspace = true, optional = true } # --- Dependencies for diagram feature +jsonschema = { version = "0.62", default-features = false, optional = true } schemars = { workspace = true, optional = true } serde_with = { workspace = true, optional = true } cel-interpreter = { version = "0.9.0", features = ["json"], optional = true } @@ -152,6 +153,7 @@ json = [ single_threaded_async = ["dep:async-task"] diagram = [ "json", + "dep:jsonschema", "dep:cel-interpreter", "dep:semver", "dep:serde_with", diff --git a/diagram-editor/dist.hash b/diagram-editor/dist.hash index dd31433b..bfb7f735 100644 --- a/diagram-editor/dist.hash +++ b/diagram-editor/dist.hash @@ -1 +1 @@ -04431de9d34dd48519d8e1a7d3b846e91743f9021e023ad7427ac3b12492dd24 \ No newline at end of file +48877e9161887be9da9a19db2aed9a4376751b1242f5ebbce9f7336095d74869 \ No newline at end of file diff --git a/diagram-editor/frontend/api.preprocessed.schema.json b/diagram-editor/frontend/api.preprocessed.schema.json index 1cc4e725..f81dcd88 100644 --- a/diagram-editor/frontend/api.preprocessed.schema.json +++ b/diagram-editor/frontend/api.preprocessed.schema.json @@ -1364,6 +1364,13 @@ "type": "string" }, "config": true, + "config_bindings": { + "additionalProperties": { + "type": "string" + }, + "description": "JSON pointers within config linked to properties of the enclosing template.", + "type": "object" + }, "display_text": { "description": "Override for text that should be displayed for an operation within an\neditor.", "type": [ @@ -1872,6 +1879,13 @@ "config": { "description": "Configured data to pass into the function that `run` refers to. This will\nbe passed in as a keyword argument named `config`." }, + "config_bindings": { + "additionalProperties": { + "type": "string" + }, + "description": "JSON pointers within config linked to properties of the enclosing template.", + "type": "object" + }, "display_text": { "description": "Override for text that should be displayed for an operation within an\neditor.", "type": [ @@ -2061,8 +2075,12 @@ { "description": "Connect the request to a registered section.\n\n```\n# crossflow::Diagram::from_json_str(r#\"\n{\n \"version\": \"0.1.0\",\n \"start\": \"section_op\",\n \"ops\": {\n \"section_op\": {\n \"type\": \"section\",\n \"builder\": \"my_section_builder\",\n \"connect\": {\n \"my_section_output\": { \"builtin\": \"terminate\" }\n }\n }\n }\n}\n# \"#)?;\n# Ok::<_, serde_json::Error>(())\n```\n\nCustom sections can also be created via templates\n```\n# crossflow::Diagram::from_json_str(r#\"\n{\n \"version\": \"0.1.0\",\n \"templates\": {\n \"my_template\": {\n \"inputs\": [\"section_input\"],\n \"outputs\": [\"section_output\"],\n \"buffers\": [],\n \"ops\": {\n \"section_input\": {\n \"type\": \"node\",\n \"builder\": \"my_node\",\n \"next\": \"section_output\"\n }\n }\n }\n },\n \"start\": \"section_op\",\n \"ops\": {\n \"section_op\": {\n \"type\": \"section\",\n \"template\": \"my_template\",\n \"connect\": {\n \"section_output\": { \"builtin\": \"terminate\" }\n }\n }\n }\n}\n# \"#)?;\n# Ok::<_, serde_json::Error>(())\n```", "properties": { - "config": { - "default": null + "config": true, + "config_bindings": { + "additionalProperties": { + "type": "string" + }, + "type": "object" }, "connect": { "additionalProperties": { @@ -2104,6 +2122,23 @@ "buffers": { "$ref": "#/$defs/InputRemapping" }, + "config_schema": { + "anyOf": [ + { + "$ref": "#/$defs/Schema" + }, + { + "type": "null" + } + ] + }, + "input_schemas": { + "additionalProperties": { + "$ref": "#/$defs/Schema" + }, + "description": "JSON Schemas for the template's exposed input ports.", + "type": "object" + }, "inputs": { "$ref": "#/$defs/InputRemapping" }, @@ -2114,6 +2149,13 @@ "description": "Operations that define the behavior of the section.", "type": "object" }, + "output_schemas": { + "additionalProperties": { + "$ref": "#/$defs/Schema" + }, + "description": "JSON Schemas for the template's exposed output ports.", + "type": "object" + }, "outputs": { "default": [], "description": "These are the outputs that the section is exposing so you can connect\nthem into siblings of the section.", diff --git a/diagram-editor/frontend/command-panel.tsx b/diagram-editor/frontend/command-panel.tsx index 9f98614d..5103d361 100644 --- a/diagram-editor/frontend/command-panel.tsx +++ b/diagram-editor/frontend/command-panel.tsx @@ -88,34 +88,36 @@ function CommandPanel({ )} - {editorMode.mode === EditorMode.Normal && ( - - - - )} - {editorMode.mode === EditorMode.Normal && ( - - - - )} + + + + + + {editorMode.mode === EditorMode.Normal && ( + + + + + ); +} + +function Properties({ + value, + onChange, +}: { + value: SchemaObject; + onChange: (schema: SchemaObject) => void; +}) { + const fields = (value.properties ?? {}) as Record; + const required = (value.required ?? []) as string[]; + const [editing, setEditing] = useState<{ key?: string } | null>(null); + function update(name: string, schema?: Schema, isRequired = false) { + const properties = { ...fields, [name]: schema }; + if (schema === undefined) delete properties[name]; + const keys = isRequired + ? [...new Set([...required, name])] + : required.filter((key) => key !== name); + const { required: _previous, ...rest } = value; + onChange({ + ...rest, + properties, + ...(keys.length > 0 && { required: keys }), + }); + setEditing(null); + } + return ( + + {Object.entries(fields).map(([name, schema]) => ( + + + {name} + {required.includes(name) && ' *'} + + + {schemaSummary(schema)} + + setEditing({ key: name })} + > + + + { + if (window.confirm(`Delete property “${name}”?`)) update(name); + }} + > + + + + ))} + + {editing && ( + setEditing(null)} + onSave={(schema, name, required) => update(name, schema, required)} + /> + )} + + ); +} + +export default function SchemaEditor({ + label, + value, + onChange, + object = false, + removable = true, + alternative = false, +}: EditorProps) { + const [open, setOpen] = useState(false); + const schema: Schema = value ?? (object ? { type: 'object' } : initial); + const inlineTitle = alternative && typeof schema === 'object'; + const { title, ...definition } = inlineTitle ? schema : {}; + const name = typeof title === 'string' ? title : ''; + return ( + + + {inlineTitle ? ( + + onChange( + target.value + ? { ...definition, title: target.value } + : definition, + ) + } + /> + ) : ( + + {label} + + )} + {!object && value !== undefined && ( + + {schemaSummary(inlineTitle ? definition : value)} + + )} + + {removable && value !== undefined && ( + { + if (!object || window.confirm('Remove the configuration schema?')) + onChange(undefined); + }} + > + + + )} + + {object && !schemaError(schema) && kindOf(schema) === 'object' && ( + <> + + + + )} + {open && ( + setOpen(false)} + onSave={(next) => { + onChange(next); + setOpen(false); + }} + /> + )} + + ); +} diff --git a/diagram-editor/frontend/forms/script-environment-workspace.test.tsx b/diagram-editor/frontend/forms/script-environment-workspace.test.tsx index a2790a2d..5a0004e4 100644 --- a/diagram-editor/frontend/forms/script-environment-workspace.test.tsx +++ b/diagram-editor/frontend/forms/script-environment-workspace.test.tsx @@ -224,20 +224,25 @@ describe('ScriptEnvironmentWorkspace', () => { screen.getByRole('option', { name: 'generic-script-builder' }), ); - await waitFor(() => { - expect( - screen.getByLabelText('Builder Config (JSON)'), - ).toBeInTheDocument(); - }); - const config = screen.getByLabelText('Builder Config (JSON)'); - fireEvent.change(config, { - target: { value: '{"script_content":"first"}' }, - }); + fireEvent.change( + await screen.findByRole('textbox', { name: 'script_content' }), + { + target: { value: 'first' }, + }, + ); fireEvent.mouseDown(screen.getByLabelText('Code Field')); fireEvent.click(screen.getByRole('option', { name: 'script_content' })); expect(scriptEditor()).toHaveValue('first'); + expect( + screen.queryByRole('textbox', { name: 'script_content' }), + ).not.toBeInTheDocument(); changeScript('second'); - expect(JSON.parse((config as HTMLTextAreaElement).value)).toEqual({ + fireEvent.click(screen.getByRole('button', { name: 'Edit as JSON' })); + expect( + JSON.parse( + (screen.getByLabelText('Builder Config') as HTMLTextAreaElement).value, + ), + ).toEqual({ script_content: 'second', }); }); diff --git a/diagram-editor/frontend/forms/script-environment-workspace.tsx b/diagram-editor/frontend/forms/script-environment-workspace.tsx index 36a4022f..12d90097 100644 --- a/diagram-editor/frontend/forms/script-environment-workspace.tsx +++ b/diagram-editor/frontend/forms/script-environment-workspace.tsx @@ -37,6 +37,7 @@ import { useRegistry } from '../registry-provider'; import { useTransientEditorDrafts } from '../transient-editor-drafts'; import type { DiagramElementMetadata } from '../types/api'; import { EnvironmentWindow } from './environment-window'; +import SchemaConfigForm from './schema-config-form'; import { ScriptEnvironmentPanel } from './script-environment-panel'; import { scriptEnvironmentPlugins } from './script-environments/registry'; @@ -191,6 +192,7 @@ export function ScriptEnvironmentWorkspace({ }, [draft, editorWindow, expanded, width, updateDraft]); const plugin = scriptEnvironmentPlugins[builder]; const activeCodeField = plugin?.defaultCodeField || selectedCodeField; + const builderSchema = registry.scripting?.[builder]?.config_schema; const builderDraft = useCallback( (builder: string) => ({ @@ -215,7 +217,7 @@ export function ScriptEnvironmentWorkspace({ const values = builderDraft(environment?.builder || defaultBuilder); if (environment) values.config = JSON.stringify( - objectConfig(environment.config), + environment.config === undefined ? {} : environment.config, null, 2, ); @@ -260,13 +262,14 @@ export function ScriptEnvironmentWorkspace({ [nodeManager.nodes], ); - let parsedConfig: Record = {}; + let configValue: unknown; let jsonError: string | null = null; try { - parsedConfig = objectConfig(JSON.parse(config)); + configValue = JSON.parse(config); } catch (error) { jsonError = (error as Error).message; } + const parsedConfig = objectConfig(configValue); const configKeys = Object.keys(parsedConfig).filter( (key) => typeof parsedConfig[key] === 'string', ); @@ -732,6 +735,29 @@ export function ScriptEnvironmentWorkspace({ registry={registry} scriptText={scriptText} /> + ) : builderSchema && + typeof builderSchema === 'object' && + Object.keys(builderSchema).length ? ( + { + if (text !== undefined) updateDraft({ config: text }); + }} + onChange={(value) => + updateDraft({ config: JSON.stringify(value, null, 2) ?? '' }) + } + /> ) : ( { const selectElement = screen.getByLabelText('Environment Ownership'); expect(selectElement).toBeTruthy(); - expect(screen.getByText('Persistent')).toBeTruthy(); + expect(screen.getByText('persistent')).toBeTruthy(); }); test('invokes onChange when ownership option is changed', async () => { @@ -56,7 +56,7 @@ describe('PythonPropertiesForm', () => { fireEvent.mouseDown(selectElement); // Select 'Isolated' - const isolatedOption = screen.getByRole('option', { name: 'Isolated' }); + const isolatedOption = screen.getByRole('option', { name: 'isolated' }); fireEvent.click(isolatedOption); expect(mockOnChange).toHaveBeenCalled(); @@ -128,9 +128,9 @@ describe('PythonPropertiesForm', () => { const selectElement = screen.getByRole('combobox'); fireEvent.mouseDown(selectElement); - expect(screen.getByRole('option', { name: 'Shared_custom' })).toBeTruthy(); + expect(screen.getByRole('option', { name: 'shared_custom' })).toBeTruthy(); expect( - screen.getByRole('option', { name: 'Persistent_custom' }), + screen.getByRole('option', { name: 'persistent_custom' }), ).toBeTruthy(); }); }); diff --git a/diagram-editor/frontend/forms/script-environments/python-form.tsx b/diagram-editor/frontend/forms/script-environments/python-form.tsx index 3bee173c..fc45ffca 100644 --- a/diagram-editor/frontend/forms/script-environments/python-form.tsx +++ b/diagram-editor/frontend/forms/script-environments/python-form.tsx @@ -1,24 +1,15 @@ -import { MenuItem, TextField } from '@mui/material'; +import type { RJSFSchema } from '@rjsf/utils'; import { useEffect, useMemo } from 'react'; +import SchemaConfigForm from '../schema-config-form'; import type { ScriptEnvironmentFormProps } from './registry'; -type JsonSchemaProperty = { - $ref?: string; - anyOf?: JsonSchemaProperty[]; - enum?: string[]; +const fallback = { + type: 'object', + properties: { + ownership: { type: 'string', enum: ['shared', 'persistent', 'isolated'] }, + }, }; -type JsonSchemaObject = JsonSchemaProperty & { - definitions?: Record; - properties?: Record; -}; - -function schemaObject(value: unknown): JsonSchemaObject | null { - return typeof value === 'object' && value !== null && !Array.isArray(value) - ? (value as JsonSchemaObject) - : null; -} - export function PythonPropertiesForm({ config, onChange, @@ -27,73 +18,32 @@ export function PythonPropertiesForm({ registry, scriptText, }: ScriptEnvironmentFormProps) { - const ownershipOptions = useMemo(() => { - const schema = schemaObject( - registry?.scripting?.['process-bound-python']?.config_schema, - ); - const ownershipProp = schema?.properties?.ownership; - const ref = ownershipProp?.$ref || ownershipProp?.anyOf?.[0]?.$ref; - let enumValues: string[] = ['shared', 'persistent', 'isolated']; - if (ref) { - const defName = ref.split('/').pop(); - const def = defName - ? schemaObject(schema?.definitions?.[defName]) || - schemaObject(registry?.schemas?.[defName]) - : null; - if (def?.enum) { - enumValues = def.enum; - } - } else if (ownershipProp?.enum) { - enumValues = ownershipProp.enum; - } - return enumValues; - }, [registry]); - - const getOwnershipValue = () => { - try { - const obj = JSON.parse(config); - return obj.ownership || 'persistent'; - } catch { - return 'persistent'; - } - }; - - // Validate config is valid JSON - useEffect(() => { + const parsed = useMemo(() => { try { - JSON.parse(config); - onValidationError(null); - } catch (err) { - onValidationError(err instanceof Error ? err.message : 'Invalid JSON'); + return { value: JSON.parse(config), error: null }; + } catch (error) { + return { value: { script: scriptText }, error: String(error) }; } - }, [config, onValidationError]); - - const handleOwnershipChange = (newVal: string) => { - try { - const obj = JSON.parse(config) || {}; - obj.ownership = newVal; - onChange(JSON.stringify(obj, null, 2)); - } catch { - const obj = { ownership: newVal, script: scriptText }; - onChange(JSON.stringify(obj, null, 2)); - } - }; - + }, [config, scriptText]); + useEffect( + () => onValidationError(parsed.error), + [parsed.error, onValidationError], + ); + const schema = registry?.scripting?.['process-bound-python']?.config_schema as + | RJSFSchema + | undefined; return ( - handleOwnershipChange(e.target.value)} - fullWidth + onChange(JSON.stringify(value, null, 2))} disabled={mode === 'view'} - sx={{ flex: 1 }} - > - {ownershipOptions.map((opt) => ( - - {opt.charAt(0).toUpperCase() + opt.slice(1)} - - ))} - + uiSchema={{ + 'ui:label': false, + ownership: { 'ui:title': 'Environment Ownership' }, + script: { 'ui:widget': 'hidden' }, + }} + /> ); } diff --git a/diagram-editor/frontend/forms/script-form.tsx b/diagram-editor/frontend/forms/script-form.tsx index 81fc850d..c716c312 100644 --- a/diagram-editor/frontend/forms/script-form.tsx +++ b/diagram-editor/frontend/forms/script-form.tsx @@ -7,14 +7,14 @@ import { Tooltip, Typography, } from '@mui/material'; -import { useMemo, useState } from 'react'; +import { useMemo } from 'react'; import { useDiagramProperties } from '../diagram-properties-provider'; import { useDiagramSidePanel } from '../diagram-side-panel-controller'; import { MaterialSymbol } from '../nodes'; -import { useTransientEditorDrafts } from '../transient-editor-drafts'; import BaseEditOperationForm, { type BaseEditOperationFormProps, } from './base-edit-operation-form'; +import OperationConfigForm from './operation-config-form'; import { useScriptEnvironmentNavigation } from './use-script-environment-navigation'; export type ScriptFormProps = BaseEditOperationFormProps<'script'>; @@ -23,7 +23,6 @@ const CREATE_ENVIRONMENT_VALUE = '__create_script_environment__'; function ScriptForm(props: ScriptFormProps) { const [diagramProperties] = useDiagramProperties(); - const { drafts, setOperationConfigDraft } = useTransientEditorDrafts(); const environments = diagramProperties.script_environments || {}; const openScriptEnvironment = useScriptEnvironmentNavigation(); const { @@ -33,26 +32,6 @@ function ScriptForm(props: ScriptFormProps) { requestEnvironmentLeave, } = useDiagramSidePanel(); - // Track raw string of node config to support JSON editing - const configDraftKey = `script:${props.node.id}:config`; - const [configValue, setConfigValue] = useState( - () => - drafts.operationConfigs[configDraftKey] ?? - (props.node.data.op.config - ? JSON.stringify(props.node.data.op.config, null, 2) - : ''), - ); - - const configError = useMemo(() => { - if (configValue === '') return false; - try { - JSON.parse(configValue); - return false; - } catch { - return true; - } - }, [configValue]); - const handleEnvChange = (envName: string) => requestEnvironmentLeave(() => { const updatedNode = { @@ -215,33 +194,10 @@ function ScriptForm(props: ScriptFormProps) { )} /> - { - setConfigValue(ev.target.value); - try { - const updatedNode = { ...props.node }; - updatedNode.data.op.config = - ev.target.value === '' ? undefined : JSON.parse(ev.target.value); - props.onChange?.({ - type: 'replace', - id: props.node.id, - item: updatedNode, - }); - setOperationConfigDraft(configDraftKey, undefined); - } catch { - setOperationConfigDraft(configDraftKey, ev.target.value); - } - }} - error={configError} - slotProps={{ - htmlInput: { - sx: { fontFamily: 'monospace', whiteSpace: 'nowrap' }, - }, - }} /> ); diff --git a/diagram-editor/frontend/forms/section-form.tsx b/diagram-editor/frontend/forms/section-form.tsx index a58db85d..27058bd7 100644 --- a/diagram-editor/frontend/forms/section-form.tsx +++ b/diagram-editor/frontend/forms/section-form.tsx @@ -21,10 +21,14 @@ import { } from '../nodes'; import { useRegistry } from '../registry-provider'; import { useTemplates } from '../templates-provider'; +import { useTransientEditorDrafts } from '../transient-editor-drafts'; import BaseEditOperationForm, { type BaseEditOperationFormProps, } from './base-edit-operation-form'; +import OperationConfigForm from './operation-config-form'; +import SchemaEditor from './schema-editor'; + export interface BaseSectionInterfaceFormProps { node: SectionInterfaceNode; onDelete?: (change: NodeRemoveChange) => void; @@ -80,6 +84,17 @@ export function SectionInputForm({ }); }} /> + + onChange?.({ + type: 'replace', + id: node.id, + item: { ...node, data: { ...node.data, schema } }, + }) + } + /> ); @@ -144,6 +159,17 @@ export function SectionOutputForm({ }); }} /> + + onChange?.({ + type: 'replace', + id: node.id, + item: { ...node, data: { ...node.data, schema } }, + }) + } + /> ); @@ -152,66 +178,70 @@ export function SectionOutputForm({ export type SectionFormProps = BaseEditOperationFormProps<'section'>; export function SectionForm(props: SectionFormProps) { + const { clearOperationConfigDrafts } = useTransientEditorDrafts(); const registry = useRegistry(); const [templates, _setTemplates] = useTemplates(); const sectionBuilders = Object.keys(registry.sections); const sectionTemplates = Object.keys(templates); const sections = [...sectionBuilders, ...sectionTemplates].sort(); + const op = props.node.data.op; + const template = + typeof op.template === 'string' ? templates[op.template] : undefined; + const schema = + typeof op.builder === 'string' + ? registry.sections[op.builder]?.config_schema + : template?.config_schema; + + function replaceOp(next: typeof op) { + props.onChange?.({ + type: 'replace', + id: props.node.id, + item: { ...props.node, data: { ...props.node.data, op: next } }, + }); + } + return ( { - try { - const updatedNode = { ...props.node }; - updatedNode.data.op.display_text = ev.target.value || undefined; - props.onChange?.({ - type: 'replace', - id: props.node.id, - item: updatedNode, - }); - } catch {} - }} + value={op.display_text || ''} + onChange={(ev) => + replaceOp({ ...op, display_text: ev.target.value || undefined }) + } /> option} - value={ - (props.node.data.op.builder || - props.node.data.op.template || - '') as string - } + value={(op.builder ?? op.template ?? '') as string} onChange={(_, value) => { - if (value === null) { - return; - } - - const updatedNode = { ...props.node }; - if (sectionBuilders.includes(value)) { - updatedNode.data.op.builder = value; - delete updatedNode.data.op.template; - } else if (sectionTemplates.includes(value)) { - updatedNode.data.op.template = value; - delete updatedNode.data.op.builder; - } else { - // unable to determine if selected option is a builder or template, assume template. - updatedNode.data.op.template = value; - delete updatedNode.data.op.builder; - } - props.onChange?.({ - type: 'replace', - id: props.node.id, - item: updatedNode, - }); + if (value === null || value === (op.builder ?? op.template)) return; + clearOperationConfigDrafts([props.node.id]); + const { + builder: _builder, + template: _template, + config_bindings: _bindings, + ...rest + } = op; + replaceOp( + sectionBuilders.includes(value) + ? { ...rest, builder: value } + : { ...rest, template: value }, + ); }} renderInput={(params) => ( )} /> + {(!template || schema != null) && ( + + )} ); } diff --git a/diagram-editor/frontend/forms/template-panel.tsx b/diagram-editor/frontend/forms/template-panel.tsx new file mode 100644 index 00000000..69b0e0b9 --- /dev/null +++ b/diagram-editor/frontend/forms/template-panel.tsx @@ -0,0 +1,116 @@ +import { Divider, Stack, Typography } from '@mui/material'; +import { useCompatibilityChecker } from '../connection-compatibility-provider'; +import { useNodeManager } from '../node-manager'; +import { templatePropertyNames, useTemplates } from '../templates-provider'; +import type { Schema } from '../types/api'; +import { useEdges } from '../use-edges'; +import { useReactFlow } from '../use-react-flow'; +import SchemaEditor, { schemaSummary } from './schema-editor'; + +export default function TemplatePanel({ templateId }: { templateId: string }) { + const [templates, setTemplates] = useTemplates(); + const { nodes } = useNodeManager(); + const { updateNodeData } = useReactFlow(); + const edges = useEdges(); + const { edgeResults } = useCompatibilityChecker(); + const ports = nodes.flatMap((node) => { + if (node.type !== 'sectionInput' && node.type !== 'sectionOutput') + return []; + const input = node.type === 'sectionInput'; + const edge = edges.find((e) => (input ? e.source : e.target) === node.id); + const result = edge && edgeResults.get(edge.id); + const inferredType = input ? result?.targetType : result?.sourceType; + return [ + { + id: node.id, + name: input ? node.data.remappedId : node.data.outputId, + direction: input ? 'Inputs' : 'Outputs', + type: + node.data.schema === undefined + ? (inferredType ?? 'unknown') + : schemaSummary(node.data.schema), + }, + ]; + }); + + function updateSchema(config_schema: Schema | undefined) { + const next = templatePropertyNames(config_schema); + const removed = templatePropertyNames( + templates[templateId].config_schema, + ).filter((name) => !next.includes(name)); + if (removed.length) { + for (const node of nodes) { + if ( + node.type !== 'node' && + node.type !== 'section' && + node.type !== 'script' + ) + continue; + const op = node.data.op; + const bindings = Object.entries(op.config_bindings ?? {}); + const retained = bindings.filter(([, name]) => !removed.includes(name)); + if (retained.length !== bindings.length) { + updateNodeData(node.id, { + op: { + ...op, + config_bindings: retained.length + ? Object.fromEntries(retained) + : undefined, + }, + }); + } + } + } + setTemplates((prev) => ({ + ...prev, + [templateId]: { ...prev[templateId], config_schema }, + })); + } + + return ( + + {ports.length > 0 && ( + <> + + {['Inputs', 'Outputs'].map((direction) => ( + + {direction} + {ports + .filter((port) => port.direction === direction) + .map((port) => ( + + + {port.name} + + + {port.type} + + + ))} + + ))} + + + + )} + + + ); +} diff --git a/diagram-editor/frontend/nodes/create-node.ts b/diagram-editor/frontend/nodes/create-node.ts index 1c6ea388..f67df21d 100644 --- a/diagram-editor/frontend/nodes/create-node.ts +++ b/diagram-editor/frontend/nodes/create-node.ts @@ -1,6 +1,6 @@ import type { XYPosition } from '@xyflow/react'; import { v4 as uuidv4 } from 'uuid'; -import type { DiagramOperation, NextOperation } from '../types/api'; +import type { DiagramOperation, NextOperation, Schema } from '../types/api'; import { calculateScopeBounds, LAYOUT_OPTIONS } from '../utils/layout'; import { joinNamespaces } from '../utils/namespace'; import { generateOperationId } from '../utils/operation-id'; @@ -49,11 +49,12 @@ export function createSectionInputNode( remappedId: string, targetId: NextOperation, position: XYPosition, + schema?: Schema, ): SectionInputNode { return { id: uuidv4(), type: 'sectionInput', - data: { remappedId, targetId }, + data: { remappedId, targetId, schema }, position, }; } @@ -61,11 +62,12 @@ export function createSectionInputNode( export function createSectionOutputNode( outputId: string, position: XYPosition, + schema?: Schema, ): SectionOutputNode { return { id: uuidv4(), type: 'sectionOutput', - data: { outputId }, + data: { outputId, schema }, position, }; } diff --git a/diagram-editor/frontend/nodes/section-node.tsx b/diagram-editor/frontend/nodes/section-node.tsx index ff2234df..ef9bb737 100644 --- a/diagram-editor/frontend/nodes/section-node.tsx +++ b/diagram-editor/frontend/nodes/section-node.tsx @@ -1,7 +1,7 @@ import { type NodeProps, Position } from '@xyflow/react'; import { Handle, HandleType } from '../handles'; import { useRegistry } from '../registry-provider'; -import type { NextOperation } from '../types/api'; +import type { NextOperation, Schema } from '../types/api'; import type { Node } from '../types/react-flow'; import { isSectionBuilder } from '../utils/operation'; import type { OperationNode } from '.'; @@ -16,12 +16,14 @@ import { export type SectionInputData = { remappedId: string; targetId: NextOperation; + schema?: Schema; }; export type SectionInputNode = Node; export type SectionOutputData = { outputId: string; + schema?: Schema; }; export type SectionOutputNode = Node; diff --git a/diagram-editor/frontend/templates-provider.tsx b/diagram-editor/frontend/templates-provider.tsx index ec099e0c..5dc7dbd2 100644 --- a/diagram-editor/frontend/templates-provider.tsx +++ b/diagram-editor/frontend/templates-provider.tsx @@ -6,8 +6,17 @@ import { useContext, useState, } from 'react'; +import { useTemplateId } from './editor-mode'; import type { SectionTemplate } from './types/api'; +export function templatePropertyNames( + schema: SectionTemplate['config_schema'], +): string[] { + return typeof schema === 'object' && schema?.properties + ? Object.keys(schema.properties) + : []; +} + export type TemplatesContext = [ Record, Dispatch>>, @@ -27,6 +36,12 @@ export function TemplatesProvider({ children }: PropsWithChildren) { ); } +export function useActiveTemplate(): SectionTemplate | undefined { + const id = useTemplateId(); + const context = useContext(TemplatesContextComp); + return id === undefined ? undefined : context?.[0][id]; +} + export function useTemplates(): TemplatesContext { const context = useContext(TemplatesContextComp); if (!context) { diff --git a/diagram-editor/frontend/transient-editor-drafts.tsx b/diagram-editor/frontend/transient-editor-drafts.tsx index b28efcb0..5b5d82d7 100644 --- a/diagram-editor/frontend/transient-editor-drafts.tsx +++ b/diagram-editor/frontend/transient-editor-drafts.tsx @@ -68,15 +68,12 @@ export function TransientEditorDraftProvider({ children }: PropsWithChildren) { const operationConfigs = { ...prev.operationConfigs }; let changed = false; for (const key of keys) { - const nodeKey = `node:${key}:config`; - const scriptKey = `script:${key}:config`; - if (nodeKey in operationConfigs) { - delete operationConfigs[nodeKey]; - changed = true; - } - if (scriptKey in operationConfigs) { - delete operationConfigs[scriptKey]; - changed = true; + for (const type of ['node', 'script', 'section']) { + const field = `${type}:${key}:config`; + if (field in operationConfigs) { + delete operationConfigs[field]; + changed = true; + } } } return changed ? { ...prev, operationConfigs } : prev; diff --git a/diagram-editor/frontend/types/api.d.ts b/diagram-editor/frontend/types/api.d.ts index ca8848df..e93f0c53 100644 --- a/diagram-editor/frontend/types/api.d.ts +++ b/diagram-editor/frontend/types/api.d.ts @@ -154,6 +154,9 @@ export type SectionSchema = ( } ) & { config?: unknown; + config_bindings?: { + [k: string]: string; + }; connect?: { [k: string]: NextOperation; }; @@ -619,6 +622,12 @@ export interface InputExample { export interface NodeSchema { builder: string; config?: unknown; + /** + * JSON pointers within config linked to properties of the enclosing template. + */ + config_bindings?: { + [k: string]: string; + }; /** * Override for text that should be displayed for an operation within an * editor. @@ -1306,6 +1315,12 @@ export interface ScriptSchema { * be passed in as a keyword argument named `config`. */ config?: unknown; + /** + * JSON pointers within config linked to properties of the enclosing template. + */ + config_bindings?: { + [k: string]: string; + }; /** * Override for text that should be displayed for an operation within an * editor. @@ -1354,6 +1369,13 @@ export interface ScriptEnvironmentSchema { */ export interface SectionTemplate { buffers?: InputRemapping; + config_schema?: Schema | null; + /** + * JSON Schemas for the template's exposed input ports. + */ + input_schemas?: { + [k: string]: Schema; + }; inputs?: InputRemapping; /** * Operations that define the behavior of the section. @@ -1361,6 +1383,12 @@ export interface SectionTemplate { ops: { [k: string]: DiagramOperation; }; + /** + * JSON Schemas for the template's exposed output ports. + */ + output_schemas?: { + [k: string]: Schema; + }; /** * These are the outputs that the section is exposing so you can connect * them into siblings of the section. diff --git a/diagram-editor/frontend/utils/compatibility.ts b/diagram-editor/frontend/utils/compatibility.ts index 74534b22..3a2b8a5d 100644 --- a/diagram-editor/frontend/utils/compatibility.ts +++ b/diagram-editor/frontend/utils/compatibility.ts @@ -283,12 +283,15 @@ function portRefsForEdge( focusPorts, sourcePort: templateSection && - (sourceNode.type === 'sectionInput' || + ((sourceNode.type === 'sectionInput' && + sourceNode.data.schema === undefined) || sourceNode.type === 'sectionBuffer') ? undefined : sourcePort, targetPort: - templateSection && targetNode.type === 'sectionOutput' + templateSection && + targetNode.type === 'sectionOutput' && + targetNode.data.schema === undefined ? undefined : targetPort, }; @@ -345,6 +348,7 @@ export function buildCompatibilityRequest( graph.registry, nodeManager, edges, + graph.templates[graph.templateId], ), }, script_environments: cloneJson(graph.diagramProperties) diff --git a/diagram-editor/frontend/utils/export-diagram.ts b/diagram-editor/frontend/utils/export-diagram.ts index 1138e0aa..190b7d02 100644 --- a/diagram-editor/frontend/utils/export-diagram.ts +++ b/diagram-editor/frontend/utils/export-diagram.ts @@ -553,6 +553,7 @@ export function exportTemplate( registry: DiagramElementMetadata, nodeManager: NodeManager, edges: DiagramEditorEdge[], + source?: SectionTemplate, ): SectionTemplate { nodeManager = new NodeManager(JSON.parse(JSON.stringify(nodeManager.nodes))); const fakeRoot: SubOperations = { @@ -560,11 +561,14 @@ export function exportTemplate( ops: {}, }; const template = { + ...source, + input_schemas: undefined as SectionTemplate['input_schemas'], + output_schemas: undefined as SectionTemplate['output_schemas'], inputs: {} as Record, outputs: [] as string[], buffers: {} as Record, ops: fakeRoot.ops, - } satisfies Required; + } satisfies SectionTemplate; syncEdges(registry, nodeManager, fakeRoot, edges); @@ -583,8 +587,16 @@ export function exportTemplate( } } else if (node.type === 'sectionInput') { template.inputs[node.data.remappedId] = node.data.targetId; + if (node.data.schema !== undefined) { + template.input_schemas ??= {}; + template.input_schemas[node.data.remappedId] = node.data.schema; + } } else if (node.type === 'sectionOutput') { template.outputs.push(node.data.outputId); + if (node.data.schema !== undefined) { + template.output_schemas ??= {}; + template.output_schemas[node.data.outputId] = node.data.schema; + } } else if (node.type === 'sectionBuffer') { template.buffers[node.data.remappedId] = node.data.targetId; } diff --git a/diagram-editor/frontend/utils/load-diagram.ts b/diagram-editor/frontend/utils/load-diagram.ts index 709b1c76..69741d2c 100644 --- a/diagram-editor/frontend/utils/load-diagram.ts +++ b/diagram-editor/frontend/utils/load-diagram.ts @@ -198,18 +198,18 @@ export function loadTemplate(template: SectionTemplate): Graph { stubDiagram.ops = template.ops; const initialNodes: DiagramEditorNode[] = []; - if (template.inputs) { - if (Array.isArray(template.inputs)) { - for (const input of template.inputs) { - initialNodes.push(createSectionInputNode(input, input, { x: 0, y: 0 })); - } - } else { - for (const [remappedId, targetId] of Object.entries(template.inputs)) { - initialNodes.push( - createSectionInputNode(remappedId, targetId, { x: 0, y: 0 }), - ); - } - } + const inputs = Array.isArray(template.inputs) + ? template.inputs.map((name) => [name, name] as const) + : Object.entries(template.inputs ?? {}); + for (const [name, target] of inputs) { + initialNodes.push( + createSectionInputNode( + name, + target, + { x: 0, y: 0 }, + template.input_schemas?.[name], + ), + ); } if (template.buffers) { @@ -230,7 +230,13 @@ export function loadTemplate(template: SectionTemplate): Graph { if (template.outputs) { for (const output of template.outputs) { - initialNodes.push(createSectionOutputNode(output, { x: 0, y: 0 })); + initialNodes.push( + createSectionOutputNode( + output, + { x: 0, y: 0 }, + template.output_schemas?.[output], + ), + ); } } diff --git a/diagram-editor/jest-setup.ts b/diagram-editor/jest-setup.ts index 600b9be0..ae9dc577 100644 --- a/diagram-editor/jest-setup.ts +++ b/diagram-editor/jest-setup.ts @@ -1,5 +1,11 @@ import '@testing-library/jest-dom'; +// RJSF clones JSON values with the browser's structuredClone API. +if (!globalThis.structuredClone) { + const { serialize, deserialize } = jest.requireActual('node:v8'); + globalThis.structuredClone = (value) => deserialize(serialize(value)); +} + // jsdom has no layout engine and so no ResizeObserver. if (!globalThis.ResizeObserver) { globalThis.ResizeObserver = class { diff --git a/diagram-editor/jest.config.js b/diagram-editor/jest.config.js index a6804d98..45fd32bb 100644 --- a/diagram-editor/jest.config.js +++ b/diagram-editor/jest.config.js @@ -7,6 +7,10 @@ export default { testEnvironment: 'jsdom', transform: { ...tsJestTransformCfg, + '^.+\\.js$': ['ts-jest', { tsconfig: { allowJs: true }, diagnostics: false }], }, + // Use the same MUI exports as the browser and compile RJSF's ESM dependencies. + moduleNameMapper: { '^@rjsf/mui$': '/node_modules/@rjsf/mui/lib/index.js' }, + transformIgnorePatterns: ['node_modules/(?!\\.pnpm/|@x0k/json-schema-merge/|@rjsf/mui/)'], setupFilesAfterEnv: ['./jest-setup.ts'], }; diff --git a/diagram-editor/package.json b/diagram-editor/package.json index cd65dbaf..04f4a506 100644 --- a/diagram-editor/package.json +++ b/diagram-editor/package.json @@ -32,10 +32,15 @@ "@emotion/styled": "^11.14.0", "@fontsource/roboto": "^5.2.5", "@material-symbols/font-400": "^0.31.9", + "@mui/icons-material": "7.1.0", "@mui/material": "^7.1.0", + "@rjsf/core": "6.11.1", + "@rjsf/mui": "6.11.1", + "@rjsf/utils": "6.11.1", + "@rjsf/validator-ajv8": "6.11.1", "@uiw/react-codemirror": "^4.25.9", "@xyflow/react": "^12.6.1", - "ajv": "^8.17.1", + "ajv": "^8.20.0", "ajv-formats": "^3.0.1", "cel-js": "^0.7.1", "fast-deep-equal": "^3.1.3", diff --git a/diagram-editor/server/api/executor.rs b/diagram-editor/server/api/executor.rs index 427df1c9..3adad492 100644 --- a/diagram-editor/server/api/executor.rs +++ b/diagram-editor/server/api/executor.rs @@ -266,7 +266,7 @@ fn check_connections( .connections .into_iter() .map(|connection| match &inference { - Ok(inference) => check_connection(registry, connection, inference), + Ok(inference) => check_connection(registry, &request.diagram, connection, inference), Err(error) => CompatibilityResult::terminal( connection.id, CompatibilityStatus::Unknown, @@ -279,6 +279,7 @@ fn check_connections( fn check_connection( registry: &DiagramElementRegistry, + diagram: &Diagram, connection: CompatibilityConnection, inference: &HashMap>>, ) -> CompatibilityResult { @@ -397,8 +398,71 @@ fn check_connection( names.dedup(); (!names.is_empty()).then(|| names.join(" | ")) }; - let source_type_name = type_names(&source_types); - let target_type_name = type_names(&target_types); + let source_declared = connection + .source_port + .as_ref() + .and_then(|p| declared_port_schema(diagram, p)); + let target_declared = connection + .target_port + .as_ref() + .and_then(|p| declared_port_schema(diagram, p)); + let declared_label = |schema: &serde_json::Value| { + ["title", "type", "$ref"] + .iter() + .find_map(|key| schema[key].as_str().map(str::to_owned)) + }; + let source_type_name = source_declared + .and_then(declared_label) + .or_else(|| type_names(&source_types)); + let target_type_name = target_declared + .and_then(declared_label) + .or_else(|| type_names(&target_types)); + if source_declared.is_some() || target_declared.is_some() { + let inferred_schemas = |types: &[(usize, bool)]| { + types + .iter() + .filter(|(_, certain)| *certain) + .map(|(index, _)| { + registry + .message_schema(*index) + .map(|schema| schema.as_value()) + }) + .collect::>() + }; + let sources = source_declared + .map(|s| vec![Some(s)]) + .unwrap_or_else(|| inferred_schemas(&source_types)); + let targets = target_declared + .map(|s| vec![Some(s)]) + .unwrap_or_else(|| inferred_schemas(&target_types)); + let mut uncertain = sources.is_empty() || targets.is_empty(); + for source in &sources { + for target in &targets { + let compatible = source + .zip(*target) + .and_then(|(s, t)| registry.message_schemas_compatible(s, t)); + match compatible { + Some(true) => {} + Some(false) => { + return CompatibilityResult::with_types( + connection.id, + CompatibilityStatus::Incompatible, + "The source and target schemas accept no common value", + source_type_name, + target_type_name, + ); + } + None => uncertain = true, + } + } + } + if uncertain { + unknown.get_or_insert(( + "Cannot determine whether the port schemas match".into(), + true, + )); + } + } if let Some((reason, provisional)) = unknown { return CompatibilityResult { provisional, @@ -440,6 +504,51 @@ fn check_connection( ) } +fn declared_port_schema<'a>(diagram: &'a Diagram, port: &PortRef) -> Option<&'a serde_json::Value> { + use crossflow::{Identifier, OperationRef, OutputRef, SectionProvider}; + let (namespaces, section, name, input) = match port { + PortRef::Input(OperationRef::Named(port)) => ( + &port.namespaces, + port.exposed_namespace.as_ref()?, + &port.name, + true, + ), + PortRef::Output(OutputRef::Named(port)) => { + let [Identifier::Name(key), Identifier::Name(name)] = &port.key[..] else { + return None; + }; + if key.as_ref() != "connect" { + return None; + } + (&port.namespaces, &port.operation, name, false) + } + _ => return None, + }; + let template = |op: &DiagramOperation| { + let DiagramOperation::Section(section) = op else { + return None; + }; + let SectionProvider::Template(template) = §ion.provider else { + return None; + }; + diagram.templates.get(template) + }; + let mut ops = &diagram.ops; + for namespace in namespaces.iter() { + ops = match ops.get(namespace)?.as_ref() { + DiagramOperation::Scope(scope) => &scope.ops, + op => &template(op)?.ops, + }; + } + let section = template(ops.get(section)?)?; + let declarations = if input { + §ion.input_schemas + } else { + §ion.output_schemas + }; + Some(declarations.get(name)?.as_value()) +} + fn is_missing_context_error(error: &DiagramError) -> bool { matches!( &error.code, diff --git a/diagram-editor/wasm/src/executor.rs b/diagram-editor/wasm/src/executor.rs index 8ccbcf0d..186dc3c4 100644 --- a/diagram-editor/wasm/src/executor.rs +++ b/diagram-editor/wasm/src/executor.rs @@ -113,6 +113,7 @@ mod tests { let add_op = Arc::new(DiagramOperation::Node(NodeSchema { builder: "add3".into(), config: serde_json::Value::Null.into(), + config_bindings: Default::default(), next: NextOperation::Builtin { builtin: crossflow::BuiltinTarget::Terminate, }, @@ -141,6 +142,7 @@ mod tests { let add_op = Arc::new(DiagramOperation::Node(NodeSchema { builder: "add3".into(), config: serde_json::Value::Null.into(), + config_bindings: Default::default(), next: NextOperation::Builtin { builtin: crossflow::BuiltinTarget::Terminate, }, diff --git a/diagram.schema.json b/diagram.schema.json index 2fee07e4..04b12030 100644 --- a/diagram.schema.json +++ b/diagram.schema.json @@ -654,6 +654,13 @@ "type": "string" }, "config": true, + "config_bindings": { + "description": "JSON pointers within config linked to properties of the enclosing template.", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, "display_text": { "description": "Override for text that should be displayed for an operation within an\neditor.", "type": [ @@ -733,6 +740,12 @@ } ] }, + "Schema": { + "type": [ + "object", + "boolean" + ] + }, "ScopeSchema": { "description": "Create a scope which will function like its own encapsulated workflow\nwithin the paren workflow. Each message that enters a scope will trigger\na new independent session for that scope to begin running with the incoming\nmessage itself being the input message of the scope. When multiple sessions\nfor the same scope are running, they cannot see or interfere with each other.\n\nOnce a session terminates, the scope will send the terminating message as\nits output. Scopes can use the `stream_out` operation to stream messages out\nto the parent workflow while running.\n\nScopes have two common uses:\n* isolate - Prevent simultaneous runs of the same workflow components\n (especially buffers) from interfering with each other.\n* race - Run multiple branches simultaneously inside the scope and race\n them against each ohter. The first branch that reaches the scope's\n terminate operation \"wins\" the race, and only its output will continue\n on in the parent workflow. All other branches will be disposed.\n\n# Examples\n```\n# crossflow::Diagram::from_json_str(r#\"\n{\n \"version\": \"0.1.0\",\n \"start\": \"approach_door\",\n \"ops\": {\n \"approach_door\": {\n \"type\": \"scope\",\n \"start\": \"begin\",\n \"ops\": {\n \"begin\": {\n \"type\": \"fork_clone\",\n \"next\": [\n \"move_to_door\",\n \"detect_door_proximity\"\n ]\n },\n \"move_to_door\": {\n \"type\": \"node\",\n \"builder\": \"move\",\n \"config\": {\n \"place\": \"L1_north_lobby_outside\"\n },\n \"next\": { \"builtin\" : \"terminate\" }\n },\n \"detect_proximity\": {\n \"type\": \"node\",\n \"builder\": \"detect_proximity\",\n \"config\": {\n \"type\": \"door\",\n \"name\": \"L1_north_lobby\"\n },\n \"next\": { \"builtin\" : \"terminate\" }\n }\n },\n \"next\": { \"builtin\" : \"try_open_door\" }\n }\n }\n}\n# \"#)?;\n# Ok::<_, serde_json::Error>(())\n```", "type": "object", @@ -844,6 +857,13 @@ "config": { "description": "Configured data to pass into the function that `run` refers to. This will\nbe passed in as a keyword argument named `config`." }, + "config_bindings": { + "description": "JSON pointers within config linked to properties of the enclosing template.", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, "display_text": { "description": "Override for text that should be displayed for an operation within an\neditor.", "type": [ @@ -909,8 +929,12 @@ "description": "Connect the request to a registered section.\n\n```\n# crossflow::Diagram::from_json_str(r#\"\n{\n \"version\": \"0.1.0\",\n \"start\": \"section_op\",\n \"ops\": {\n \"section_op\": {\n \"type\": \"section\",\n \"builder\": \"my_section_builder\",\n \"connect\": {\n \"my_section_output\": { \"builtin\": \"terminate\" }\n }\n }\n }\n}\n# \"#)?;\n# Ok::<_, serde_json::Error>(())\n```\n\nCustom sections can also be created via templates\n```\n# crossflow::Diagram::from_json_str(r#\"\n{\n \"version\": \"0.1.0\",\n \"templates\": {\n \"my_template\": {\n \"inputs\": [\"section_input\"],\n \"outputs\": [\"section_output\"],\n \"buffers\": [],\n \"ops\": {\n \"section_input\": {\n \"type\": \"node\",\n \"builder\": \"my_node\",\n \"next\": \"section_output\"\n }\n }\n }\n },\n \"start\": \"section_op\",\n \"ops\": {\n \"section_op\": {\n \"type\": \"section\",\n \"template\": \"my_template\",\n \"connect\": {\n \"section_output\": { \"builtin\": \"terminate\" }\n }\n }\n }\n}\n# \"#)?;\n# Ok::<_, serde_json::Error>(())\n```", "type": "object", "properties": { - "config": { - "default": null + "config": true, + "config_bindings": { + "type": "object", + "additionalProperties": { + "type": "string" + } }, "connect": { "type": "object", @@ -977,6 +1001,24 @@ "$ref": "#/$defs/InputRemapping", "default": [] }, + "config_schema": { + "description": "The JSON Schema of a section instance's configuration.", + "anyOf": [ + { + "$ref": "#/$defs/Schema" + }, + { + "type": "null" + } + ] + }, + "input_schemas": { + "description": "JSON Schemas for the template's exposed input ports.", + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/Schema" + } + }, "inputs": { "description": "These are the inputs that the section is exposing for its sibling\noperations to send outputs into.", "$ref": "#/$defs/InputRemapping", @@ -989,6 +1031,13 @@ "$ref": "#/$defs/DiagramOperation" } }, + "output_schemas": { + "description": "JSON Schemas for the template's exposed output ports.", + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/Schema" + } + }, "outputs": { "description": "These are the outputs that the section is exposing so you can connect\nthem into siblings of the section.", "type": "array", diff --git a/handbook/src/diagram-section-templates.md b/handbook/src/diagram-section-templates.md index 7dc4c94a..974ed360 100644 --- a/handbook/src/diagram-section-templates.md +++ b/handbook/src/diagram-section-templates.md @@ -13,7 +13,7 @@ Whereas section builders have static message types for their inputs and outputs, ### Section Template Schema -The [`SectionTemplate`][SectionTemplate] schema consists of four fields: +The [`SectionTemplate`][SectionTemplate] schema describes the graph and its interface: * [`"inputs"`][SectionTemplate::inputs]: an [input remapping] that says which input slots inside the section should be exposed to operations that are outside of the section. These are similar to the `InputSlot<_>` fields of a [section builder](./diagram-section-builders.md#closure). @@ -22,6 +22,24 @@ The [`SectionTemplate`][SectionTemplate] schema consists of four fields: None of the operations inside `"ops"` can use any of these names as a key. * [`"ops"`][SectionTemplate::ops]: a dictionary of operation instances that exist inside this section, along with information about how they connect to each other. The syntax of this section is exactly the same as the `"ops"` section of regular [diagrams](./diagram-syntax.md#operations) and scope operations. +* `config_schema` is an optional JSON Schema for the configuration supplied by each instance. +* `input_schemas` and `output_schemas` optionally declare schemas by exposed port name. The editor uses these declarations to check connections. Ports without declarations use the existing type inference. + +### Configuring an Instance + +For example, a template can expose a required integer named `factor` through this configuration schema. + +```json +{ + "type": "object", + "properties": { "factor": { "type": "integer" } }, + "required": ["factor"] +} +``` + +Bindings refer to names in the configuration schema’s top-level `properties`. A property can itself use a registered type or alternatives. In the editor, add `factor` in the Template panel. Open the multiply node inside the template and use the link beside its numeric config to select `factor`. The editor saves `"config_bindings": { "": "factor" }` on that node. The empty JSON Pointer addresses its entire numeric config. A pointer such as `"/scale"` addresses a field inside an object config. + +Give one section instance `"config": { "factor": 3 }` and another `"config": { "factor": 5 }`. The same template now multiplies an input of 2 by 3 or 5, producing 6 or 10. The executor validates each instance when building the diagram. For an omitted optional property it uses the property's declared default, or keeps the node's own value if there is no default. ### Referencing Section Templates diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 52e36600..8df885fb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -47,9 +47,24 @@ importers: '@material-symbols/font-400': specifier: ^0.31.9 version: 0.31.9 + '@mui/icons-material': + specifier: 7.1.0 + version: 7.1.0(@mui/material@7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(@types/react@19.1.5)(react@19.1.0) '@mui/material': specifier: ^7.1.0 version: 7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0) + '@rjsf/core': + specifier: 6.11.1 + version: 6.11.1(@rjsf/utils@6.11.1(react@19.1.0))(react@19.1.0) + '@rjsf/mui': + specifier: 6.11.1 + version: 6.11.1(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@mui/icons-material@7.1.0(@mui/material@7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@mui/material@7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(@rjsf/core@6.11.1(@rjsf/utils@6.11.1(react@19.1.0))(react@19.1.0))(@rjsf/utils@6.11.1(react@19.1.0))(react@19.1.0) + '@rjsf/utils': + specifier: 6.11.1 + version: 6.11.1(react@19.1.0) + '@rjsf/validator-ajv8': + specifier: 6.11.1 + version: 6.11.1(@rjsf/utils@6.11.1(react@19.1.0)) '@uiw/react-codemirror': specifier: ^4.25.9 version: 4.25.9(@babel/runtime@7.27.6)(@codemirror/autocomplete@6.20.1)(@codemirror/language@6.12.3)(@codemirror/lint@6.9.5)(@codemirror/search@6.7.0)(@codemirror/state@6.6.0)(@codemirror/theme-one-dark@6.1.3)(@codemirror/view@6.41.1)(codemirror@6.0.2)(react-dom@19.1.0(react@19.1.0))(react@19.1.0) @@ -57,11 +72,11 @@ importers: specifier: ^12.6.1 version: 12.6.4(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0) ajv: - specifier: ^8.17.1 - version: 8.17.1 + specifier: ^8.20.0 + version: 8.20.0 ajv-formats: specifier: ^3.0.1 - version: 3.0.1(ajv@8.17.1) + version: 3.0.1(ajv@8.20.0) cel-js: specifier: ^0.7.1 version: 0.7.1 @@ -789,6 +804,17 @@ packages: '@mui/core-downloads-tracker@7.1.0': resolution: {integrity: sha512-E0OqhZv548Qdc0PwWhLVA2zmjJZSTvaL4ZhoswmI8NJEC1tpW2js6LLP827jrW9MEiXYdz3QS6+hask83w74yQ==} + '@mui/icons-material@7.1.0': + resolution: {integrity: sha512-1mUPMAZ+Qk3jfgL5ftRR06ATH/Esi0izHl1z56H+df6cwIlCWG66RXciUqeJCttbOXOQ5y2DCjLZI/4t3Yg3LA==} + engines: {node: '>=14.0.0'} + peerDependencies: + '@mui/material': ^7.1.0 + '@types/react': ^17.0.0 || ^18.0.0 || ^19.0.0 + react: ^17.0.0 || ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + '@types/react': + optional: true + '@mui/material@7.1.0': resolution: {integrity: sha512-ahUJdrhEv+mCp4XHW+tHIEYzZMSRLg8z4AjUOsj44QpD1ZaMxQoVOG2xiHvLFdcsIPbgSRx1bg1eQSheHBgvtg==} engines: {node: '>=14.0.0'} @@ -884,6 +910,37 @@ packages: '@popperjs/core@2.11.8': resolution: {integrity: sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==} + '@rjsf/core@6.11.1': + resolution: {integrity: sha512-2kH39lspUUQf552l+vSTj9vnwdv1gSOyDKqSDmFuTo16+92zbJ381knrQpk3KKowjp/sbxu4qPiBptgXH6i4UQ==} + engines: {node: '>=20'} + peerDependencies: + '@rjsf/utils': ^6.11.1 + react: '>=18' + + '@rjsf/mui@6.11.1': + resolution: {integrity: sha512-CzPi4qel4xfCN0uJvfPSHNW1tnl1kKDT+oRz3YHs7fyd/GcKabr3iyJxLXnDWdSCVAiqUYFjc/A8wh7cZ2nH1w==} + engines: {node: '>=20'} + peerDependencies: + '@emotion/react': ^11.7.0 + '@emotion/styled': ^11.6.0 + '@mui/icons-material': ^7.0.0 || ^9.0.0 + '@mui/material': ^7.0.0 || ^9.0.0 + '@rjsf/core': ^6.11.1 + '@rjsf/utils': ^6.11.1 + react: '>=18' + + '@rjsf/utils@6.11.1': + resolution: {integrity: sha512-rHQ4jNkhws3YUjvM/6RyW78l0mVfnt6w2j3/giUcS5F0cendCLYykFuSnE2fQxBwmknv4ANMOugwXOgcIbfvnA==} + engines: {node: '>=20'} + peerDependencies: + react: '>=18' + + '@rjsf/validator-ajv8@6.11.1': + resolution: {integrity: sha512-LV7ibrep/kaRzkwzhLAmJY9SHOIZuX9fQO+0VCfm0FOGXneGU9xQEJvHft7R84uqtDTTQZqRq40HcQjqY0rsyw==} + engines: {node: '>=20'} + peerDependencies: + '@rjsf/utils': ^6.11.1 + '@rollup/pluginutils@5.1.4': resolution: {integrity: sha512-USm05zrsFxYLPdWWq+K3STlWiT/3ELn3RcV5hJMghpeAIhxfsUIg6mt12CBJBInWMV4VneoV7SfGv8xIwo2qNQ==} engines: {node: '>=14.0.0'} @@ -1396,6 +1453,9 @@ packages: '@webassemblyjs/wast-printer@1.14.1': resolution: {integrity: sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw==} + '@x0k/json-schema-merge@1.2.0': + resolution: {integrity: sha512-PeMfO7U8RrH4NfyxRPh0E9DN32FSFl7JsyG/IOI87YgQomK6kfNat2ETHCEX3S41AsoEfRTxiScUNkrd0mgbyw==} + '@xtuc/ieee754@1.2.0': resolution: {integrity: sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==} @@ -1457,8 +1517,8 @@ packages: peerDependencies: ajv: ^8.8.2 - ajv@8.17.1: - resolution: {integrity: sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==} + ajv@8.20.0: + resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} ansi-escapes@4.3.2: resolution: {integrity: sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==} @@ -2028,6 +2088,10 @@ packages: fast-deep-equal@3.1.3: resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + fast-equals@6.4.1: + resolution: {integrity: sha512-qHLxdeRmasP83VXLGXCyUh7D2bo2WFI/IEB+T0WSf3mwuTD2A5F+HQQmeF+UXCfuLPmqUNYcFJjwAN9JabA6+Q==} + engines: {node: '>=6.0.0'} + fast-glob@3.3.3: resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==} engines: {node: '>=8.6.0'} @@ -2041,6 +2105,9 @@ packages: fast-uri@3.0.6: resolution: {integrity: sha512-Atfo14OibSv5wAp4VWNsFYE1AchQRTv9cBGWET4pZWHzYshFSS9NQI6I57rdKn9croWVMbYFbLhJ+yJvmZIIHw==} + fast-uri@4.2.3: + resolution: {integrity: sha512-I1PXwP5eAhlNlcdpjt9CgB59op2ZvZfxw+BkqGFVIUOgNpCVTcTqp3HhTX7brxj5vsip+nSY4nTvff+eIA76hg==} + fastq@1.19.1: resolution: {integrity: sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==} @@ -2558,6 +2625,10 @@ packages: jsonfile@6.1.0: resolution: {integrity: sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==} + jsonpointer@5.0.1: + resolution: {integrity: sha512-p/nXbhSEcu3pZRdkW1OfJhpsVtW1gd4Wa1fnQc9YLiTfAjn0312eMKimbdIQzuZl9aa9xUGaRlP9T/CJE/ditQ==} + engines: {node: '>=0.10.0'} + keyv@4.5.4: resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} @@ -2631,6 +2702,24 @@ packages: makeerror@1.0.12: resolution: {integrity: sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==} + markdown-to-jsx@9.10.6: + resolution: {integrity: sha512-vvd4cMAAK6RDCzklzRYykG8Tos1Wyid8IoxenyiSAnGb1JIX2fTzn6MuU5QBu9Kb4BdjOCnKlbs84NQRVsaaVA==} + engines: {node: '>= 18'} + peerDependencies: + react: '>= 16.0.0' + react-native: '*' + solid-js: '>=1.0.0' + vue: '>=3.0.0' + peerDependenciesMeta: + react: + optional: true + react-native: + optional: true + solid-js: + optional: true + vue: + optional: true + math-intrinsics@1.1.0: resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} engines: {node: '>= 0.4'} @@ -4284,6 +4373,14 @@ snapshots: '@mui/core-downloads-tracker@7.1.0': {} + '@mui/icons-material@7.1.0(@mui/material@7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(@types/react@19.1.5)(react@19.1.0)': + dependencies: + '@babel/runtime': 7.27.6 + '@mui/material': 7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0) + react: 19.1.0 + optionalDependencies: + '@types/react': 19.1.5 + '@mui/material@7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0)': dependencies: '@babel/runtime': 7.27.1 @@ -4377,6 +4474,41 @@ snapshots: '@popperjs/core@2.11.8': {} + '@rjsf/core@6.11.1(@rjsf/utils@6.11.1(react@19.1.0))(react@19.1.0)': + dependencies: + '@rjsf/utils': 6.11.1(react@19.1.0) + markdown-to-jsx: 9.10.6(react@19.1.0) + react: 19.1.0 + transitivePeerDependencies: + - react-native + - solid-js + - vue + + '@rjsf/mui@6.11.1(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@mui/icons-material@7.1.0(@mui/material@7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@mui/material@7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(@rjsf/core@6.11.1(@rjsf/utils@6.11.1(react@19.1.0))(react@19.1.0))(@rjsf/utils@6.11.1(react@19.1.0))(react@19.1.0)': + dependencies: + '@emotion/react': 11.14.0(@types/react@19.1.5)(react@19.1.0) + '@emotion/styled': 11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0) + '@mui/icons-material': 7.1.0(@mui/material@7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(@types/react@19.1.5)(react@19.1.0) + '@mui/material': 7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0) + '@rjsf/core': 6.11.1(@rjsf/utils@6.11.1(react@19.1.0))(react@19.1.0) + '@rjsf/utils': 6.11.1(react@19.1.0) + react: 19.1.0 + + '@rjsf/utils@6.11.1(react@19.1.0)': + dependencies: + '@x0k/json-schema-merge': 1.2.0 + fast-equals: 6.4.1 + fast-uri: 4.2.3 + jsonpointer: 5.0.1 + react: 19.1.0 + react-is: 18.3.1 + + '@rjsf/validator-ajv8@6.11.1(@rjsf/utils@6.11.1(react@19.1.0))': + dependencies: + '@rjsf/utils': 6.11.1(react@19.1.0) + ajv: 8.20.0 + ajv-formats: 2.1.1(ajv@8.20.0) + '@rollup/pluginutils@5.1.4(rollup@4.43.0)': dependencies: '@types/estree': 1.0.8 @@ -4901,6 +5033,10 @@ snapshots: '@webassemblyjs/ast': 1.14.1 '@xtuc/long': 4.2.2 + '@x0k/json-schema-merge@1.2.0': + dependencies: + '@types/json-schema': 7.0.15 + '@xtuc/ieee754@1.2.0': {} '@xtuc/long@4.2.2': {} @@ -4947,20 +5083,20 @@ snapshots: transitivePeerDependencies: - supports-color - ajv-formats@2.1.1(ajv@8.17.1): + ajv-formats@2.1.1(ajv@8.20.0): optionalDependencies: - ajv: 8.17.1 + ajv: 8.20.0 - ajv-formats@3.0.1(ajv@8.17.1): + ajv-formats@3.0.1(ajv@8.20.0): optionalDependencies: - ajv: 8.17.1 + ajv: 8.20.0 - ajv-keywords@5.1.0(ajv@8.17.1): + ajv-keywords@5.1.0(ajv@8.20.0): dependencies: - ajv: 8.17.1 + ajv: 8.20.0 fast-deep-equal: 3.1.3 - ajv@8.17.1: + ajv@8.20.0: dependencies: fast-deep-equal: 3.1.3 fast-uri: 3.0.6 @@ -5560,6 +5696,8 @@ snapshots: fast-deep-equal@3.1.3: {} + fast-equals@6.4.1: {} + fast-glob@3.3.3: dependencies: '@nodelib/fs.stat': 2.0.5 @@ -5574,6 +5712,8 @@ snapshots: fast-uri@3.0.6: {} + fast-uri@4.2.3: {} + fastq@1.19.1: dependencies: reusify: 1.1.0 @@ -6324,6 +6464,8 @@ snapshots: optionalDependencies: graceful-fs: 4.2.11 + jsonpointer@5.0.1: {} + keyv@4.5.4: dependencies: json-buffer: 3.0.1 @@ -6388,6 +6530,10 @@ snapshots: dependencies: tmpl: 1.0.5 + markdown-to-jsx@9.10.6(react@19.1.0): + optionalDependencies: + react: 19.1.0 + math-intrinsics@1.1.0: {} memfs@4.17.2: @@ -6766,9 +6912,9 @@ snapshots: schema-utils@4.3.2: dependencies: '@types/json-schema': 7.0.15 - ajv: 8.17.1 - ajv-formats: 2.1.1(ajv@8.17.1) - ajv-keywords: 5.1.0(ajv@8.17.1) + ajv: 8.20.0 + ajv-formats: 2.1.1(ajv@8.20.0) + ajv-keywords: 5.1.0(ajv@8.20.0) semver@6.3.1: {} diff --git a/src/diagram/node_schema.rs b/src/diagram/node_schema.rs index 265a5da9..a393faa4 100644 --- a/src/diagram/node_schema.rs +++ b/src/diagram/node_schema.rs @@ -20,9 +20,9 @@ use serde::{Deserialize, Serialize}; use std::{collections::HashMap, sync::Arc}; use super::{ - BuildDiagramOperation, BuildStatus, BuilderContext, BuilderId, DiagramErrorCode, - InferenceContext, JsonMessage, MissingStream, NextOperation, OperationName, Operations, - Templates, TraceInfo, TraceSettings, is_default, + BuildDiagramOperation, BuildStatus, BuilderContext, BuilderId, ConfigBindings, + DiagramErrorCode, InferenceContext, JsonMessage, MissingStream, NextOperation, OperationName, + Operations, Templates, TraceInfo, TraceSettings, is_default, }; /// Create an operation that that takes an input message and produces an @@ -73,6 +73,9 @@ pub struct NodeSchema { pub builder: BuilderId, #[serde(default, skip_serializing_if = "is_default")] pub config: Arc, + /// JSON pointers within config linked to properties of the enclosing template. + #[serde(default, skip_serializing_if = "ConfigBindings::is_empty")] + pub config_bindings: ConfigBindings, pub next: NextOperation, #[serde(default, skip_serializing_if = "is_default")] pub stream_out: HashMap, @@ -86,6 +89,9 @@ impl BuildDiagramOperation for NodeSchema { id: &OperationName, ctx: &mut BuilderContext, ) -> Result { + if !self.config_bindings.is_empty() { + return Err(super::SectionError::UnresolvedConfigBindings.into()); + } let node_registration = ctx.registry.get_node_registration(&self.builder)?; let mut node = node_registration.create_node(ctx.builder, (*self.config).clone())?; diff --git a/src/diagram/registration.rs b/src/diagram/registration.rs index 57566558..d34757c2 100644 --- a/src/diagram/registration.rs +++ b/src/diagram/registration.rs @@ -371,6 +371,51 @@ impl DiagramElementRegistry { self.messages.registration.get::() } + /// JSON schema of a registered message, for comparing it with a declared port. + pub fn message_schema(&self, index: usize) -> Option<&Schema> { + self.messages + .registration + .get_by_index(index) + .ok()? + .schema + .as_ref() + } + + pub(super) fn schema_with_definitions(&self, schema: &JsonMessage) -> JsonMessage { + let mut schema = schema.clone(); + if let Some(object) = schema.as_object_mut() { + object.entry("schemas").or_insert_with(|| { + JsonMessage::Object(self.messages.schema_generator.definitions().clone()) + }); + } + schema + } + + /// Whether all source messages satisfy the target schema. Partially overlapping + /// schemas and cases that cannot be decided statically return `None`. + pub fn message_schemas_compatible( + &self, + source: &JsonMessage, + target: &JsonMessage, + ) -> Option { + use jsonschema::canonical::{Containment, Satisfiability}; + let canonical = |schema| { + jsonschema::canonical::options() + .should_validate_formats(false) + .canonicalize(&self.schema_with_definitions(schema)) + .ok() + }; + let source = canonical(source)?; + let target = canonical(target)?; + if target.covers(&source).ok()? == Containment::Yes { + Some(true) + } else if source.intersect(&target).ok()?.satisfiability() == Satisfiability::No { + Some(false) + } else { + None + } + } + pub fn get_message_operations_by_index( &self, message_index: usize, diff --git a/src/diagram/script_schema.rs b/src/diagram/script_schema.rs index 9bc1afed..d71fb3fb 100644 --- a/src/diagram/script_schema.rs +++ b/src/diagram/script_schema.rs @@ -27,10 +27,11 @@ use std::{ }; use crate::{ - Async, BasicConnect, BuildDiagramOperation, BuildStatus, BuilderContext, ConnectIntoTarget, - DiagramErrorCode, DynInputSlot, DynOutput, DynamicallyNamedStream, InferenceContext, - IntoCallback, JsonMessage, NextOperation, Node, OperationName, Operations, ScriptMessage, - StreamOf, Templates, Text, TraceInfo, TraceSettings, TypeInfo, TypeMismatch, is_default, + Async, BasicConnect, BuildDiagramOperation, BuildStatus, BuilderContext, ConfigBindings, + ConnectIntoTarget, DiagramErrorCode, DynInputSlot, DynOutput, DynamicallyNamedStream, + InferenceContext, IntoCallback, JsonMessage, NextOperation, Node, OperationName, Operations, + ScriptMessage, StreamOf, Templates, Text, TraceInfo, TraceSettings, TypeInfo, TypeMismatch, + is_default, }; #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] @@ -44,6 +45,9 @@ pub struct ScriptSchema { /// be passed in as a keyword argument named `config`. #[serde(default, skip_serializing_if = "is_default")] pub config: Arc, + /// JSON pointers within config linked to properties of the enclosing template. + #[serde(default, skip_serializing_if = "ConfigBindings::is_empty")] + pub config_bindings: ConfigBindings, /// The operation that the final output of this Python operation will be passed to pub next: NextOperation, /// Specify what happens if an error occurs during the script, such as an @@ -70,6 +74,9 @@ impl BuildDiagramOperation for ScriptSchema { id: &OperationName, ctx: &mut BuilderContext, ) -> Result { + if !self.config_bindings.is_empty() { + return Err(super::SectionError::UnresolvedConfigBindings.into()); + } let env = ctx.get_script_environment(&self.environment)?; let script = env.compile(&self.run, &self.config).map_err(|error| { DiagramErrorCode::ScriptCompileError { diff --git a/src/diagram/section_schema.rs b/src/diagram/section_schema.rs index 941b21e0..2aa3ecd9 100644 --- a/src/diagram/section_schema.rs +++ b/src/diagram/section_schema.rs @@ -15,9 +15,12 @@ * */ -use std::{collections::HashMap, sync::Arc}; +use std::{ + collections::{BTreeMap, HashMap}, + sync::Arc, +}; -use schemars::JsonSchema; +use schemars::{JsonSchema, Schema}; use serde::{Deserialize, Serialize}; use crate::{ @@ -26,13 +29,16 @@ use crate::{ use super::{ BuildDiagramOperation, BuildStatus, BuilderContext, BuilderId, DiagramElementRegistry, - DiagramErrorCode, DynInputSlot, DynOutput, MessageRegistrations, NamespacedOperation, - NextOperation, OperationName, OperationRef, Operations, RedirectConnection, Templates, - TraceInfo, TraceSettings, + DiagramErrorCode, DiagramOperation, DynInputSlot, DynOutput, MessageRegistrations, + NamespacedOperation, NextOperation, OperationName, OperationRef, Operations, + RedirectConnection, Templates, TraceInfo, TraceSettings, }; pub use crossflow_derive::Section; +/// Maps JSON pointers in an operation's config to properties of its enclosing template. +pub type ConfigBindings = BTreeMap; + #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum SectionProvider { @@ -99,8 +105,15 @@ pub enum SectionProvider { pub struct SectionSchema { #[serde(flatten)] pub provider: SectionProvider, - #[serde(default)] - pub config: Arc, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "serde_with::rust::unwrap_or_skip::deserialize" + )] + #[schemars(with = "JsonMessage")] + pub config: Option>, + #[serde(default, skip_serializing_if = "ConfigBindings::is_empty")] + pub config_bindings: ConfigBindings, #[serde(default)] pub connect: HashMap, #[serde(flatten)] @@ -113,13 +126,19 @@ impl BuildDiagramOperation for SectionSchema { id: &OperationName, ctx: &mut BuilderContext, ) -> Result { + if !self.config_bindings.is_empty() { + return Err(SectionError::UnresolvedConfigBindings.into()); + } match &self.provider { SectionProvider::Builder(section_builder) => { let section_registration = ctx.registry.get_section_registration(section_builder)?; let section = section_registration - .create_section(ctx.builder, (*self.config).clone())? + .create_section( + ctx.builder, + self.config.as_deref().cloned().unwrap_or_default(), + )? .into_slots(); // TODO(@mxgrey): Figure out how to automatically trace operations @@ -162,8 +181,9 @@ impl BuildDiagramOperation for SectionSchema { SectionProvider::Template(section_template) => { let section = ctx.templates.get_template(section_template)?; - for (child_id, op) in section.ops.iter() { - ctx.add_child_operation(id, child_id, op, section.ops.clone(), None, None); + let ops = section.configured_ops(self.config.as_deref(), ctx.registry)?; + for (child_id, op) in ops.iter() { + ctx.add_child_operation(id, child_id, op, ops.clone(), None, None); } section @@ -393,6 +413,15 @@ pub struct SectionBuffer { #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct SectionTemplate { + /// The JSON Schema of a section instance's configuration. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub config_schema: Option, + /// JSON Schemas for the template's exposed input ports. + #[serde(default, skip_serializing_if = "HashMap::is_empty")] + pub input_schemas: HashMap, + /// JSON Schemas for the template's exposed output ports. + #[serde(default, skip_serializing_if = "HashMap::is_empty")] + pub output_schemas: HashMap, /// These are the inputs that the section is exposing for its sibling /// operations to send outputs into. #[serde(default)] @@ -409,6 +438,101 @@ pub struct SectionTemplate { pub ops: Operations, } +impl SectionTemplate { + fn configured_ops( + &self, + config: Option<&JsonMessage>, + registry: &DiagramElementRegistry, + ) -> Result { + let Some(schema) = &self.config_schema else { + // Unresolved bindings, including those outside a template, fail when built. + return Ok(self.ops.clone()); + }; + let schema = registry.schema_with_definitions(schema.as_value()); + let validator = jsonschema::draft202012::options() + .should_validate_formats(false) + .build(&schema) + .map_err(|e| SectionError::InvalidConfig(e.to_string()))?; + let mut values = config.cloned().unwrap_or_else(|| serde_json::json!({})); + let properties = schema["properties"].as_object(); + if let (Some(properties), Some(values)) = (properties, values.as_object_mut()) { + for (key, property) in properties { + let required = schema["required"] + .as_array() + .is_some_and(|keys| keys.iter().any(|value| value.as_str() == Some(key))); + if !required && let Some(default) = property.get("default") { + values.entry(key).or_insert_with(|| default.clone()); + } + } + } + validator + .validate(&values) + .map_err(|e| SectionError::InvalidConfig(format!("#{}: {e}", e.instance_path())))?; + let mut ops = self.ops.clone(); + bind_config(&mut ops, &values, properties)?; + Ok(ops) + } +} + +fn bind_config( + ops: &mut Operations, + values: &JsonMessage, + properties: Option<&serde_json::Map>, +) -> Result<(), SectionError> { + for op in Arc::make_mut(ops).values_mut() { + let op = Arc::make_mut(op); + let bindings = match op { + DiagramOperation::Node(node) => &mut node.config_bindings, + DiagramOperation::Script(script) => &mut script.config_bindings, + DiagramOperation::Section(section) => &mut section.config_bindings, + DiagramOperation::Scope(scope) => { + bind_config(&mut scope.ops, values, properties)?; + continue; + } + _ => continue, + }; + for (pointer, name) in std::mem::take(bindings) { + if !properties.is_some_and(|p| p.contains_key(name.as_ref())) { + return Err(SectionError::UnknownConfigProperty(name)); + } + if let Some(value) = values.get(name.as_ref()) { + let config = match op { + DiagramOperation::Node(node) => &mut node.config, + DiagramOperation::Script(script) => &mut script.config, + DiagramOperation::Section(section) => { + section.config.get_or_insert_with(Default::default) + } + _ => unreachable!(), + }; + set_config_value(Arc::make_mut(config), &pointer, value.clone()) + .ok_or(SectionError::InvalidBinding(pointer))?; + } + } + } + Ok(()) +} + +fn set_config_value(config: &mut JsonMessage, pointer: &str, value: JsonMessage) -> Option<()> { + let mut field = config; + let mut tokens = pointer.split('/'); + if tokens.next() != Some("") { + return None; + } + for token in tokens { + let key = token.replace("~1", "/").replace("~0", "~"); + if field.is_null() { + *field = serde_json::json!({}); + } + field = match field { + JsonMessage::Object(object) => object.entry(key).or_insert(JsonMessage::Null), + JsonMessage::Array(array) => array.get_mut(key.parse::().ok()?)?, + _ => return None, + }; + } + *field = value; + Some(()) +} + /// This defines how sections remap their inner operations (inputs and buffers) /// to expose them to operations that are siblings to the section. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] @@ -474,6 +598,14 @@ impl InputRemapping { pub enum SectionError { #[error("operation has extra output [{0}] that is not in the section")] UnknownOutput(OperationName), + #[error("invalid section configuration: {0}")] + InvalidConfig(String), + #[error("unknown section configuration property [{0}]")] + UnknownConfigProperty(OperationName), + #[error("invalid configuration binding path [{0}]")] + InvalidBinding(String), + #[error("configuration bindings require an enclosing template with a configuration schema")] + UnresolvedConfigBindings, } #[cfg(test)] From a60c3b6de68a249403130ab1feb2427ef10edee3 Mon Sep 17 00:00:00 2001 From: ArizmendiWan <2311602492@qq.com> Date: Wed, 25 Nov 2026 02:14:56 -0600 Subject: [PATCH 2/6] Reuse RJSF controls for section schemas and configuration Share field actions across node and section forms, preserve typed choices and nullable values, and show type warnings when binding template properties. Simplify how declared port schemas are loaded and checked. Signed-off-by: ArizmendiWan <2311602492@qq.com> --- diagram-editor/dist.hash | 2 +- diagram-editor/frontend/command-panel.tsx | 55 +- diagram-editor/frontend/diagram-editor.tsx | 38 +- .../frontend/diagram-side-panel.tsx | 9 +- .../forms/base-edit-operation-form.tsx | 12 + .../frontend/forms/field-actions.tsx | 215 +++++++ .../frontend/forms/node-form.test.tsx | 20 +- diagram-editor/frontend/forms/node-form.tsx | 16 +- .../frontend/forms/operation-config-form.tsx | 184 +++--- .../frontend/forms/schema-config-form.tsx | 547 +++++++++++------- .../frontend/forms/schema-editor.tsx | 370 ++++++------ .../script-environment-workspace.test.tsx | 9 +- .../script-environments/python-form.test.tsx | 8 +- .../forms/script-environments/python-form.tsx | 7 +- .../frontend/forms/section-form.tsx | 45 +- .../frontend/forms/template-panel.tsx | 135 +++-- diagram-editor/frontend/nodes/create-node.ts | 8 +- .../frontend/templates-provider.tsx | 8 - .../use-responsive-edit-popover-position.ts | 4 +- diagram-editor/frontend/utils/load-diagram.ts | 39 +- diagram-editor/frontend/utils/schema-types.ts | 147 +++++ diagram-editor/server/api/executor.rs | 110 ++-- src/diagram/section_schema.rs | 28 +- 23 files changed, 1226 insertions(+), 790 deletions(-) create mode 100644 diagram-editor/frontend/forms/field-actions.tsx create mode 100644 diagram-editor/frontend/utils/schema-types.ts diff --git a/diagram-editor/dist.hash b/diagram-editor/dist.hash index bfb7f735..52fa6dc8 100644 --- a/diagram-editor/dist.hash +++ b/diagram-editor/dist.hash @@ -1 +1 @@ -48877e9161887be9da9a19db2aed9a4376751b1242f5ebbce9f7336095d74869 \ No newline at end of file +7e04d640b755643ee77d285e6f4b6d5b68e7bb2520ca4af2a2f0ced1bcf1f997 \ No newline at end of file diff --git a/diagram-editor/frontend/command-panel.tsx b/diagram-editor/frontend/command-panel.tsx index 5103d361..2c1f3771 100644 --- a/diagram-editor/frontend/command-panel.tsx +++ b/diagram-editor/frontend/command-panel.tsx @@ -88,36 +88,31 @@ function CommandPanel({ )} - - - - - - + {( + [ + ['environments', 'Script Environment Manager', 'code'], + [ + 'properties', + editorMode.mode === EditorMode.Template + ? 'Template settings' + : 'Diagram properties', + 'info', + ], + ] as const + ).map(([tab, title, symbol]) => ( + + + + ))} {editorMode.mode === EditorMode.Normal && ( ); } diff --git a/diagram-editor/frontend/forms/schema-editor.tsx b/diagram-editor/frontend/forms/schema-editor.tsx index 372118ea..7361f9dc 100644 --- a/diagram-editor/frontend/forms/schema-editor.tsx +++ b/diagram-editor/frontend/forms/schema-editor.tsx @@ -13,33 +13,45 @@ import { TextField, Typography, } from '@mui/material'; -import type { FieldProps, RJSFSchema, UiSchema } from '@rjsf/utils'; -import { useMemo, useState } from 'react'; -import { MaterialSymbol } from '../nodes'; +import { + type FieldProps, + isObject, + type RJSFSchema, + type UiSchema, +} from '@rjsf/utils'; +import type { NodeChange } from '@xyflow/react'; +import { createContext, useContext, useMemo, useState } from 'react'; +import { + MaterialSymbol, + type SectionInputNode, + type SectionOutputNode, +} from '../nodes'; import { useRegistry } from '../registry-provider'; -import type { Schema } from '../types/api'; import ajv from '../utils/ajv'; import SchemaConfigForm from './schema-config-form'; -type SchemaObject = Exclude; -const types = [ - 'string', - 'integer', - 'number', - 'boolean', - 'null', - 'array', - 'object', -]; -const kinds = [...types, 'enum', 'anyOf', 'oneOf', '$ref', 'any']; -const initial = { type: 'string' }; +type Schema = RJSFSchema | boolean; +const initial: RJSFSchema = { type: 'string' }; +const schemasByKind: Record = { + string: initial, + integer: { type: 'integer' }, + number: { type: 'number' }, + boolean: { type: 'boolean' }, + null: { type: 'null' }, + array: { type: 'array', items: initial }, + object: { type: 'object' }, + enum: { enum: ['option'] }, + anyOf: { anyOf: [initial] }, + oneOf: { oneOf: [initial] }, + any: {}, +}; const choiceRef = { $ref: '#/$defs/choice' }; const choice: RJSFSchema = { default: '', - anyOf: [ + oneOf: [ { type: 'string', default: '' }, { type: 'number', default: 0 }, - { type: 'boolean', default: false }, + { type: 'boolean', enum: [true, false], default: false }, { type: 'null' }, { type: 'array', items: choiceRef, default: [] }, { type: 'object', additionalProperties: choiceRef, default: {} }, @@ -49,10 +61,12 @@ const choice: RJSFSchema = { function concreteType(type: unknown) { if (Array.isArray(type) && type.length === 2 && type.includes('null')) type = type.find((t) => t !== 'null'); - return typeof type === 'string' && types.includes(type) ? type : undefined; + return typeof type === 'string' && schemasByKind[type]?.type === type + ? type + : undefined; } -function withNull(schema: SchemaObject, allow: boolean): SchemaObject { +function withNull(schema: RJSFSchema, allow: boolean): RJSFSchema { const next = { ...schema }; const type = concreteType(schema.type); if (type && type !== 'null') next.type = allow ? [type, 'null'] : type; @@ -75,27 +89,6 @@ function kindOf(schema: Schema) { return 'JSON'; } -function schemaForKind( - kind: string, - registeredRef: string | undefined, -): SchemaObject { - switch (kind) { - case 'any': - return {}; - case '$ref': - return { $ref: registeredRef }; - case 'enum': - return { enum: ['option'] }; - case 'anyOf': - case 'oneOf': - return { [kind]: [initial] }; - case 'array': - return { type: kind, items: initial }; - default: - return { type: kind }; - } -} - export function schemaSummary(schema: Schema) { if (typeof schema === 'boolean') return schema ? 'any' : 'never'; if (typeof schema.title === 'string') return schema.title; @@ -104,10 +97,7 @@ export function schemaSummary(schema: Schema) { } function schemaError(value: unknown) { - if ( - typeof value !== 'boolean' && - (!value || typeof value !== 'object' || Array.isArray(value)) - ) + if (typeof value !== 'boolean' && !isObject(value)) return 'A JSON Schema must be an object or a boolean.'; try { if (!ajv.validateSchema(value)) return ajv.errorsText(ajv.errors); @@ -125,6 +115,28 @@ interface EditorProps { alternative?: boolean; } +const PortSchemaContext = createContext(false); + +export function PortSchemaEditor< + N extends SectionInputNode | SectionOutputNode, +>({ node, onChange }: { node: N; onChange?: (change: NodeChange) => void }) { + return ( + + + onChange?.({ + type: 'replace', + id: node.id, + item: { ...node, data: { ...node.data, schema } }, + }) + } + /> + + ); +} + function SchemaItem({ formData, onChange, fieldPathId }: FieldProps) { const index = fieldPathId.path.at(-1); return ( @@ -141,27 +153,43 @@ function SchemaItem({ formData, onChange, fieldPathId }: FieldProps) { } function schemaList(items: UiSchema): UiSchema { - const paper = { elevation: 0, sx: { bgcolor: 'transparent' } }; - const slots = (rjsfSlotProps: Record) => ({ - 'ui:options': { mui: { rjsfSlotProps } }, - }); + // RJSF provides the add button and item toolbar. Share the title row with + // the add button, keeping a single column of items below it. + const flatPaper = { elevation: 0, sx: { bgcolor: 'transparent' } }; return { - ...slots({ - arrayPaper: paper, - arrayBox: { sx: { p: 0 } }, - titleBox: { sx: { mt: 0, mb: 2 } }, - titleTypography: { variant: 'subtitle2' }, - }), + 'ui:mui': { + rjsfSlotProps: { + arrayPaper: flatPaper, + arrayBox: { sx: { p: 0, display: 'grid', rowGap: 2 } }, + titleBox: { + sx: { + gridArea: '1 / 1', + m: 0, + alignContent: 'center', + borderBottom: 1, + borderColor: 'divider', + }, + }, + titleTypography: { variant: 'subtitle2', sx: { width: 'fit-content' } }, + titleDivider: { sx: { display: 'none' } }, + arrayAddButtonGridContainer: { + sx: { gridArea: '1 / 1', justifySelf: 'end' }, + }, + arrayAddButtonBox: { sx: { mt: 0 } }, + }, + }, items: { ...items, - ...slots({ - arrayItemPaper: paper, - arrayItemInnerBox: { sx: { p: 0 } }, - arrayItemOuterBox: { sx: { mb: 0 } }, - arrayItemGridContainer: { sx: { gap: 1, mb: 2 } }, - arrayItemGridItem: { size: 'grow', sx: { overflow: 'visible' } }, - arrayItemToolbarGrid: { sx: { mt: 0 } }, - }), + 'ui:mui': { + rjsfSlotProps: { + arrayItemPaper: flatPaper, + arrayItemInnerBox: { sx: { p: 0 } }, + arrayItemOuterBox: { sx: { mb: 0 } }, + arrayItemGridContainer: { sx: { gap: 1 } }, + arrayItemGridItem: { size: 'grow', sx: { overflow: 'visible' } }, + arrayItemToolbarGrid: { sx: { mt: 0 } }, + }, + }, }, }; } @@ -173,14 +201,15 @@ function SchemaFields({ onChange, inlineTitle, }: { - value: SchemaObject; - onChange: (value: SchemaObject) => void; + value: RJSFSchema; + onChange: (value: RJSFSchema) => void; inlineTitle?: boolean; }) { const registry = useRegistry(); + const port = useContext(PortSchemaContext); const kind = kindOf(value); const type = concreteType(value.type); - const choices = Array.isArray(value.enum) ? value.enum : undefined; + const choices = value.enum; // A sibling constraint can reject null even when the type admits it. // Those schemas retain their explicit alternatives or JSON editor. const canAllowNull = @@ -218,8 +247,7 @@ function SchemaFields({ title: 'Registered type', enum: [...new Set([...refs, String(value.$ref)])], }; - if (kind === 'enum') { - const values = value.enum as NonNullable; + if (choices) { fields.enum = { type: 'array', title: 'Choices', @@ -227,8 +255,8 @@ function SchemaFields({ uniqueItems: true, items: { ...choiceRef, title: 'Choice type' }, }; - if (values.length) - fields.default = { title: 'Default value', enum: values }; + if (!port && choices.length) + fields.default = { title: 'Default value', enum: choices }; } if (kind === 'array') fields.items = { type: 'object', title: 'Items' }; if (kind === 'anyOf' || kind === 'oneOf') @@ -242,18 +270,15 @@ function SchemaFields({ fields.minimum = { type: 'number', title: 'Minimum' }; fields.maximum = { type: 'number', title: 'Maximum' }; } - if (['string', 'integer', 'number', 'boolean'].includes(kind)) + if (!port && ['string', 'integer', 'number', 'boolean'].includes(kind)) fields.default = { title: 'Default value', ...(kind === 'boolean' ? { enum: nullable ? [true, false, null] : [true, false] } - : { type: value.type as RJSFSchema['type'] }), + : { type: value.type }), }; - const data = Object.fromEntries( - Object.keys(fields) - .filter((k) => k in value) - .map((k) => [k, value[k]]), - ); + const kinds = { ...schemasByKind }; + if (refs.length || kind === '$ref') kinds.$ref = { $ref: refs[0] }; return ( @@ -263,31 +288,26 @@ function SchemaFields({ label="Type" value={kind} onChange={({ target }) => { - const next = schemaForKind(target.value, refs[0]); + const next = kinds[target.value]; onChange({ ...(canAllowNull && nullable ? withNull(next, true) : next), ...(value.title !== undefined && { title: value.title }), }); }} > - {kinds - .filter((k) => k !== '$ref' || refs.length || kind === '$ref') - .map((k) => ( - - {k === '$ref' ? 'Registered type' : k} - - ))} + {Object.keys(kinds).map((k) => ( + + {k === '$ref' ? 'Registered type' : k} + + ))} {canAllowNull && ( onChange(withNull(value, checked))} - /> - } + control={} + checked={nullable} + onChange={(_, checked) => onChange(withNull(value, checked))} /> )} @@ -298,7 +318,7 @@ function SchemaFields({ properties: fields, ...(kind === 'enum' && { $defs: { choice } }), }} - value={data} + value={value} uiSchema={{ default: { 'ui:placeholder': 'No default' }, enum: schemaList({ 'ui:emptyValue': '' }), @@ -306,19 +326,18 @@ function SchemaFields({ anyOf: schemaList(nested), oneOf: schemaList(nested), }} - onChange={(next) => { - const kept = Object.fromEntries( - Object.entries(value).filter(([key]) => !(key in fields)), - ); + onChange={(data) => { + const next = data as RJSFSchema; // Older enums declared a redundant type. Widen it when the author // adds a choice of another type, preserving other schema constraints. if ( enumType && - (value.enum as unknown[]).every((item) => enumType(item)) && - (next as { enum: unknown[] }).enum.some((item) => !enumType(item)) - ) - delete kept.type; - onChange({ ...kept, ...(next as SchemaObject) }); + choices?.every((item) => enumType(item)) && + next.enum?.some((item) => !enumType(item)) + ) { + const { type: _oldType, ...widened } = next; + onChange(widened); + } else onChange(next); }} /> {kind === 'object' && } @@ -341,22 +360,20 @@ interface DraftProps { function SchemaDialog(props: DraftProps) { const [name, setName] = useState(props.name ?? ''); const [required, setRequired] = useState(props.required ?? false); - const [value, setValue] = useState(props.value); - const [json, setJson] = useState( - props.json || schemaError(value) || kindOf(value) === 'JSON' - ? JSON.stringify(value, null, 2) - : undefined, + const [draft, setDraft] = useState(() => + props.json || schemaError(props.value) || kindOf(props.value) === 'JSON' + ? JSON.stringify(props.value, null, 2) + : props.value, ); - let schema: unknown = value; + const json = typeof draft === 'string'; + let schema = props.value; let error: string | undefined; - if (json !== undefined) { - try { - schema = JSON.parse(json); - } catch (err) { - error = String(err); - } + try { + schema = json ? JSON.parse(draft) : draft; + error = schemaError(schema); + } catch (err) { + error = String(err); } - error ??= schemaError(schema); const duplicate = props.name === '' && props.names?.includes(name); return ( @@ -378,35 +395,33 @@ function SchemaDialog(props: DraftProps) { onChange={({ target }) => setName(target.value)} /> )} - {json !== undefined ? ( + {json ? ( setJson(target.value)} + value={draft} + onChange={({ target }) => setDraft(target.value)} error={!!error} helperText={error} slotProps={{ input: { sx: { fontFamily: 'monospace' } } }} /> ) : ( )} {props.name !== undefined && ( setRequired(checked)} - /> - } + control={} + checked={required} + onChange={(_, checked) => setRequired(checked)} /> )} @@ -414,26 +429,19 @@ function SchemaDialog(props: DraftProps) { @@ -442,19 +450,32 @@ function SchemaDialog(props: DraftProps) { ); } +function iconButton(label: string, symbol: string, onClick: () => void) { + return ( + + + + ); +} + function Properties({ value, onChange, }: { - value: SchemaObject; - onChange: (schema: SchemaObject) => void; + value: RJSFSchema; + onChange: (schema: RJSFSchema) => void; }) { - const fields = (value.properties ?? {}) as Record; - const required = (value.required ?? []) as string[]; - const [editing, setEditing] = useState<{ key?: string } | null>(null); - function update(name: string, schema?: Schema, isRequired = false) { - const properties = { ...fields, [name]: schema }; + const fields = value.properties ?? {}; + const required = value.required ?? []; + const [editing, setEditing] = useState(); + function update( + schema: Schema | undefined, + name: string, + isRequired = false, + ) { + const properties = { ...fields }; if (schema === undefined) delete properties[name]; + else properties[name] = schema; const keys = isRequired ? [...new Set([...required, name])] : required.filter((key) => key !== name); @@ -464,7 +485,7 @@ function Properties({ properties, ...(keys.length > 0 && { required: keys }), }); - setEditing(null); + setEditing(undefined); } return ( @@ -486,43 +507,30 @@ function Properties({ {schemaSummary(schema)} - setEditing({ key: name })} - > - - - { - if (window.confirm(`Delete property “${name}”?`)) update(name); - }} - > - - + {iconButton(`Edit ${name}`, 'edit', () => setEditing(name))} + {iconButton(`Delete ${name}`, 'delete', () => { + if (window.confirm(`Delete property “${name}”?`)) + update(undefined, name); + })} ))} - {editing && ( + {editing !== undefined && ( setEditing(null)} - onSave={(schema, name, required) => update(name, schema, required)} + required={editing !== null && required.includes(editing)} + onClose={() => setEditing(undefined)} + onSave={update} /> )} @@ -573,23 +581,17 @@ export default function SchemaEditor({ - {removable && value !== undefined && ( - { - if (!object || window.confirm('Remove the configuration schema?')) - onChange(undefined); - }} - > - - - )} + {removable && + value !== undefined && + iconButton(`Remove ${label}`, 'delete', () => { + if (!object || window.confirm('Remove the configuration schema?')) + onChange(undefined); + })} {object && !schemaError(schema) && kindOf(schema) === 'object' && ( <> - + )} {open && ( diff --git a/diagram-editor/frontend/forms/script-environment-workspace.test.tsx b/diagram-editor/frontend/forms/script-environment-workspace.test.tsx index 5a0004e4..6807f25b 100644 --- a/diagram-editor/frontend/forms/script-environment-workspace.test.tsx +++ b/diagram-editor/frontend/forms/script-environment-workspace.test.tsx @@ -237,12 +237,9 @@ describe('ScriptEnvironmentWorkspace', () => { screen.queryByRole('textbox', { name: 'script_content' }), ).not.toBeInTheDocument(); changeScript('second'); - fireEvent.click(screen.getByRole('button', { name: 'Edit as JSON' })); - expect( - JSON.parse( - (screen.getByLabelText('Builder Config') as HTMLTextAreaElement).value, - ), - ).toEqual({ + fireEvent.click(screen.getByRole('button', { name: 'Edit JSON' })); + const config = screen.getByLabelText('Builder Config'); + expect(JSON.parse((config as HTMLTextAreaElement).value)).toEqual({ script_content: 'second', }); }); diff --git a/diagram-editor/frontend/forms/script-environments/python-form.test.tsx b/diagram-editor/frontend/forms/script-environments/python-form.test.tsx index 5f515fcc..2be575f7 100644 --- a/diagram-editor/frontend/forms/script-environments/python-form.test.tsx +++ b/diagram-editor/frontend/forms/script-environments/python-form.test.tsx @@ -35,8 +35,7 @@ describe('PythonPropertiesForm', () => { ); const selectElement = screen.getByLabelText('Environment Ownership'); - expect(selectElement).toBeTruthy(); - expect(screen.getByText('persistent')).toBeTruthy(); + expect(selectElement).toHaveValue('persistent'); }); test('invokes onChange when ownership option is changed', async () => { @@ -106,7 +105,10 @@ describe('PythonPropertiesForm', () => { }, definitions: { PythonEnvironmentOwnership: { - enum: ['shared_custom', 'persistent_custom'], + oneOf: [ + { type: 'string', const: 'shared_custom' }, + { type: 'string', const: 'persistent_custom' }, + ], }, }, }, diff --git a/diagram-editor/frontend/forms/script-environments/python-form.tsx b/diagram-editor/frontend/forms/script-environments/python-form.tsx index fc45ffca..3d31ccf2 100644 --- a/diagram-editor/frontend/forms/script-environments/python-form.tsx +++ b/diagram-editor/frontend/forms/script-environments/python-form.tsx @@ -1,4 +1,3 @@ -import type { RJSFSchema } from '@rjsf/utils'; import { useEffect, useMemo } from 'react'; import SchemaConfigForm from '../schema-config-form'; import type { ScriptEnvironmentFormProps } from './registry'; @@ -29,13 +28,11 @@ export function PythonPropertiesForm({ () => onValidationError(parsed.error), [parsed.error, onValidationError], ); - const schema = registry?.scripting?.['process-bound-python']?.config_schema as - | RJSFSchema - | undefined; + const schema = registry.scripting?.['process-bound-python']?.config_schema; return ( onChange(JSON.stringify(value, null, 2))} disabled={mode === 'view'} diff --git a/diagram-editor/frontend/forms/section-form.tsx b/diagram-editor/frontend/forms/section-form.tsx index 27058bd7..939134e1 100644 --- a/diagram-editor/frontend/forms/section-form.tsx +++ b/diagram-editor/frontend/forms/section-form.tsx @@ -24,10 +24,10 @@ import { useTemplates } from '../templates-provider'; import { useTransientEditorDrafts } from '../transient-editor-drafts'; import BaseEditOperationForm, { type BaseEditOperationFormProps, + operationUpdater, } from './base-edit-operation-form'; - import OperationConfigForm from './operation-config-form'; -import SchemaEditor from './schema-editor'; +import { PortSchemaEditor } from './schema-editor'; export interface BaseSectionInterfaceFormProps { node: SectionInterfaceNode; @@ -84,17 +84,7 @@ export function SectionInputForm({ }); }} /> - - onChange?.({ - type: 'replace', - id: node.id, - item: { ...node, data: { ...node.data, schema } }, - }) - } - /> + ); @@ -159,17 +149,7 @@ export function SectionOutputForm({ }); }} /> - - onChange?.({ - type: 'replace', - id: node.id, - item: { ...node, data: { ...node.data, schema } }, - }) - } - /> + ); @@ -180,12 +160,13 @@ export type SectionFormProps = BaseEditOperationFormProps<'section'>; export function SectionForm(props: SectionFormProps) { const { clearOperationConfigDrafts } = useTransientEditorDrafts(); const registry = useRegistry(); - const [templates, _setTemplates] = useTemplates(); + const [templates] = useTemplates(); const sectionBuilders = Object.keys(registry.sections); const sectionTemplates = Object.keys(templates); const sections = [...sectionBuilders, ...sectionTemplates].sort(); const op = props.node.data.op; + const replaceOp = operationUpdater(props); const template = typeof op.template === 'string' ? templates[op.template] : undefined; const schema = @@ -193,14 +174,6 @@ export function SectionForm(props: SectionFormProps) { ? registry.sections[op.builder]?.config_schema : template?.config_schema; - function replaceOp(next: typeof op) { - props.onChange?.({ - type: 'replace', - id: props.node.id, - item: { ...props.node, data: { ...props.node.data, op: next } }, - }); - } - return ( {(!template || schema != null) && ( - + )} ); diff --git a/diagram-editor/frontend/forms/template-panel.tsx b/diagram-editor/frontend/forms/template-panel.tsx index 69b0e0b9..15010c5f 100644 --- a/diagram-editor/frontend/forms/template-panel.tsx +++ b/diagram-editor/frontend/forms/template-panel.tsx @@ -1,64 +1,65 @@ -import { Divider, Stack, Typography } from '@mui/material'; +import { Box, Divider, Stack, Typography } from '@mui/material'; +import { Fragment, type ReactNode } from 'react'; import { useCompatibilityChecker } from '../connection-compatibility-provider'; import { useNodeManager } from '../node-manager'; -import { templatePropertyNames, useTemplates } from '../templates-provider'; +import { useTemplates } from '../templates-provider'; import type { Schema } from '../types/api'; import { useEdges } from '../use-edges'; import { useReactFlow } from '../use-react-flow'; +import { schemaDocument } from '../utils/schema-types'; import SchemaEditor, { schemaSummary } from './schema-editor'; export default function TemplatePanel({ templateId }: { templateId: string }) { const [templates, setTemplates] = useTemplates(); + const template = templates[templateId]; const { nodes } = useNodeManager(); const { updateNodeData } = useReactFlow(); const edges = useEdges(); const { edgeResults } = useCompatibilityChecker(); - const ports = nodes.flatMap((node) => { - if (node.type !== 'sectionInput' && node.type !== 'sectionOutput') - return []; + const ports: Record<'Inputs' | 'Outputs', ReactNode[]> = { + Inputs: [], + Outputs: [], + }; + for (const node of nodes) { + if (node.type !== 'sectionInput' && node.type !== 'sectionOutput') continue; const input = node.type === 'sectionInput'; const edge = edges.find((e) => (input ? e.source : e.target) === node.id); const result = edge && edgeResults.get(edge.id); - const inferredType = input ? result?.targetType : result?.sourceType; - return [ - { - id: node.id, - name: input ? node.data.remappedId : node.data.outputId, - direction: input ? 'Inputs' : 'Outputs', - type: - node.data.schema === undefined - ? (inferredType ?? 'unknown') - : schemaSummary(node.data.schema), - }, - ]; - }); + const type = + node.data.schema === undefined + ? ((input ? result?.targetType : result?.sourceType) ?? 'unknown') + : schemaSummary(node.data.schema); + ports[input ? 'Inputs' : 'Outputs'].push( + +
{input ? node.data.remappedId : node.data.outputId}
+
{type}
+
, + ); + } function updateSchema(config_schema: Schema | undefined) { - const next = templatePropertyNames(config_schema); - const removed = templatePropertyNames( - templates[templateId].config_schema, - ).filter((name) => !next.includes(name)); - if (removed.length) { - for (const node of nodes) { - if ( - node.type !== 'node' && - node.type !== 'section' && - node.type !== 'script' - ) - continue; - const op = node.data.op; - const bindings = Object.entries(op.config_bindings ?? {}); - const retained = bindings.filter(([, name]) => !removed.includes(name)); - if (retained.length !== bindings.length) { - updateNodeData(node.id, { - op: { - ...op, - config_bindings: retained.length - ? Object.fromEntries(retained) - : undefined, - }, - }); - } + const names = Object.keys(schemaDocument(config_schema).properties ?? {}); + const removed = Object.keys( + schemaDocument(template.config_schema).properties ?? {}, + ).filter((name) => !names.includes(name)); + for (const node of nodes) { + if ( + node.type !== 'node' && + node.type !== 'section' && + node.type !== 'script' + ) + continue; + const op = node.data.op; + if (!op.config_bindings) continue; + const bindings = Object.entries(op.config_bindings); + const kept = bindings.filter(([, name]) => !removed.includes(name)); + if (kept.length !== bindings.length) { + updateNodeData(node.id, { + op: { + ...op, + config_bindings: kept.length ? Object.fromEntries(kept) : undefined, + }, + }); } } setTemplates((prev) => ({ @@ -69,36 +70,30 @@ export default function TemplatePanel({ templateId }: { templateId: string }) { return ( - {ports.length > 0 && ( + {(ports.Inputs.length > 0 || ports.Outputs.length > 0) && ( <> - {['Inputs', 'Outputs'].map((direction) => ( + {Object.entries(ports).map(([direction, entries]) => ( {direction} - {ports - .filter((port) => port.direction === direction) - .map((port) => ( - - - {port.name} - - - {port.type} - - - ))} + + {entries} + ))} @@ -108,7 +103,7 @@ export default function TemplatePanel({ templateId }: { templateId: string }) { diff --git a/diagram-editor/frontend/nodes/create-node.ts b/diagram-editor/frontend/nodes/create-node.ts index f67df21d..1c6ea388 100644 --- a/diagram-editor/frontend/nodes/create-node.ts +++ b/diagram-editor/frontend/nodes/create-node.ts @@ -1,6 +1,6 @@ import type { XYPosition } from '@xyflow/react'; import { v4 as uuidv4 } from 'uuid'; -import type { DiagramOperation, NextOperation, Schema } from '../types/api'; +import type { DiagramOperation, NextOperation } from '../types/api'; import { calculateScopeBounds, LAYOUT_OPTIONS } from '../utils/layout'; import { joinNamespaces } from '../utils/namespace'; import { generateOperationId } from '../utils/operation-id'; @@ -49,12 +49,11 @@ export function createSectionInputNode( remappedId: string, targetId: NextOperation, position: XYPosition, - schema?: Schema, ): SectionInputNode { return { id: uuidv4(), type: 'sectionInput', - data: { remappedId, targetId, schema }, + data: { remappedId, targetId }, position, }; } @@ -62,12 +61,11 @@ export function createSectionInputNode( export function createSectionOutputNode( outputId: string, position: XYPosition, - schema?: Schema, ): SectionOutputNode { return { id: uuidv4(), type: 'sectionOutput', - data: { outputId, schema }, + data: { outputId }, position, }; } diff --git a/diagram-editor/frontend/templates-provider.tsx b/diagram-editor/frontend/templates-provider.tsx index 5dc7dbd2..2c7a9d4c 100644 --- a/diagram-editor/frontend/templates-provider.tsx +++ b/diagram-editor/frontend/templates-provider.tsx @@ -9,14 +9,6 @@ import { import { useTemplateId } from './editor-mode'; import type { SectionTemplate } from './types/api'; -export function templatePropertyNames( - schema: SectionTemplate['config_schema'], -): string[] { - return typeof schema === 'object' && schema?.properties - ? Object.keys(schema.properties) - : []; -} - export type TemplatesContext = [ Record, Dispatch>>, diff --git a/diagram-editor/frontend/use-responsive-edit-popover-position.ts b/diagram-editor/frontend/use-responsive-edit-popover-position.ts index 9ccb7248..ec7e2cd0 100644 --- a/diagram-editor/frontend/use-responsive-edit-popover-position.ts +++ b/diagram-editor/frontend/use-responsive-edit-popover-position.ts @@ -20,9 +20,9 @@ function useViewportWidth(): number { return viewportWidth; } -export function useDiagramSidePanelWidth(): number { +export function useDiagramSidePanelWidth(open: boolean): number { const { - state: { open, expanded, width }, + state: { expanded, width }, } = useDiagramSidePanel(); const viewportWidth = useViewportWidth(); diff --git a/diagram-editor/frontend/utils/load-diagram.ts b/diagram-editor/frontend/utils/load-diagram.ts index 69741d2c..6559f87e 100644 --- a/diagram-editor/frontend/utils/load-diagram.ts +++ b/diagram-editor/frontend/utils/load-diagram.ts @@ -198,18 +198,18 @@ export function loadTemplate(template: SectionTemplate): Graph { stubDiagram.ops = template.ops; const initialNodes: DiagramEditorNode[] = []; - const inputs = Array.isArray(template.inputs) - ? template.inputs.map((name) => [name, name] as const) - : Object.entries(template.inputs ?? {}); - for (const [name, target] of inputs) { - initialNodes.push( - createSectionInputNode( - name, - target, - { x: 0, y: 0 }, - template.input_schemas?.[name], - ), - ); + if (template.inputs) { + if (Array.isArray(template.inputs)) { + for (const input of template.inputs) { + initialNodes.push(createSectionInputNode(input, input, { x: 0, y: 0 })); + } + } else { + for (const [remappedId, targetId] of Object.entries(template.inputs)) { + initialNodes.push( + createSectionInputNode(remappedId, targetId, { x: 0, y: 0 }), + ); + } + } } if (template.buffers) { @@ -230,15 +230,16 @@ export function loadTemplate(template: SectionTemplate): Graph { if (template.outputs) { for (const output of template.outputs) { - initialNodes.push( - createSectionOutputNode( - output, - { x: 0, y: 0 }, - template.output_schemas?.[output], - ), - ); + initialNodes.push(createSectionOutputNode(output, { x: 0, y: 0 })); } } + for (const port of initialNodes) { + if (port.type === 'sectionInput') { + port.data.schema = template.input_schemas?.[port.data.remappedId]; + } else if (port.type === 'sectionOutput') { + port.data.schema = template.output_schemas?.[port.data.outputId]; + } + } return buildGraph(stubDiagram, { nodes: initialNodes, edges: [] }); } diff --git a/diagram-editor/frontend/utils/schema-types.ts b/diagram-editor/frontend/utils/schema-types.ts new file mode 100644 index 00000000..3a60ab87 --- /dev/null +++ b/diagram-editor/frontend/utils/schema-types.ts @@ -0,0 +1,147 @@ +import { + type FieldTemplateProps, + findSchemaDefinition, + guessType, + type RJSFSchema, +} from '@rjsf/utils'; + +type Schema = RJSFSchema | boolean; + +function resolve(schema: Schema, root: RJSFSchema) { + if (typeof schema === 'boolean') return undefined; + try { + return schema.$ref ? findSchemaDefinition(schema.$ref, root) : schema; + } catch { + return undefined; + } +} + +function choices(schema: RJSFSchema) { + return 'const' in schema ? [schema.const] : schema.enum; +} + +export function schemaDocument( + schema: object | boolean | null | undefined, + definitions?: Record, +) { + return { + schemas: definitions, + $defs: definitions, + definitions, + ...(typeof schema === 'object' && schema), + } as RJSFSchema; +} + +// An unknown branch may accept additional types, so don't infer a mismatch from it. +export function schemaTypes( + schema: Schema, + root: RJSFSchema, + refs: string[] = [], +): string[] { + if (typeof schema === 'boolean') return []; + if (schema.$ref) { + if (refs.includes(schema.$ref)) return []; + const resolved = resolve(schema, root); + return resolved ? schemaTypes(resolved, root, [...refs, schema.$ref]) : []; + } + const values = choices(schema); + if (values) { + return [ + ...new Set( + values.map((v) => (Number.isInteger(v) ? 'integer' : guessType(v))), + ), + ]; + } + if (schema.type) + return Array.isArray(schema.type) ? schema.type : [schema.type]; + const branches = (schema.anyOf ?? schema.oneOf)?.map((s) => + schemaTypes(s, root, refs), + ); + return branches?.every((types) => types.length) + ? [...new Set(branches.flat())] + : []; +} + +function numericWarning(schema: RJSFSchema, dest: RJSFSchema, types: string[]) { + // Other source constraints may narrow the range beyond its declared bounds. + if ( + !schema.type || + !types.some((t) => t === 'number' || t === 'integer') || + (['multipleOf', 'anyOf', 'oneOf', 'allOf', 'not', 'if'] as const).some( + (key) => schema[key], + ) + ) + return; + const integer = !types.includes('number'); + const lower = schema.exclusiveMinimum ?? -Infinity, + upper = schema.exclusiveMaximum ?? Infinity; + const min = integer + ? Math.max(Math.ceil(schema.minimum ?? -Infinity), Math.floor(lower) + 1) + : (schema.minimum ?? -Infinity); + const max = integer + ? Math.min(Math.floor(schema.maximum ?? Infinity), Math.ceil(upper) - 1) + : (schema.maximum ?? Infinity); + if (dest.minimum !== undefined && min < dest.minimum && lower < dest.minimum) + return `Minimum ${dest.minimum} expected`; + if (dest.maximum !== undefined && max > dest.maximum && upper > dest.maximum) + return `Maximum ${dest.maximum} expected`; + if ( + dest.exclusiveMinimum !== undefined && + min <= dest.exclusiveMinimum && + lower < dest.exclusiveMinimum + ) + return `Greater than ${dest.exclusiveMinimum} expected`; + if ( + dest.exclusiveMaximum !== undefined && + max >= dest.exclusiveMaximum && + upper > dest.exclusiveMaximum + ) + return `Less than ${dest.exclusiveMaximum} expected`; +} + +export function bindingProperties( + root: RJSFSchema, + field?: FieldTemplateProps, +) { + const target = field && resolve(field.schema, field.registry.rootSchema); + const expected = field + ? schemaTypes(field.schema, field.registry.rootSchema) + : []; + const accepted = new Set(expected); + if (accepted.has('number')) accepted.add('integer'); + + function warningFor(schema: Schema, types: string[]) { + if (!field) return; + const source = resolve(schema, root); + if (!source) return; + const values = choices(source); + if (values) { + const validator = field.registry.schemaUtils.getValidator(); + for (const value of values) { + if ( + validator.isValid(source, value, root) && + !validator.isValid(field.schema, value, field.registry.rootSchema) + ) + return `${JSON.stringify(value)} is outside the expected values`; + } + return; + } + if (accepted.size && types.some((type) => !accepted.has(type))) + return `${expected.join(' | ')} expected`; + if (target) return numericWarning(source, target, types); + } + + return Object.entries(root.properties ?? {}).map(([name, schema]) => { + const types = schemaTypes(schema, root); + const ref = typeof schema === 'object' ? schema.$ref : undefined; + const type = + ref?.split('/').at(-1) || + types.join(' | ') || + (schema === false + ? 'never' + : schema === true || !Object.keys(schema).length + ? 'any' + : 'unknown'); + return { name, type, warning: warningFor(schema, types) }; + }); +} diff --git a/diagram-editor/server/api/executor.rs b/diagram-editor/server/api/executor.rs index 3adad492..f38b33e0 100644 --- a/diagram-editor/server/api/executor.rs +++ b/diagram-editor/server/api/executor.rs @@ -398,43 +398,31 @@ fn check_connection( names.dedup(); (!names.is_empty()).then(|| names.join(" | ")) }; - let source_declared = connection - .source_port - .as_ref() - .and_then(|p| declared_port_schema(diagram, p)); - let target_declared = connection - .target_port - .as_ref() - .and_then(|p| declared_port_schema(diagram, p)); - let declared_label = |schema: &serde_json::Value| { - ["title", "type", "$ref"] - .iter() - .find_map(|key| schema[key].as_str().map(str::to_owned)) + let port_info = |port: &Option, types: &[(usize, bool)]| { + let schema = port.as_ref().and_then(|p| declared_port_schema(diagram, p)); + let label = schema.and_then(|s| { + ["title", "type", "$ref"] + .into_iter() + .find_map(|key| s[key].as_str()) + }); + let name = label.map(str::to_owned).or_else(|| type_names(types)); + (schema, name) }; - let source_type_name = source_declared - .and_then(declared_label) - .or_else(|| type_names(&source_types)); - let target_type_name = target_declared - .and_then(declared_label) - .or_else(|| type_names(&target_types)); + let (source_declared, source_type_name) = port_info(&connection.source_port, &source_types); + let (target_declared, target_type_name) = port_info(&connection.target_port, &target_types); if source_declared.is_some() || target_declared.is_some() { - let inferred_schemas = |types: &[(usize, bool)]| { + let schemas = |declared, types: &[(usize, bool)]| { + if let Some(schema) = declared { + return vec![Some(schema)]; + } types .iter() .filter(|(_, certain)| *certain) - .map(|(index, _)| { - registry - .message_schema(*index) - .map(|schema| schema.as_value()) - }) + .map(|(index, _)| registry.message_schema(*index).map(|s| s.as_value())) .collect::>() }; - let sources = source_declared - .map(|s| vec![Some(s)]) - .unwrap_or_else(|| inferred_schemas(&source_types)); - let targets = target_declared - .map(|s| vec![Some(s)]) - .unwrap_or_else(|| inferred_schemas(&target_types)); + let sources = schemas(source_declared, &source_types); + let targets = schemas(target_declared, &target_types); let mut uncertain = sources.is_empty() || targets.is_empty(); for source in &sources { for target in &targets { @@ -505,48 +493,38 @@ fn check_connection( } fn declared_port_schema<'a>(diagram: &'a Diagram, port: &PortRef) -> Option<&'a serde_json::Value> { - use crossflow::{Identifier, OperationRef, OutputRef, SectionProvider}; - let (namespaces, section, name, input) = match port { - PortRef::Input(OperationRef::Named(port)) => ( - &port.namespaces, - port.exposed_namespace.as_ref()?, - &port.name, - true, - ), - PortRef::Output(OutputRef::Named(port)) => { - let [Identifier::Name(key), Identifier::Name(name)] = &port.key[..] else { - return None; - }; - if key.as_ref() != "connect" { - return None; - } - (&port.namespaces, &port.operation, name, false) - } - _ => return None, + use crossflow::{ + BuildDiagramOperation, Identifier, OperationName, OperationRef, OutputRef, SectionProvider, }; - let template = |op: &DiagramOperation| { - let DiagramOperation::Section(section) = op else { + let template = |namespaces: &[OperationName], id: &OperationName| { + let mut ops = diagram.ops.clone(); + for namespace in namespaces { + let parent = ops.get(namespace)?; + ops = parent.child_operations(&diagram.templates).ok()??; + } + let DiagramOperation::Section(section) = ops.get(id)?.as_ref() else { return None; }; - let SectionProvider::Template(template) = §ion.provider else { + let SectionProvider::Template(id) = §ion.provider else { return None; }; - diagram.templates.get(template) - }; - let mut ops = &diagram.ops; - for namespace in namespaces.iter() { - ops = match ops.get(namespace)?.as_ref() { - DiagramOperation::Scope(scope) => &scope.ops, - op => &template(op)?.ops, - }; - } - let section = template(ops.get(section)?)?; - let declarations = if input { - §ion.input_schemas - } else { - §ion.output_schemas + diagram.templates.get(id) }; - Some(declarations.get(name)?.as_value()) + let schema = match port { + PortRef::Input(OperationRef::Named(port)) => { + let section = template(&port.namespaces, port.exposed_namespace.as_ref()?)?; + section.input_schemas.get(&port.name) + } + PortRef::Output(OutputRef::Named(port)) => match &port.key[..] { + [Identifier::Name(key), Identifier::Name(name)] if key.as_ref() == "connect" => { + let section = template(&port.namespaces, &port.operation)?; + section.output_schemas.get(name) + } + _ => None, + }, + _ => return None, + }?; + Some(schema.as_value()) } fn is_missing_context_error(error: &DiagramError) -> bool { diff --git a/src/diagram/section_schema.rs b/src/diagram/section_schema.rs index 2aa3ecd9..29c0228f 100644 --- a/src/diagram/section_schema.rs +++ b/src/diagram/section_schema.rs @@ -15,10 +15,7 @@ * */ -use std::{ - collections::{BTreeMap, HashMap}, - sync::Arc, -}; +use std::{collections::HashMap, sync::Arc}; use schemars::{JsonSchema, Schema}; use serde::{Deserialize, Serialize}; @@ -37,7 +34,7 @@ use super::{ pub use crossflow_derive::Section; /// Maps JSON pointers in an operation's config to properties of its enclosing template. -pub type ConfigBindings = BTreeMap; +pub type ConfigBindings = std::collections::BTreeMap; #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "snake_case")] @@ -454,13 +451,13 @@ impl SectionTemplate { .build(&schema) .map_err(|e| SectionError::InvalidConfig(e.to_string()))?; let mut values = config.cloned().unwrap_or_else(|| serde_json::json!({})); - let properties = schema["properties"].as_object(); - if let (Some(properties), Some(values)) = (properties, values.as_object_mut()) { + let properties = &schema["properties"]; + if let (Some(properties), Some(values)) = (properties.as_object(), values.as_object_mut()) { + let required = schema["required"].as_array(); for (key, property) in properties { - let required = schema["required"] - .as_array() - .is_some_and(|keys| keys.iter().any(|value| value.as_str() == Some(key))); - if !required && let Some(default) = property.get("default") { + if let Some(default) = property.get("default") + && !required.is_some_and(|keys| keys.iter().any(|k| k == key)) + { values.entry(key).or_insert_with(|| default.clone()); } } @@ -477,7 +474,7 @@ impl SectionTemplate { fn bind_config( ops: &mut Operations, values: &JsonMessage, - properties: Option<&serde_json::Map>, + properties: &JsonMessage, ) -> Result<(), SectionError> { for op in Arc::make_mut(ops).values_mut() { let op = Arc::make_mut(op); @@ -492,7 +489,7 @@ fn bind_config( _ => continue, }; for (pointer, name) in std::mem::take(bindings) { - if !properties.is_some_and(|p| p.contains_key(name.as_ref())) { + if properties.get(name.as_ref()).is_none() { return Err(SectionError::UnknownConfigProperty(name)); } if let Some(value) = values.get(name.as_ref()) { @@ -520,11 +517,8 @@ fn set_config_value(config: &mut JsonMessage, pointer: &str, value: JsonMessage) } for token in tokens { let key = token.replace("~1", "/").replace("~0", "~"); - if field.is_null() { - *field = serde_json::json!({}); - } field = match field { - JsonMessage::Object(object) => object.entry(key).or_insert(JsonMessage::Null), + JsonMessage::Null | JsonMessage::Object(_) => &mut field[key], JsonMessage::Array(array) => array.get_mut(key.parse::().ok()?)?, _ => return None, }; From f30db787963649d88d561b9322a1c45bb773f082 Mon Sep 17 00:00:00 2001 From: ArizmendiWan <2311602492@qq.com> Date: Wed, 25 Nov 2026 15:16:12 -0600 Subject: [PATCH 3/6] Align section form controls and shorten type labels Signed-off-by: ArizmendiWan <2311602492@qq.com> --- diagram-editor/dist.hash | 2 +- .../frontend/forms/field-actions.tsx | 24 ++++++--- .../frontend/forms/operation-config-form.tsx | 51 ++++++++++-------- .../frontend/forms/schema-config-form.tsx | 50 ++++++++++++++++- .../frontend/forms/schema-editor.tsx | 53 +++++++++---------- .../frontend/forms/template-panel.tsx | 12 ++--- diagram-editor/frontend/forms/type-label.tsx | 40 ++++++++++++++ 7 files changed, 167 insertions(+), 65 deletions(-) create mode 100644 diagram-editor/frontend/forms/type-label.tsx diff --git a/diagram-editor/dist.hash b/diagram-editor/dist.hash index 52fa6dc8..ce5eeb5b 100644 --- a/diagram-editor/dist.hash +++ b/diagram-editor/dist.hash @@ -1 +1 @@ -7e04d640b755643ee77d285e6f4b6d5b68e7bb2520ca4af2a2f0ced1bcf1f997 \ No newline at end of file +a37b74d2afb82dd0e78a349144c80ff88681f5017945cc4eb74c5e325580af9e \ No newline at end of file diff --git a/diagram-editor/frontend/forms/field-actions.tsx b/diagram-editor/frontend/forms/field-actions.tsx index 4afb4489..2afb94cd 100644 --- a/diagram-editor/frontend/forms/field-actions.tsx +++ b/diagram-editor/frontend/forms/field-actions.tsx @@ -117,6 +117,7 @@ export function useFieldActions(id: string) { const MuiInput = Templates.BaseInputTemplate as ComponentType; const MuiTitle = Templates.TitleFieldTemplate as ComponentType; +const actionGutter = { paddingInlineEnd: 2 }; function useInputProps( id: string, @@ -133,15 +134,17 @@ function useInputProps( {props?.endAdornment} ), - ...(select && { - sx: { + sx: [ + ...(Array.isArray(props?.sx) ? props.sx : [props?.sx ?? {}]), + !props?.endAdornment && actionGutter, + select && { display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) auto', alignItems: 'center', '& .MuiSelect-select, & .MuiSelect-icon': { gridArea: '1 / 1' }, '& .MuiSelect-icon': { position: 'static', justifySelf: 'end' }, }, - }), + ], }; } @@ -182,10 +185,17 @@ export function FieldRow({ id, children }: PropsWithChildren<{ id: string }>) { direction="row" alignItems="center" justifyContent="space-between" - sx={{ '& > .MuiFormControlLabel-root': { ml: 0 } }} + sx={{ + overflowWrap: 'anywhere', + '& > .MuiFormControlLabel-root': { ml: 0 }, + }} > {children} - {actions && {actions}} + {actions && ( + + {actions} + + )} ); } @@ -205,10 +215,10 @@ export function TitleWithActions(props: TitleFieldProps) { + {props.optionalDataControl} {actions} - + } /> ); diff --git a/diagram-editor/frontend/forms/operation-config-form.tsx b/diagram-editor/frontend/forms/operation-config-form.tsx index a65ec8e5..8cb0f0ff 100644 --- a/diagram-editor/frontend/forms/operation-config-form.tsx +++ b/diagram-editor/frontend/forms/operation-config-form.tsx @@ -1,4 +1,4 @@ -import { Chip, MenuItem, Stack, Tooltip, Typography } from '@mui/material'; +import { Chip, MenuItem, TextField, Tooltip } from '@mui/material'; import { Templates } from '@rjsf/mui'; import type { FieldTemplateProps } from '@rjsf/utils'; import { @@ -7,6 +7,7 @@ import { type PropsWithChildren, useContext, } from 'react'; +import { EditPopoverWidth } from '../diagram-side-panel-layout'; import { MaterialSymbol } from '../nodes'; import { useRegistry } from '../registry-provider'; import { useActiveTemplate } from '../templates-provider'; @@ -20,6 +21,7 @@ import { FieldActions, FieldMenu } from './field-actions'; import SchemaConfigForm, { type SchemaConfigFormProps, } from './schema-config-form'; +import TypeLabel from './type-label'; type Bindings = Record; const BindingContext = createContext<{ @@ -58,17 +60,28 @@ function BindableField({ }; if (linked !== undefined) { return ( - - - {label} - - } - onDelete={() => select()} - /> - + } + onDelete={() => select()} + /> + ), + }, + }} + /> ); } @@ -78,12 +91,15 @@ function BindableField({ label={`Link ${label} to a section property`} menuListSx={{ display: 'grid', - gridTemplateColumns: '1fr auto auto', + maxWidth: EditPopoverWidth, + gridTemplateColumns: 'minmax(0, 1fr) auto fit-content(50%)', columnGap: 1, '& > li': { display: 'grid', gridColumn: '1 / -1', gridTemplateColumns: 'subgrid', + whiteSpace: 'normal', + overflowWrap: 'anywhere', }, }} > @@ -107,14 +123,7 @@ function BindableField({ />
)} - - {type} - + {type} )); }} diff --git a/diagram-editor/frontend/forms/schema-config-form.tsx b/diagram-editor/frontend/forms/schema-config-form.tsx index 0ad40d85..1faf8a21 100644 --- a/diagram-editor/frontend/forms/schema-config-form.tsx +++ b/diagram-editor/frontend/forms/schema-config-form.tsx @@ -1,5 +1,6 @@ import { Autocomplete, + Box, Button, MenuItem, Stack, @@ -8,6 +9,7 @@ import { import { getDefaultRegistry } from '@rjsf/core'; import Form, { Templates } from '@rjsf/mui'; import { + type ArrayFieldItemTemplateProps, type FieldProps, type FieldTemplateProps, getDefaultFormState, @@ -63,7 +65,7 @@ const MuiObjectField = function ObjectLayout(props: ObjectFieldTemplateProps) { const rjsfSlotProps = { titleBox: { sx: { m: 0 } }, - titleTypography: { variant: 'subtitle2' }, + titleTypography: { variant: 'subtitle2', sx: { overflowWrap: 'anywhere' } }, titleGridContainer: { alignItems: 'center' }, objectGridItem: { sx: { mb: 0 } }, objectGridContainer: { @@ -78,6 +80,51 @@ function ObjectLayout(props: ObjectFieldTemplateProps) { ); } +function ArrayItemLayout({ + children, + buttonsProps, + hasToolbar, + registry, + schema, +}: ArrayFieldItemTemplateProps) { + const Buttons = registry.templates.ArrayFieldItemButtonsTemplate; + const inlineToolbar = hasToolbar && schema.type !== 'array'; + return ( + .rjsf-field, & > .rjsf-field > .MuiFormControl-root': { + display: 'contents', + }, + '& > .rjsf-field > .MuiFormControl-root > *': { gridColumn: 1 }, + '& > .rjsf-field-object > .MuiFormControl-root > .MuiGrid-container': { + gridColumn: '1 / -1', + }, + }} + > + {children} + {hasToolbar && ( + + + + )} + + ); +} + function AlternativesLayout({ selector, optionSchemaField, @@ -624,6 +671,7 @@ export default function SchemaConfigForm(props: SchemaConfigFormProps) { CheckboxWidget: CheckboxWithActions, }} templates={{ + ArrayFieldItemTemplate: ArrayItemLayout, BaseInputTemplate: InputWithActions, TitleFieldTemplate: TitleWithActions, ObjectFieldTemplate: ObjectLayout, diff --git a/diagram-editor/frontend/forms/schema-editor.tsx b/diagram-editor/frontend/forms/schema-editor.tsx index 7361f9dc..9b0d3669 100644 --- a/diagram-editor/frontend/forms/schema-editor.tsx +++ b/diagram-editor/frontend/forms/schema-editor.tsx @@ -29,6 +29,7 @@ import { import { useRegistry } from '../registry-provider'; import ajv from '../utils/ajv'; import SchemaConfigForm from './schema-config-form'; +import TypeLabel from './type-label'; type Schema = RJSFSchema | boolean; const initial: RJSFSchema = { type: 'string' }; @@ -155,12 +156,11 @@ function SchemaItem({ formData, onChange, fieldPathId }: FieldProps) { function schemaList(items: UiSchema): UiSchema { // RJSF provides the add button and item toolbar. Share the title row with // the add button, keeping a single column of items below it. - const flatPaper = { elevation: 0, sx: { bgcolor: 'transparent' } }; return { 'ui:mui': { rjsfSlotProps: { - arrayPaper: flatPaper, - arrayBox: { sx: { p: 0, display: 'grid', rowGap: 2 } }, + arrayPaper: { elevation: 0, sx: { bgcolor: 'transparent' } }, + arrayBox: { sx: { p: 0, display: 'grid' } }, titleBox: { sx: { gridArea: '1 / 1', @@ -178,19 +178,7 @@ function schemaList(items: UiSchema): UiSchema { arrayAddButtonBox: { sx: { mt: 0 } }, }, }, - items: { - ...items, - 'ui:mui': { - rjsfSlotProps: { - arrayItemPaper: flatPaper, - arrayItemInnerBox: { sx: { p: 0 } }, - arrayItemOuterBox: { sx: { mb: 0 } }, - arrayItemGridContainer: { sx: { gap: 1 } }, - arrayItemGridItem: { size: 'grow', sx: { overflow: 'visible' } }, - arrayItemToolbarGrid: { sx: { mt: 0 } }, - }, - }, - }, + items, }; } @@ -497,16 +485,21 @@ function Properties({ alignItems="center" sx={{ borderBottom: 1, borderColor: 'divider', py: 0.5 }} > - - {name} - {required.includes(name) && ' *'} - - - {schemaSummary(schema)} - + + {name} + {required.includes(name) && ' *'} + + {schemaSummary(schema)} + {iconButton(`Edit ${name}`, 'edit', () => setEditing(name))} {iconButton(`Delete ${name}`, 'delete', () => { if (window.confirm(`Delete property “${name}”?`)) @@ -552,7 +545,11 @@ export default function SchemaEditor({ const name = typeof title === 'string' ? title : ''; return ( - + {inlineTitle ? ( )} {!object && value !== undefined && ( - + {schemaSummary(inlineTitle ? definition : value)} - + )} @@ -449,10 +458,8 @@ function iconButton(label: string, symbol: string, onClick: () => void) { function Properties({ value, onChange, -}: { - value: RJSFSchema; - onChange: (schema: RJSFSchema) => void; -}) { + onRenameProperty, +}: SchemaFieldsProps & { onRenameProperty?: RenameProperty }) { const fields = value.properties ?? {}; const required = value.required ?? []; const [editing, setEditing] = useState(); @@ -461,19 +468,25 @@ function Properties({ name: string, isRequired = false, ) { - const properties = { ...fields }; - if (schema === undefined) delete properties[name]; - else properties[name] = schema; - const keys = isRequired - ? [...new Set([...required, name])] - : required.filter((key) => key !== name); - const { required: _previous, ...rest } = value; - onChange({ - ...rest, - properties, - ...(keys.length > 0 && { required: keys }), - }); - setEditing(undefined); + const previous = editing ?? name; + const rename = (key: string) => (key === previous ? name : key); + const properties = new Map( + Object.entries(fields).map(([key, field]) => [rename(key), field]), + ); + if (schema === undefined) properties.delete(name); + else properties.set(name, schema); + const keys = new Set(required.map(rename)); + if (isRequired) keys.add(name); + else keys.delete(name); + const next: RJSFSchema = { + ...value, + properties: Object.fromEntries(properties), + }; + if (keys.size) next.required = [...keys]; + else delete next.required; + if (previous !== name && onRenameProperty) + return onRenameProperty(previous, name, next); + onChange(next); } return ( @@ -520,7 +533,11 @@ function Properties({ label={editing === null ? 'Add property' : `Edit ${editing}`} name={editing ?? ''} value={editing === null ? initial : fields[editing]} - names={Object.keys(fields)} + names={ + editing === null || onRenameProperty + ? Object.keys(fields) + : undefined + } required={editing !== null && required.includes(editing)} onClose={() => setEditing(undefined)} onSave={update} @@ -534,10 +551,19 @@ export default function SchemaEditor({ label, value, onChange, + onRenameProperty, object = false, removable = true, alternative = false, -}: EditorProps) { +}: { + label: string; + value?: Schema; + onChange: (value: Schema | undefined) => void; + onRenameProperty?: RenameProperty; + object?: boolean; + removable?: boolean; + alternative?: boolean; +}) { const [open, setOpen] = useState(false); const schema: Schema = value ?? (object ? { type: 'object' } : initial); const inlineTitle = alternative && typeof schema === 'object'; @@ -585,10 +611,14 @@ export default function SchemaEditor({ onChange(undefined); })} - {object && !schemaError(schema) && kindOf(schema) === 'object' && ( + {object && readSchema(schema).kind === 'object' && ( <> - + )} {open && ( @@ -600,7 +630,7 @@ export default function SchemaEditor({ onClose={() => setOpen(false)} onSave={(next) => { onChange(next); - setOpen(false); + return undefined; }} /> )} diff --git a/diagram-editor/frontend/forms/template-panel.tsx b/diagram-editor/frontend/forms/template-panel.tsx index 35f20da8..f465271c 100644 --- a/diagram-editor/frontend/forms/template-panel.tsx +++ b/diagram-editor/frontend/forms/template-panel.tsx @@ -2,15 +2,26 @@ import { Box, Divider, Stack, Typography } from '@mui/material'; import { Fragment, type ReactNode } from 'react'; import { useCompatibilityChecker } from '../connection-compatibility-provider'; import { useNodeManager } from '../node-manager'; +import { isOperationNode } from '../nodes'; import { useTemplates } from '../templates-provider'; import type { Schema } from '../types/api'; import { useEdges } from '../use-edges'; import { useReactFlow } from '../use-react-flow'; +import { bindingEntries } from '../utils/rename-template-property'; import { schemaDocument } from '../utils/schema-types'; -import SchemaEditor, { schemaSummary } from './schema-editor'; +import SchemaEditor, { + type RenameProperty, + schemaSummary, +} from './schema-editor'; import TypeLabel from './type-label'; -export default function TemplatePanel({ templateId }: { templateId: string }) { +export default function TemplatePanel({ + templateId, + onRenameProperty, +}: { + templateId: string; + onRenameProperty: RenameProperty; +}) { const [templates, setTemplates] = useTemplates(); const template = templates[templateId]; const { nodes } = useNodeManager(); @@ -46,15 +57,9 @@ export default function TemplatePanel({ templateId }: { templateId: string }) { schemaDocument(template.config_schema).properties ?? {}, ).filter((name) => !names.includes(name)); for (const node of nodes) { - if ( - node.type !== 'node' && - node.type !== 'section' && - node.type !== 'script' - ) - continue; + if (!isOperationNode(node)) continue; const op = node.data.op; - if (!op.config_bindings) continue; - const bindings = Object.entries(op.config_bindings); + const bindings = bindingEntries(op); const kept = bindings.filter(([, name]) => !removed.includes(name)); if (kept.length !== bindings.length) { updateNodeData(node.id, { @@ -103,6 +108,7 @@ export default function TemplatePanel({ templateId }: { templateId: string }) { label="Configuration schema" value={template.config_schema ?? undefined} onChange={updateSchema} + onRenameProperty={onRenameProperty} /> ); diff --git a/diagram-editor/frontend/utils/rename-template-property.ts b/diagram-editor/frontend/utils/rename-template-property.ts new file mode 100644 index 00000000..307caf31 --- /dev/null +++ b/diagram-editor/frontend/utils/rename-template-property.ts @@ -0,0 +1,102 @@ +import { isObject } from '@rjsf/utils'; +import { type DiagramEditorNode, isOperationNode } from '../nodes'; +import type { DiagramOperation, SectionTemplate } from '../types/api'; +import { pointerSegment } from './schema-types'; + +export function bindingEntries(op: DiagramOperation) { + return op.type === 'node' || op.type === 'script' || op.type === 'section' + ? Object.entries(op.config_bindings ?? {}) + : []; +} + +export function renameTemplateProperty( + templateId: string, + from: string, + to: string, + config_schema: SectionTemplate['config_schema'], + editedNodes: DiagramEditorNode[], + mainNodes: DiagramEditorNode[], + templates: Record, + drafts: Record, +) { + const oldPath = `/${pointerSegment(from)}`; + const newPath = `/${pointerSegment(to)}`; + let error: string | undefined; + + function rename( + op: DiagramOperation, + inside: boolean, + location: string, + nodeId?: string, + ): DiagramOperation { + const instance = op.type === 'section' && op.template === templateId; + if (instance && nodeId && `section:${nodeId}:config` in drafts) { + error = `Finish editing the config for “${location}” before renaming “${from}”.`; + return op; + } + const entries = bindingEntries(op); + const config = instance && isObject(op.config) ? op.config : {}; + const hasValue = Object.keys(config).includes(from); + const owns = (path: string, prefix: string) => + instance && (path === prefix || path.startsWith(`${prefix}/`)); + const movesPath = entries.some(([path]) => owns(path, oldPath)); + if ( + (hasValue || movesPath) && + (Object.keys(config).includes(to) || + entries.some(([path]) => owns(path, newPath))) + ) { + error = `“${to}” already has a value or binding in “${location}”.`; + return op; + } + + let result = op; + if (hasValue) { + const { [from]: value, ...rest } = config; + result = { ...op, config: { ...rest, [to]: value } }; + } + if (movesPath || (inside && entries.some(([, name]) => name === from))) { + const bindings = entries.map(([path, name]) => [ + owns(path, oldPath) ? newPath + path.slice(oldPath.length) : path, + inside && name === from ? to : name, + ]); + result = { ...result, config_bindings: Object.fromEntries(bindings) }; + } + return result; + } + + // Open graphs store scope children as separate nodes. Saved templates nest them in ops. + function graph(nodes: DiagramEditorNode[], inside: boolean) { + return nodes.map((node) => { + if (!isOperationNode(node)) return node; + const { op, namespace, opId } = node.data; + const location = [inside && templateId, namespace, opId] + .filter(Boolean) + .join('/'); + const next = rename(op, inside, location, node.id); + return next === op ? node : { ...node, data: { ...node.data, op: next } }; + }); + } + + function stored(ops: SectionTemplate['ops'], parent: string) { + const result = { ...ops }; + for (const [id, op] of Object.entries(ops)) { + const location = `${parent}/${id}`; + result[id] = + op.type === 'scope' + ? { ...op, ops: stored(op.ops, location) } + : rename(op, false, location); + } + return result; + } + + const edited = graph(editedNodes, true); + const main = graph(mainNodes, false); + const updated = { ...templates }; + for (const [id, template] of Object.entries(templates)) { + updated[id] = + id === templateId + ? { ...template, config_schema } + : { ...template, ops: stored(template.ops, id) }; + } + return error ?? { edited, main, templates: updated }; +} diff --git a/diagram-editor/frontend/utils/schema-types.ts b/diagram-editor/frontend/utils/schema-types.ts index 3a60ab87..65d5a3b4 100644 --- a/diagram-editor/frontend/utils/schema-types.ts +++ b/diagram-editor/frontend/utils/schema-types.ts @@ -7,6 +7,10 @@ import { type Schema = RJSFSchema | boolean; +export function pointerSegment(name: string) { + return name.replace(/~/g, '~0').replace(/\//g, '~1'); +} + function resolve(schema: Schema, root: RJSFSchema) { if (typeof schema === 'boolean') return undefined; try { diff --git a/diagram-editor/server/api/executor.rs b/diagram-editor/server/api/executor.rs index f38b33e0..1c9a04c1 100644 --- a/diagram-editor/server/api/executor.rs +++ b/diagram-editor/server/api/executor.rs @@ -15,11 +15,15 @@ use bevy_ecs::{prelude::Entity, schedule::IntoScheduleConfigs}; #[cfg(feature = "router")] use crossflow::TracedEventKind; use crossflow::{ - Diagram, DiagramElementRegistry, DiagramError, DiagramErrorCode, DiagramOperation, - InferenceBoundaryConditions, MetadataAccess, Outcome, PortRef, RequestExt, TracedEvent, trace, + Diagram, DiagramElementMetadata, DiagramElementRegistry, DiagramError, DiagramErrorCode, + DiagramOperation, InferenceBoundaryConditions, MetadataAccess, Outcome, PortRef, RequestExt, + TracedEvent, trace, }; use serde::{Deserialize, Serialize}; +use serde_json::Value; use std::{ + borrow::Cow, + cell::OnceCell, collections::HashMap, error::Error, sync::{Arc, Mutex}, @@ -262,11 +266,14 @@ fn check_connections( .flat_map(|connection| connection.ports().cloned()), ) }); + let metadata = OnceCell::new(); let results = request .connections .into_iter() .map(|connection| match &inference { - Ok(inference) => check_connection(registry, &request.diagram, connection, inference), + Ok(inference) => { + check_connection(registry, &request.diagram, connection, inference, &metadata) + } Err(error) => CompatibilityResult::terminal( connection.id, CompatibilityStatus::Unknown, @@ -282,6 +289,7 @@ fn check_connection( diagram: &Diagram, connection: CompatibilityConnection, inference: &HashMap>>, + metadata: &OnceCell, ) -> CompatibilityResult { let mut focus_ports: Vec<_> = connection.ports().collect(); focus_ports.sort(); @@ -293,6 +301,13 @@ fn check_connection( "No ports were provided for compatibility checking", ); } + let source_declared = declared_port_schema(diagram, connection.source_port.as_ref()); + let target_declared = declared_port_schema(diagram, connection.target_port.as_ref()); + // A declared endpoint does not depend on inference inside its template. + focus_ports.retain(|p| { + !(source_declared.is_some() && Some(*p) == connection.source_port.as_ref() + || target_declared.is_some() && Some(*p) == connection.target_port.as_ref()) + }); let mut unknown = None; for inferred in focus_ports.iter().flat_map(|port| &inference[*port]) { match inferred { @@ -337,30 +352,41 @@ fn check_connection( } } - let port_types = |port: &Option| { + let effective = |port: &Option, declared, source| { + if let Some(schema) = declared { + let messages = metadata.get_or_init(|| registry.metadata()).messages(); + return vec![(PortType::declared(schema, messages, registry, source), true)]; + } port.iter() - .flat_map(|port| &inference[port]) - .filter_map(|result| result.as_ref().ok().copied()) - .collect::>() - }; - let source_types = port_types(&connection.source_port); - let target_types = port_types(&connection.target_port); - let type_name = |message_type| { - registry - .message_type_name(message_type) - .ok() - .map(ToOwned::to_owned) + .flat_map(|p| &inference[p]) + .filter_map(|r| r.as_ref().ok()) + .map(|native| { + let (i, certain) = *native; + ( + PortType { + name: registry.message_type_name(i).ok(), + native_types: Cow::Borrowed(std::slice::from_ref(native)), + schema: registry.message_schema(i).map(|s| s.as_value()), + structural: false, + }, + certain, + ) + }) + .collect() }; + let source_types = effective(&connection.source_port, source_declared, true); + let target_types = effective(&connection.target_port, target_declared, false); + let type_name = |port: &PortType| port.name.map(str::to_owned); // A section output can forward several internal producers. Check each real // type; an unresolved producer must not hide a proven mismatch in another. let mut reason = "All source message types can be delivered to the target".to_string(); - for &(source_type, source_certain) in &source_types { - for &(target_type, target_certain) in &target_types { - if !source_certain || !target_certain { + for (source_type, source_certain) in &source_types { + for (target_type, target_certain) in &target_types { + if !*source_certain || !*target_certain { continue; } - match can_connect_message_types(registry, source_type, target_type) { + match source_type.delivery_to(target_type, registry) { Ok(Some(message)) => { if source_types.len() == 1 && target_types.len() == 1 { reason = message; @@ -386,71 +412,20 @@ fn check_connection( ); } Err(error) => { - unknown.get_or_insert((error.to_string(), false)); + unknown.get_or_insert(error); } } } } - let type_names = |types: &[(usize, bool)]| { - let mut names: Vec<_> = types.iter().filter_map(|(ty, _)| type_name(*ty)).collect(); + let type_names = |types: &[(PortType, bool)]| { + let mut names: Vec<_> = types.iter().filter_map(|(ty, _)| type_name(ty)).collect(); names.sort(); names.dedup(); (!names.is_empty()).then(|| names.join(" | ")) }; - let port_info = |port: &Option, types: &[(usize, bool)]| { - let schema = port.as_ref().and_then(|p| declared_port_schema(diagram, p)); - let label = schema.and_then(|s| { - ["title", "type", "$ref"] - .into_iter() - .find_map(|key| s[key].as_str()) - }); - let name = label.map(str::to_owned).or_else(|| type_names(types)); - (schema, name) - }; - let (source_declared, source_type_name) = port_info(&connection.source_port, &source_types); - let (target_declared, target_type_name) = port_info(&connection.target_port, &target_types); - if source_declared.is_some() || target_declared.is_some() { - let schemas = |declared, types: &[(usize, bool)]| { - if let Some(schema) = declared { - return vec![Some(schema)]; - } - types - .iter() - .filter(|(_, certain)| *certain) - .map(|(index, _)| registry.message_schema(*index).map(|s| s.as_value())) - .collect::>() - }; - let sources = schemas(source_declared, &source_types); - let targets = schemas(target_declared, &target_types); - let mut uncertain = sources.is_empty() || targets.is_empty(); - for source in &sources { - for target in &targets { - let compatible = source - .zip(*target) - .and_then(|(s, t)| registry.message_schemas_compatible(s, t)); - match compatible { - Some(true) => {} - Some(false) => { - return CompatibilityResult::with_types( - connection.id, - CompatibilityStatus::Incompatible, - "The source and target schemas accept no common value", - source_type_name, - target_type_name, - ); - } - None => uncertain = true, - } - } - } - if uncertain { - unknown.get_or_insert(( - "Cannot determine whether the port schemas match".into(), - true, - )); - } - } + let source_type_name = type_names(&source_types); + let target_type_name = type_names(&target_types); if let Some((reason, provisional)) = unknown { return CompatibilityResult { provisional, @@ -492,7 +467,115 @@ fn check_connection( ) } -fn declared_port_schema<'a>(diagram: &'a Diagram, port: &PortRef) -> Option<&'a serde_json::Value> { +struct PortType<'a> { + name: Option<&'a str>, + // Registry index and whether that representation guarantees the declared schema. + native_types: Cow<'a, [(usize, bool)]>, + schema: Option<&'a Value>, + structural: bool, +} + +impl<'a> PortType<'a> { + fn declared( + schema: &'a Value, + messages: &[crossflow::MessageMetadata], + registry: &DiagramElementRegistry, + source: bool, + ) -> Self { + let reference = schema.get("$ref"); + let types = &schema["type"]; + let types = types + .as_array() + .map_or(std::slice::from_ref(types), Vec::as_slice); + let name = ["title", "type", "$ref"] + .into_iter() + .find_map(|k| schema[k].as_str()) + .unwrap_or("declared schema"); + let mut ids = Vec::new(); + for (i, message) in messages.iter().enumerate() { + let Some(native) = message.schema().as_ref().map(|s| s.as_value()) else { + continue; + }; + // Match a named type by its registry reference, and scalar declarations by + // the native representations that can carry their advertised values. + let matches_type = match reference { + Some(r) => native.get("$ref") == Some(r), + None => { + matches!( + native["type"].as_str(), + Some("boolean" | "integer" | "number" | "string" | "null") + ) && types.contains(&native["type"]) + } + }; + if !matches_type { + continue; + } + let coverage = if native == schema { + Some(true) + } else if source { + registry.message_schemas_compatible(schema, native) + } else { + registry.message_schemas_compatible(native, schema) + }; + if coverage != Some(false) { + ids.push((i, coverage == Some(true))); + } + } + if reference.is_some() && ids.len() > 1 { + // A shared schema reference cannot identify a particular native conversion. + ids.clear(); + } + Self { + name: Some(name), + structural: reference.is_none() || ids.is_empty(), + native_types: Cow::Owned(ids), + schema: Some(schema), + } + } + + fn delivery_to( + &self, + target: &Self, + registry: &DiagramElementRegistry, + ) -> Result, (String, bool)> { + let delivery = |from, to| { + can_connect_message_types(registry, from, to).map_err(|err| (err.to_string(), false)) + }; + let sources = self.native_types.as_ref(); + let targets = target.native_types.as_ref(); + if let Some(&(index, _)) = sources.iter().find(|id| id.1 && targets.contains(id)) { + return delivery(index, index); + } + let mut possible = false; + for &(source, source_certain) in sources { + for &(dest, target_certain) in targets { + if let Some(reason) = delivery(source, dest)? { + if source_certain && target_certain { + return Ok(Some(reason)); + } + possible = true; + } + } + } + let compatible = if self.structural || target.structural { + self.schema + .zip(target.schema) + .and_then(|(s, t)| registry.message_schemas_compatible(s, t)) + } else { + Some(false) + }; + match compatible { + Some(true) => Ok(Some("The source messages satisfy the target schema".into())), + Some(false) if !possible => Ok(None), + _ => Err(( + "Cannot determine whether the port schemas match".into(), + true, + )), + } + } +} + +fn declared_port_schema<'a>(diagram: &'a Diagram, port: Option<&PortRef>) -> Option<&'a Value> { use crossflow::{ BuildDiagramOperation, Identifier, OperationName, OperationRef, OutputRef, SectionProvider, }; @@ -510,7 +593,7 @@ fn declared_port_schema<'a>(diagram: &'a Diagram, port: &PortRef) -> Option<&'a }; diagram.templates.get(id) }; - let schema = match port { + let schema = match port? { PortRef::Input(OperationRef::Named(port)) => { let section = template(&port.namespaces, port.exposed_namespace.as_ref()?)?; section.input_schemas.get(&port.name) From 65cf1a8ff5ff1abce367e7bcf0412b9a437296d2 Mon Sep 17 00:00:00 2001 From: ArizmendiWan <2311602492@qq.com> Date: Wed, 25 Nov 2026 17:17:04 -0600 Subject: [PATCH 5/6] Keep section bindings in sync with config edits Signed-off-by: ArizmendiWan <2311602492@qq.com> --- diagram-editor/dist.hash | 2 +- diagram-editor/frontend/diagram-editor.tsx | 14 +- .../forms/base-edit-operation-form.tsx | 24 ++- diagram-editor/frontend/forms/node-form.tsx | 9 +- .../frontend/forms/operation-config-form.tsx | 56 +++--- .../frontend/forms/schema-config-form.tsx | 101 ++++++++++- diagram-editor/frontend/forms/script-form.tsx | 64 ++----- .../frontend/forms/section-form.tsx | 7 +- .../frontend/forms/template-panel.tsx | 50 ++---- .../utils/rename-template-property.ts | 102 ----------- diagram-editor/frontend/utils/schema-types.ts | 8 + .../frontend/utils/update-template-schema.ts | 166 ++++++++++++++++++ 12 files changed, 362 insertions(+), 241 deletions(-) delete mode 100644 diagram-editor/frontend/utils/rename-template-property.ts create mode 100644 diagram-editor/frontend/utils/update-template-schema.ts diff --git a/diagram-editor/dist.hash b/diagram-editor/dist.hash index 51b508e5..29e0d89a 100644 --- a/diagram-editor/dist.hash +++ b/diagram-editor/dist.hash @@ -1 +1 @@ -0fab76ab2c42d332d18ee8d295f8b465a02efc737da51ebfa3f0503e3fd26163 \ No newline at end of file +d07f108c826cdf7d99e8b793b7fbdd106c6bf37b70729f98470f34a7d7c8f770 \ No newline at end of file diff --git a/diagram-editor/frontend/diagram-editor.tsx b/diagram-editor/frontend/diagram-editor.tsx index 05c888d2..226046fb 100644 --- a/diagram-editor/frontend/diagram-editor.tsx +++ b/diagram-editor/frontend/diagram-editor.tsx @@ -125,7 +125,7 @@ import { } from './utils/load-diagram'; import { joinNamespaces, ROOT_NAMESPACE } from './utils/namespace'; import { updateOperationIds } from './utils/operation-id'; -import { renameTemplateProperty } from './utils/rename-template-property'; +import { updateTemplateSchema } from './utils/update-template-schema'; // Keep canvas clicks available while giving MUI a real modal root to restore // focus and accessibility when a nested select or field menu closes. @@ -1607,18 +1607,20 @@ function DiagramEditor() { editorMode.mode === EditorMode.Template && ( { - const edit = renameTemplateProperty( + onChangeSchema={(config_schema, rename) => { + const edit = updateTemplateSchema( editorMode.templateId, - from, - to, config_schema, + rename, nodes, savedNodes.current, templates, transientEditorDrafts.operationConfigs, ); - if (typeof edit === 'string') return edit; + if (typeof edit === 'string') { + if (!rename) showErrorToast(edit); + return edit; + } savedNodes.current = edit.main; setNodes(edit.edited); setTemplates(edit.templates); diff --git a/diagram-editor/frontend/forms/base-edit-operation-form.tsx b/diagram-editor/frontend/forms/base-edit-operation-form.tsx index b2fd9a27..dcd93f3c 100644 --- a/diagram-editor/frontend/forms/base-edit-operation-form.tsx +++ b/diagram-editor/frontend/forms/base-edit-operation-form.tsx @@ -10,6 +10,7 @@ import type { NodeChange, NodeRemoveChange } from '@xyflow/react'; import { type PropsWithChildren, useState } from 'react'; import type { OperationNode, OperationNodeTypes } from '../nodes'; import { MaterialSymbol } from '../nodes'; +import type { DiagramOperation } from '../types/api'; export interface BaseEditOperationFormProps< NodeType extends OperationNodeTypes = OperationNodeTypes, @@ -19,16 +20,37 @@ export interface BaseEditOperationFormProps< onDelete?: (change: NodeRemoveChange) => void; } +function switchesConfig(before: DiagramOperation, after: DiagramOperation) { + if (before.type === 'script' && after.type === 'script') + return before.environment !== after.environment || before.run !== after.run; + if (before.type === 'section' && after.type === 'section') + return ( + before.template !== after.template || before.builder !== after.builder + ); + return ( + before.type === 'node' && + after.type === 'node' && + before.builder !== after.builder + ); +} + export function operationUpdater({ node, onChange, }: BaseEditOperationFormProps) { - return (op: OperationNode['data']['op']) => + return (op: OperationNode['data']['op']) => { + if ( + 'config_bindings' in op && + op.config_bindings && + switchesConfig(node.data.op, op) + ) + op = { ...op, config_bindings: undefined }; onChange?.({ type: 'replace', id: node.id, item: { ...node, data: { ...node.data, op } }, }); + }; } function BaseEditOperationForm({ diff --git a/diagram-editor/frontend/forms/node-form.tsx b/diagram-editor/frontend/forms/node-form.tsx index a8eff076..9f0f38bd 100644 --- a/diagram-editor/frontend/forms/node-form.tsx +++ b/diagram-editor/frontend/forms/node-form.tsx @@ -26,10 +26,6 @@ function NodeForm(props: NodeFormProps) { const builderMetadata = registry.nodes[op.builder]; const replaceOp = operationUpdater(props); - const updateConfig = (config: unknown) => { - const { config: _config, ...rest } = op; - replaceOp(config === undefined ? rest : { ...rest, config }); - }; return ( @@ -60,7 +56,6 @@ function NodeForm(props: NodeFormProps) { replaceOp({ ...op, builder, - ...(builder !== op.builder && { config_bindings: undefined }), ...(defaults !== undefined && { config: defaults }), }); }} @@ -97,7 +92,9 @@ function NodeForm(props: NodeFormProps) { + replaceOp({ ...op, config, config_bindings: undefined }) + } /> ); diff --git a/diagram-editor/frontend/forms/operation-config-form.tsx b/diagram-editor/frontend/forms/operation-config-form.tsx index 182d7b5c..88f84e4c 100644 --- a/diagram-editor/frontend/forms/operation-config-form.tsx +++ b/diagram-editor/frontend/forms/operation-config-form.tsx @@ -14,8 +14,9 @@ import { useActiveTemplate } from '../templates-provider'; import { useTransientEditorDrafts } from '../transient-editor-drafts'; import { bindingProperties, - pointerSegment, + fieldPointer, schemaDocument, + withinField, } from '../utils/schema-types'; import { type BaseEditOperationFormProps, @@ -32,7 +33,7 @@ const BindingContext = createContext<{ schema: ReturnType; pointer?: string; bindings: Bindings; - update: (bindings: Bindings) => void; + setLink: (pointer: string, property?: string) => void; } | null>(null); const MuiField = Templates.FieldTemplate as ComponentType; @@ -50,26 +51,13 @@ function BindableField( if ( !context || field?.hidden || - path.some((segment) => typeof segment === 'number') || - (!path.length && field?.schema.type === 'object') + path.some((segment) => typeof segment === 'number') ) return children; - const pointer = path.map((key) => `/${pointerSegment(String(key))}`).join(''); + const pointer = fieldPointer(path); if (context.pointer === pointer) return children; const linked = context.bindings[pointer]; - const select = (property?: string) => { - const next = { ...context.bindings }; - if (property === undefined) { - delete next[pointer]; - } else { - for (const child of Object.keys(next)) { - if (child.startsWith(`${pointer}/`)) delete next[child]; - } - next[pointer] = property; - } - context.update(next); - }; if (linked !== undefined) { return ( } - onDelete={() => select()} + onDelete={() => context.setLink(pointer)} /> ), }, @@ -96,6 +84,7 @@ function BindableField( /> ); } + if (!path.length && field?.schema.type === 'object') return children; const menu = ( select(name)} + onClick={() => context.setLink(pointer, name)} > {name} {warning && ( @@ -163,14 +152,30 @@ export default function OperationConfigForm(props: OperationProps) { const op = node.data.op; const replaceOp = operationUpdater(props); const key = `${op.type}:${node.id}:config`; + function updateConfig( + config: unknown, + removed: string[] = [], + link?: [string, string], + ) { + const links = new Map(Object.entries(op.config_bindings ?? {})); + for (const path of removed) links.delete(path); + if (link) links.set(...link); + replaceOp({ + ...op, + config, + config_bindings: links.size ? Object.fromEntries(links) : undefined, + }); + } + const trackedFields = Object.keys(op.config_bindings ?? {}); const binding = template && { bindings: op.config_bindings ?? {}, schema: schemaDocument(template.config_schema, definitions), - update: (next: Bindings) => - replaceOp({ - ...op, - config_bindings: Object.keys(next).length ? next : undefined, - }), + setLink: (pointer: string, property?: string) => + updateConfig( + op.config, + trackedFields.filter((path) => withinField(path, pointer)), + property === undefined ? undefined : [pointer, property], + ), }; const form = ( replaceOp({ ...op, config })} + trackedFields={trackedFields} + onChange={updateConfig} fieldTemplate={binding ? BindableField : undefined} rawDraft={drafts.operationConfigs[key]} onRawDraftChange={(text) => setOperationConfigDraft(key, text)} diff --git a/diagram-editor/frontend/forms/schema-config-form.tsx b/diagram-editor/frontend/forms/schema-config-form.tsx index f540d8c3..82bdb670 100644 --- a/diagram-editor/frontend/forms/schema-config-form.tsx +++ b/diagram-editor/frontend/forms/schema-config-form.tsx @@ -10,9 +10,12 @@ import { getDefaultRegistry } from '@rjsf/core'; import Form, { Templates } from '@rjsf/mui'; import { type ArrayFieldItemTemplateProps, + createSchemaUtils, type FieldProps, type FieldTemplateProps, + getByPath, getDefaultFormState, + getDiscriminatorFieldFromSchema, getSchemaType, guessType, isObject, @@ -40,7 +43,12 @@ import { useRef, useState, } from 'react'; -import { schemaDocument, schemaTypes } from '../utils/schema-types'; +import { + fieldPointer, + schemaDocument, + schemaTypes, + withinField, +} from '../utils/schema-types'; import { ActionTextField, CheckboxWithActions, @@ -157,7 +165,8 @@ export interface SchemaConfigFormProps { schema: unknown; definitions?: Record; value?: unknown; - onChange: (value: unknown) => void; + onChange: (value: unknown, replacedFields?: string[]) => void; + trackedFields?: string[]; label?: string; disabled?: boolean; nodeDefaults?: boolean; @@ -182,6 +191,54 @@ function schemaRoot(schema: unknown, definitions?: Record) { : root; } +// A linked optional field can have no literal. Follow its path to distinguish +// a removed container or switched alternative from a sibling's ordinary edit. +function fieldRemoved( + pointer: string, + before: unknown, + after: unknown, + root?: RJSFSchema, +) { + const utils = root && createSchemaUtils(validator, root); + let schemas = root ? [root] : []; + for (const token of pointer.split('/').slice(1)) { + if (equal(before, after)) return false; + if (!isObject(after) && !Array.isArray(after)) return true; + if (before !== undefined && Array.isArray(before) !== Array.isArray(after)) + return true; + const key = token.replace(/~1/g, '/').replace(/~0/g, '~'); + const children: RJSFSchema[] = []; + if (utils) + for (const schema of schemas) { + const field = utils.retrieveSchema(schema, after); + let alternatives = field.anyOf ?? []; + if (field.oneOf) { + const options = field.oneOf.map((s) => + typeof s === 'boolean' ? (s ? {} : { not: {} }) : s, + ); + const discriminator = getDiscriminatorFieldFromSchema(field); + const match = (data: unknown, index: number) => + utils.getClosestMatchingOption(data, options, index, discriminator); + const previous = match(before, 0); + if (match(after, previous) !== previous) return true; + alternatives = [options[previous]]; + } + // A parallel anyOf and its base schema may both define this key. + for (const part of [field, ...alternatives]) { + if (typeof part !== 'object') continue; + const s = part === field ? field : utils.retrieveSchema(part, after); + const child = s.properties?.[key] ?? s.additionalProperties; + if (typeof child === 'object') children.push(child); + } + } + schemas = children; + before = getByPath(before, key); + after = getByPath(after, key); + if (before !== undefined && after === undefined) return true; + } + return false; +} + // Existing node builders expect their required fields to exist even before the // first edit. Section instances and schema authors edit their actual input. function fillNodeFields( @@ -597,7 +654,23 @@ function OneOfField(props: FieldProps) { option.title ?? (typeof option.type === 'string' ? option.type : undefined), })); - return ; + return ( + { + // Form forwards the event id but omits the path. Carry the exact + // pointer through a variant switch, even when both values are empty. + const switched = id === `${props.fieldPathId.$id}__oneof_select`; + props.onChange( + value, + path, + errors, + switched ? `#${fieldPointer(path)}` : id, + ); + }} + /> + ); } // A node keeps its last usable number while an integer or required number is @@ -646,7 +719,19 @@ export default function SchemaConfigForm(props: SchemaConfigFormProps) { useEffect(() => { if (value !== props.value) props.onChange(value); }, [value, props.value, props.onChange]); - if (!root) return ; + const change = (next: unknown, switched?: string, rawSchema?: RJSFSchema) => + props.onChange( + next, + props.trackedFields?.filter( + (path) => + (switched !== undefined && withinField(path, switched)) || + fieldRemoved(path, value, next, rawSchema), + ), + ); + const rawEditor = ( + change(next, undefined, root)} /> + ); + if (!root) return rawEditor; const raw = editJson || props.rawDraft !== undefined; const editor = ( @@ -687,14 +772,18 @@ export default function SchemaConfigForm(props: SchemaConfigFormProps) { onChange={({ formData }, fieldId) => { // RJSF also reports suggested defaults when it mounts. Only user edits // have a field id. Opening a panel must not change a saved diagram. - if (fieldId) props.onChange(formData); + if (fieldId) + change( + formData, + fieldId.startsWith('#') ? fieldId.slice(1) : undefined, + ); }} /> ); if (!props.allowJson) return editor; return ( - {raw ? : editor} + {raw ? rawEditor : editor}