feat: 参考原型图 ui优化提交 个人端-用户中心 相关的页面

This commit is contained in:
zhanjunhao
2026-11-04 19:59:06 +08:00
parent 472e534fe1
commit e6c41e7587
576 changed files with 18075 additions and 18912 deletions
+321
View File
@@ -0,0 +1,321 @@
/*
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';
const FormContext = createContext(null);
const fieldPath = (field) =>
typeof field === 'string'
? field.replace(/\[(\d+)\]/g, '.$1').split('.')
: field;
export const Form = forwardRef(function Form(
{
initValues,
values,
onSubmit,
onSubmitFail,
onValueChange,
getFormApi,
children,
labelPosition,
labelWidth,
labelAlign,
layout,
allowEmpty,
trigger,
stopValidateWithError,
...props
},
ref,
) {
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) => {
form.setFieldValue(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(),
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}>
<AntForm
{...props}
form={form}
initialValues={initValues}
layout={
layout === 'horizontal' || labelPosition === 'left'
? 'horizontal'
: layout === 'inline'
? 'inline'
: 'vertical'
}
labelCol={labelWidth ? { flex: labelWidth } : undefined}
labelAlign={labelAlign}
onFinish={onSubmit}
onFinishFailed={onSubmitFail}
onValuesChange={(_, all) => {
callbacks.current.onValueChange?.(all);
renderValues();
}}
>
{typeof children === 'function'
? children({
formState: { values: form.getFieldsValue(true) },
formApi: api,
values: form.getFieldsValue(true),
})
: children}
</AntForm>
</FormContext.Provider>
);
});
function labelProps(label) {
return label &&
typeof label === 'object' &&
!React.isValidElement(label) &&
'text' in label
? { label: label.text, required: label.required, 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 control =
field === undefined && props.children && Component === Controls.Input ? (
props.children
) : (
<Component {...props} ref={ref} style={style} />
);
// Unnamed slots remain controlled by the page; named fields use Ant Form's store.
return (
<AntForm.Item
{...(noLabel ? {} : labelProps(label))}
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>
);
};