;
+const actionGutter = { paddingInlineEnd: 2 };
+
+// The MUI input template, select widget and raw text field all forward InputProps.
+function withFieldActions>(
+ Input: ComponentType
,
+ select = false,
+) {
+ 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 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);
+ return (
+ .MuiFormControlLabel-root': { ml: 0 },
+ }}
+ >
+ {children}
+ {actions && (
+
+ {actions}
+
+ )}
+
+ );
+}
+
+export function CheckboxWithActions(props: WidgetProps) {
+ return (
+
+
+
+ );
+}
+
+export function TitleWithActions(props: TitleFieldProps) {
+ const actions = useFieldActions(props.id);
+ if (!actions) return ;
+ return (
+
+ {props.optionalDataControl}
+ {actions}
+
+ }
+ />
+ );
+}
diff --git a/diagram-editor/frontend/forms/node-form.test.tsx b/diagram-editor/frontend/forms/node-form.test.tsx
index 5d132b17..5a022f6f 100644
--- a/diagram-editor/frontend/forms/node-form.test.tsx
+++ b/diagram-editor/frontend/forms/node-form.test.tsx
@@ -97,10 +97,8 @@ test('renders typed controls for a supported object schema and loads existing co
1.5,
);
expect(screen.getByRole('spinbutton', { name: /attempts/ })).toHaveValue(3);
- expect(screen.getByRole('combobox', { name: /enabled/ })).toHaveTextContent(
- 'true',
- );
- expect(screen.getByRole('combobox', { name: /strategy/ })).toHaveTextContent(
+ expect(screen.getByRole('checkbox', { name: /enabled/ })).toBeChecked();
+ expect(screen.getByRole('combobox', { name: /strategy/ })).toHaveValue(
'safe',
);
expect(screen.queryByLabelText('Config')).not.toBeInTheDocument();
@@ -178,7 +176,7 @@ test('renders and updates a numeric control when the entire node config is a num
expect(onChange).not.toHaveBeenCalled();
});
-test('an Option config opts out through its own checkbox', async () => {
+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({
@@ -189,40 +187,33 @@ test('an Option config opts out through its own checkbox', async () => {
,
registry,
);
-
- // Starts opted out: the box is disabled until the config is switched on.
- const optOut = await screen.findByRole('checkbox', { name: 'Set Config' });
- expect(optOut).not.toBeChecked();
- expect(screen.getByRole('spinbutton', { name: /Config/ })).toBeDisabled();
-
- fireEvent.click(optOut);
- expect(onChange.mock.calls.at(-1)?.[0].item.data.op.config).toBe(0);
+ 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);
- // And back again, which is the route to `null` that emptying the box is not.
- fireEvent.click(screen.getByRole('checkbox', { name: 'Set Config' }));
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Config value options' }),
+ );
+ fireEvent.click(await screen.findByRole('menuitem', { name: 'Set to null' }));
expect(onChange.mock.calls.at(-1)?.[0].item.data.op.config).toBeNull();
});
-test('an optional Option property gets one checkbox, not two', 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',
properties: {
compared_to: { anyOf: [{ type: 'number' }, { type: 'null' }] },
},
});
-
- render(, registry);
-
- expect(
- await screen.findByRole('checkbox', { name: 'Set compared_to' }),
- ).toBeInTheDocument();
- expect(screen.getAllByRole('checkbox')).toHaveLength(1);
+ render(, registry);
+ await screen.findByRole('button', { name: 'compared_to value options' });
+ expect(onChange).not.toHaveBeenCalled();
});
test('a non-nullable numeric config is not cleared by emptying it', async () => {
@@ -246,25 +237,20 @@ test('a non-nullable numeric config is not cleared by emptying it', async () =>
expect(count).toBeInvalid();
});
-test('booleans are edited as a two-option list', async () => {
+test('editing a boolean writes a boolean value', async () => {
const onChange = jest.fn();
const registry = createRegistry({
type: 'object',
properties: { print: { type: 'boolean' } },
required: ['print'],
});
-
render(
,
registry,
);
-
- const print = await screen.findByRole('combobox', { name: /print/ });
- expect(print).toHaveTextContent('true');
- expect(screen.queryByRole('checkbox')).not.toBeInTheDocument();
-
- fireEvent.mouseDown(print);
- fireEvent.click(await screen.findByRole('option', { name: 'false' }));
+ const print = await screen.findByRole('checkbox', { name: /print/ });
+ expect(print).toBeChecked();
+ fireEvent.click(print);
expect(onChange.mock.calls.at(-1)?.[0].item.data.op.config).toEqual({
print: false,
});
@@ -372,15 +358,11 @@ test('optional properties can be added and omitted', async () => {
registry,
);
- const includeOptional = await screen.findByRole('checkbox', {
- name: 'Set optional_text',
- });
- expect(includeOptional).not.toBeChecked();
- expect(screen.getByRole('textbox', { name: 'optional_text' })).toBeDisabled();
- fireEvent.click(includeOptional);
+ 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: '',
+ optional_text: 'present',
});
rerender(
@@ -392,9 +374,7 @@ test('optional properties can be added and omitted', async () => {
onChange={onChange}
/>,
);
- fireEvent.click(
- await screen.findByRole('checkbox', { name: 'Set optional_text' }),
- );
+ fireEvent.change(input, { target: { value: '' } });
expect(onChange.mock.calls.at(-1)?.[0].item.data.op.config).toEqual({
required_text: 'required',
});
@@ -427,13 +407,15 @@ test('control edits write the same JSON-compatible config object', async () => {
});
expect(onChange.mock.calls.at(-1)?.[0].item.data.op.config).toEqual({
...config,
+ title: 'Updated',
threshold: 2.75,
});
- fireEvent.mouseDown(screen.getByRole('combobox', { name: /enabled/ }));
- fireEvent.click(await screen.findByRole('option', { name: 'false' }));
+ 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,
});
@@ -441,6 +423,9 @@ test('control edits write the same JSON-compatible config object', async () => {
fireEvent.click(await screen.findByRole('option', { name: 'fast' }));
expect(onChange.mock.calls.at(-1)?.[0].item.data.op.config).toEqual({
...config,
+ title: 'Updated',
+ threshold: 2.75,
+ enabled: false,
strategy: 'fast',
});
});
@@ -527,7 +512,7 @@ test('nests a group per level, each editing against its own schema', async () =>
});
});
-test('switching on an optional object seeds its required fields', async () => {
+test('editing a field in an absent optional object creates that object', async () => {
const onChange = jest.fn();
const registry = createRegistry({
type: 'object',
@@ -542,15 +527,12 @@ test('switching on an optional object seeds its required fields', async () => {
},
},
});
-
render(, registry);
-
- // Until the object is switched on, nothing inside it is editable.
- expect(await screen.findByRole('textbox', { name: /inner/ })).toBeDisabled();
- fireEvent.click(screen.getByRole('checkbox', { name: 'Set opts' }));
-
+ const inner = await screen.findByRole('textbox', { name: /inner/ });
+ expect(onChange).not.toHaveBeenCalled();
+ fireEvent.change(inner, { target: { value: 'saved' } });
expect(onChange.mock.calls.at(-1)?.[0].item.data.op.config).toEqual({
- opts: { inner: '', extra: 7 },
+ opts: { inner: 'saved' },
});
});
@@ -577,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,
@@ -599,10 +580,9 @@ test('a required boolean reads as a value, never as an empty box', async () => {
render(, registry);
- // The list shows `false`, and the config says so.
expect(
- await screen.findByRole('combobox', { name: /print/ }),
- ).toHaveTextContent('false');
+ await screen.findByRole('checkbox', { name: /print/ }),
+ ).not.toBeChecked();
expect(onChange.mock.calls.at(-1)?.[0].item.data.op.config).toEqual({
greeting: '',
print: false,
@@ -618,7 +598,7 @@ test('leaves a config-less node alone when nothing is required', async () => {
render(, registry);
- await screen.findByRole('checkbox', { name: 'Set note' });
+ await screen.findByRole('textbox', { name: 'note' });
await waitFor(() => expect(onChange).not.toHaveBeenCalled());
});
@@ -669,7 +649,7 @@ test('edits the whole config as JSON when the builder is not registered', async
);
});
-test('falls back to JSON per property, keeping the rest of the form typed', async () => {
+test('edits array items alongside the other typed properties', async () => {
const onChange = jest.fn();
const registry = createRegistry({
type: 'object',
@@ -692,16 +672,15 @@ test('falls back to JSON per property, keeping the rest of the form typed', asyn
'kept',
);
const values = screen.getByRole('textbox', { name: /values/ });
- expect(values).toHaveValue('["a"]');
-
- fireEvent.change(values, { target: { value: '["a","b"]' } });
+ expect(values).toHaveValue('a');
+ fireEvent.change(values, { target: { value: 'b' } });
expect(onChange.mock.calls.at(-1)?.[0].item.data.op.config).toEqual({
title: 'kept',
- values: ['a', 'b'],
+ values: ['b'],
});
});
-test('falls back to JSON at the point a schema recurses', async () => {
+test('expands a recursive property on demand', async () => {
const registry = createRegistry(
{ $ref: '#/$defs/Recursive' },
{
@@ -724,9 +703,8 @@ test('falls back to JSON at the point a schema recurses', async () => {
expect(await screen.findByRole('textbox', { name: /name/ })).toHaveValue(
'root',
);
- expect(screen.getByRole('textbox', { name: /child/ })).toHaveValue(
- JSON.stringify({ name: 'leaf' }),
- );
+ fireEvent.click(screen.getByRole('button', { name: /Expand Cycle/ }));
+ expect(screen.getByDisplayValue('leaf')).toBeInTheDocument();
});
function StatefulConfigForm({ schema }: { schema: unknown }) {
diff --git a/diagram-editor/frontend/forms/node-form.tsx b/diagram-editor/frontend/forms/node-form.tsx
index 56a5bd42..9f0f38bd 100644
--- a/diagram-editor/frontend/forms/node-form.tsx
+++ b/diagram-editor/frontend/forms/node-form.tsx
@@ -8,38 +8,24 @@ import {
} from '@mui/material';
import { MaterialSymbol } from '../nodes';
import { useRegistry } from '../registry-provider';
-import { useTransientEditorDrafts } from '../transient-editor-drafts';
import BaseEditOperationForm, {
type BaseEditOperationFormProps,
+ operationUpdater,
} from './base-edit-operation-form';
import ConfigExamples from './config-examples';
-import SchemaConfigForm, {
- getSchemaConfigDefaults,
-} from './schema-config-form';
+import OperationConfigForm from './operation-config-form';
+import { getSchemaConfigDefaults } from './schema-config-form';
export type NodeFormProps = BaseEditOperationFormProps<'node'>;
function NodeForm(props: NodeFormProps) {
const registry = useRegistry();
- const { drafts, setOperationConfigDraft } = useTransientEditorDrafts();
const nodes = Object.keys(registry.nodes).sort();
- const configDraftKey = `node:${props.node.id}:config`;
const op = props.node.data.op;
const existingConfig = op.config;
const builderMetadata = registry.nodes[op.builder];
- const replaceOp = (updatedOp: typeof op) => {
- props.onChange?.({
- type: 'replace',
- id: props.node.id,
- item: { ...props.node, data: { ...props.node.data, op: updatedOp } },
- });
- };
-
- const updateConfig = (config: unknown) => {
- const { config: _config, ...rest } = op;
- replaceOp(config === undefined ? rest : { ...rest, config });
- };
+ const replaceOp = operationUpdater(props);
return (
@@ -103,19 +89,12 @@ function NodeForm(props: NodeFormProps) {
{builderMetadata.description}
)}
-
- setOperationConfigDraft(configDraftKey, value)
- }
- />
+
+ 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
new file mode 100644
index 00000000..88f84e4c
--- /dev/null
+++ b/diagram-editor/frontend/forms/operation-config-form.tsx
@@ -0,0 +1,204 @@
+import { Chip, MenuItem, TextField, Tooltip } from '@mui/material';
+import { Templates } from '@rjsf/mui';
+import type { FieldTemplateProps } from '@rjsf/utils';
+import {
+ type ComponentType,
+ createContext,
+ 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';
+import { useTransientEditorDrafts } from '../transient-editor-drafts';
+import {
+ bindingProperties,
+ fieldPointer,
+ schemaDocument,
+ withinField,
+} from '../utils/schema-types';
+import {
+ type BaseEditOperationFormProps,
+ operationUpdater,
+} from './base-edit-operation-form';
+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<{
+ schema: ReturnType;
+ pointer?: string;
+ bindings: Bindings;
+ setLink: (pointer: string, property?: string) => void;
+} | null>(null);
+const MuiField = Templates.FieldTemplate as ComponentType;
+
+// 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);
+ 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')
+ )
+ return children;
+ const pointer = fieldPointer(path);
+ if (context.pointer === pointer) return children;
+
+ const linked = context.bindings[pointer];
+ if (linked !== undefined) {
+ return (
+ }
+ onDelete={() => context.setLink(pointer)}
+ />
+ ),
+ },
+ }}
+ />
+ );
+ }
+ if (!path.length && field?.schema.type === 'object') return children;
+
+ const menu = (
+ li': {
+ display: 'grid',
+ gridColumn: '1 / -1',
+ gridTemplateColumns: 'subgrid',
+ whiteSpace: 'normal',
+ overflowWrap: 'anywhere',
+ },
+ }}
+ >
+ {() => {
+ const properties = bindingProperties(context.schema, field);
+ if (!properties.length)
+ return ;
+ return properties.map(({ name, type, warning }) => (
+
+ ));
+ }}
+
+ );
+ return (
+
+
+ {children}
+
+
+ );
+}
+
+type OperationProps = BaseEditOperationFormProps<
+ 'node' | 'script' | 'section'
+> &
+ Pick;
+
+export default function OperationConfigForm(props: OperationProps) {
+ const { node, schema, label = 'Config' } = props;
+ const { schemas: definitions } = useRegistry();
+ const template = useActiveTemplate();
+ const { drafts, setOperationConfigDraft } = useTransientEditorDrafts();
+ 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),
+ setLink: (pointer: string, property?: string) =>
+ updateConfig(
+ op.config,
+ trackedFields.filter((path) => withinField(path, pointer)),
+ property === undefined ? undefined : [pointer, property],
+ ),
+ };
+ const form = (
+ setOperationConfigDraft(key, text)}
+ />
+ );
+ return (
+
+ {binding && (!schema || typeof schema === 'boolean') ? (
+ {form}
+ ) : (
+ form
+ )}
+
+ );
+}
diff --git a/diagram-editor/frontend/forms/schema-config-form.tsx b/diagram-editor/frontend/forms/schema-config-form.tsx
index a64336d3..82bdb670 100644
--- a/diagram-editor/frontend/forms/schema-config-form.tsx
+++ b/diagram-editor/frontend/forms/schema-config-form.tsx
@@ -1,407 +1,294 @@
import {
+ Autocomplete,
Box,
- Checkbox,
- FormControlLabel,
+ Button,
MenuItem,
Stack,
- TextField,
Typography,
} from '@mui/material';
+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,
+ type MultiSchemaFieldTemplateProps,
+ type ObjectFieldTemplateProps,
+ optionsList,
+ RJSF_REF_CYCLE_KEY,
+ RJSF_REF_KEY,
+ type RJSFMarkedSchema,
+ type RJSFSchema,
+ retrieveSchema,
+ setByPath,
+ toFieldPathId,
+ type UiSchema,
+ useDeepCompareMemo,
+} from '@rjsf/utils';
+import { customizeValidator } from '@rjsf/validator-ajv8';
+import Ajv2020 from 'ajv/dist/2020';
import equal from 'fast-deep-equal';
-import { useEffect, useMemo, useState } from 'react';
-
-type JsonConfigObject = Record;
-
-type JsonSchema = Record;
-type EnumValue = string | number | boolean;
+import {
+ type ComponentType,
+ useEffect,
+ useId,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
+import {
+ fieldPointer,
+ schemaDocument,
+ schemaTypes,
+ withinField,
+} from '../utils/schema-types';
+import {
+ ActionTextField,
+ CheckboxWithActions,
+ FieldActionContext,
+ FieldActions,
+ FieldMenu,
+ FieldRow,
+ InputWithActions,
+ SelectWithActions,
+ TitleWithActions,
+} from './field-actions';
+
+const validator = customizeValidator({
+ AjvClass: Ajv2020,
+ ajvOptionsOverrides: { strict: false, validateFormats: false },
+ ajvFormatOptions: false,
+});
+
+const MuiObjectField =
+ Templates.ObjectFieldTemplate as ComponentType;
+
+function ObjectLayout(props: ObjectFieldTemplateProps) {
+ const rjsfSlotProps = {
+ titleBox: { sx: { m: 0 } },
+ titleTypography: { variant: 'subtitle2', sx: { overflowWrap: 'anywhere' } },
+ titleGridContainer: { alignItems: 'center' },
+ objectGridItem: { sx: { mb: 0 } },
+ objectGridContainer: {
+ sx: { mt: props.title || props.description ? 2 : 0 },
+ },
+ };
+ return (
+
+ );
+}
-/**
- * A schema paired with the control that edits it. `raw` is the bottom case:
- * whatever this form cannot express as a typed control is edited as JSON, so an
- * unsupported corner of a schema never limits what the user can enter, and a
- * node without a schema is just the case where the whole config is raw.
- */
-type ResolvedSchema = {
- description?: string;
- defaultValue?: unknown;
- /** The schema also accepts `null`, i.e. it came from an `Option`. */
- nullable?: boolean;
-} & (
- | { type: 'raw' }
- | { type: 'string'; enumValues?: EnumValue[] }
- | {
- type: 'number' | 'integer';
- enumValues?: EnumValue[];
- minimum?: number;
- maximum?: number;
- }
- // Booleans are always edited as a two-option list rather than a checkbox, so
- // that a nullable one can sit beside its opt-out box without a second
- // checkbox next to it. These values are synthesised, not read from a schema.
- | { type: 'boolean'; enumValues: EnumValue[] }
- | {
- type: 'object';
- properties: Record;
- required: Set;
- }
-);
+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 && (
+
+
+
+ )}
+
+ );
+}
-type ResolvedObjectSchema = Extract;
-type ResolvedNumberSchema = Extract<
- ResolvedSchema,
- { type: 'number' | 'integer' }
->;
+function AlternativesLayout({
+ selector,
+ optionSchemaField,
+}: MultiSchemaFieldTemplateProps) {
+ return (
+
+ {selector}
+
+ {optionSchemaField}
+
+
+ );
+}
-interface SchemaConfigFormProps {
+const editingDefaults = {
+ emptyObjectFields: 'skipDefaults',
+ requiredBooleanDefault: 'skip',
+ arrayMinItems: { populate: 'never' },
+ constAsDefaults: 'skipOneOf',
+} as const;
+
+const emptyScalars: Record = {
+ string: '',
+ integer: 0,
+ number: 0,
+ boolean: false,
+};
+
+export interface SchemaConfigFormProps {
schema: unknown;
- definitions: Record;
+ definitions?: Record;
value?: unknown;
- onChange: (value: unknown) => void;
+ onChange: (value: unknown, replacedFields?: string[]) => void;
+ trackedFields?: string[];
+ label?: string;
+ disabled?: boolean;
+ nodeDefaults?: boolean;
+ allowJson?: boolean;
+ uiSchema?: UiSchema;
+ fieldTemplate?: ComponentType;
rawDraft?: string;
onRawDraftChange?: (value: string | undefined) => void;
}
-function schemaObject(value: unknown): JsonSchema | null {
- return typeof value === 'object' && value !== null && !Array.isArray(value)
- ? (value as JsonSchema)
- : null;
-}
-
-// `Object.hasOwn` needs a newer lib target than this package compiles against,
-// and biome rewrites a `hasOwnProperty` call into it.
-function hasOwn(object: object, key: PropertyKey): boolean {
- return Object.getOwnPropertyDescriptor(object, key) !== undefined;
-}
-
-function resolveRef(
- ref: string,
- definitions: Record,
-): JsonSchema | null {
- if (!ref.startsWith('#/')) {
- return null;
- }
- const name = ref.split('/').at(-1)?.replace(/~1/g, '/').replace(/~0/g, '~');
- return name ? schemaObject(definitions[name]) : null;
-}
-
-function isNullSchema(option: unknown): boolean {
- const type = schemaObject(option)?.type;
- return Array.isArray(type) ? type.includes('null') : type === 'null';
-}
-
-function schemaType(schema: JsonSchema): string | null {
- if (typeof schema.type === 'string') {
- return schema.type;
- }
- if (Array.isArray(schema.type)) {
- const nonNullTypes = schema.type.filter((type) => type !== 'null');
- return schema.type.includes('null') &&
- nonNullTypes.length === 1 &&
- typeof nonNullTypes[0] === 'string'
- ? nonNullTypes[0]
- : null;
- }
- if (Array.isArray(schema.enum) && schema.enum.length > 0) {
- return schema.enum.every((value) => typeof value === 'string')
- ? 'string'
- : null;
+// Registry references point outside the operation's schema. Give RJSF the same
+// document root it would have had when resolving the schema in the registry.
+function schemaRoot(schema: unknown, definitions?: Record) {
+ if (!schema || typeof schema !== 'object' || !Object.keys(schema).length) {
+ return undefined;
}
- return null;
+ const root = schemaDocument(schema, definitions);
+ // Compilation checks every reachable branch, including a map's value type
+ // before its first key exists. Unresolvable imported schemas stay editable.
+ return validator.rawValidation(root, undefined).validationError
+ ? undefined
+ : root;
}
-const unsupportedKeywords = [
- 'allOf',
- 'oneOf',
- 'not',
- 'if',
- 'then',
- 'else',
- 'patternProperties',
- 'dependentSchemas',
- 'dependencies',
-];
-
-/**
- * Resolves the parts of a schema this form has a typed control for, returning
- * `null` for anything it cannot type. Callers go through {@link resolveSchema},
- * which turns that `null` into a raw JSON field.
- */
-function resolveTypedSchema(
- schema: JsonSchema,
- definitions: Record,
- resolvingRefs: Set,
-): ResolvedSchema | null {
- if (typeof schema.$ref === 'string') {
- // A cycle resolves to a raw field at the point it closes, leaving the rest
- // of the schema typed.
- if (resolvingRefs.has(schema.$ref)) {
- return null;
- }
- const referenced = resolveRef(schema.$ref, definitions);
- if (!referenced) {
- return null;
- }
- const { $ref: _ref, ...overrides } = schema;
- return resolveTypedSchema(
- { ...referenced, ...overrides },
- definitions,
- new Set(resolvingRefs).add(schema.$ref),
- );
- }
-
- // `Option` serializes as a two-branch `anyOf`; unwrap it to edit the `T`.
- if (Array.isArray(schema.anyOf)) {
- const nonNull = schema.anyOf.filter((option) => !isNullSchema(option));
- const unwrapped = schemaObject(nonNull[0]);
- if (nonNull.length !== schema.anyOf.length - 1 || !unwrapped) {
- return null;
- }
- const { anyOf: _anyOf, ...overrides } = schema;
- const resolved = resolveTypedSchema(
- { ...unwrapped, ...overrides },
- definitions,
- resolvingRefs,
- );
- return resolved && { ...resolved, nullable: true };
- }
-
- if (unsupportedKeywords.some((key) => key in schema)) {
- return null;
- }
-
- const type = schemaType(schema);
- const base = {
- description:
- typeof schema.description === 'string' ? schema.description : undefined,
- defaultValue: schema.default,
- // The other spelling of `Option`: `"type": ["number", "null"]`.
- nullable: Array.isArray(schema.type) && schema.type.includes('null'),
- };
-
- if (type === 'boolean') {
- return schema.enum === undefined
- ? { ...base, type, enumValues: [true, false] }
- : null;
- }
-
- if (type === 'string' || type === 'number' || type === 'integer') {
- let enumValues: EnumValue[] | undefined;
- if (schema.enum !== undefined) {
- if (
- !Array.isArray(schema.enum) ||
- schema.enum.length === 0 ||
- !schema.enum.every(
- (value) => typeof value === 'string' || typeof value === 'number',
- )
- ) {
- return null;
+// 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);
+ }
}
- enumValues = schema.enum as EnumValue[];
- }
- if (type === 'string') {
- return { ...base, type, enumValues };
- }
- return {
- ...base,
- type,
- enumValues,
- minimum: typeof schema.minimum === 'number' ? schema.minimum : undefined,
- maximum: typeof schema.maximum === 'number' ? schema.maximum : undefined,
- };
+ schemas = children;
+ before = getByPath(before, key);
+ after = getByPath(after, key);
+ if (before !== undefined && after === undefined) return true;
}
+ return false;
+}
- if (type === 'object') {
- // A map type has no fixed set of fields to lay out, so edit it as raw JSON.
- if (
- schema.additionalProperties !== undefined &&
- schema.additionalProperties !== false
- ) {
- return null;
- }
- const rawProperties = schemaObject(schema.properties ?? {});
- const requiredValues = schema.required ?? [];
+// 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(
+ schema: RJSFSchema,
+ root: RJSFSchema,
+ value: unknown,
+ required = false,
+): unknown {
+ if (RJSF_REF_CYCLE_KEY in schema) return value ?? null;
+ if (required && value === undefined)
+ value = getDefaultFormState(validator, schema, undefined, root);
+ const resolved = retrieveSchema(validator, schema, root, value);
+ const type = getSchemaType(resolved);
+ if (type !== 'object') {
+ if (value !== undefined || !required) return value;
+ if ('default' in resolved) return resolved.default;
if (
- !rawProperties ||
- !Array.isArray(requiredValues) ||
- !requiredValues.every((value) => typeof value === 'string')
- ) {
+ (Array.isArray(resolved.type) && resolved.type.includes('null')) ||
+ resolved.anyOf?.some((s) => isObject(s) && s.type === 'null')
+ )
return null;
- }
- const properties: Record = {};
- for (const [name, propertySchema] of Object.entries(rawProperties)) {
- properties[name] = resolveSchema(
- propertySchema,
- definitions,
- resolvingRefs,
- );
- }
- return {
- ...base,
- type,
- properties,
- required: new Set(requiredValues as string[]),
- };
- }
-
- return null;
-}
-
-function resolveSchema(
- rawSchema: unknown,
- definitions: Record,
- resolvingRefs = new Set(),
-): ResolvedSchema {
- const schema = schemaObject(rawSchema);
- const typed =
- schema && resolveTypedSchema(schema, definitions, resolvingRefs);
- return (
- typed ?? {
- type: 'raw',
- description:
- typeof schema?.description === 'string'
- ? schema.description
- : undefined,
- defaultValue: schema?.default,
- }
- );
-}
-
-function schemaDefault(schema: ResolvedSchema): unknown {
- if (schema.defaultValue !== undefined) {
- // Config values are JSON, so a round trip is enough to detach the default
- // from the registry.
- return JSON.parse(JSON.stringify(schema.defaultValue));
+ if (resolved.enum?.length) return resolved.enum[0];
+ return typeof type === 'string' ? (emptyScalars[type] ?? null) : null;
}
- if (schema.type !== 'object') {
+ if (value !== undefined && !isObject(value)) return value;
+ if (value === undefined && !required && !resolved.required?.length)
return undefined;
- }
- const value: JsonConfigObject = {};
- for (const [name, property] of Object.entries(schema.properties)) {
- const propertyDefault = schemaDefault(property);
- if (propertyDefault !== undefined) {
- value[name] = propertyDefault;
+ const object = { ...(value as Record) };
+ for (const [key, child] of Object.entries(resolved.properties ?? {})) {
+ const needed = resolved.required?.includes(key) ?? false;
+ if (needed || key in object) {
+ object[key] = fillNodeFields(
+ typeof child === 'boolean' ? {} : child,
+ root,
+ object[key],
+ needed,
+ );
}
}
- return Object.keys(value).length > 0 ? value : undefined;
+ return equal(object, value) ? value : object;
}
-/**
- * The config a newly created node starts with: schema defaults, plus the
- * required keys that have none, so the node is already the shape the form would
- * give it.
- */
export function getSchemaConfigDefaults(
schema: unknown,
definitions: Record,
): unknown {
- const resolvedSchema = resolveSchema(schema, definitions);
- return completeRequired(resolvedSchema, schemaDefault(resolvedSchema));
-}
-
-/**
- * Whether the field carries its own "is this set" checkbox. Objects and raw
- * JSON fields are left out: an object is a group rather than a single control,
- * and `null` can simply be typed into a JSON box.
- */
-function hasNullToggle(schema: ResolvedSchema): boolean {
- return (
- schema.nullable === true &&
- schema.type !== 'object' &&
- schema.type !== 'raw'
- );
-}
-
-/** The value a nullable field takes when its checkbox is ticked. */
-function enabledValue(schema: ResolvedSchema): unknown {
- return schema.defaultValue === undefined || schema.defaultValue === null
- ? presentValue(schema)
- : JSON.parse(JSON.stringify(schema.defaultValue));
-}
-
-/** The value written when an optional property is switched on. */
-function initialValue(schema: ResolvedSchema): unknown {
- if (schema.defaultValue !== undefined) {
- return JSON.parse(JSON.stringify(schema.defaultValue));
- }
- if (schema.nullable) {
- // An `Option` with no default starts out as `None`.
- return null;
- }
- return presentValue(schema);
-}
-
-/** The empty-but-present value for a schema, ignoring whether it is nullable. */
-function presentValue(schema: ResolvedSchema): unknown {
- switch (schema.type) {
- case 'raw':
- return null;
- case 'string':
- return schema.enumValues?.[0] ?? '';
- case 'number':
- case 'integer':
- return schema.enumValues?.[0] ?? 0;
- case 'boolean':
- return false;
- case 'object': {
- // Seed required children too, otherwise switching on an object writes a
- // `{}` the schema rejects.
- const value: JsonConfigObject = {};
- for (const [name, property] of Object.entries(schema.properties)) {
- if (schema.required.has(name)) {
- value[name] = initialValue(property);
- } else {
- const propertyDefault = schemaDefault(property);
- if (propertyDefault !== undefined) {
- value[name] = propertyDefault;
- }
- }
- }
- return value;
- }
- }
-}
-
-/**
- * Fills in every required key the config is missing, so that a field the form
- * renders always corresponds to a key that exists. Returns `value` itself when
- * there was nothing to add, which is what stops {@link SchemaConfigForm} from
- * reporting a change on every render.
- *
- * Only absent keys are filled: a key that is present but holds the wrong shape
- * is the user's data and is left for them to see and correct.
- */
-function completeRequired(schema: ResolvedSchema, value: unknown): unknown {
- if (schema.type !== 'object') {
- return value;
- }
- const object = schemaObject(value);
- if (!object) {
- // Nothing to complete unless the schema insists on keys; a config-less node
- // whose fields are all optional stays config-less.
- return schema.required.size > 0 ? initialValue(schema) : value;
- }
-
- let completed = object;
- const fill = (name: string, propertyValue: unknown) => {
- if (completed === object) {
- completed = { ...object };
- }
- completed[name] = propertyValue;
- };
-
- for (const [name, property] of Object.entries(schema.properties)) {
- if (!hasOwn(object, name)) {
- if (schema.required.has(name)) {
- fill(name, initialValue(property));
- }
- continue;
- }
- const child = completeRequired(property, object[name]);
- if (child !== object[name]) {
- fill(name, child);
- }
- }
- return completed;
+ const root = schemaRoot(schema, definitions);
+ if (!root) return undefined;
+ const defaults = getDefaultFormState(validator, root, undefined, root);
+ return fillNodeFields(root, root, equal(defaults, {}) ? undefined : defaults);
}
function formatJson(value: unknown): string {
@@ -419,49 +306,14 @@ function parseJson(draft: string): { value: unknown } | null {
}
}
-function formatNumber(value: unknown): string {
- return typeof value === 'number' ? String(value) : '';
-}
-
-function parseNumber(
- draft: string,
- type: ResolvedNumberSchema['type'],
-): number | undefined {
- if (draft.trim() === '') {
- return undefined;
- }
- const parsed = Number(draft);
- if (
- !Number.isFinite(parsed) ||
- (type === 'integer' && !Number.isInteger(parsed))
- ) {
- return undefined;
- }
- return parsed;
-}
-
-interface FieldProps {
- label: string;
- schema: ResolvedSchema;
- value: unknown;
- required: boolean;
- disabled: boolean;
- onChange: (value: unknown) => void;
-}
-
function RawField({
- label,
- schema,
+ label = 'Config',
value,
- required,
- disabled,
onChange,
- draftValue,
- onDraftChange,
-}: FieldProps & {
- draftValue?: string;
- onDraftChange?: (value: string | undefined) => void;
-}) {
+ rawDraft: draftValue,
+ onRawDraftChange: onDraftChange,
+ disabled,
+}: Omit) {
const [draft, setDraft] = useState(() => draftValue ?? formatJson(value));
// Only adopt an incoming value that the box does not already say. Re-encoding
// on every keystroke would strip the user's whitespace and move the cursor.
@@ -476,15 +328,13 @@ function RawField({
}, [draftValue, value]);
return (
- {
setDraft(event.target.value);
const parsed = parseJson(event.target.value);
@@ -496,303 +346,452 @@ function RawField({
}
}}
slotProps={{
- htmlInput: {
- sx: { fontFamily: 'monospace', whiteSpace: 'nowrap' },
- },
+ htmlInput: { sx: { fontFamily: 'monospace' } },
}}
/>
);
}
-function NumberField({
- label,
- schema,
- value,
- required,
- disabled,
- onChange,
-}: FieldProps & { schema: ResolvedNumberSchema }) {
- const [draft, setDraft] = useState(() => formatNumber(value));
- // As in RawField: keep a draft that already means `value`, so a trailing `.`
- // or `0` survives the round trip through the config.
- useEffect(() => {
- setDraft((current) =>
- parseNumber(current, schema.type) === (value ?? undefined)
- ? current
- : formatNumber(value),
- );
- }, [value, schema.type]);
+const nativeFields = getDefaultRegistry().fields;
- return (
- `
- // unwraps to `T`, so a `null` here is an absent value, not a wrong one.
- error={parseNumber(draft, schema.type) !== (value ?? undefined)}
- helperText={schema.description}
- slotProps={{
- htmlInput: {
- min: schema.minimum,
- max: schema.maximum,
- step: schema.type === 'integer' ? 1 : 'any',
- },
- }}
- onChange={(event) => {
- setDraft(event.target.value);
- const parsed = parseNumber(event.target.value, schema.type);
- if (parsed !== undefined) {
- onChange(parsed);
- }
- }}
- />
- );
+function fieldTitle({ name, schema, uiSchema }: FieldProps) {
+ return uiSchema?.['ui:title'] ?? schema.title ?? name;
}
-function EnumField({
- label,
- schema,
- value,
- required,
- disabled,
- onChange,
- enumValues,
-}: FieldProps & { enumValues: EnumValue[] }) {
- // Selected by index so that string, number and boolean options round trip
- // alike - `String(option)` would flatten `1` and `"1"` onto each other.
- const selectedIndex = enumValues.findIndex((option) => option === value);
+function acceptsNull(schema: RJSFSchema, registry: FieldProps['registry']) {
+ return validator.isValid(schema, null, registry.rootSchema);
+}
+
+function EnumField(props: FieldProps) {
+ const { schema, uiSchema, fieldPathId, formData } = props;
+ const choices = optionsList(schema, uiSchema) ?? [
+ { label: 'null', value: null, schema },
+ ];
+ const strings = choices.every(({ value }) => typeof value === 'string');
+ const options = choices.filter(
+ ({ value }) =>
+ (!schema.oneOf && value !== null) ||
+ validator.isValid(schema, value, props.registry.rootSchema),
+ );
return (
- onChange(enumValues[Number(event.target.value)])}
- >
- {enumValues.map((option, index) => (
-
- ))}
-
+ JSON.stringify(value)}
+ getOptionLabel={({ label, value, schema: option }) =>
+ option?.title !== undefined ||
+ label !== String(value) ||
+ (strings && value)
+ ? label
+ : JSON.stringify(value)
+ }
+ value={options.find(({ value }) => equal(value, formData)) ?? null}
+ disableClearable={props.required}
+ disabled={props.disabled}
+ readOnly={props.readonly}
+ onChange={(_, choice) => props.onChange(choice?.value, fieldPathId.path)}
+ renderInput={(params) => (
+
+ )}
+ />
);
}
-function SchemaField(props: FieldProps) {
- const { label, schema, value, required, disabled, onChange } = props;
-
- // An `Option` opts out through a checkbox beside its control, so every
- // nullable field says "no value" the same way. Rendering the control again
- // without `nullable` is what stops this from recursing.
- if (hasNullToggle(schema)) {
- const enabled = value !== null;
- return (
-
- {/* Centred against the input itself rather than the whole field, so a
- description below the input does not drag the checkbox down. 56px is
- the height of an outlined input at the default size. */}
-
-
- onChange(event.target.checked ? enabledValue(schema) : null)
- }
- />
-
-
-
-
-
- );
- }
-
- if (schema.type === 'raw') {
- return ;
- }
-
- if (schema.type === 'object') {
- return (
-
-
- {label}
-
- {schema.description && (
-
- {schema.description}
-
- )}
-
-
- );
- }
+function FieldContents({ children }: FieldTemplateProps) {
+ return children;
+}
- // Booleans are checked by type rather than by having `enumValues`, because
- // that is what narrows them out of the union for the branches below.
- if (schema.type === 'boolean') {
- return ;
- }
+// The outer field already supplies the binding, label and validation errors.
+function inlineUiSchema({ 'ui:field': _field, ...rest }: UiSchema = {}) {
+ return { ...rest, 'ui:FieldTemplate': FieldContents };
+}
- if (schema.enumValues) {
- return ;
- }
+function hasEditor(schema: RJSFSchema) {
+ return getSchemaType(schema) || schema.oneOf || schema.anyOf;
+}
- if (schema.type === 'string') {
- return (
- onChange(event.target.value)}
- />
+// anyOf validates a single JSON value. Each editor writes to that same path,
+// so overlapping choices can match together and object members can coexist.
+function ParallelAnyOfField(props: FieldProps) {
+ const { formData, fieldPathId, registry, schema } = props;
+ const { SchemaField: Field } = registry.fields;
+ const { anyOf = [], ...base } = schema;
+ const title = fieldTitle(props);
+ const current = useRef(formData);
+ current.current = formData;
+ const branches = anyOf
+ .filter((s) => s !== false)
+ .map((s) =>
+ registry.schemaUtils.retrieveSchema(s === true ? {} : s, formData),
);
+ const rawEditor = (label: string, key?: string) => (
+ props.onChange(value, fieldPathId.path)}
+ />
+ );
+ if (!branches.length) return rawEditor(title);
+ const concrete = branches.filter(
+ (s) => !equal(schemaTypes(s, registry.rootSchema), ['null']),
+ );
+ if (concrete.length < branches.length && acceptsNull(schema, registry)) {
+ if (!concrete.length)
+ return ;
+ const nonNullSchema = {
+ ...base,
+ ...(concrete.length === 1 ? concrete[0] : { anyOf: concrete }),
+ };
+ // A registered nullable type may already provide its own null control.
+ if (concrete.length === 1 && acceptsNull(concrete[0], registry)) {
+ if (!hasEditor(nonNullSchema)) return rawEditor(title);
+ return (
+
+ );
+ }
+ return ;
}
+ return (
+
+
+ {title}
+
+
+ {base.properties && (
+
+ )}
+ {branches.map((option, index) => {
+ const optionId = `${registry.globalFormOptions.idPrefix}_anyOf${index}`;
+ const type = getSchemaType(option) ?? getSchemaType(base);
+ const ref = (option as RJSFMarkedSchema)[RJSF_REF_KEY];
+ const name =
+ option.title ??
+ (typeof ref === 'string' ? ref.split('/').at(-1) : undefined) ??
+ (typeof type === 'string' ? type : `Alternative ${index + 1}`);
+ const values =
+ option.enum ??
+ (option.const === undefined ? undefined : [option.const]);
+ if (base.properties && !hasEditor(option)) return null; // A required-only branch constrains the shared object above.
+ if (!type && !values && !option.anyOf && !option.oneOf)
+ return rawEditor(name, optionId);
+ const matchesType =
+ type === guessType(formData) ||
+ (type === 'integer' && typeof formData === 'number');
+ const globalFormOptions = {
+ ...registry.globalFormOptions,
+ idPrefix: optionId,
+ };
+ return (
+ {
+ const child = path.slice(fieldPathId.path.length);
+ if (
+ child.length &&
+ (type === 'object' || type === 'array') &&
+ type !== guessType(current.current)
+ ) {
+ const container = setByPath(
+ type === 'array' ? [] : {},
+ child,
+ value,
+ );
+ props.onChange(container, fieldPathId.path, errors, id);
+ } else {
+ props.onChange(value, path, errors, id);
+ }
+ }}
+ />
+ );
+ })}
+
+
+ );
+}
- return ;
+function NullableField({
+ concrete: alternative,
+ ...props
+}: FieldProps & { concrete?: RJSFSchema }) {
+ const { schema, formData, fieldPathId, registry } = props;
+ const label = fieldTitle(props);
+ const type = getSchemaType(schema) as RJSFSchema['type'];
+ const concrete = alternative ?? { ...schema, type };
+ if (concrete.default === null) delete concrete.default;
+ const set = (value: unknown) => props.onChange(value, fieldPathId.path);
+ const canUnset =
+ !props.required && typeof fieldPathId.path.at(-1) !== 'number';
+ const Field = registry.fields.SchemaField;
+ const action = formData === null ? 'Edit value' : 'Set to null';
+ const first = (concrete.anyOf?.[0] as RJSFSchema) ?? concrete;
+ const editValue = () =>
+ fillNodeFields(first, registry.rootSchema, undefined, true);
+ const menu = (
+
+ {() => [
+ ,
+ canUnset && (
+
+ ),
+ ]}
+
+ );
+ return (
+
+ {formData === null ? (
+
+ ) : (
+
+ )}
+
+ );
}
-interface ObjectFieldsProps {
- schema: ResolvedObjectSchema;
- value: JsonConfigObject;
- onChange: (value: JsonConfigObject) => void;
+function SchemaField(props: FieldProps) {
+ 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') &&
+ acceptsNull(input, registry)
+ )
+ field = NullableField;
+ return (
+
+ );
}
-function ObjectFields({ schema, value, onChange }: ObjectFieldsProps) {
+function OneOfField(props: FieldProps) {
+ // RJSF otherwise reports undefined when the author selects a null branch.
+ const options = (props.options as RJSFSchema[]).map((option) => ({
+ ...option,
+ ...(option.type === 'null' && { default: null }),
+ title:
+ option.title ??
+ (typeof option.type === 'string' ? option.type : undefined),
+ }));
return (
-
- {Object.entries(schema.properties).map(([name, propertySchema]) => {
- const required = schema.required.has(name);
- const present = hasOwn(value, name);
- const setProperty = (propertyValue: unknown) => {
- const nextValue = { ...value };
- if (propertyValue === undefined) {
- delete nextValue[name];
- } else {
- nextValue[name] = propertyValue;
- }
- onChange(nextValue);
- };
- // A nullable field brings its own checkbox, and `#[serde(default)]` on
- // an `Option` makes a property both optional and nullable - so
- // deferring to that one checkbox is what keeps them from stacking up.
- const optOut = !required && !hasNullToggle(propertySchema);
- return (
-
- {optOut && (
-
- setProperty(
- event.target.checked
- ? initialValue(propertySchema)
- : undefined,
- )
- }
- />
- }
- label={`Set ${name}`}
- />
- )}
-
-
+ {
+ // 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,
);
- })}
-
+ }}
+ />
);
}
-export default function SchemaConfigForm({
- schema,
- definitions,
- value,
- onChange,
- rawDraft,
- onRawDraftChange,
-}: SchemaConfigFormProps) {
- const resolvedSchema = useMemo(
- () => resolveSchema(schema, definitions),
- [schema, definitions],
+// A node keeps its last usable number while an integer or required number is
+// incomplete. RJSF still controls the numeric widget and its formatting.
+function NodeNumberField(props: FieldProps) {
+ const [draft, setDraft] = useState<{ input: unknown; previous: unknown }>();
+ const invalid = draft !== undefined && draft.previous === props.formData;
+ return (
+ {
+ if (
+ (input === undefined &&
+ (props.required || !props.fieldPathId.path.length)) ||
+ (input !== undefined &&
+ getSchemaType(props.schema) === 'integer' &&
+ !Number.isInteger(input))
+ ) {
+ setDraft({ input, previous: props.formData });
+ return;
+ }
+ setDraft(undefined);
+ props.onChange(input, ...rest);
+ }}
+ />
);
+}
- // The form defines the shape of the config, so every field it renders has a
- // key behind it whether or not the user has touched that field. Editing is
- // done against the completed config, and the parent is told about the keys
- // that were filled in.
- const completed = useMemo(
- () => completeRequired(resolvedSchema, value),
- [resolvedSchema, value],
+export default function SchemaConfigForm(props: SchemaConfigFormProps) {
+ const id = useId();
+ const [editJson, setEditJson] = useState(props.rawDraft !== undefined);
+ const schema = useDeepCompareMemo(props.schema);
+ const root = useMemo(
+ () => schemaRoot(schema, props.definitions),
+ [schema, props.definitions],
+ );
+ const value = useMemo(
+ () =>
+ root && props.nodeDefaults
+ ? fillNodeFields(root, root, props.value)
+ : props.value,
+ [root, props.nodeDefaults, props.value],
);
useEffect(() => {
- if (completed !== value) {
- onChange(completed);
- }
- }, [completed, value, onChange]);
-
- // The top level is the form itself, so its fields go straight into the
- // surrounding layout rather than into a labelled group.
- if (resolvedSchema.type === 'object') {
- return (
-
+ if (value !== props.value) props.onChange(value);
+ }, [value, props.value, props.onChange]);
+ 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),
+ ),
);
- }
-
- if (resolvedSchema.type === 'raw') {
- return (
-
- );
- }
-
- return (
- change(next, undefined, root)} />
+ );
+ if (!root) return rawEditor;
+
+ const raw = editJson || props.rawDraft !== undefined;
+ const editor = (
+