Files
monkey-ai-web/src/components/ui/form.jsx
T

390 lines
11 KiB
React

/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, {
createContext,
forwardRef,
useContext,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useReducer,
} from 'react';
import { Checkbox, Form as AntForm } from 'antd';
import * as Controls from './controls';
import { useConsolePage } from '../console/ConsoleContext';
import { ConsoleForm } from '../console/ConsolePrimitives';
const FormContext = createContext(null);
const fieldPath = (field) =>
typeof field === 'string'
? field.replace(/\[(\d+)\]/g, '.$1').split('.')
: field;
function FormRenderContent({ form, api, children }) {
const values = form.getFieldsValue(true);
return children({ formState: { values }, formApi: api, values });
}
function fieldUpdate(form, path, value) {
let update = value;
for (let index = path.length - 1; index > 0; index--) {
const previous = form.getFieldValue(path.slice(0, index));
const parent = Array.isArray(previous)
? [...previous]
: previous == null && typeof path[index] === 'number'
? []
: { ...previous };
parent[path[index]] = update;
update = parent;
}
return { [path[0]]: update };
}
export const Form = forwardRef(function Form(
{
initValues,
values,
onSubmit,
onSubmitFail,
onValueChange,
getFormApi,
children,
labelPosition,
labelWidth,
labelAlign,
layout,
allowEmpty,
trigger,
stopValidateWithError,
...props
},
ref,
) {
const consolePage = useConsolePage();
const FormComponent = consolePage ? ConsoleForm : AntForm;
const [form] = AntForm.useForm();
const [, renderValues] = useReducer((value) => value + 1, 0);
const callbacks = useRef({ getFormApi, onValueChange });
callbacks.current = { getFormApi, onValueChange };
const api = useMemo(
() => ({
getValues: () => form.getFieldsValue(true),
getValue: (field) => form.getFieldValue(fieldPath(field)),
setValue: (field, value) => {
// External value updates avoid setFieldValue's redundant validation-meta reset.
form.setFieldsValue(fieldUpdate(form, fieldPath(field), value));
callbacks.current.onValueChange?.(form.getFieldsValue(true), {
[field]: value,
});
renderValues();
},
setValues: (next) => {
form.setFieldsValue(next);
callbacks.current.onValueChange?.(form.getFieldsValue(true), next);
renderValues();
},
reset: (fields) => {
form.resetFields(fields?.map?.(fieldPath));
callbacks.current.onValueChange?.(form.getFieldsValue(true));
renderValues();
},
validate: (fields) => form.validateFields(fields?.map?.(fieldPath)),
submitForm: () => form.submit(),
scrollToError: () => {
const first = form
.getFieldsError()
.find((field) => field.errors.length);
if (first) form.scrollToField(first.name, { block: 'nearest' });
},
getFieldExist: (field) =>
form.getFieldInstance(fieldPath(field)) !== undefined,
}),
[form],
);
useImperativeHandle(ref, () => ({ formApi: api, ...api }), [api]);
useEffect(() => {
callbacks.current.getFormApi?.(api);
renderValues();
}, [api]);
useEffect(() => {
if (values) form.setFieldsValue(values);
}, [form, values]);
return (
<FormContext.Provider value={form}>
<FormComponent
{...props}
form={form}
initialValues={initValues}
layout={
layout === 'horizontal' || labelPosition === 'left'
? 'horizontal'
: layout === 'inline'
? 'inline'
: 'vertical'
}
labelCol={
props.labelCol ??
(labelWidth
? {
flex: `0 0 ${typeof labelWidth === 'number' ? `${labelWidth}px` : labelWidth}`,
}
: undefined)
}
wrapperCol={
props.wrapperCol ?? (labelWidth ? { flex: '1 1 0' } : undefined)
}
labelAlign={labelAlign}
onFinish={onSubmit}
onFinishFailed={
consolePage && onSubmitFail
? ({ errorFields }) =>
onSubmitFail(
Object.fromEntries(
errorFields.map(({ name, errors }) => [
name.join('.'),
errors,
]),
),
)
: onSubmitFail
}
onValuesChange={(_, all) => {
callbacks.current.onValueChange?.(all);
renderValues();
}}
>
{typeof children === 'function' ? (
<FormRenderContent form={form} api={api}>
{children}
</FormRenderContent>
) : (
children
)}
</FormComponent>
</FormContext.Provider>
);
});
function labelProps(label) {
return label &&
typeof label === 'object' &&
!React.isValidElement(label) &&
'text' in label
? {
label: label.text,
required: label.required,
...(label.name ? { htmlFor: label.name } : {}),
}
: { label };
}
// Legacy Form.RadioGroup reports the selected value; standalone RadioGroup reports an event.
const FieldRadioGroup = forwardRef(function FieldRadioGroup(
{ onChange, ...props },
ref,
) {
return (
<Controls.RadioGroup
{...props}
ref={ref}
onChange={(event) => onChange?.(event.target.value, event)}
/>
);
});
export function withField(
Component,
{ valueKey = 'value', onKeyChangeFnName = 'onChange' } = {},
) {
const Field = forwardRef(function Field(
{
field,
label,
noLabel,
initValue,
rules,
validate,
required,
extraText,
helpText,
pure,
trigger,
stopValidateWithError,
validateStatus,
className,
style,
...props
},
ref,
) {
const form = useContext(FormContext);
const normalizedRules =
rules?.map((rule) => {
if (!rule.validator) return rule;
return {
...rule,
validator: (_, value) =>
new Promise((resolve, reject) => {
let settled = false;
const callback = (error) => {
if (settled) return;
settled = true;
error ? reject(new Error(error.message || error)) : resolve();
};
try {
const result = rule.validator(
rule,
value,
callback,
form?.getFieldsValue(true),
);
if (result?.then) result.then(() => callback(), callback);
else if (result === true) callback();
else if (
result === false ||
typeof result === 'string' ||
result instanceof Error
)
callback(result || rule.message || 'Invalid value');
} catch (error) {
callback(error);
}
}),
};
}) || [];
if (validate)
normalizedRules.push({
validator: async (_, value) => {
const error = await validate(value, form?.getFieldsValue(true));
if (error) throw new Error(String(error));
},
});
const fieldLabel = labelProps(label);
const control =
field === undefined && props.children && Component === Controls.Input ? (
props.children
) : (
<Component
{...props}
id={props.id ?? fieldLabel.htmlFor}
ref={ref}
style={style}
/>
);
// Unnamed slots remain controlled by the page; named fields use Ant Form's store.
return (
<AntForm.Item
{...(noLabel
? {}
: {
...fieldLabel,
...(control?.props?.id ? { htmlFor: control.props.id } : {}),
})}
name={field === undefined ? undefined : fieldPath(field)}
initialValue={initValue}
rules={normalizedRules}
required={required || labelProps(label).required}
valuePropName={valueKey}
trigger={onKeyChangeFnName}
validateTrigger={trigger === 'blur' ? 'onBlur' : 'onChange'}
getValueFromEvent={(...args) =>
valueKey === 'checked'
? (args[0]?.target?.checked ?? args[0])
: valueKey === 'fileList'
? args[0]?.fileList
: args[0]
}
extra={extraText}
help={helpText}
validateStatus={
validateStatus === 'default' ? undefined : validateStatus
}
className={className}
noStyle={pure}
>
{control}
</AntForm.Item>
);
});
Field.Option = Component.Option;
Field.OptGroup = Component.OptGroup;
return Field;
}
for (const name of [
'Input',
'TextArea',
'InputNumber',
'Select',
'DatePicker',
'TimePicker',
'RadioGroup',
'CheckboxGroup',
'TagInput',
'TreeSelect',
'AutoComplete',
'Upload',
]) {
const Component =
name === 'CheckboxGroup'
? Checkbox.Group
: name === 'RadioGroup'
? FieldRadioGroup
: Controls[name];
Form[name] = withField(Component);
}
Form.Switch = withField(Controls.Switch, { valueKey: 'checked' });
Form.Checkbox = withField(Checkbox, { valueKey: 'checked' });
Form.Upload = withField(Controls.Upload, { valueKey: 'fileList' });
Form.Slot = function Slot({ label, error, children, ...props }) {
return (
<AntForm.Item
{...props}
{...labelProps(label)}
validateStatus={error?.error ? 'error' : undefined}
help={
error?.error ? (
<span id={error.errorMessageId}>{error.error}</span>
) : undefined
}
>
{children}
</AntForm.Item>
);
};
Form.Section = function Section({ text, extraText, children, ...props }) {
return (
<section {...props}>
<h3 className='ui-form-section'>{text}</h3>
{extraText && <p className='ui-field-help'>{extraText}</p>}
{children}
</section>
);
};
Form.Label = function Label({ required, children, ...props }) {
return (
<label {...props}>
{required && <span className='ui-required'>*</span>}
{children}
</label>
);
};