;
const actionGutter = { paddingInlineEnd: 2 };
-function useInputProps(
- id: string,
- props?: TextFieldProps['InputProps'],
+// The MUI input template, select widget and raw text field all forward InputProps.
+function withFieldActions>(
+ Input: ComponentType
,
select = false,
) {
- const actions = useFieldActions(id);
- if (!actions) return props;
- return {
- ...props,
- endAdornment: (
- <>
- {actions}
- {props?.endAdornment}
- >
- ),
- 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' },
- },
- ],
+ return function InputWithActions(props: P) {
+ const actions = useFieldActions(props.id ?? '');
+ if (!actions) return ;
+ const input = props.InputProps;
+ return (
+
+ {actions}
+ {input?.endAdornment}
+ >
+ ),
+ sx: [
+ ...(Array.isArray(input?.sx) ? input.sx : [input?.sx ?? {}]),
+ !input?.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' },
+ },
+ ],
+ }}
+ />
+ );
};
}
-export function ActionTextField(props: TextFieldProps) {
- return (
-
- );
-}
-
-export function InputWithActions(props: BaseInputTemplateProps) {
- return (
-
- );
-}
-
-export function SelectWithActions(props: WidgetProps) {
- return (
-
- );
-}
+export const ActionTextField = withFieldActions(TextField);
+export const InputWithActions = withFieldActions(
+ Templates.BaseInputTemplate as ComponentType,
+);
+export const SelectWithActions = withFieldActions(
+ Widgets.SelectWidget,
+ true,
+);
export function FieldRow({ id, children }: PropsWithChildren<{ id: string }>) {
const actions = useFieldActions(id);
diff --git a/diagram-editor/frontend/forms/node-form.test.tsx b/diagram-editor/frontend/forms/node-form.test.tsx
index 30d5354f..5a022f6f 100644
--- a/diagram-editor/frontend/forms/node-form.test.tsx
+++ b/diagram-editor/frontend/forms/node-form.test.tsx
@@ -165,7 +165,7 @@ test('renders and updates a numeric control when the entire node config is a num
render(, registry);
- const config = await screen.findByRole('spinbutton');
+ const config = await screen.findByRole('spinbutton', { name: /Config/ });
expect(config).toHaveValue(3);
fireEvent.change(config, { target: { value: '4.5' } });
@@ -178,10 +178,22 @@ test('renders and updates a numeric control when the entire node config is a num
test('choosing the null alternative writes JSON null', async () => {
const onChange = jest.fn();
+ // `add` takes an `Option`, and ships `null` as one of its examples.
const registry = createRegistry({
anyOf: [{ type: 'number' }, { type: 'null' }],
});
- render(, registry);
+
+ const { rerender } = render(
+ ,
+ registry,
+ );
+ expect(await screen.findByDisplayValue('null')).toBeInTheDocument();
+ expect(onChange).not.toHaveBeenCalled();
+
+ rerender();
+ const config = screen.getByRole('spinbutton', { name: /Config/ });
+ expect(config).toBeEnabled();
+ expect(config).toHaveValue(5);
fireEvent.click(
await screen.findByRole('button', { name: 'Config value options' }),
@@ -191,6 +203,7 @@ test('choosing the null alternative writes JSON null', async () => {
});
test('an absent optional nullable property stays absent when the form opens', async () => {
+ // `#[serde(default)] compared_to: Option` is both optional and nullable.
const onChange = jest.fn();
const registry = createRegistry({
type: 'object',
@@ -336,19 +349,31 @@ test('optional properties can be added and omitted', async () => {
},
required: ['required_text'],
});
- render(
+
+ const { rerender } = render(
,
registry,
);
+
const input = await screen.findByRole('textbox', { name: 'optional_text' });
fireEvent.change(input, { target: { value: 'present' } });
expect(onChange.mock.calls.at(-1)?.[0].item.data.op.config).toEqual({
required_text: 'required',
optional_text: 'present',
});
+
+ rerender(
+ ,
+ );
fireEvent.change(input, { target: { value: '' } });
expect(onChange.mock.calls.at(-1)?.[0].item.data.op.config).toEqual({
required_text: 'required',
@@ -365,14 +390,35 @@ test('control edits write the same JSON-compatible config object', async () => {
enabled: true,
strategy: 'safe',
};
+
render(, registry);
- fireEvent.change(await screen.findByRole('textbox', { name: /title/ }), {
+ await screen.findByRole('textbox', { name: /title/ });
+
+ fireEvent.change(screen.getByRole('textbox', { name: /title/ }), {
target: { value: 'Updated' },
});
+ expect(onChange.mock.calls.at(-1)?.[0].item.data.op.config).toEqual({
+ ...config,
+ title: 'Updated',
+ });
+
fireEvent.change(screen.getByRole('spinbutton', { name: /threshold/ }), {
target: { value: '2.75' },
});
+ expect(onChange.mock.calls.at(-1)?.[0].item.data.op.config).toEqual({
+ ...config,
+ title: 'Updated',
+ threshold: 2.75,
+ });
+
fireEvent.click(screen.getByRole('checkbox', { name: /enabled/ }));
+ expect(onChange.mock.calls.at(-1)?.[0].item.data.op.config).toEqual({
+ ...config,
+ title: 'Updated',
+ threshold: 2.75,
+ enabled: false,
+ });
+
fireEvent.mouseDown(screen.getByRole('combobox', { name: /strategy/ }));
fireEvent.click(await screen.findByRole('option', { name: 'fast' }));
expect(onChange.mock.calls.at(-1)?.[0].item.data.op.config).toEqual({
@@ -473,7 +519,10 @@ test('editing a field in an absent optional object creates that object', async (
properties: {
opts: {
type: 'object',
- properties: { inner: { type: 'string' } },
+ properties: {
+ inner: { type: 'string' },
+ extra: { type: 'integer', default: 7 },
+ },
required: ['inner'],
},
},
@@ -510,8 +559,7 @@ test('fills in required keys the config is missing', async () => {
);
await screen.findByRole('textbox', { name: /title/ });
- // Required keys are materialised down the tree; `note` is optional, so it
- // stays absent until its checkbox is switched on.
+ // Required keys are materialised down the tree; the optional note stays absent.
expect(onChange.mock.calls.at(-1)?.[0].item.data.op.config).toEqual({
title: 'kept',
count: 0,
diff --git a/diagram-editor/frontend/forms/operation-config-form.tsx b/diagram-editor/frontend/forms/operation-config-form.tsx
index 8cb0f0ff..182d7b5c 100644
--- a/diagram-editor/frontend/forms/operation-config-form.tsx
+++ b/diagram-editor/frontend/forms/operation-config-form.tsx
@@ -12,7 +12,11 @@ import { MaterialSymbol } from '../nodes';
import { useRegistry } from '../registry-provider';
import { useActiveTemplate } from '../templates-provider';
import { useTransientEditorDrafts } from '../transient-editor-drafts';
-import { bindingProperties, schemaDocument } from '../utils/schema-types';
+import {
+ bindingProperties,
+ pointerSegment,
+ schemaDocument,
+} from '../utils/schema-types';
import {
type BaseEditOperationFormProps,
operationUpdater,
@@ -32,18 +36,26 @@ const BindingContext = createContext<{
} | null>(null);
const MuiField = Templates.FieldTemplate as ComponentType;
-function BindableField({
- field,
- pointer = '',
- label = field?.label ?? 'Config',
- children,
-}: PropsWithChildren<{
- field?: FieldTemplateProps;
- pointer?: string;
- label?: string;
-}>) {
+// RJSF supplies the field template for a known schema. A raw config supplies
+// its editor directly, and can bind the root value in the same way.
+function BindableField(
+ props: FieldTemplateProps | PropsWithChildren<{ label: string }>,
+) {
+ const field = 'fieldPathId' in props ? props : undefined;
+ const children = field ? : props.children;
+ const { label } = props;
const context = useContext(BindingContext);
- if (!context || context.pointer === pointer) return children;
+ const path = field?.fieldPathId.path ?? [];
+ // Reordering a list would make an index binding point to a different item.
+ if (
+ !context ||
+ field?.hidden ||
+ path.some((segment) => typeof segment === 'number') ||
+ (!path.length && field?.schema.type === 'object')
+ )
+ return children;
+ const pointer = path.map((key) => `/${pointerSegment(String(key))}`).join('');
+ if (context.pointer === pointer) return children;
const linked = context.bindings[pointer];
const select = (property?: string) => {
@@ -138,26 +150,6 @@ function BindableField({
);
}
-function OperationField(props: FieldTemplateProps) {
- const path = props.fieldPathId.path;
- const field = ;
- // Reordering a list would make an index binding point to a different item.
- if (
- props.hidden ||
- path.some((segment) => typeof segment === 'number') ||
- (!path.length && props.schema.type === 'object')
- )
- return field;
- const pointer = path
- .map((key) => `/${String(key).replace(/~/g, '~0').replace(/\//g, '~1')}`)
- .join('');
- return (
-
- {field}
-
- );
-}
-
type OperationProps = BaseEditOperationFormProps<
'node' | 'script' | 'section'
> &
@@ -189,7 +181,7 @@ export default function OperationConfigForm(props: OperationProps) {
nodeDefaults={op.type === 'node'}
value={op.config}
onChange={(config) => replaceOp({ ...op, config })}
- fieldTemplate={binding ? OperationField : undefined}
+ 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 1faf8a21..f540d8c3 100644
--- a/diagram-editor/frontend/forms/schema-config-form.tsx
+++ b/diagram-editor/frontend/forms/schema-config-form.tsx
@@ -546,43 +546,44 @@ function NullableField({
}
function SchemaField(props: FieldProps) {
- const schema = props.schema.$ref
- ? props.registry.schemaUtils.retrieveSchema(props.schema, props.formData)
- : props.schema;
- const nullable =
+ const { schema: input, uiSchema, registry, fieldPathId } = props;
+ const schema = input.$ref
+ ? registry.schemaUtils.retrieveSchema(input, props.formData)
+ : input;
+ let field: ComponentType | undefined;
+ if (schema.anyOf) field = ParallelAnyOfField;
+ else if (
+ schema.type === 'null' &&
+ typeof fieldPathId.path.at(-1) === 'string'
+ ) {
+ // RJSF's NullField silently sets missing properties to null on mount.
+ field = EnumField;
+ } else if (schema.enum || schema.oneOf) {
+ if (
+ uiSchema?.['ui:widget'] !== 'hidden' &&
+ (schema.enum || registry.schemaUtils.isSelect(schema))
+ )
+ field = EnumField;
+ } else if (
Array.isArray(schema.type) &&
schema.type.length === 2 &&
schema.type.includes('null') &&
- !schema.enum &&
- !schema.anyOf &&
- !schema.oneOf &&
- acceptsNull(props.schema, props.registry);
- // RJSF's NullField silently sets missing properties to null on mount.
- const enumField =
- ((schema.enum ||
- (schema.oneOf && props.registry.schemaUtils.isSelect(schema))) &&
- props.uiSchema?.['ui:widget'] !== 'hidden') ||
- (schema.type === 'null' &&
- typeof props.fieldPathId.path.at(-1) === 'string');
- const field = schema.anyOf
- ? ParallelAnyOfField
- : nullable
- ? NullableField
- : enumField
- ? EnumField
- : undefined;
+ acceptsNull(input, registry)
+ )
+ field = NullableField;
return (
);
}
@@ -653,6 +654,7 @@ export default function SchemaConfigForm(props: SchemaConfigFormProps) {
tagName="div"
idPrefix={id}
schema={root}
+ formContext={{ nullRoot: value === null ? id : undefined }}
uiSchema={{
'ui:title': props.label ?? 'Config',
'ui:submitButtonOptions': { norender: true },
diff --git a/diagram-editor/frontend/forms/schema-editor.tsx b/diagram-editor/frontend/forms/schema-editor.tsx
index 9b0d3669..bb58a996 100644
--- a/diagram-editor/frontend/forms/schema-editor.tsx
+++ b/diagram-editor/frontend/forms/schema-editor.tsx
@@ -28,6 +28,7 @@ import {
} from '../nodes';
import { useRegistry } from '../registry-provider';
import ajv from '../utils/ajv';
+import { pointerSegment } from '../utils/schema-types';
import SchemaConfigForm from './schema-config-form';
import TypeLabel from './type-label';
@@ -47,6 +48,16 @@ const schemasByKind: Record = {
any: {},
};
const choiceRef = { $ref: '#/$defs/choice' };
+const nullConstraints = [
+ 'const',
+ '$ref',
+ '$dynamicRef',
+ 'allOf',
+ 'anyOf',
+ 'oneOf',
+ 'not',
+ 'if',
+];
const choice: RJSFSchema = {
default: '',
oneOf: [
@@ -80,14 +91,14 @@ function withNull(schema: RJSFSchema, allow: boolean): RJSFSchema {
}
function kindOf(schema: Schema) {
- if (schema && typeof schema === 'object') {
- if (Object.keys(schema).every((key) => key === 'title')) return 'any';
- if (Array.isArray(schema.enum)) return 'enum';
- const type = concreteType(schema.type);
- if (type) return type;
- for (const key of ['anyOf', 'oneOf', '$ref']) if (key in schema) return key;
- }
- return 'JSON';
+ if (typeof schema === 'boolean') return 'JSON';
+ if (Object.keys(schema).every((key) => key === 'title')) return 'any';
+ if (Array.isArray(schema.enum)) return 'enum';
+ return (
+ concreteType(schema.type) ??
+ ['anyOf', 'oneOf', '$ref'].find((key) => key in schema) ??
+ 'JSON'
+ );
}
export function schemaSummary(schema: Schema) {
@@ -97,24 +108,25 @@ export function schemaSummary(schema: Schema) {
return Array.isArray(schema.type) ? schema.type.join(' | ') : kindOf(schema);
}
-function schemaError(value: unknown) {
- if (typeof value !== 'boolean' && !isObject(value))
- return 'A JSON Schema must be an object or a boolean.';
+function readSchema(draft: Schema | string) {
try {
- if (!ajv.validateSchema(value)) return ajv.errorsText(ajv.errors);
+ const schema: Schema =
+ typeof draft === 'string' ? JSON.parse(draft) : draft;
+ if (typeof schema !== 'boolean' && !isObject(schema))
+ return { error: 'A JSON Schema must be an object or a boolean.' };
+ if (!ajv.validateSchema(schema))
+ return { schema, error: ajv.errorsText(ajv.errors) };
+ return { schema, kind: kindOf(schema) };
} catch (err) {
- return String(err);
+ return { error: String(err) };
}
}
-interface EditorProps {
- label: string;
- value?: Schema;
- onChange: (value: Schema | undefined) => void;
- object?: boolean;
- removable?: boolean;
- alternative?: boolean;
-}
+export type RenameProperty = (
+ from: string,
+ to: string,
+ schema: RJSFSchema,
+) => string | undefined;
const PortSchemaContext = createContext(false);
@@ -153,6 +165,11 @@ function SchemaItem({ formData, onChange, fieldPathId }: FieldProps) {
);
}
+interface SchemaFieldsProps {
+ value: RJSFSchema;
+ onChange: (value: RJSFSchema) => void;
+}
+
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.
@@ -182,17 +199,23 @@ function schemaList(items: UiSchema): UiSchema {
};
}
+const schemaItem = { 'ui:field': SchemaItem };
+const alternatives = schemaList(schemaItem);
+const schemaUi: UiSchema = {
+ default: { 'ui:placeholder': 'No default' },
+ enum: schemaList({ 'ui:emptyValue': '' }),
+ items: schemaItem,
+ anyOf: alternatives,
+ oneOf: alternatives,
+};
+
// RJSF edits the schema document itself. For example, its standard array
// control adds and reorders the schema objects saved under anyOf or oneOf.
function SchemaFields({
value,
onChange,
inlineTitle,
-}: {
- value: RJSFSchema;
- onChange: (value: RJSFSchema) => void;
- inlineTitle?: boolean;
-}) {
+}: SchemaFieldsProps & { inlineTitle?: boolean }) {
const registry = useRegistry();
const port = useContext(PortSchemaContext);
const kind = kindOf(value);
@@ -202,16 +225,7 @@ function SchemaFields({
// Those schemas retain their explicit alternatives or JSON editor.
const canAllowNull =
(type ? type !== 'null' : choices && value.type === undefined) &&
- ![
- 'const',
- '$ref',
- '$dynamicRef',
- 'allOf',
- 'anyOf',
- 'oneOf',
- 'not',
- 'if',
- ].some((key) => key in value);
+ !nullConstraints.some((key) => key in value);
const nullable =
(value.type === undefined ||
(Array.isArray(value.type) && value.type.includes('null'))) &&
@@ -224,47 +238,43 @@ function SchemaFields({
[kind, value.type],
);
const refs = Object.keys(registry.schemas).map(
- (name) => `#/schemas/${name.replace(/~/g, '~0').replace(/\//g, '~1')}`,
+ (name) => `#/schemas/${pointerSegment(name)}`,
);
const fields: Record = {};
if (!inlineTitle) fields.title = { type: 'string', title: 'Title' };
- const nested = { 'ui:field': SchemaItem };
if (kind === '$ref')
fields.$ref = {
type: 'string',
title: 'Registered type',
enum: [...new Set([...refs, String(value.$ref)])],
};
- if (choices) {
- fields.enum = {
+ if (choices || kind === 'anyOf' || kind === 'oneOf') {
+ fields[kind] = {
type: 'array',
- title: 'Choices',
minItems: 1,
- uniqueItems: true,
- items: { ...choiceRef, title: 'Choice type' },
+ title: choices ? 'Choices' : 'Alternatives',
+ items: choices
+ ? { ...choiceRef, title: 'Choice type' }
+ : { type: 'object', default: initial },
};
- if (!port && choices.length)
- fields.default = { title: 'Default value', enum: choices };
+ if (choices) fields.enum.uniqueItems = true;
}
if (kind === 'array') fields.items = { type: 'object', title: 'Items' };
- if (kind === 'anyOf' || kind === 'oneOf')
- fields[kind] = {
- type: 'array',
- title: 'Alternatives',
- minItems: 1,
- items: { type: 'object', default: initial },
- };
if (['number', 'integer'].includes(kind)) {
fields.minimum = { type: 'number', title: 'Minimum' };
fields.maximum = { type: 'number', title: 'Maximum' };
}
- 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 }),
- };
+ if (
+ !port &&
+ (choices?.length ||
+ ['string', 'integer', 'number', 'boolean'].includes(kind))
+ ) {
+ fields.default = { title: 'Default value' };
+ if (choices) fields.default.enum = choices;
+ else if (kind === 'boolean')
+ fields.default.enum = nullable ? [true, false, null] : [true, false];
+ else fields.default.type = value.type;
+ }
const kinds = { ...schemasByKind };
if (refs.length || kind === '$ref') kinds.$ref = { $ref: refs[0] };
return (
@@ -307,13 +317,7 @@ function SchemaFields({
...(kind === 'enum' && { $defs: { choice } }),
}}
value={value}
- uiSchema={{
- default: { 'ui:placeholder': 'No default' },
- enum: schemaList({ 'ui:emptyValue': '' }),
- items: nested,
- anyOf: schemaList(nested),
- oneOf: schemaList(nested),
- }}
+ uiSchema={schemaUi}
onChange={(data) => {
const next = data as RJSFSchema;
// Older enums declared a redundant type. Widen it when the author
@@ -341,46 +345,47 @@ interface DraftProps {
names?: string[];
json?: boolean;
inlineTitle?: boolean;
- onSave: (schema: Schema, name: string, required: boolean) => void;
+ onSave: (
+ schema: Schema,
+ name: string,
+ required: boolean,
+ ) => string | undefined;
onClose: () => void;
}
function SchemaDialog(props: DraftProps) {
const [name, setName] = useState(props.name ?? '');
+ const [nameError, setNameError] = useState();
const [required, setRequired] = useState(props.required ?? false);
- const [draft, setDraft] = useState(() =>
- props.json || schemaError(props.value) || kindOf(props.value) === 'JSON'
+ const [draft, setDraft] = useState(() => {
+ const { kind } = readSchema(props.value);
+ return props.json || !kind || kind === 'JSON'
? JSON.stringify(props.value, null, 2)
- : props.value,
- );
+ : props.value;
+ });
const json = typeof draft === 'string';
- let schema = props.value;
- let error: string | undefined;
- try {
- schema = json ? JSON.parse(draft) : draft;
- error = schemaError(schema);
- } catch (err) {
- error = String(err);
- }
- const duplicate = props.name === '' && props.names?.includes(name);
+ const { schema = props.value, kind, error } = readSchema(draft);
+ const duplicate =
+ name !== props.name && props.names?.includes(name)
+ ? 'A property with this name already exists.'
+ : undefined;
return (