Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor: migrate forms to @lobehub/ui/base-ui/form (#20317)

Innei6a65c7a4cd46
diff --git a/package.json b/package.json
index 69e01ba2666..5debeee46bd 100644
--- a/package.json
+++ b/package.json
@@ -324,7 +324,7 @@
"@lobehub/icons": "^5.18.0",
"@lobehub/market-sdk": "0.41.0",
"@lobehub/tts": "^5.1.2",
- "@lobehub/ui": "^5.50.2",
+ "@lobehub/ui": "^5.56.0",
"@modelcontextprotocol/sdk": "^1.30.0",
"@neondatabase/serverless": "^1.1.0",
"@next/third-parties": "^16.3.0",
diff --git a/packages/const/src/layoutTokens.ts b/packages/const/src/layoutTokens.ts
index 7e3e40c752b..94c9986e57c 100644
--- a/packages/const/src/layoutTokens.ts
+++ b/packages/const/src/layoutTokens.ts
@@ -1,4 +1,5 @@
-import type { ActionIconProps, FormProps } from '@lobehub/ui';
+import type { ActionIconProps } from '@lobehub/ui';
+import type { FormProps } from '@lobehub/ui/base-ui/form';
export const HEADER_HEIGHT = 64;
export const MOBILE_NABBAR_HEIGHT = 44;
@@ -31,7 +32,7 @@ export const CONVERSATION_KEEP_WIDTH = 420;
export const MARKET_SIDEBAR_WIDTH = 400;
export const FOLDER_WIDTH = 270;
export const MAX_WIDTH = 1024;
-export const FORM_STYLE: FormProps = {
+export const FORM_STYLE: Pick<FormProps, 'itemMinWidth' | 'style'> = {
itemMinWidth: 'max(34%, 240px)',
style: { maxWidth: MAX_WIDTH, width: '100%' },
};
diff --git a/src/business/client/hooks/useTransferAgentsFormItem.ts b/src/business/client/hooks/useTransferAgentsFormItem.ts
index 8838e616f0f..15a08bb076d 100644
--- a/src/business/client/hooks/useTransferAgentsFormItem.ts
+++ b/src/business/client/hooks/useTransferAgentsFormItem.ts
@@ -1,3 +1,3 @@
-import type { FormGroupItemType } from '@lobehub/ui';
+import type { FormFieldProps } from '@lobehub/ui/base-ui/form';
-export const useTransferAgentsFormItem = (): FormGroupItemType['children'] | null => null;
+export const useTransferAgentsFormItem = (): FormFieldProps[] | null => null;
diff --git a/src/components/FeedbackModal/FeedbackContent.tsx b/src/components/FeedbackModal/FeedbackContent.tsx
index 1daa3195c5b..aea330a11a4 100644
--- a/src/components/FeedbackModal/FeedbackContent.tsx
+++ b/src/components/FeedbackModal/FeedbackContent.tsx
@@ -3,7 +3,7 @@
import { BRANDING_EMAIL } from '@lobechat/business-const';
import { Flexbox, Icon } from '@lobehub/ui';
import { Button, Input, toast, Upload, useModalContext } from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form, useForm, useWatch } from '@lobehub/ui/base-ui/form';
import { ImagePlus, Send } from 'lucide-react';
import { memo, useCallback, useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
@@ -29,8 +29,8 @@ const FeedbackContent = memo<FeedbackContentProps>(({ initialValues }) => {
const { t } = useTranslation('common');
const { close } = useModalContext();
- const [form] = Form.useForm<FormValues>();
- const title = Form.useWatch('title', form);
+ const form = useForm<FormValues>({ initialValues: { message: '', title: '', ...initialValues } });
+ const title = useWatch(form, 'title');
const [loading, setLoading] = useState(false);
const [screenshotUrl, setScreenshotUrl] = useState<string | null>(null);
@@ -70,7 +70,9 @@ const FeedbackContent = memo<FeedbackContentProps>(({ initialValues }) => {
const handleSubmit = useCallback(async () => {
try {
- const values = await form.validateFields();
+ const { valid } = await form.validate();
+ if (!valid) return;
+ const values = form.getValues();
setLoading(true);
await lambdaClient.market.submitFeedback.mutate({
@@ -87,7 +89,7 @@ const FeedbackContent = memo<FeedbackContentProps>(({ initialValues }) => {
});
toast.success(t('feedback.success'));
- form.resetFields();
+ form.reset();
setScreenshotUrl(null);
close();
} catch (error: any) {
@@ -99,7 +101,7 @@ const FeedbackContent = memo<FeedbackContentProps>(({ initialValues }) => {
}, [close, form, screenshotUrl, t, userEmail]);
const handleCancel = useCallback(() => {
- form.resetFields();
+ form.reset();
setScreenshotUrl(null);
close();
}, [close, form]);
@@ -124,29 +126,29 @@ const FeedbackContent = memo<FeedbackContentProps>(({ initialValues }) => {
/>
</p>
- <Form form={form} initialValues={initialValues} layout="vertical">
- <Form.Item
+ <Form form={form} gap={0} layout="vertical">
+ <Form.Field
label={t('feedback.fields.title.label')}
name="title"
- rules={[
- { message: t('feedback.fields.title.required'), required: true },
- { max: 200, message: t('feedback.fields.title.maxLength') },
- ]}
+ required={t('feedback.fields.title.required')}
+ validate={(value: string) =>
+ value.length > 200 ? t('feedback.fields.title.maxLength') : undefined
+ }
>
<Input
maxLength={200}
placeholder={t('feedback.fields.title.placeholder')}
suffix={`${title?.length ?? 0} / 200`}
/>
- </Form.Item>
+ </Form.Field>
- <Form.Item
+ <Form.Field
label={t('feedback.fields.message.label')}
name="message"
- rules={[
- { message: t('feedback.fields.message.required'), required: true },
- { max: 5000, message: t('feedback.fields.message.maxLength') },
- ]}
+ required={t('feedback.fields.message.required')}
+ validate={(value: string) =>
+ value.length > 5000 ? t('feedback.fields.message.maxLength') : undefined
+ }
>
<TextArea
showCount
@@ -154,9 +156,9 @@ const FeedbackContent = memo<FeedbackContentProps>(({ initialValues }) => {
placeholder={t('feedback.fields.message.placeholder')}
rows={6}
/>
- </Form.Item>
+ </Form.Field>
- <Form.Item label={t('feedback.fields.screenshot.label')} style={{ marginBottom: 0 }}>
+ <Form.Field label={t('feedback.fields.screenshot.label')} style={{ marginBottom: 0 }}>
<Flexbox gap={8}>
{screenshotUrl ? (
<Flexbox gap={8}>
@@ -182,7 +184,7 @@ const FeedbackContent = memo<FeedbackContentProps>(({ initialValues }) => {
<p style={{ color: 'var(--colorTextSecondary)', fontSize: 12, marginTop: 8 }}>
{t('feedback.fields.screenshot.hint')}
</p>
- </Form.Item>
+ </Form.Field>
</Form>
<Flexbox horizontal gap={8} justify="flex-end">
diff --git a/src/components/FormInput/FormInput.test.tsx b/src/components/FormInput/FormInput.test.tsx
index cc641c31dea..f8e15a034b5 100644
--- a/src/components/FormInput/FormInput.test.tsx
+++ b/src/components/FormInput/FormInput.test.tsx
@@ -30,6 +30,17 @@ describe('FormInput', () => {
expect(onChangeMock).toHaveBeenCalledWith('new value');
});
+ test('失焦时同时触发 onChange 和外部 onBlur', async () => {
+ const onBlurMock = vi.fn();
+ render(<FormInput onBlur={onBlurMock} onChange={onChangeMock} />);
+ const input = screen.getByRole('textbox');
+
+ await user.type(input, 'typed');
+ fireEvent.blur(input);
+ expect(onChangeMock).toHaveBeenCalledWith('typed');
+ expect(onBlurMock).toHaveBeenCalledTimes(1);
+ });
+
test('按下 Enter 触发 onChange', async () => {
render(<FormInput onChange={onChangeMock} />);
const input = screen.getByRole('textbox');
@@ -56,6 +67,15 @@ describe('FormInput', () => {
expect(onChangeMock).toHaveBeenCalledWith('nihao');
});
+ test('初始值为空、之后注入值时同步显示', () => {
+ const { rerender } = render(<FormInput value={undefined} />);
+ const input = screen.getByRole('textbox');
+ expect(input).toHaveValue('');
+
+ rerender(<FormInput value="loaded value" />);
+ expect(input).toHaveValue('loaded value');
+ });
+
test('defaultValue 更新时同步显示新值', async () => {
const { rerender } = render(<FormInput value="old value" />);
diff --git a/src/components/FormInput/FormInput.tsx b/src/components/FormInput/FormInput.tsx
index 6c9039b2af7..1948865a130 100644
--- a/src/components/FormInput/FormInput.tsx
+++ b/src/components/FormInput/FormInput.tsx
@@ -7,7 +7,7 @@ interface FormInputProps extends Omit<Props, 'onChange'> {
onChange?: (value: string) => void;
}
-const FormInput = memo<FormInputProps>(({ onChange, value: defaultValue, ...props }) => {
+const FormInput = memo<FormInputProps>(({ onBlur, onChange, value: defaultValue, ...props }) => {
const ref = useRef<HTMLInputElement>(null);
const { compositionProps, isComposingRef } = useIMECompositionEvent();
@@ -20,8 +20,9 @@ const FormInput = memo<FormInputProps>(({ onChange, value: defaultValue, ...prop
return (
<Input
ref={ref}
- onBlur={() => {
+ onBlur={(e) => {
onChange?.(value);
+ onBlur?.(e);
}}
onChange={(e) => {
setValue(e.target.value);
@@ -32,7 +33,7 @@ const FormInput = memo<FormInputProps>(({ onChange, value: defaultValue, ...prop
onChange?.(value);
}}
{...props}
- value={value}
+ value={value ?? ''}
/>
);
});
diff --git a/src/components/FormInput/FormPassword.tsx b/src/components/FormInput/FormPassword.tsx
index d5d6ecfdc2d..7a5f241540a 100644
--- a/src/components/FormInput/FormPassword.tsx
+++ b/src/components/FormInput/FormPassword.tsx
@@ -7,38 +7,41 @@ interface FormPasswordProps extends Omit<Props, 'onChange'> {
onChange?: (value: string) => void;
}
-const FormPassword = memo<FormPasswordProps>(({ onChange, value: defaultValue, ...props }) => {
- const ref = useRef<HTMLInputElement>(null);
- const { compositionProps, isComposingRef } = useIMECompositionEvent();
-
- const [value, setValue] = useState(defaultValue as string);
-
- useEffect(() => {
- setValue(defaultValue as string);
- }, [defaultValue]);
-
- return (
- <InputPassword
- ref={ref}
- onBlur={() => {
- onChange?.(value);
- }}
- onChange={(e) => {
- setValue(e.target.value);
- }}
- {...compositionProps}
- onPressEnter={() => {
- if (isComposingRef.current) return;
- onChange?.(value);
- }}
- // Secret field (API keys, tokens): suppress autofill of the saved login
- // password. Overridable by callers via {...props}.
- autoComplete="new-password"
- {...props}
- value={value}
- />
- );
-});
+const FormPassword = memo<FormPasswordProps>(
+ ({ onBlur, onChange, value: defaultValue, ...props }) => {
+ const ref = useRef<HTMLInputElement>(null);
+ const { compositionProps, isComposingRef } = useIMECompositionEvent();
+
+ const [value, setValue] = useState(defaultValue as string);
+
+ useEffect(() => {
+ setValue(defaultValue as string);
+ }, [defaultValue]);
+
+ return (
+ <InputPassword
+ ref={ref}
+ onBlur={(e) => {
+ onChange?.(value);
+ onBlur?.(e);
+ }}
+ onChange={(e) => {
+ setValue(e.target.value);
+ }}
+ {...compositionProps}
+ onPressEnter={() => {
+ if (isComposingRef.current) return;
+ onChange?.(value);
+ }}
+ // Secret field (API keys, tokens): suppress autofill of the saved login
+ // password. Overridable by callers via {...props}.
+ autoComplete="new-password"
+ {...props}
+ value={value ?? ''}
+ />
+ );
+ },
+);
FormPassword.displayName = 'FormPassword';
diff --git a/src/components/FormInput/FormSliderWithInput.tsx b/src/components/FormInput/FormSliderWithInput.tsx
index cc8eddb5c51..6f519314334 100644
--- a/src/components/FormInput/FormSliderWithInput.tsx
+++ b/src/components/FormInput/FormSliderWithInput.tsx
@@ -11,7 +11,7 @@ interface FormSliderWithInputProps extends Omit<SliderWithInputProps, 'onChange'
* Only triggers onChange on blur to prevent excessive updates during user interaction.
*/
const FormSliderWithInput = memo<FormSliderWithInputProps>(
- ({ onChange, value: defaultValue, ...props }) => {
+ ({ onBlur, onChange, value: defaultValue, ...props }) => {
const [value, setValue] = useState(defaultValue ?? 0);
useEffect(() => {
@@ -20,8 +20,9 @@ const FormSliderWithInput = memo<FormSliderWithInputProps>(
return (
<SliderWithInput
- onBlur={() => {
+ onBlur={(e) => {
onChange?.(value);
+ onBlur?.(e);
}}
onChange={(newValue) => {
if (typeof newValue === 'number') {
diff --git a/src/components/Skeleton/Settings/Profile.tsx b/src/components/Skeleton/Settings/Profile.tsx
index d9a01281ef8..97cc7b82087 100644
--- a/src/components/Skeleton/Settings/Profile.tsx
+++ b/src/components/Skeleton/Settings/Profile.tsx
@@ -1,6 +1,7 @@
'use client';
-import { Flexbox, FormGroup } from '@lobehub/ui';
+import { Flexbox } from '@lobehub/ui';
+import { Form } from '@lobehub/ui/base-ui/form';
import { createStaticStyles, cssVar } from 'antd-style';
import { type ReactNode } from 'react';
@@ -98,11 +99,10 @@ const SettingsProfileSkeleton = () => {
const email = useUserStore(userProfileSelectors.email);
return (
- <FormGroup
+ <Form.Group
aria-busy
collapsible={false}
data-testid={'settings-profile-skeleton'}
- gap={16}
title={<SkeletonBar height={18} width={80} />}
variant={'filled'}
>
@@ -130,7 +130,7 @@ const SettingsProfileSkeleton = () => {
</>
)}
</Flexbox>
- </FormGroup>
+ </Form.Group>
);
};
diff --git a/src/components/Skeleton/Settings/Section.tsx b/src/components/Skeleton/Settings/Section.tsx
index f0ca12d1b9a..35841961094 100644
--- a/src/components/Skeleton/Settings/Section.tsx
+++ b/src/components/Skeleton/Settings/Section.tsx
@@ -1,6 +1,7 @@
'use client';
-import { Flexbox, FormGroup } from '@lobehub/ui';
+import { Flexbox } from '@lobehub/ui';
+import { Form } from '@lobehub/ui/base-ui/form';
import { createStaticStyles, cssVar } from 'antd-style';
import SkeletonBar from '../Bar';
@@ -33,7 +34,7 @@ const Row = ({ index }: { index: number }) => (
);
const Group = ({ rows, titleWidth }: { rows: number; titleWidth: number }) => (
- <FormGroup
+ <Form.Group
collapsible={false}
title={<SkeletonBar height={18} width={titleWidth} />}
variant={'filled'}
@@ -46,7 +47,7 @@ const Group = ({ rows, titleWidth }: { rows: number; titleWidth: number }) => (
</Flexbox>
))}
</Flexbox>
- </FormGroup>
+ </Form.Group>
);
const SettingsSectionSkeleton = () => (
diff --git a/src/components/Skeleton/Surface.tsx b/src/components/Skeleton/Surface.tsx
index 1f7968b28e6..54f1626494a 100644
--- a/src/components/Skeleton/Surface.tsx
+++ b/src/components/Skeleton/Surface.tsx
@@ -1,6 +1,7 @@
'use client';
-import { Flexbox, FormGroup, Grid } from '@lobehub/ui';
+import { Flexbox, Grid } from '@lobehub/ui';
+import { Form } from '@lobehub/ui/base-ui/form';
import { createStaticStyles, cssVar } from 'antd-style';
import type { ComponentType } from 'react';
@@ -67,7 +68,7 @@ const ListSkeleton = () => (
const FormSkeleton = () => (
<Flexbox align={'center'} padding={24}>
- <FormGroup
+ <Form.Group
collapsible={false}
style={{ width: 'min(800px, 100%)' }}
title={<SkeletonBar height={18} width={112} />}
@@ -93,7 +94,7 @@ const FormSkeleton = () => (
</Flexbox>
))}
</Flexbox>
- </FormGroup>
+ </Form.Group>
</Flexbox>
);
diff --git a/src/components/TextArea/index.tsx b/src/components/TextArea/index.tsx
index 0c52370c119..a2437c9677d 100644
--- a/src/components/TextArea/index.tsx
+++ b/src/components/TextArea/index.tsx
@@ -7,7 +7,7 @@ interface TextAreaProps extends Omit<Props, 'onChange'> {
onChange?: (value: string) => void;
}
-const TextArea = memo<TextAreaProps>(({ onChange, value: defaultValue, ...props }) => {
+const TextArea = memo<TextAreaProps>(({ onBlur, onChange, value: defaultValue, ...props }) => {
const ref = useRef<HTMLTextAreaElement>(null);
const { compositionProps, isComposingRef } = useIMECompositionEvent();
@@ -16,8 +16,9 @@ const TextArea = memo<TextAreaProps>(({ onChange, value: defaultValue, ...props
return (
<LobeTextArea
ref={ref}
- onBlur={() => {
+ onBlur={(e) => {
onChange?.(value);
+ onBlur?.(e);
}}
onChange={(e) => {
setValue(e.target.value);
@@ -28,7 +29,7 @@ const TextArea = memo<TextAreaProps>(({ onChange, value: defaultValue, ...props
onChange?.(value);
}}
{...props}
- value={value}
+ value={value ?? ''}
/>
);
});
diff --git a/src/features/AgentPermission/PermissionForm.tsx b/src/features/AgentPermission/PermissionForm.tsx
index f59f9a682f0..baa3ebb7754 100644
--- a/src/features/AgentPermission/PermissionForm.tsx
+++ b/src/features/AgentPermission/PermissionForm.tsx
@@ -1,9 +1,9 @@
'use client';
import type { AgentModelSelectionPolicy, AgentTopicSharePolicy } from '@lobechat/types';
-import type { FormGroupItemType } from '@lobehub/ui';
-import { Empty, Form, Icon } from '@lobehub/ui';
+import { Empty, Icon } from '@lobehub/ui';
import { Alert } from '@lobehub/ui/base-ui';
+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import { createStaticStyles } from 'antd-style';
import { Bot, InfoIcon, LockIcon, MonitorSmartphone, Share2, UsersIcon } from 'lucide-react';
import { memo, useMemo } from 'react';
@@ -54,6 +54,7 @@ const PermissionForm = memo<PermissionFormProps>(({ agentId }) => {
setTopicSharePolicy,
topicSharePolicy,
} = useAgentPermission(agentId);
+ const form = useForm();
const labelKeys = getSelectionPolicyLabelKeys(isPrivate);
@@ -144,7 +145,7 @@ const PermissionForm = memo<PermissionFormProps>(({ agentId }) => {
);
}
- const memberGroup: FormGroupItemType | undefined = !accessError
+ const memberGroup: FormGroupItem | undefined = !accessError
? {
children: [
{
@@ -201,7 +202,7 @@ const PermissionForm = memo<PermissionFormProps>(({ agentId }) => {
}
: undefined;
- const configGroup: FormGroupItemType = {
+ const configGroup: FormGroupItem = {
children: [
{
avatar: (
@@ -265,6 +266,7 @@ const PermissionForm = memo<PermissionFormProps>(({ agentId }) => {
) : null}
<Form
collapsible={false}
+ form={form}
items={[...(memberGroup ? [memberGroup] : []), configGroup]}
itemsType={'group'}
variant={'filled'}
diff --git a/src/features/AgentSetting/AgentChannel/feishu/UserIdExtras.tsx b/src/features/AgentSetting/AgentChannel/feishu/UserIdExtras.tsx
index 814372dde73..7c777de6bea 100644
--- a/src/features/AgentSetting/AgentChannel/feishu/UserIdExtras.tsx
+++ b/src/features/AgentSetting/AgentChannel/feishu/UserIdExtras.tsx
@@ -2,7 +2,7 @@
import { isMaskedBotCredential } from '@lobechat/const';
import { Button, toast } from '@lobehub/ui/base-ui';
-import { Form as AntdForm } from 'antd';
+import { useFormInstance, useWatch } from '@lobehub/ui/base-ui/form';
import { Download } from 'lucide-react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -43,9 +43,9 @@ export const FeishuUserIdExtras = ({
const { t: _t } = useTranslation('agent');
const t = _t as (key: string) => string;
- const form = AntdForm.useFormInstance();
- const applicationId = AntdForm.useWatch('applicationId', form) as string | undefined;
- const appSecret = AntdForm.useWatch(['credentials', 'appSecret'], form) as string | undefined;
+ const form = useFormInstance();
+ const applicationId = useWatch(form, 'applicationId') as string | undefined;
+ const appSecret = useWatch(form, 'credentials.appSecret') as string | undefined;
const [loading, setLoading] = useState(false);
const requestRef = useRef(0);
@@ -78,13 +78,17 @@ export const FeishuUserIdExtras = ({
platform: platformId === 'lark' ? 'lark' : 'feishu',
},
fetchOwner: feishuFetchOwnerId,
- form,
+ form: {
+ getFieldValue: (name) => form.getValue(Array.isArray(name) ? name.join('.') : name),
+ isFieldTouched: (name) => form.isTouched(name.join('.')),
+ setFieldValue: (name, value) => form.setValue(name.join('.'), value),
+ },
isCurrent: () => request === requestRef.current,
});
if (!owner) return;
// Mirror the field's own validation/dirty handling: `setFieldValue`
// neither validates nor notifies, so do both explicitly.
- form.validateFields([['settings', 'userId']]).catch(() => undefined);
+ void form.validate(['settings.userId']);
onFilled?.();
const base = t(
mode === 'auto'
@@ -107,11 +111,11 @@ export const FeishuUserIdExtras = ({
);
// Whether the field currently holds a value, which decides whether the
- // retry button is worth showing at all. antd hydrates the form after mount,
+ // retry button is worth showing at all. The form may hydrate after mount,
// so an `undefined` watch means "not loaded yet" rather than "empty" — fall
// back to the saved value during that window so an already-configured bot
// never flashes a button it doesn't need.
- const watchedUserId = AntdForm.useWatch(['settings', 'userId'], form) as string | undefined;
+ const watchedUserId = useWatch(form, 'settings.userId') as string | undefined;
const [formHydrated, setFormHydrated] = useState(false);
useEffect(() => {
if (watchedUserId !== undefined) setFormHydrated(true);
diff --git a/src/features/AgentSetting/AgentOpening/index.tsx b/src/features/AgentSetting/AgentOpening/index.tsx
index ff8a52b5fea..6af192eaded 100644
--- a/src/features/AgentSetting/AgentOpening/index.tsx
+++ b/src/features/AgentSetting/AgentOpening/index.tsx
@@ -1,24 +1,19 @@
'use client';
-import { Form } from '@lobehub/ui';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import OpeningMessage from './OpeningMessage';
import OpeningQuestions from './OpeningQuestions';
-const wrapperCol = {
- style: {
- maxWidth: '100%',
- width: '100%',
- },
-};
-
const AgentOpening = memo(() => {
const { t } = useTranslation('setting');
+ const form = useForm();
return (
<Form
+ form={form}
itemsType={'flat'}
variant={'borderless'}
items={[
@@ -27,14 +22,12 @@ const AgentOpening = memo(() => {
desc: t('settingOpening.openingMessage.desc'),
label: t('settingOpening.openingMessage.title'),
layout: 'vertical',
- wrapperCol,
},
{
children: <OpeningQuestions />,
desc: t('settingOpening.openingQuestions.desc'),
label: t('settingOpening.openingQuestions.title'),
layout: 'vertical',
- wrapperCol,
},
]}
/>
diff --git a/src/features/AgentSetting/AgentSelfIteration/index.tsx b/src/features/AgentSetting/AgentSelfIteration/index.tsx
index 59faeb43934..4cb568d0fcf 100644
--- a/src/features/AgentSetting/AgentSelfIteration/index.tsx
+++ b/src/features/AgentSetting/AgentSelfIteration/index.tsx
@@ -1,7 +1,7 @@
'use client';
-import { Form } from '@lobehub/ui';
import { Switch } from '@lobehub/ui/base-ui';
+import { Form, type FormFieldProps, useForm } from '@lobehub/ui/base-ui/form';
import isEqual from 'fast-deep-equal';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,48 +9,48 @@ import { useTranslation } from 'react-i18next';
import { FORM_STYLE } from '@/const/layoutTokens';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
+import { type LobeAgentChatConfig } from '@/types/agent';
import { selectors, useStore } from '../store';
const AgentSelfIteration = memo(() => {
const { t } = useTranslation('setting');
- const [form] = Form.useForm();
const [disabled, updateConfig] = useStore((s) => [s.disabled, s.setChatConfig]);
const config = useStore(selectors.currentChatConfig, isEqual);
const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
+ const form = useForm<LobeAgentChatConfig>({
+ initialValues: config,
+ onSubmit: (values) => {
+ if (disabled) return;
- const selfIterationItem = isInbox
+ updateConfig(values);
+ },
+ });
+
+ const selfIterationItem: FormFieldProps<LobeAgentChatConfig> = isInbox
? {
children: <Switch checked disabled />,
desc: t('settingSelfIteration.enabled.managedDesc'),
label: t('settingSelfIteration.enabled.title'),
- layout: 'horizontal' as const,
+ layout: 'horizontal',
minWidth: undefined,
}
: {
- children: <Switch />,
+ children: <Switch disabled={disabled} />,
desc: t('settingSelfIteration.enabled.desc'),
label: t('settingSelfIteration.enabled.title'),
- layout: 'horizontal' as const,
+ layout: 'horizontal',
minWidth: undefined,
- name: ['selfIteration', 'enabled'],
- valuePropName: 'checked',
+ name: 'selfIteration.enabled',
};
return (
<Form
- disabled={disabled}
footer={isInbox ? undefined : <Form.SubmitFooter />}
form={form}
- initialValues={config}
items={[selfIterationItem]}
itemsType={'flat'}
variant={'borderless'}
- onFinish={(values) => {
- if (disabled) return;
-
- updateConfig(values);
- }}
{...FORM_STYLE}
/>
);
diff --git a/src/features/AgentSkillEdit/SkillEditForm.tsx b/src/features/AgentSkillEdit/SkillEditForm.tsx
index d8adb853786..411570763d9 100644
--- a/src/features/AgentSkillEdit/SkillEditForm.tsx
+++ b/src/features/AgentSkillEdit/SkillEditForm.tsx
@@ -10,9 +10,8 @@ import {
ReactTablePlugin,
} from '@lobehub/editor';
import { Editor, useEditor } from '@lobehub/editor/react';
-import { Form, type FormItemProps } from '@lobehub/ui';
import { Input, TextArea } from '@lobehub/ui/base-ui';
-import { Form as AForm, type FormInstance } from 'antd';
+import { Form, type FormFieldProps, type FormInstance } from '@lobehub/ui/base-ui/form';
import { createStaticStyles, cssVar } from 'antd-style';
import { memo, useCallback, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
@@ -50,115 +49,106 @@ export interface SkillEditFormValues {
interface SkillEditFormProps {
disabled?: boolean;
- form: FormInstance;
+ form: FormInstance<SkillEditFormValues>;
initialValues: SkillEditFormValues;
name?: string;
- onSubmit: (values: SkillEditFormValues) => void;
}
-const SkillEditForm = memo<SkillEditFormProps>(
- ({ name, disabled, form, initialValues, onSubmit }) => {
- const { t } = useTranslation('setting');
- const editor = useEditor();
- const currentValueRef = useRef(initialValues.content);
+const SkillEditForm = memo<SkillEditFormProps>(({ name, disabled, form, initialValues }) => {
+ const { t } = useTranslation('setting');
+ const editor = useEditor();
+ const currentValueRef = useRef(initialValues.content);
- useEffect(() => {
- form.setFieldsValue(initialValues);
- }, [initialValues]);
+ useEffect(() => {
+ form.setValues(initialValues);
+ }, [form, initialValues]);
- useEffect(() => {
- currentValueRef.current = initialValues.content;
- }, [initialValues.content]);
+ useEffect(() => {
+ currentValueRef.current = initialValues.content;
+ }, [initialValues.content]);
- useEffect(() => {
- if (!editor) return;
- try {
- setTimeout(() => {
- if (initialValues.content) {
- editor.setDocument('markdown', initialValues.content);
- }
- }, 100);
- } catch {
- setTimeout(() => {
+ useEffect(() => {
+ if (!editor) return;
+ try {
+ setTimeout(() => {
+ if (initialValues.content) {
editor.setDocument('markdown', initialValues.content);
- }, 100);
- }
- }, [editor, initialValues.content]);
-
- const handleContentChange = useCallback(
- (e: any) => {
- if (disabled) return;
- const nextContent = (e.getDocument('markdown') as unknown as string) || '';
- if (nextContent !== currentValueRef.current) {
- currentValueRef.current = nextContent;
- form.setFieldValue('content', nextContent);
}
- },
- [disabled, form],
- );
+ }, 100);
+ } catch {
+ setTimeout(() => {
+ editor.setDocument('markdown', initialValues.content);
+ }, 100);
+ }
+ }, [editor, initialValues.content]);
- const items: FormItemProps[] = [
- {
- children: <Input disabled readOnly value={name} />,
- desc: t('agentSkillEdit.nameDesc'),
- label: t('settingAgent.name.title'),
- },
- {
- children: (
- <TextArea
- autoSize={{ maxRows: 4, minRows: 2 }}
- disabled={disabled}
- placeholder={t('agentSkillModal.descriptionPlaceholder')}
- />
- ),
- desc: t('agentSkillEdit.descriptionDesc'),
- label: t('agentSkillModal.description'),
- name: 'description',
- },
- {
- children: (
- <div
- className={styles.editorWrapper}
- style={{ pointerEvents: disabled ? 'none' : undefined }}
- >
- <Editor
- content={''}
- editor={editor}
- lineEmptyPlaceholder={t('agentSkillEdit.instructionsPlaceholder')}
- placeholder={t('agentSkillEdit.instructionsPlaceholder')}
- plugins={PLUGINS}
- style={{ paddingBottom: 48 }}
- type={'text'}
- variant={'chat'}
- onTextChange={handleContentChange}
- />
- </div>
- ),
- desc: t('agentSkillEdit.instructionsDesc'),
- label: t('agentSkillEdit.instructions'),
- },
- ];
+ const handleContentChange = useCallback(
+ (e: any) => {
+ if (disabled) return;
+ const nextContent = (e.getDocument('markdown') as unknown as string) || '';
+ if (nextContent !== currentValueRef.current) {
+ currentValueRef.current = nextContent;
+ form.setValue('content', nextContent);
+ }
+ },
+ [disabled, form],
+ );
- return (
- <div className={styles.wrapper}>
- <Form
- form={form}
- gap={0}
- initialValues={initialValues}
- items={items}
- itemsType={'flat'}
- layout={'vertical'}
- variant={'borderless'}
- onFinish={onSubmit}
+ const items: FormFieldProps<SkillEditFormValues>[] = [
+ {
+ children: <Input disabled readOnly value={name} />,
+ desc: t('agentSkillEdit.nameDesc'),
+ label: t('settingAgent.name.title'),
+ },
+ {
+ children: (
+ <TextArea
+ autoSize={{ maxRows: 4, minRows: 2 }}
+ disabled={disabled}
+ placeholder={t('agentSkillModal.descriptionPlaceholder')}
+ />
+ ),
+ desc: t('agentSkillEdit.descriptionDesc'),
+ label: t('agentSkillModal.description'),
+ name: 'description',
+ },
+ {
+ children: (
+ <div
+ className={styles.editorWrapper}
+ style={{ pointerEvents: disabled ? 'none' : undefined }}
>
- <AForm.Item hidden name="content">
- <Input type="hidden" />
- </AForm.Item>
- </Form>
- </div>
- );
- },
-);
+ <Editor
+ content={''}
+ editor={editor}
+ lineEmptyPlaceholder={t('agentSkillEdit.instructionsPlaceholder')}
+ placeholder={t('agentSkillEdit.instructionsPlaceholder')}
+ plugins={PLUGINS}
+ style={{ paddingBottom: 48 }}
+ type={'text'}
+ variant={'chat'}
+ onTextChange={handleContentChange}
+ />
+ </div>
+ ),
+ desc: t('agentSkillEdit.instructionsDesc'),
+ label: t('agentSkillEdit.instructions'),
+ },
+ ];
+
+ return (
+ <div className={styles.wrapper}>
+ <Form
+ form={form}
+ gap={0}
+ items={items}
+ itemsType={'flat'}
+ layout={'vertical'}
+ variant={'borderless'}
+ />
+ </div>
+ );
+});
SkillEditForm.displayName = 'SkillEditForm';
diff --git a/src/features/AgentSkillEdit/index.tsx b/src/features/AgentSkillEdit/index.tsx
index 779c892ff23..455813f4085 100644
--- a/src/features/AgentSkillEdit/index.tsx
+++ b/src/features/AgentSkillEdit/index.tsx
@@ -5,7 +5,7 @@ import { TITLE_BAR_HEIGHT } from '@lobechat/desktop-bridge';
import { type SkillResourceTreeNode } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
import { Alert, Button, confirmModal, Drawer, toast } from '@lobehub/ui/base-ui';
-import { Form as AForm } from 'antd';
+import { useForm } from '@lobehub/ui/base-ui/form';
import { createStaticStyles } from 'antd-style';
import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -67,7 +67,6 @@ const AgentSkillEdit = memo<AgentSkillEditProps>(({ skillId, open, onClose }) =>
const [selectedFile, setSelectedFile] = useState('SKILL.md');
const [saving, setSaving] = useState(false);
- const [form] = AForm.useForm();
const { data, isLoading } = useToolStore((s) => s.useFetchAgentSkillDetail)(
open ? skillId : undefined,
@@ -103,6 +102,8 @@ const AgentSkillEdit = memo<AgentSkillEditProps>(({ skillId, open, onClose }) =>
}
};
+ const form = useForm<SkillEditFormValues>({ initialValues, onSubmit: handleSubmit });
+
const handleDelete = async () => {
if (!canEdit) return;
await deleteAgentSkill(skillId);
@@ -189,7 +190,6 @@ const AgentSkillEdit = memo<AgentSkillEditProps>(({ skillId, open, onClose }) =>
form={form}
initialValues={initialValues}
name={skillDetail?.name}
- onSubmit={handleSubmit}
/>
</div>
{selectedFile !== 'SKILL.md' && (
diff --git a/src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsx b/src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsx
index 759679debe8..269115f7474 100644
--- a/src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsx
+++ b/src/features/AgentTasks/AgentTaskList/TasksGroupConfig.tsx
@@ -1,6 +1,6 @@
-import { type FormItemProps } from '@lobehub/ui';
-import { Flexbox, Form, Icon, Popover } from '@lobehub/ui';
+import { Flexbox, Icon, Popover } from '@lobehub/ui';
import { ActionIcon, Select, Switch, Tabs } from '@lobehub/ui/base-ui';
+import { Form, type FormFieldProps, useForm } from '@lobehub/ui/base-ui/form';
import { createStaticStyles } from 'antd-style';
import {
ArrowDownWideNarrow,
@@ -36,7 +36,8 @@ interface TasksHeaderProps {
const styles = createStaticStyles(({ css, cssVar }) => {
return {
form: css`
- label {
+ label,
+ label * {
font-size: 13px !important;
color: ${cssVar.colorTextSecondary} !important;
}
@@ -50,6 +51,7 @@ const TasksGroupConfig = memo<TasksHeaderProps>(({ options, pinnedOptions, setOp
const { t } = useTranslation('chat');
const viewMode = useGlobalStore(systemStatusSelectors.taskListViewMode);
const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
+ const form = useForm();
const groupingOptions = useMemo<Array<{ label: string; value: TaskGroupBy }>>(
() => [
{ label: t('taskList.groupBy.none'), value: 'none' },
@@ -102,7 +104,7 @@ const TasksGroupConfig = memo<TasksHeaderProps>(({ options, pinnedOptions, setOp
/>
),
label: viewMode === 'kanban' ? t('taskList.form.columns') : t('taskList.form.grouping'),
- } satisfies FormItemProps;
+ } satisfies FormFieldProps;
const showCompletedFormItem = {
children: (
@@ -116,9 +118,9 @@ const TasksGroupConfig = memo<TasksHeaderProps>(({ options, pinnedOptions, setOp
),
minWidth: undefined,
label: t('taskList.form.showCompleted'),
- } satisfies FormItemProps;
+ } satisfies FormFieldProps;
- const formItems: FormItemProps[] = [
+ const formItems: FormFieldProps[] = [
groupingFormItem,
...(isSubGroupingEnabled
? [
@@ -135,7 +137,7 @@ const TasksGroupConfig = memo<TasksHeaderProps>(({ options, pinnedOptions, setOp
/>
),
label: t('taskList.form.subGrouping'),
- } satisfies FormItemProps,
+ } satisfies FormFieldProps,
]
: []),
...(isPinned('ordering')
@@ -166,7 +168,7 @@ const TasksGroupConfig = memo<TasksHeaderProps>(({ options, pinnedOptions, setOp
</Flexbox>
),
label: t('taskList.form.ordering'),
- } satisfies FormItemProps,
+ } satisfies FormFieldProps,
]),
{
children: (
@@ -197,7 +199,7 @@ const TasksGroupConfig = memo<TasksHeaderProps>(({ options, pinnedOptions, setOp
),
minWidth: undefined,
label: t('taskList.form.showSubTasks'),
- } satisfies FormItemProps,
+ } satisfies FormFieldProps,
]),
// Only meaningful once sub-tasks are on the list — otherwise the toggle
// would sit there controlling nothing.
@@ -215,7 +217,7 @@ const TasksGroupConfig = memo<TasksHeaderProps>(({ options, pinnedOptions, setOp
),
minWidth: undefined,
label: t('taskList.form.nestedSubTasks'),
- } satisfies FormItemProps,
+ } satisfies FormFieldProps,
]
: []),
];
@@ -243,12 +245,12 @@ const TasksGroupConfig = memo<TasksHeaderProps>(({ options, pinnedOptions, setOp
/>
<Form
className={styles.form}
+ form={form}
items={viewMode === 'kanban' ? boardFormItems : formItems}
itemsType={'flat'}
- size={'small'}
variant={'borderless'}
styles={{
- item: { padding: 0 },
+ item: { paddingBlock: 4, paddingInline: 0 },
}}
/>
</Flexbox>
diff --git a/src/features/AgentViewAll/ListConfig.tsx b/src/features/AgentViewAll/ListConfig.tsx
index 4c3e9fb68e5..2ff58934b5f 100644
--- a/src/features/AgentViewAll/ListConfig.tsx
+++ b/src/features/AgentViewAll/ListConfig.tsx
@@ -1,8 +1,8 @@
'use client';
-import { type FormItemProps } from '@lobehub/ui';
-import { Flexbox, Form, Icon, Popover } from '@lobehub/ui';
+import { Flexbox, Icon, Popover } from '@lobehub/ui';
import { ActionIcon, Select, Switch, Tabs } from '@lobehub/ui/base-ui';
+import { Form, type FormFieldProps, useForm } from '@lobehub/ui/base-ui/form';
import { createStaticStyles } from 'antd-style';
import {
ArrowDownWideNarrow,
@@ -32,7 +32,8 @@ interface ListConfigProps {
const styles = createStaticStyles(({ css, cssVar }) => {
return {
form: css`
- label {
+ label,
+ label * {
font-size: 13px !important;
color: ${cssVar.colorTextSecondary} !important;
}
@@ -43,6 +44,7 @@ const styles = createStaticStyles(({ css, cssVar }) => {
const ListConfig = memo<ListConfigProps>(
({ options, setOptions, setViewMode, showAuthor, viewMode }) => {
const [open, setOpen] = useState(false);
+ const form = useForm();
const { t } = useTranslation('common');
const groupingOptions = useMemo<Array<{ label: string; value: AgentGroupBy }>>(
@@ -66,7 +68,7 @@ const ListConfig = memo<ListConfigProps>(
[showAuthor, t],
);
- const formItems: FormItemProps[] = [
+ const formItems: FormFieldProps[] = [
{
children: (
<Select
@@ -138,12 +140,12 @@ const ListConfig = memo<ListConfigProps>(
/>
<Form
className={styles.form}
+ form={form}
items={formItems}
itemsType={'flat'}
- size={'small'}
variant={'borderless'}
styles={{
- item: { padding: 0 },
+ item: { paddingBlock: 4, paddingInline: 0 },
}}
/>
</Flexbox>
diff --git a/src/features/Auth/ResetPassword/ResetPasswordContent.tsx b/src/features/Auth/ResetPassword/ResetPasswordContent.tsx
index a733f4c4ef8..bb5173785b2 100644
--- a/src/features/Auth/ResetPassword/ResetPasswordContent.tsx
+++ b/src/features/Auth/ResetPassword/ResetPasswordContent.tsx
@@ -1,6 +1,6 @@
import { Block, Icon } from '@lobehub/ui';
import { Button, InputPassword, Text } from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form } from '@lobehub/ui/base-ui/form';
import { Lock } from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -18,7 +18,7 @@ export const ResetPasswordContent = ({
onSuccessRedirect,
}: ResetPasswordContentProps) => {
const { t } = useTranslation('auth');
- const { form, handleResetPassword, loading } = useResetPassword({
+ const { form, loading } = useResetPassword({
email,
onSuccessRedirect,
token,
@@ -35,14 +35,15 @@ export const ResetPasswordContent = ({
}
return (
- <Form form={form} layout="vertical" onFinish={handleResetPassword}>
- <Form.Item
+ <Form form={form} gap={0} layout="vertical">
+ <Form.Field
name="newPassword"
- rules={[
- { message: t('betterAuth.errors.passwordRequired'), required: true },
- { message: t('betterAuth.errors.passwordMinLength'), min: 8 },
- { max: 64, message: t('betterAuth.errors.passwordMaxLength') },
- ]}
+ style={{ gap: 0, paddingBlock: '0 24px' }}
+ validate={(value: string) => {
+ if (!value) return t('betterAuth.errors.passwordRequired');
+ if (value.length < 8) return t('betterAuth.errors.passwordMinLength');
+ if (value.length > 64) return t('betterAuth.errors.passwordMaxLength');
+ }}
>
<InputPassword
autoComplete="new-password"
@@ -57,19 +58,15 @@ export const ResetPasswordContent = ({
/>
}
/>
- </Form.Item>
- <Form.Item
- dependencies={['newPassword']}
+ </Form.Field>
+ <Form.Field
+ deps={['newPassword']}
name="confirmPassword"
- rules={[
- { message: t('betterAuth.resetPassword.confirmPasswordRequired'), required: true },
- ({ getFieldValue }) => ({
- validator(_, value) {
- if (!value || getFieldValue('newPassword') === value) return Promise.resolve();
- return Promise.reject(new Error(t('betterAuth.resetPassword.passwordMismatch')));
- },
- }),
- ]}
+ style={{ gap: 0, paddingBlock: '0 24px' }}
+ validate={(value: string, values: { newPassword: string }) => {
+ if (!value) return t('betterAuth.resetPassword.confirmPasswordRequired');
+ if (values.newPassword !== value) return t('betterAuth.resetPassword.passwordMismatch');
+ }}
>
<InputPassword
autoComplete="new-password"
@@ -84,12 +81,10 @@ export const ResetPasswordContent = ({
/>
}
/>
- </Form.Item>
- <Form.Item style={{ marginBottom: 0 }}>
- <Button block htmlType="submit" loading={loading} size="large" type="primary">
- {t('betterAuth.resetPassword.submit')}
- </Button>
- </Form.Item>
+ </Form.Field>
+ <Button block htmlType="submit" loading={loading} size="large" type="primary">
+ {t('betterAuth.resetPassword.submit')}
+ </Button>
</Form>
);
};
diff --git a/src/features/Auth/ResetPassword/useResetPassword.ts b/src/features/Auth/ResetPassword/useResetPassword.ts
index d430d0627a2..5b20c717c58 100644
--- a/src/features/Auth/ResetPassword/useResetPassword.ts
+++ b/src/features/Auth/ResetPassword/useResetPassword.ts
@@ -1,5 +1,5 @@
import { toast } from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { useForm } from '@lobehub/ui/base-ui/form';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -18,7 +18,6 @@ interface UseResetPasswordParams {
export const useResetPassword = ({ email, token, onSuccessRedirect }: UseResetPasswordParams) => {
const { t } = useTranslation('auth');
- const [form] = Form.useForm<ResetPasswordFormValues>();
const [loading, setLoading] = useState(false);
const handleResetPassword = async (values: ResetPasswordFormValues) => {
@@ -45,9 +44,13 @@ export const useResetPassword = ({ email, token, onSuccessRedirect }: UseResetPa
}
};
+ const form = useForm<ResetPasswordFormValues>({
+ initialValues: { confirmPassword: '', newPassword: '' },
+ onSubmit: handleResetPassword,
+ });
+
return {
form,
- handleResetPassword,
loading,
};
};
diff --git a/src/features/Auth/SignIn/SignInEmailStep.tsx b/src/features/Auth/SignIn/SignInEmailStep.tsx
index fb9980cc75f..f9cf551a8d8 100644
--- a/src/features/Auth/SignIn/SignInEmailStep.tsx
+++ b/src/features/Auth/SignIn/SignInEmailStep.tsx
@@ -1,8 +1,7 @@
import { BRANDING_NAME } from '@lobechat/business-const';
import { Flexbox, Icon } from '@lobehub/ui';
import { Alert, Badge, Button, Divider, Input, Text } from '@lobehub/ui/base-ui';
-import { type FormInstance } from 'antd';
-import { Form } from 'antd';
+import { Form, type FormInstance } from '@lobehub/ui/base-ui/form';
import { createStaticStyles } from 'antd-style';
import { Mail } from 'lucide-react';
import { type CSSProperties, useEffect, useRef } from 'react';
@@ -10,7 +9,7 @@ import { useTranslation } from 'react-i18next';
import AuthIcons from '@/components/AuthIcons';
import AuthCard from '@/features/AuthCard';
-import AuthAgreement, { useAuthAgreement } from '@/features/AuthShell/AuthAgreement';
+import AuthAgreement from '@/features/AuthShell/AuthAgreement';
const styles = createStaticStyles(({ css, cssVar }) => ({
inlineLink: css`
@@ -37,23 +36,27 @@ const getProviderName = (provider: string) =>
provider.toLowerCase().replaceAll(/(^|[_-])([a-z])/g, (_, __, c) => c.toUpperCase());
export interface SignInEmailStepProps {
+ agreementChecked: boolean;
+ continueWithAgreement: (continueAction: () => void) => void;
disableEmailPassword?: boolean;
form: FormInstance<{ email: string }>;
isSocialOnly: boolean;
lastAuthProvider?: string | null;
loading: boolean;
oAuthSSOProviders: string[];
- onCheckUser: (values: { email: string }) => Promise<void>;
onGoToSignup: () => void;
onResetEmail: () => void;
onSetPassword: () => void;
onSocialSignIn: (provider: string) => void;
serverConfigInit: boolean;
sessionExpired?: boolean;
+ setAgreementChecked: (checked: boolean) => void;
socialLoading: string | null;
}
export const SignInEmailStep = ({
+ agreementChecked,
+ continueWithAgreement,
disableEmailPassword,
form,
isSocialOnly,
@@ -62,15 +65,14 @@ export const SignInEmailStep = ({
oAuthSSOProviders,
serverConfigInit,
sessionExpired,
+ setAgreementChecked,
socialLoading,
- onCheckUser,
onGoToSignup,
onResetEmail,
onSetPassword,
onSocialSignIn,
}: SignInEmailStepProps) => {
const { t } = useTranslation('auth');
- const { agreementChecked, continueWithAgreement, setAgreementChecked } = useAuthAgreement();
const emailInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
@@ -152,30 +154,16 @@ export const SignInEmailStep = ({
<Alert showIcon description={t('betterAuth.signin.ssoOnlyNoProviders')} type="warning" />
)}
{showEmailForm && (
- <Form
- form={form}
- layout="vertical"
- onFinish={(values) =>
- continueWithAgreement(() => {
- void onCheckUser(values as { email: string });
- })
- }
- >
- <Form.Item
+ <Form form={form} gap={0} layout="vertical">
+ <Form.Field
name="email"
- rules={[
- { message: t('betterAuth.errors.emailRequired'), required: true },
- {
- validator: (_, value) => {
- if (!value) return Promise.resolve();
- const trimmedValue = (value as string).trim();
- if (EMAIL_REGEX.test(trimmedValue) || USERNAME_REGEX.test(trimmedValue)) {
- return Promise.resolve();
- }
- return Promise.reject(new Error(t('betterAuth.errors.emailInvalid')));
- },
- },
- ]}
+ style={{ gap: 0, paddingBlock: '0 24px' }}
+ validate={(value: string) => {
+ if (!value) return t('betterAuth.errors.emailRequired');
+ const trimmedValue = value.trim();
+ if (EMAIL_REGEX.test(trimmedValue) || USERNAME_REGEX.test(trimmedValue)) return;
+ return t('betterAuth.errors.emailInvalid');
+ }}
>
<Input
autoComplete="username"
@@ -186,7 +174,7 @@ export const SignInEmailStep = ({
size="large"
style={{ padding: 6 }}
/>
- </Form.Item>
+ </Form.Field>
<AuthAgreement checked={agreementChecked} onChange={setAgreementChecked} />
<Button block htmlType="submit" loading={loading} size="large" type="primary">
{t('betterAuth.signin.nextStep')}
diff --git a/src/features/Auth/SignIn/SignInPasswordStep.tsx b/src/features/Auth/SignIn/SignInPasswordStep.tsx
index 35a9c542b09..39e2ebff7b1 100644
--- a/src/features/Auth/SignIn/SignInPasswordStep.tsx
+++ b/src/features/Auth/SignIn/SignInPasswordStep.tsx
@@ -1,7 +1,6 @@
import { Icon } from '@lobehub/ui';
import { Button, InputPassword, Text } from '@lobehub/ui/base-ui';
-import { type FormInstance } from 'antd';
-import { Form } from 'antd';
+import { Form, type FormInstance } from '@lobehub/ui/base-ui/form';
import { Lock } from 'lucide-react';
import { useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
@@ -15,7 +14,6 @@ export interface SignInPasswordStepProps {
loading: boolean;
onBackToEmail: () => void;
onForgotPassword: () => Promise<void>;
- onSubmit: (values: { password: string }) => Promise<void>;
}
export const SignInPasswordStep = ({
@@ -25,7 +23,6 @@ export const SignInPasswordStep = ({
loading,
onBackToEmail,
onForgotPassword,
- onSubmit,
}: SignInPasswordStepProps) => {
const { t } = useTranslation('auth');
const passwordInputRef = useRef<HTMLInputElement>(null);
@@ -57,14 +54,13 @@ export const SignInPasswordStep = ({
</Text>
}
>
- <Form
- form={form}
- layout="vertical"
- onFinish={(values) => onSubmit(values as { password: string })}
- >
- <Form.Item
+ <Form form={form} gap={0} layout="vertical">
+ <Form.Field
name="password"
- rules={[{ message: t('betterAuth.errors.passwordRequired'), required: true }]}
+ style={{ gap: 0, paddingBlock: '0 24px' }}
+ validate={(value: string) =>
+ value ? undefined : t('betterAuth.errors.passwordRequired')
+ }
>
<InputPassword
autoComplete="current-password"
@@ -74,7 +70,7 @@ export const SignInPasswordStep = ({
size="large"
style={{ padding: 6 }}
/>
- </Form.Item>
+ </Form.Field>
<Button block htmlType="submit" loading={loading} size="large" type="primary">
{t('betterAuth.signin.submit')}
</Button>
diff --git a/src/features/Auth/SignIn/index.tsx b/src/features/Auth/SignIn/index.tsx
index b6f91324c1e..d3831305e92 100644
--- a/src/features/Auth/SignIn/index.tsx
+++ b/src/features/Auth/SignIn/index.tsx
@@ -8,16 +8,16 @@ import { useSignIn } from './useSignIn';
const SignIn = () => {
const {
+ agreementChecked,
+ continueWithAgreement,
disableEmailPassword,
email,
form,
handleBackFromSent,
handleBackToEmail,
- handleCheckUser,
handleForgotPassword,
handleGoToSignup,
handleResendEmail,
- handleSignIn,
handleSocialSignIn,
isSocialOnly,
lastAuthProvider,
@@ -27,6 +27,7 @@ const SignIn = () => {
sessionExpired,
sentInfo,
serverConfigInit,
+ setAgreementChecked,
socialLoading,
step,
} = useSignIn();
@@ -51,13 +52,14 @@ const SignIn = () => {
loading={loading}
onBackToEmail={handleBackToEmail}
onForgotPassword={handleForgotPassword}
- onSubmit={handleSignIn}
/>
);
return (
<>
<SignInEmailStep
+ agreementChecked={agreementChecked}
+ continueWithAgreement={continueWithAgreement}
disableEmailPassword={disableEmailPassword}
form={form as any}
isSocialOnly={isSocialOnly}
@@ -66,8 +68,8 @@ const SignIn = () => {
oAuthSSOProviders={oAuthSSOProviders}
serverConfigInit={serverConfigInit}
sessionExpired={sessionExpired}
+ setAgreementChecked={setAgreementChecked}
socialLoading={socialLoading}
- onCheckUser={handleCheckUser}
onGoToSignup={handleGoToSignup}
onResetEmail={handleBackToEmail}
onSetPassword={handleForgotPassword}
diff --git a/src/features/Auth/SignIn/useSignIn.test.ts b/src/features/Auth/SignIn/useSignIn.test.ts
index e257609b85b..f5a4b0d4c37 100644
--- a/src/features/Auth/SignIn/useSignIn.test.ts
+++ b/src/features/Auth/SignIn/useSignIn.test.ts
@@ -81,31 +81,17 @@ vi.mock('@/features/AuthShell/AuthServerConfigProvider', () => ({
}),
}));
-const mockSetFieldValue = vi.fn();
-const mockGetFieldValue = vi.fn();
-const mockValidateFields = vi.fn();
-const mockSetFields = vi.fn();
-const mockResetFields = vi.fn();
-const mockSubmit = vi.fn();
-vi.mock('antd', async () => {
- const actual: any = await vi.importActual('antd');
- return {
- ...actual,
- Form: {
- ...actual.Form,
- useForm: () => [
- {
- getFieldValue: mockGetFieldValue,
- resetFields: mockResetFields,
- setFields: mockSetFields,
- setFieldValue: mockSetFieldValue,
- submit: mockSubmit,
- validateFields: mockValidateFields,
- },
- ],
- },
- };
-});
+const mockForm = vi.hoisted(() => ({
+ getValue: vi.fn(),
+ getValues: vi.fn(() => ({ email: '[email protected]', password: 'stale' })),
+ reset: vi.fn(),
+ setErrors: vi.fn(),
+ setValue: vi.fn(),
+ validate: vi.fn(),
+}));
+vi.mock('@lobehub/ui/base-ui/form', () => ({
+ useForm: () => mockForm,
+}));
const mockFetch = vi.fn();
vi.stubGlobal('fetch', mockFetch);
@@ -322,9 +308,7 @@ describe('useSignIn', () => {
});
// Error is pinned inline on the password field, not shown as a toast
- expect(mockSetFields).toHaveBeenCalledWith([
- { errors: ['Invalid credentials'], name: 'password' },
- ]);
+ expect(mockForm.setErrors).toHaveBeenCalledWith({ password: 'Invalid credentials' });
expect(mockMessageError).not.toHaveBeenCalled();
});
@@ -532,7 +516,7 @@ describe('useSignIn', () => {
expect(result.current.isSocialOnly).toBe(false);
// The shared form's password (+ any inline error) must be cleared so the
// next email doesn't remount pre-filled with the previous account's value.
- expect(mockResetFields).toHaveBeenCalledWith(['password']);
+ expect(mockForm.reset).toHaveBeenCalledWith({ email: '[email protected]', password: '' });
});
});
@@ -718,7 +702,7 @@ describe('useSignIn', () => {
expect(result.current.step).toBe('email');
expect(result.current.email).toBe('');
expect(result.current.sentInfo).toBeNull();
- expect(mockResetFields).toHaveBeenCalledWith(['password']);
+ expect(mockForm.reset).toHaveBeenCalledWith({ email: '[email protected]', password: '' });
});
});
diff --git a/src/features/Auth/SignIn/useSignIn.ts b/src/features/Auth/SignIn/useSignIn.ts
index 5ed6b60a8fe..d5bfea7f259 100644
--- a/src/features/Auth/SignIn/useSignIn.ts
+++ b/src/features/Auth/SignIn/useSignIn.ts
@@ -1,5 +1,5 @@
import { toast } from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { useForm } from '@lobehub/ui/base-ui/form';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate, useSearchParams } from 'react-router';
@@ -7,6 +7,7 @@ import { useNavigate, useSearchParams } from 'react-router';
import type { CheckUserResponseData } from '@/app/(backend)/api/auth/check-user/route';
import type { ResolveUsernameResponseData } from '@/app/(backend)/api/auth/resolve-username/route';
import { useBusinessSignin } from '@/business/client/hooks/useBusinessSignin';
+import { useAuthAgreement } from '@/features/AuthShell/AuthAgreement';
import { useAuthServerConfigStore } from '@/features/AuthShell/AuthServerConfigProvider';
import { trackLoginOrSignupClicked } from '@/features/User/UserLoginOrSignup/trackLoginOrSignupClicked';
import { requestPasswordReset, signIn } from '@/libs/better-auth/auth-client';
@@ -52,7 +53,19 @@ export const useSignIn = () => {
const enableBusinessFeatures = useAuthServerConfigStore(
(s) => s.serverConfig.enableBusinessFeatures || false,
);
- const [form] = Form.useForm<SignInFormValues>();
+ const { agreementChecked, continueWithAgreement, setAgreementChecked } = useAuthAgreement();
+ const form = useForm<SignInFormValues>({
+ initialValues: { email: '', password: '' },
+ onSubmit: (values) => {
+ if (step === 'password') {
+ void handleSignIn(values);
+ return;
+ }
+ continueWithAgreement(() => {
+ void handleCheckUser(values);
+ });
+ },
+ });
const [loading, setLoading] = useState(false);
// Locks the email-dispatch actions (magic link / password reset / resend) so a
// slow network can't be double-clicked into multiple emails.
@@ -79,7 +92,7 @@ export const useSignIn = () => {
useEffect(() => {
const emailParam = searchParams.get('email');
- if (emailParam) form.setFieldValue('email', emailParam);
+ if (emailParam) form.setValue('email', emailParam);
}, [searchParams, form]);
const handleSendMagicLink = async (targetEmail?: string): Promise<boolean> => {
@@ -88,9 +101,8 @@ export const useSignIn = () => {
const emailValue =
targetEmail ||
(await form
- .validateFields(['email'])
- .then((v) => v.email as string)
- .catch(() => null));
+ .validate(['email'])
+ .then(({ valid }) => (valid ? form.getValue('email') : null)));
if (!emailValue) return false;
setSending(true);
@@ -115,10 +127,8 @@ export const useSignIn = () => {
setStep('emailSent');
return true;
} catch (error) {
- if (!(error as any)?.errorFields) {
- console.error('Magic link error:', error);
- toast.error(t('betterAuth.signin.magicLinkError'));
- }
+ console.error('Magic link error:', error);
+ toast.error(t('betterAuth.signin.magicLinkError'));
return false;
} finally {
setSending(false);
@@ -245,12 +255,7 @@ export const useSignIn = () => {
// Wrong password is the most common sign-in failure. Keep the error
// pinned inline on the field (persistent, with retry context) rather
// than a toast that vanishes in 3s (ux Read §1.1 / Same-Page Error).
- form.setFields([
- {
- errors: [result.error.message || t('betterAuth.signin.error')],
- name: 'password',
- },
- ]);
+ form.setErrors({ password: result.error.message || t('betterAuth.signin.error') });
}
} catch (error) {
console.error('Sign in error:', error);
@@ -322,11 +327,11 @@ export const useSignIn = () => {
// Drop the previous account's password + any inline error. The form
// instance is shared across steps and defaults to preserve, so without this
// the next email's password step remounts pre-filled with the stale value.
- form.resetFields(['password']);
+ form.reset({ ...form.getValues(), password: '' });
};
const handleGoToSignup = () => {
- const currentEmail = form.getFieldValue('email');
+ const currentEmail = form.getValue('email');
const callbackUrl = searchParams.get('callbackUrl') || '/';
const params = new URLSearchParams();
if (currentEmail) params.set('email', currentEmail);
@@ -399,6 +404,8 @@ export const useSignIn = () => {
: resolvedProviders;
return {
+ agreementChecked,
+ continueWithAgreement,
disableEmailPassword,
email,
form,
@@ -418,6 +425,7 @@ export const useSignIn = () => {
sessionExpired,
sentInfo,
serverConfigInit: enableBusinessFeatures ? true : serverConfigInit,
+ setAgreementChecked,
socialLoading,
step,
};
diff --git a/src/features/Auth/SignUp/BetterAuthSignUpForm.tsx b/src/features/Auth/SignUp/BetterAuthSignUpForm.tsx
index 230eb5b0b44..c2e131d92f6 100644
--- a/src/features/Auth/SignUp/BetterAuthSignUpForm.tsx
+++ b/src/features/Auth/SignUp/BetterAuthSignUpForm.tsx
@@ -3,25 +3,27 @@
import { BRANDING_NAME } from '@lobechat/business-const';
import { Icon } from '@lobehub/ui';
import { Button, Input, InputPassword, Text } from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form } from '@lobehub/ui/base-ui/form';
import { Lock, Mail } from 'lucide-react';
-import { useEffect, useRef } from 'react';
+import { type CSSProperties, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useNavigate, useSearchParams } from 'react-router';
import { AuthCard } from '@/features/AuthCard';
-import AuthAgreement, { useAuthAgreement } from '@/features/AuthShell/AuthAgreement';
+import AuthAgreement from '@/features/AuthShell/AuthAgreement';
import { trackLoginOrSignupClicked } from '@/features/User/UserLoginOrSignup/trackLoginOrSignupClicked';
+import { EMAIL_REGEX } from '../SignIn/SignInEmailStep';
import { useSignUp } from './useSignUp';
+const FIELD_STYLE: CSSProperties = { gap: 0, paddingBlock: '0 24px' };
+
const BetterAuthSignUpForm = () => {
- const { form, loading, onSubmit, businessElement } = useSignUp();
+ const { agreementChecked, businessElement, form, loading, setAgreementChecked } = useSignUp();
const { t } = useTranslation('auth');
const navigate = useNavigate();
const [searchParams] = useSearchParams();
- const { agreementChecked, continueWithAgreement, setAgreementChecked } = useAuthAgreement();
const emailInputRef = useRef<HTMLInputElement>(null);
const passwordInputRef = useRef<HTMLInputElement>(null);
@@ -29,7 +31,7 @@ const BetterAuthSignUpForm = () => {
useEffect(() => {
const email = searchParams.get('email');
if (email) {
- form.setFieldsValue({ email });
+ form.setValue('email', email);
passwordInputRef.current?.focus();
} else {
emailInputRef.current?.focus();
@@ -55,21 +57,14 @@ const BetterAuthSignUpForm = () => {
return (
<AuthCard footer={footer} title={t('betterAuth.signup.cardTitle', { appName: BRANDING_NAME })}>
- <Form
- form={form}
- layout="vertical"
- onFinish={(values) =>
- continueWithAgreement(() => {
- void onSubmit(values);
- })
- }
- >
- <Form.Item
+ <Form form={form} gap={0} layout="vertical">
+ <Form.Field
name="email"
- rules={[
- { message: t('betterAuth.errors.emailRequired'), required: true },
- { message: t('betterAuth.errors.emailInvalid'), type: 'email' },
- ]}
+ style={FIELD_STYLE}
+ validate={(value: string) => {
+ if (!value) return t('betterAuth.errors.emailRequired');
+ if (!EMAIL_REGEX.test(value)) return t('betterAuth.errors.emailInvalid');
+ }}
>
<Input
autoComplete="email"
@@ -87,23 +82,17 @@ const BetterAuthSignUpForm = () => {
/>
}
/>
- </Form.Item>
- <Form.Item
+ </Form.Field>
+ <Form.Field
name="password"
- rules={[
- { message: t('betterAuth.errors.passwordRequired'), required: true },
- { message: t('betterAuth.errors.passwordMinLength'), min: 8 },
- { max: 64, message: t('betterAuth.errors.passwordMaxLength') },
- {
- message: t('betterAuth.errors.passwordFormat'),
- validator: (_, value) => {
- if (!value) return Promise.resolve();
- const hasLetter = /[a-z]/i.test(value);
- const hasNumber = /\d/.test(value);
- return hasLetter && hasNumber ? Promise.resolve() : Promise.reject();
- },
- },
- ]}
+ style={FIELD_STYLE}
+ validate={(value: string) => {
+ if (!value) return t('betterAuth.errors.passwordRequired');
+ if (value.length < 8) return t('betterAuth.errors.passwordMinLength');
+ if (value.length > 64) return t('betterAuth.errors.passwordMaxLength');
+ if (!/[a-z]/i.test(value) || !/\d/.test(value))
+ return t('betterAuth.errors.passwordFormat');
+ }}
>
<InputPassword
autoComplete="new-password"
@@ -119,21 +108,15 @@ const BetterAuthSignUpForm = () => {
/>
}
/>
- </Form.Item>
- <Form.Item
- dependencies={['password']}
+ </Form.Field>
+ <Form.Field
+ deps={['password']}
name="confirmPassword"
- rules={[
- { message: t('betterAuth.errors.confirmPasswordRequired'), required: true },
- ({ getFieldValue }) => ({
- validator(_, value) {
- if (!value || getFieldValue('password') === value) {
- return Promise.resolve();
- }
- return Promise.reject(new Error(t('betterAuth.errors.passwordMismatch')));
- },
- }),
- ]}
+ style={FIELD_STYLE}
+ validate={(value: string, values: { password: string }) => {
+ if (!value) return t('betterAuth.errors.confirmPasswordRequired');
+ if (values.password !== value) return t('betterAuth.errors.passwordMismatch');
+ }}
>
<InputPassword
autoComplete="new-password"
@@ -148,16 +131,14 @@ const BetterAuthSignUpForm = () => {
/>
}
/>
- </Form.Item>
+ </Form.Field>
- {businessElement}
+ {businessElement && <div style={{ paddingBlockEnd: 24 }}>{businessElement}</div>}
<AuthAgreement checked={agreementChecked} onChange={setAgreementChecked} />
- <Form.Item>
- <Button block htmlType="submit" loading={loading} size="large" type="primary">
- {t('betterAuth.signup.submit')}
- </Button>
- </Form.Item>
+ <Button block htmlType="submit" loading={loading} size="large" type="primary">
+ {t('betterAuth.signup.submit')}
+ </Button>
</Form>
</AuthCard>
);
diff --git a/src/features/Auth/SignUp/useSignUp.ts b/src/features/Auth/SignUp/useSignUp.ts
index 4dd666d9ae1..0f9cd0d74a0 100644
--- a/src/features/Auth/SignUp/useSignUp.ts
+++ b/src/features/Auth/SignUp/useSignUp.ts
@@ -1,5 +1,5 @@
import { toast } from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { useForm } from '@lobehub/ui/base-ui/form';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate, useSearchParams } from 'react-router';
@@ -8,6 +8,7 @@ import type { BusinessSignupFomData } from '@/business/client/hooks/useBusinessS
import { useBusinessSignup } from '@/business/client/hooks/useBusinessSignup';
import type { AuthFetchOptions } from '@/features/Auth/utils/authFetchOptions';
import { withCaptchaToken } from '@/features/Auth/utils/authFetchOptions';
+import { useAuthAgreement } from '@/features/AuthShell/AuthAgreement';
import { useAuthServerConfigStore } from '@/features/AuthShell/AuthServerConfigProvider';
import { trackLoginOrSignupClicked } from '@/features/User/UserLoginOrSignup/trackLoginOrSignupClicked';
import { signUp } from '@/libs/better-auth/auth-client';
@@ -31,7 +32,14 @@ export const useSignUp = () => {
const { t } = useTranslation(['auth', 'authError']);
const navigate = useNavigate();
const [searchParams] = useSearchParams();
- const [form] = Form.useForm<SignUpFormValues>();
+ const { agreementChecked, continueWithAgreement, setAgreementChecked } = useAuthAgreement();
+ const form = useForm<SignUpFormValues>({
+ initialValues: { confirmPassword: '', email: '', password: '' },
+ onSubmit: (values) =>
+ continueWithAgreement(() => {
+ void handleSignUp(values);
+ }),
+ });
const [loading, setLoading] = useState(false);
const { getCaptchaTokenOnError, getFetchOptions, preSocialSignupCheck, businessElement } =
useBusinessSignup(form);
@@ -116,5 +124,12 @@ export const useSignUp = () => {
}
};
- return { businessElement, form, loading, onSubmit: handleSignUp };
+ return {
+ agreementChecked,
+ businessElement,
+ form,
+ loading,
+ onSubmit: handleSignUp,
+ setAgreementChecked,
+ };
};
diff --git a/src/features/AuthShell/AuthAgreement.test.tsx b/src/features/AuthShell/AuthAgreement.test.tsx
index b9d27395755..218ff91fd92 100644
--- a/src/features/AuthShell/AuthAgreement.test.tsx
+++ b/src/features/AuthShell/AuthAgreement.test.tsx
@@ -1,6 +1,6 @@
import * as BaseUI from '@lobehub/ui/base-ui';
+import { useForm } from '@lobehub/ui/base-ui/form';
import { act, fireEvent, render, renderHook, screen } from '@testing-library/react';
-import { Form } from 'antd';
import type { ReactElement } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -68,18 +68,21 @@ describe('SignInEmailStep', () => {
const onSocialSignIn = vi.fn();
const TestSignInEmailStep = () => {
- const [form] = Form.useForm<{ email: string }>();
+ const form = useForm<{ email: string }>();
+ const { agreementChecked, continueWithAgreement, setAgreementChecked } = useAuthAgreement();
return (
<SignInEmailStep
disableEmailPassword
serverConfigInit
+ agreementChecked={agreementChecked}
+ continueWithAgreement={continueWithAgreement}
form={form}
isSocialOnly={false}
loading={false}
oAuthSSOProviders={['google']}
+ setAgreementChecked={setAgreementChecked}
socialLoading={null}
- onCheckUser={vi.fn(async () => {})}
onGoToSignup={vi.fn()}
onResetEmail={vi.fn()}
onSetPassword={vi.fn()}
diff --git a/src/features/ChatInput/ActionBar/History/Controls.tsx b/src/features/ChatInput/ActionBar/History/Controls.tsx
index 3f99ea84460..7b086f5bc27 100644
--- a/src/features/ChatInput/ActionBar/History/Controls.tsx
+++ b/src/features/ChatInput/ActionBar/History/Controls.tsx
@@ -1,7 +1,5 @@
-import { type FormItemProps } from '@lobehub/ui';
-import { Form } from '@lobehub/ui';
import { SliderWithInput, Switch } from '@lobehub/ui/base-ui';
-import { Form as AntdForm } from 'antd';
+import { Form, type FormFieldProps, useForm } from '@lobehub/ui/base-ui/form';
import { debounce } from 'es-toolkit/compat';
import { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -12,9 +10,13 @@ import { chatConfigByIdSelectors } from '@/store/agent/selectors';
import { useAgentId } from '../../hooks/useAgentId';
import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
+interface HistoryValues {
+ enableHistoryCount?: boolean;
+ historyCount?: number;
+}
+
const Controls = () => {
const { t } = useTranslation('setting');
- const [form] = AntdForm.useForm();
const [updating, setUpdating] = useState(false);
const agentId = useAgentId();
const { updateAgentChatConfig } = useUpdateAgentConfig();
@@ -24,14 +26,6 @@ const Controls = () => {
chatConfigByIdSelectors.getEnableHistoryCountById(agentId)(s),
]);
- // Sync external store updates to the form without remounting to keep Switch animation
- useEffect(() => {
- form?.setFieldsValue({
- enableHistoryCount,
- historyCount,
- });
- }, [enableHistoryCount, historyCount, form]);
-
const handleValuesChange = useMemo(
() =>
debounce(async (values) => {
@@ -47,14 +41,23 @@ const Controls = () => {
useEffect(() => () => handleValuesChange.cancel(), [handleValuesChange]);
- const items: FormItemProps[] = [
+ const form = useForm<HistoryValues>({
+ initialValues: { enableHistoryCount, historyCount },
+ onValuesChange: handleValuesChange,
+ });
+
+ // Sync external store updates to the form without remounting to keep Switch animation
+ useEffect(() => {
+ form.setValues({ enableHistoryCount, historyCount });
+ }, [enableHistoryCount, historyCount, form]);
+
+ const items: FormFieldProps<HistoryValues>[] = [
{
children: <Switch loading={updating} size={'small'} />,
label: t('settingChat.enableHistoryCount.title'),
layout: 'horizontal',
minWidth: undefined,
name: 'enableHistoryCount',
- valuePropName: 'checked',
},
{
children: (
@@ -73,8 +76,8 @@ const Controls = () => {
}}
/>
),
+ bare: true,
name: 'historyCount',
- noStyle: true,
},
];
@@ -83,16 +86,11 @@ const Controls = () => {
form={form}
items={items}
itemsType={'flat'}
- initialValues={{
- enableHistoryCount,
- historyCount,
- }}
styles={{
group: {
background: 'transparent',
},
}}
- onValuesChange={handleValuesChange}
/>
);
};
diff --git a/src/features/ChatInput/ActionBar/Params/Controls.tsx b/src/features/ChatInput/ActionBar/Params/Controls.tsx
index 0765d174558..eb6471d4ef3 100644
--- a/src/features/ChatInput/ActionBar/Params/Controls.tsx
+++ b/src/features/ChatInput/ActionBar/Params/Controls.tsx
@@ -6,7 +6,7 @@ import {
import { resolveEffectiveReasoningChatConfig } from '@lobechat/model-runtime/utils/modelExtendParams';
import { Flexbox, Icon } from '@lobehub/ui';
import { Select, SliderWithInput, Spin, Switch, TextArea } from '@lobehub/ui/base-ui';
-import { Form as AntdForm } from 'antd';
+import { useForm } from '@lobehub/ui/base-ui/form';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import { debounce } from 'es-toolkit/compat';
import isEqual from 'fast-deep-equal';
@@ -192,49 +192,6 @@ const styles = createStaticStyles(({ css }) => ({
`,
modelConfigSection: css`
padding-block: 12px;
-
- .ant-form {
- margin: 0;
- }
-
- .ant-form-item {
- padding-block: 12px;
- }
-
- .ant-form-item-row {
- gap: 10px;
- }
-
- .ant-form-item-label > label {
- font-size: 13px;
- font-weight: 500;
- line-height: 20px;
- color: ${cssVar.colorTextSecondary};
- }
-
- .ant-form-item-label > label div {
- color: ${cssVar.colorTextSecondary};
- }
-
- .ant-form-item-label > label small,
- .ant-form-item-label > label small *:not(a) {
- font-size: 12px;
- font-weight: 400;
- line-height: 18px;
- color: ${cssVar.colorTextTertiary};
- }
-
- .ant-form-item:first-child {
- padding-block-start: 0;
- }
-
- .ant-form-item:last-child {
- padding-block-end: 0;
- }
-
- .ant-divider {
- display: none;
- }
`,
panel: css`
overflow: hidden;
@@ -261,10 +218,6 @@ const styles = createStaticStyles(({ css }) => ({
.ant-switch.ant-switch-checked {
background: ${cssVar.colorText};
}
-
- .ant-form-item {
- margin: 0;
- }
`,
sidebarPanel: css`
width: 100%;
@@ -366,11 +319,11 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-const PARAM_NAME_MAP: Record<ParamKey, (string | number)[]> = {
- frequency_penalty: ['params', 'frequency_penalty'],
- presence_penalty: ['params', 'presence_penalty'],
- temperature: ['params', 'temperature'],
- top_p: ['params', 'top_p'],
+const PARAM_NAME_MAP: Record<ParamKey, string> = {
+ frequency_penalty: 'params.frequency_penalty',
+ presence_penalty: 'params.presence_penalty',
+ temperature: 'params.temperature',
+ top_p: 'params.top_p',
};
const PARAM_DEFAULTS: Record<ParamKey, number> = {
@@ -560,32 +513,29 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
REASONING_PARAMS_SET.has(param),
);
const enableAgentMode = useAgentStore(agentByIdSelectors.getAgentEnableModeById(agentId));
- const [form] = AntdForm.useForm();
+ const form = useForm();
const [advancedOpen, setAdvancedOpen] = useState(() => getStoredOpen(ADVANCED_OPEN_STORAGE_KEY));
const [modelConfigOpen, setModelConfigOpen] = useState(() =>
getStoredOpen(MODEL_CONFIG_OPEN_STORAGE_KEY),
);
const [, refreshFormValues] = useState(0);
- const enableContextCompression = form.getFieldValue(['chatConfig', 'enableContextCompression']);
- const enableMaxTokens = form.getFieldValue(['chatConfig', 'enableMaxTokens']);
- const enableHistoryCount = form.getFieldValue(['chatConfig', 'enableHistoryCount']);
- const historyCountValue = form.getFieldValue(['chatConfig', 'historyCount']);
- const maxTokensValue = form.getFieldValue(['params', 'max_tokens']);
- const inputTemplateValue = form.getFieldValue(['chatConfig', 'inputTemplate']);
- const enableAutoScrollOnStreaming = form.getFieldValue([
- 'chatConfig',
- 'enableAutoScrollOnStreaming',
- ]);
- const enableStreaming = form.getFieldValue(['chatConfig', 'enableStreaming']);
- const enableStaleToolResultTrim = form.getFieldValue(['chatConfig', 'enableStaleToolResultTrim']);
- const enableFollowUpChips = form.getFieldValue(['chatConfig', 'enableFollowUpChips']);
+ const enableContextCompression = form.getValue('chatConfig.enableContextCompression');
+ const enableMaxTokens = form.getValue('chatConfig.enableMaxTokens');
+ const enableHistoryCount = form.getValue('chatConfig.enableHistoryCount');
+ const historyCountValue = form.getValue('chatConfig.historyCount');
+ const maxTokensValue = form.getValue('params.max_tokens');
+ const inputTemplateValue = form.getValue('chatConfig.inputTemplate');
+ const enableAutoScrollOnStreaming = form.getValue('chatConfig.enableAutoScrollOnStreaming');
+ const enableStreaming = form.getValue('chatConfig.enableStreaming');
+ const enableStaleToolResultTrim = form.getValue('chatConfig.enableStaleToolResultTrim');
+ const enableFollowUpChips = form.getValue('chatConfig.enableFollowUpChips');
const globalFollowUp = useUserStore(systemAgentSelectors.followUpAction, isEqual);
const globalFollowUpReady =
globalFollowUp.enabled === true && !!globalFollowUp.model && !!globalFollowUp.provider;
const showFollowUpHint = !globalFollowUpReady && Boolean(enableFollowUpChips);
- const enableReasoningEffort = form.getFieldValue(['chatConfig', 'enableReasoningEffort']);
- const reasoningEffortValue = form.getFieldValue(['params', 'reasoning_effort']);
+ const enableReasoningEffort = form.getValue('chatConfig.enableReasoningEffort');
+ const reasoningEffortValue = form.getValue('params.reasoning_effort');
const { frequency_penalty, presence_penalty, temperature, top_p } = config.params ?? {};
const historyCountFromStore = useAgentStore((s) =>
@@ -604,7 +554,7 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
});
useEffect(() => {
- form.setFieldsValue(config);
+ form.setValues(config);
if (typeof temperature === 'number') lastValuesRef.current.temperature = temperature;
if (typeof top_p === 'number') lastValuesRef.current.top_p = top_p;
@@ -622,9 +572,9 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
// Skip syncing when updating to avoid overwriting user's in-progress edits
if (updating) return;
- form.setFieldsValue({
+ form.setValues({
chatConfig: {
- ...form.getFieldValue('chatConfig'),
+ ...form.getValue('chatConfig'),
enableHistoryCount: enableHistoryCountFromStore,
historyCount: historyCountFromStore,
},
@@ -632,10 +582,10 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
refreshFormValues((value) => value + 1);
}, [form, enableHistoryCountFromStore, historyCountFromStore, updating]);
- const temperatureValue = form.getFieldValue(PARAM_NAME_MAP.temperature);
- const topPValue = form.getFieldValue(PARAM_NAME_MAP.top_p);
- const presencePenaltyValue = form.getFieldValue(PARAM_NAME_MAP.presence_penalty);
- const frequencyPenaltyValue = form.getFieldValue(PARAM_NAME_MAP.frequency_penalty);
+ const temperatureValue = form.getValue(PARAM_NAME_MAP.temperature);
+ const topPValue = form.getValue(PARAM_NAME_MAP.top_p);
+ const presencePenaltyValue = form.getValue(PARAM_NAME_MAP.presence_penalty);
+ const frequencyPenaltyValue = form.getValue(PARAM_NAME_MAP.frequency_penalty);
const enabledMap: Record<ParamKey, boolean> = {
frequency_penalty: typeof frequencyPenaltyValue === 'number',
@@ -704,24 +654,24 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
let newValue: number | undefined;
if (!enabled) {
- const currentValue = form.getFieldValue(namePath);
+ const currentValue = form.getValue(namePath);
if (typeof currentValue === 'number') {
lastValuesRef.current[key] = currentValue;
}
newValue = undefined;
- form.setFieldValue(namePath, undefined);
+ form.setValue(namePath, undefined);
} else {
const fallback = lastValuesRef.current[key];
const nextValue = typeof fallback === 'number' ? fallback : PARAM_DEFAULTS[key];
lastValuesRef.current[key] = nextValue;
newValue = nextValue;
- form.setFieldValue(namePath, nextValue);
+ form.setValue(namePath, nextValue);
}
refreshFormValues((value) => value + 1);
// Save changes immediately - manually construct config object to ensure latest values are used
setUpdating(true);
- const currentValues = form.getFieldsValue(true) as PartialDeep<LobeAgentConfig>;
+ const currentValues = form.getValues() as PartialDeep<LobeAgentConfig>;
const prevParams = (currentValues.params ?? {}) as Partial<
Record<ParamKey, null | number | undefined>
>;
@@ -768,19 +718,15 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
);
const handleFieldChange = useCallback(
- (namePath: (string | number)[], value: boolean | number | string) => {
+ (namePath: string, value: boolean | number | string) => {
if (!canCreate) return;
- form.setFieldValue(namePath, value);
- if (
- namePath[0] === 'params' &&
- typeof namePath[1] === 'string' &&
- namePath[1] in PARAM_NAME_MAP &&
- typeof value === 'number'
- ) {
- lastValuesRef.current[namePath[1] as ParamKey] = value;
+ form.setValue(namePath, value);
+ const [scope, key] = namePath.split('.');
+ if (scope === 'params' && key in PARAM_NAME_MAP && typeof value === 'number') {
+ lastValuesRef.current[key as ParamKey] = value;
}
refreshFormValues((current) => current + 1);
- handleValuesChange(form.getFieldsValue(true) as PartialDeep<LobeAgentConfig>);
+ handleValuesChange(form.getValues() as PartialDeep<LobeAgentConfig>);
},
[canCreate, form, handleValuesChange, refreshFormValues],
);
@@ -860,7 +806,7 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
disabled={!canCreate}
size={'small'}
onChange={(checked) => {
- handleFieldChange(['chatConfig', 'enableContextCompression'], checked);
+ handleFieldChange('chatConfig.enableContextCompression', checked);
}}
/>
}
@@ -875,7 +821,7 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
disabled={!canCreate}
size={'small'}
onChange={(checked) => {
- handleFieldChange(['chatConfig', 'enableHistoryCount'], checked);
+ handleFieldChange('chatConfig.enableHistoryCount', checked);
}}
/>
}
@@ -890,7 +836,7 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
step={1}
value={typeof historyCountValue === 'number' ? historyCountValue : 0}
onChange={(value) => {
- handleFieldChange(['chatConfig', 'historyCount'], value);
+ handleFieldChange('chatConfig.historyCount', value);
}}
/>
)}
@@ -905,7 +851,7 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
disabled={!canCreate}
size={'small'}
onChange={(checked) => {
- handleFieldChange(['chatConfig', 'enableStaleToolResultTrim'], checked);
+ handleFieldChange('chatConfig.enableStaleToolResultTrim', checked);
}}
/>
}
@@ -919,7 +865,7 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
checked={Boolean(enableAutoScrollOnStreaming)}
size={'small'}
onChange={(checked) => {
- handleFieldChange(['chatConfig', 'enableAutoScrollOnStreaming'], checked);
+ handleFieldChange('chatConfig.enableAutoScrollOnStreaming', checked);
}}
/>
}
@@ -933,7 +879,7 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
checked={enableStreaming !== false}
size={'small'}
onChange={(checked) => {
- handleFieldChange(['chatConfig', 'enableStreaming'], checked);
+ handleFieldChange('chatConfig.enableStreaming', checked);
}}
/>
}
@@ -947,7 +893,7 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
checked={Boolean(enableFollowUpChips)}
size={'small'}
onChange={(checked) => {
- handleFieldChange(['chatConfig', 'enableFollowUpChips'], checked);
+ handleFieldChange('chatConfig.enableFollowUpChips', checked);
}}
/>
}
@@ -967,7 +913,7 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
placeholder={t('settingChat.inputTemplate.placeholder')}
value={typeof inputTemplateValue === 'string' ? inputTemplateValue : ''}
onChange={(e) => {
- handleFieldChange(['chatConfig', 'inputTemplate'], e.target.value);
+ handleFieldChange('chatConfig.inputTemplate', e.target.value);
}}
/>
</ControlRow>
@@ -1059,7 +1005,7 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
{enabled && (
<SliderField
disabled={!canCreate}
- value={form.getFieldValue(PARAM_NAME_MAP[key])}
+ value={form.getValue(PARAM_NAME_MAP[key])}
onChange={(value) => {
handleFieldChange(PARAM_NAME_MAP[key], value);
}}
@@ -1080,9 +1026,9 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
size={'small'}
onChange={(checked) => {
if (checked && typeof maxTokensValue !== 'number') {
- form.setFieldValue(['params', 'max_tokens'], 4096);
+ form.setValue('params.max_tokens', 4096);
}
- handleFieldChange(['chatConfig', 'enableMaxTokens'], checked);
+ handleFieldChange('chatConfig.enableMaxTokens', checked);
}}
/>
}
@@ -1097,7 +1043,7 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
step={100}
value={typeof maxTokensValue === 'number' ? maxTokensValue : 4096}
onChange={(value) => {
- handleFieldChange(['params', 'max_tokens'], value);
+ handleFieldChange('params.max_tokens', value);
}}
/>
)}
@@ -1113,9 +1059,9 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
size={'small'}
onChange={(checked) => {
if (checked && typeof reasoningEffortValue !== 'string') {
- form.setFieldValue(['params', 'reasoning_effort'], 'medium');
+ form.setValue('params.reasoning_effort', 'medium');
}
- handleFieldChange(['chatConfig', 'enableReasoningEffort'], checked);
+ handleFieldChange('chatConfig.enableReasoningEffort', checked);
}}
/>
}
@@ -1141,7 +1087,7 @@ const Controls = ({ variant = 'popover' }: ControlsProps) => {
: 'medium'
}
onChange={(value) => {
- handleFieldChange(['params', 'reasoning_effort'], value);
+ handleFieldChange('params.reasoning_effort', value);
}}
/>
)}
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/KeyValueEditor.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/KeyValueEditor.tsx
index 6a9e2730795..e92f8d273b2 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/KeyValueEditor.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/KeyValueEditor.tsx
@@ -1,10 +1,9 @@
import { Flexbox, Icon } from '@lobehub/ui';
import { ActionIcon, Button, Input, toast } from '@lobehub/ui/base-ui';
-import { type FormInstance } from 'antd';
-import { Form } from 'antd';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import { createStaticStyles } from 'antd-style';
import { LucidePlus, LucideTrash } from 'lucide-react';
-import { memo, useEffect, useRef, useState } from 'react';
+import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
const styles = createStaticStyles(({ css, cssVar }) => ({
@@ -16,8 +15,12 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
padding: 8px;
border-radius: ${cssVar.borderRadiusLG};
`,
+ error: css`
+ font-size: 12px;
+ color: ${cssVar.colorError};
+ `,
formItem: css`
- margin-block-end: 4px !important;
+ margin-block-end: 4px;
`,
input: css`
font-family: ${cssVar.fontFamilyCode};
@@ -69,20 +72,21 @@ const formListToRecord = (list: KeyValueItem[]): Record<string, any> => {
const KeyValueEditor = memo<KeyValueEditorProps>(({ initialValue = {}, onFinish, onCancel }) => {
const { t } = useTranslation(['tool', 'common']);
- const [form] = Form.useForm();
-
- const formRef = useRef<FormInstance>(null);
+ const form = useForm<{ items: KeyValueItem[] }>({
+ initialValues: { items: recordToFormList(initialValue) },
+ });
useEffect(() => {
- form.setFieldsValue({ items: recordToFormList(initialValue) });
+ form.setValues({ items: recordToFormList(initialValue) });
}, [initialValue, form]);
const [updating, setUpdating] = useState(false);
const handleFinish = async () => {
setUpdating(true);
try {
- await form.validateFields();
- const values = form.getFieldsValue();
+ const { errors, valid } = await form.validate();
+ if (!valid) throw errors;
+ const values = form.getValues();
const record = formListToRecord(values.items || []);
await onFinish?.(record);
} catch (errorInfo) {
@@ -96,34 +100,22 @@ const KeyValueEditor = memo<KeyValueEditorProps>(({ initialValue = {}, onFinish,
onCancel?.();
};
- const validateKeys = (_: any, item: KeyValueItem, items: KeyValueItem[]) => {
- if (!item?.key) {
- return Promise.resolve();
- }
- const keys = items.map((i) => i?.key).filter(Boolean);
- if (keys.filter((k) => k === item.key).length > 1) {
- return Promise.reject(new Error(t('updateArgs.duplicateKeyError')));
- }
-
- return Promise.resolve();
+ const validateKey = (key: string | undefined, values: { items?: KeyValueItem[] }) => {
+ if (!key) return;
+ const keys = (values.items ?? []).map((i) => i?.key).filter(Boolean);
+ if (keys.filter((k) => k === key).length > 1) return t('updateArgs.duplicateKeyError');
};
return (
- <Form
- autoComplete="off"
- className={styles.form}
- form={form}
- initialValues={{ items: recordToFormList(initialValue) }}
- ref={formRef}
- >
+ <Form autoComplete="off" className={styles.form} form={form} gap={0}>
<Flexbox horizontal className={styles.title} gap={8}>
<Flexbox flex={1}>key</Flexbox>
<Flexbox flex={4}>value</Flexbox>
</Flexbox>
<Form.List name="items">
- {(fields, { add, remove }) => (
+ {({ fields, add, remove }) => (
<Flexbox width={'100%'}>
- {fields.map(({ key, name, ...restField }, index) => (
+ {fields.map(({ key, name, index }) => (
<Flexbox
horizontal
align="center"
@@ -132,44 +124,38 @@ const KeyValueEditor = memo<KeyValueEditorProps>(({ initialValue = {}, onFinish,
key={key}
width={'100%'}
>
- <Form.Item
- {...restField}
- className={styles.formItem}
- name={[name, 'key']}
- style={{ flex: 1 }}
- validateTrigger={['onChange', 'onBlur']}
- rules={[
- { message: t('updateArgs.keyRequired'), required: true },
- {
- validator: (rule) =>
- validateKeys(
- rule,
- form.getFieldValue(['items', index]),
- form.getFieldValue('items'),
- ),
- },
- ]}
- >
- <Input
- allowClear
- className={styles.input}
- placeholder={t('updateArgs.form.key')}
- variant={'filled'}
- />
- </Form.Item>
- <Form.Item
- {...restField}
- className={styles.formItem}
- name={[name, 'value']}
- style={{ flex: 4 }}
- >
- <Input
- allowClear
- className={styles.input}
- placeholder={t('updateArgs.form.value')}
- variant={'filled'}
- />
- </Form.Item>
+ <Form.Field
+ bare
+ name={`${name}.key`}
+ required={t('updateArgs.keyRequired')}
+ validate={validateKey}
+ validateOn={'change'}
+ render={({ error, onBlur, onChange, value }) => (
+ <Flexbox className={styles.formItem} flex={1}>
+ <Input
+ allowClear
+ aria-invalid={error ? true : undefined}
+ className={styles.input}
+ placeholder={t('updateArgs.form.key')}
+ value={value}
+ variant={'filled'}
+ onBlur={onBlur}
+ onChange={(e) => onChange(e.target.value)}
+ />
+ {error && <div className={styles.error}>{error}</div>}
+ </Flexbox>
+ )}
+ />
+ <Flexbox className={styles.formItem} flex={4}>
+ <Form.Field bare name={`${name}.value`}>
+ <Input
+ allowClear
+ className={styles.input}
+ placeholder={t('updateArgs.form.value')}
+ variant={'filled'}
+ />
+ </Form.Field>
+ </Flexbox>
<ActionIcon
icon={LucideTrash}
size={'small'}
@@ -177,31 +163,29 @@ const KeyValueEditor = memo<KeyValueEditorProps>(({ initialValue = {}, onFinish,
style={{
marginBottom: 6,
}}
- onClick={() => remove(name)}
+ onClick={() => remove(index)}
/>
</Flexbox>
))}
- <Form.Item style={{ marginBottom: 0, marginTop: 8 }}>
- <Flexbox horizontal gap={8} justify={'space-between'}>
- <Button
- icon={<Icon icon={LucidePlus} />}
- size={'small'}
- type="fill"
- onClick={() => add({ id: `new-${Date.now()}`, key: '', value: '' })}
- >
- {t('updateArgs.form.add')}
- </Button>
+ <Flexbox horizontal gap={8} justify={'space-between'} style={{ marginTop: 8 }}>
+ <Button
+ icon={<Icon icon={LucidePlus} />}
+ size={'small'}
+ type="fill"
+ onClick={() => add({ id: `new-${Date.now()}`, key: '', value: '' })}
+ >
+ {t('updateArgs.form.add')}
+ </Button>
- <Flexbox horizontal gap={8}>
- <Button size={'small'} onClick={handleCancel}>
- {t('cancel', { ns: 'common' })}
- </Button>
- <Button loading={updating} size={'small'} type={'primary'} onClick={handleFinish}>
- {t('save', { ns: 'common' })}
- </Button>
- </Flexbox>
+ <Flexbox horizontal gap={8}>
+ <Button size={'small'} onClick={handleCancel}>
+ {t('cancel', { ns: 'common' })}
+ </Button>
+ <Button loading={updating} size={'small'} type={'primary'} onClick={handleFinish}>
+ {t('save', { ns: 'common' })}
+ </Button>
</Flexbox>
- </Form.Item>
+ </Flexbox>
</Flexbox>
)}
</Form.List>
diff --git a/src/features/Conversation/components/ShareMessageModal/ShareImage/index.tsx b/src/features/Conversation/components/ShareMessageModal/ShareImage/index.tsx
index d5dd16dafa0..3f199ed2e4f 100644
--- a/src/features/Conversation/components/ShareMessageModal/ShareImage/index.tsx
+++ b/src/features/Conversation/components/ShareMessageModal/ShareImage/index.tsx
@@ -1,7 +1,7 @@
import { agentDisplayName, type UIChatMessage } from '@lobechat/types';
-import { type FormItemProps } from '@lobehub/ui';
-import { Flexbox, Form } from '@lobehub/ui';
+import { Flexbox } from '@lobehub/ui';
import { Button, Switch, Tabs } from '@lobehub/ui/base-ui';
+import { Form, type FormFieldProps, useForm } from '@lobehub/ui/base-ui/form';
import { CopyIcon } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -33,6 +33,10 @@ const ShareImage = memo<{ message: UIChatMessage; mobile?: boolean; uniqueId?: s
);
const context = useConversationStore((s) => s.context);
const [fieldValue, setFieldValue] = useState<FieldType>(DEFAULT_FIELD_VALUE);
+ const form = useForm({
+ initialValues: DEFAULT_FIELD_VALUE,
+ onValuesChange: (_, v) => setFieldValue(v),
+ });
const { t } = useTranslation(['chat', 'common']);
const widthModeOptions = [
@@ -49,14 +53,14 @@ const ShareImage = memo<{ message: UIChatMessage; mobile?: boolean; uniqueId?: s
title: currentAgentTitle ?? undefined,
});
const { loading: copyLoading, onCopy } = useImgToClipboard({ id: `#${previewId}` });
- const settings: FormItemProps[] = [
+ const settings: FormFieldProps<FieldType>[] = [
{
children: <Tabs items={widthModeOptions} />,
label: t('shareModal.widthMode.label'),
layout: 'horizontal',
minWidth: undefined,
name: 'widthMode',
- valuePropName: 'activeKey',
+ valueProp: 'activeKey',
},
{
children: <Switch />,
@@ -64,7 +68,6 @@ const ShareImage = memo<{ message: UIChatMessage; mobile?: boolean; uniqueId?: s
layout: 'horizontal',
minWidth: undefined,
name: 'withBackground',
- valuePropName: 'checked',
},
{
children: <Switch />,
@@ -72,7 +75,6 @@ const ShareImage = memo<{ message: UIChatMessage; mobile?: boolean; uniqueId?: s
layout: 'horizontal',
minWidth: undefined,
name: 'withFooter',
- valuePropName: 'checked',
},
{
children: <Tabs items={imageTypeOptions} />,
@@ -80,7 +82,7 @@ const ShareImage = memo<{ message: UIChatMessage; mobile?: boolean; uniqueId?: s
layout: 'vertical',
minWidth: undefined,
name: 'imageType',
- valuePropName: 'activeKey',
+ valueProp: 'activeKey',
},
];
@@ -115,13 +117,7 @@ const ShareImage = memo<{ message: UIChatMessage; mobile?: boolean; uniqueId?: s
previewId={previewId}
/>
<Flexbox className={styles.sidebar} gap={12}>
- <Form
- initialValues={DEFAULT_FIELD_VALUE}
- items={settings}
- itemsType={'flat'}
- onValuesChange={(_, v) => setFieldValue(v)}
- {...FORM_STYLE}
- />
+ <Form form={form} items={settings} itemsType={'flat'} {...FORM_STYLE} />
{!isMobile && button}
</Flexbox>
</Flexbox>
diff --git a/src/features/EvalCapture/CaptureContent.tsx b/src/features/EvalCapture/CaptureContent.tsx
index df9d6eb6b48..33b35cbb414 100644
--- a/src/features/EvalCapture/CaptureContent.tsx
+++ b/src/features/EvalCapture/CaptureContent.tsx
@@ -2,7 +2,7 @@
import { Flexbox, Icon } from '@lobehub/ui';
import { Divider, Segmented, Select, Text, TextArea, toast } from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import { createStaticStyles, cssVar } from 'antd-style';
import { ChevronRight } from 'lucide-react';
import { type FC, useEffect, useState } from 'react';
@@ -11,7 +11,11 @@ import { useTranslation } from 'react-i18next';
import { agentEvalService } from '@/services/agentEval';
import { type CaptureDraft } from './buildCaptureDraft';
-import { buildCapturePayload, type CapturedOutputKind } from './buildCapturePayload';
+import {
+ buildCapturePayload,
+ type CapturedOutputKind,
+ type CaptureFormValues,
+} from './buildCapturePayload';
const styles = createStaticStyles(({ css }) => ({
body: css`
@@ -126,7 +130,7 @@ const ROLE_KEYS: Record<string, string> = {
const CaptureContent: FC<CaptureContentProps> = ({ draft, formId, onLoadingChange, onSaved }) => {
const { t } = useTranslation('eval');
const roleLabel = (role: string) => (ROLE_KEYS[role] ? t(ROLE_KEYS[role] as never) : role);
- const [form] = Form.useForm();
+ const form = useForm<CaptureFormValues>({ onSubmit: (values) => handleFinish(values) });
const [datasets, setDatasets] = useState<Array<{ id: string; name: string }>>([]);
const [contextOpen, setContextOpen] = useState(false);
// A capture is usually a complaint, so the counter-example is the default —
@@ -138,9 +142,9 @@ const CaptureContent: FC<CaptureContentProps> = ({ draft, formId, onLoadingChang
// it is still that same text — never something typed since.
const handleKindChange = (next: CapturedOutputKind) => {
setKind(next);
- const current = form.getFieldValue('expected');
- if (next === 'positive' && !current?.trim()) form.setFieldValue('expected', draft.actualOutput);
- if (next === 'negative' && current === draft.actualOutput) form.setFieldValue('expected', '');
+ const current = form.getValue('expected');
+ if (next === 'positive' && !current?.trim()) form.setValue('expected', draft.actualOutput);
+ if (next === 'negative' && current === draft.actualOutput) form.setValue('expected', '');
};
useEffect(() => {
@@ -152,7 +156,7 @@ const CaptureContent: FC<CaptureContentProps> = ({ draft, formId, onLoadingChang
.catch(() => setDatasets([]));
}, []);
- const handleFinish = async (values: any) => {
+ const handleFinish = async (values: CaptureFormValues) => {
onLoadingChange?.(true);
try {
const created = await agentEvalService.createTestCase(
@@ -225,40 +229,40 @@ const CaptureContent: FC<CaptureContentProps> = ({ draft, formId, onLoadingChang
{/* Right: how it will be judged, and where it lands. */}
<Flexbox className={styles.right} gap={12}>
- <Form form={form} id={formId} layout="vertical" onFinish={handleFinish}>
- <Form.Item
+ <Form form={form} gap={0} id={formId} layout="vertical">
+ <Form.Field
label={t('capture.criteria')}
name="criteria"
- rules={[{ message: t('capture.criteriaRequired'), required: true }]}
+ required={t('capture.criteriaRequired')}
>
<TextArea
autoSize={{ maxRows: 10, minRows: 5 }}
placeholder={t('capture.criteriaPlaceholder')}
/>
- </Form.Item>
+ </Form.Field>
<Text style={{ fontSize: 12 }} type="secondary">
{t('capture.criteriaHint')}
</Text>
<Divider style={{ marginBlock: 12 }} />
- <Form.Item label={t('capture.expected')} name="expected">
+ <Form.Field label={t('capture.expected')} name="expected">
<TextArea
autoSize={{ maxRows: 5, minRows: 3 }}
placeholder={t('capture.expectedPlaceholder')}
/>
- </Form.Item>
+ </Form.Field>
- <Form.Item
+ <Form.Field
label={t('capture.dataset')}
name="datasetId"
- rules={[{ message: t('capture.datasetRequired'), required: true }]}
+ required={t('capture.datasetRequired')}
>
<Select
options={datasets.map((d) => ({ label: d.name, value: d.id }))}
placeholder={t('capture.datasetPlaceholder')}
/>
- </Form.Item>
+ </Form.Field>
</Form>
</Flexbox>
</Flexbox>
diff --git a/src/features/GroupPermission/PermissionForm.tsx b/src/features/GroupPermission/PermissionForm.tsx
index d786b73b424..efb4dcf08e2 100644
--- a/src/features/GroupPermission/PermissionForm.tsx
+++ b/src/features/GroupPermission/PermissionForm.tsx
@@ -1,9 +1,9 @@
'use client';
import type { AgentModelSelectionPolicy, AgentTopicSharePolicy } from '@lobechat/types';
-import type { FormGroupItemType } from '@lobehub/ui';
-import { Empty, Form, Icon } from '@lobehub/ui';
+import { Empty, Icon } from '@lobehub/ui';
import { Alert } from '@lobehub/ui/base-ui';
+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import { createStaticStyles } from 'antd-style';
import { Bot, InfoIcon, LockIcon, MonitorSmartphone, Share2, UsersIcon } from 'lucide-react';
import { memo, useMemo } from 'react';
@@ -56,6 +56,7 @@ const PermissionForm = memo<PermissionFormProps>(({ groupId }) => {
setTopicSharePolicy,
topicSharePolicy,
} = useGroupPermission(groupId);
+ const form = useForm();
const accessOptions = useAccessLevelOptions({ accessLevel, isPrivate });
@@ -149,7 +150,7 @@ const PermissionForm = memo<PermissionFormProps>(({ groupId }) => {
);
}
- const memberGroup: FormGroupItemType | undefined = sections.showAccessCard
+ const memberGroup: FormGroupItem | undefined = sections.showAccessCard
? {
children: [
{
@@ -209,7 +210,7 @@ const PermissionForm = memo<PermissionFormProps>(({ groupId }) => {
// Both rows write to the supervisor agent. Until group detail resolves one
// there is no row to write to, so the whole card waits rather than offering
// controls whose save would silently target nothing.
- const configGroup: FormGroupItemType | undefined = sections.showConfigCard
+ const configGroup: FormGroupItem | undefined = sections.showConfigCard
? {
children: [
{
@@ -275,6 +276,7 @@ const PermissionForm = memo<PermissionFormProps>(({ groupId }) => {
) : null}
<Form
collapsible={false}
+ form={form}
items={[...(memberGroup ? [memberGroup] : []), ...(configGroup ? [configGroup] : [])]}
itemsType={'group'}
variant={'filled'}
diff --git a/src/features/MCP/MCPInstallProgress/MCPConfigForm.tsx b/src/features/MCP/MCPInstallProgress/MCPConfigForm.tsx
index 922c861eecf..55433bd1227 100644
--- a/src/features/MCP/MCPInstallProgress/MCPConfigForm.tsx
+++ b/src/features/MCP/MCPInstallProgress/MCPConfigForm.tsx
@@ -1,6 +1,6 @@
-import { Flexbox, Form, Markdown } from '@lobehub/ui';
+import { Flexbox, Markdown } from '@lobehub/ui';
import { Button } from '@lobehub/ui/base-ui';
-import { Form as AForm } from 'antd';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import { createStaticStyles } from 'antd-style';
import * as m from 'motion/react-m';
import { memo, useState } from 'react';
@@ -44,7 +44,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const MCPConfigForm = memo<MCPConfigFormProps>(({ configSchema, identifier, onCancel }) => {
const { t } = useTranslation(['plugin', 'common']);
- const [form] = AForm.useForm();
const [loading, setLoading] = useState(false);
const { installMCPPlugin } = useToolStore();
@@ -62,6 +61,8 @@ const MCPConfigForm = memo<MCPConfigFormProps>(({ configSchema, identifier, onCa
}
};
+ const form = useForm<Record<string, any>>({ onSubmit: handleSubmit });
+
const handleCancel = () => {
if (onCancel) {
onCancel();
@@ -119,14 +120,11 @@ const MCPConfigForm = memo<MCPConfigFormProps>(({ configSchema, identifier, onCa
{item.desc as string}
</Markdown>
),
- key: item.label,
label: item.label,
name: item.name,
- rules: [{ required: true }],
+ required: true,
tag: item.tag,
- valuePropName: item.type === 'boolean' ? 'checked' : undefined,
}))}
- onFinish={handleSubmit}
/>
</m.div>
diff --git a/src/features/MCP/MCPSettings/index.tsx b/src/features/MCP/MCPSettings/index.tsx
index 41af5b54e1a..86ec6c7faa3 100644
--- a/src/features/MCP/MCPSettings/index.tsx
+++ b/src/features/MCP/MCPSettings/index.tsx
@@ -1,6 +1,6 @@
import { Flexbox, Icon } from '@lobehub/ui';
import { Button, Input, Text, toast } from '@lobehub/ui/base-ui';
-import { Form as AForm } from 'antd';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import { createStaticStyles } from 'antd-style';
import { EditIcon, LinkIcon, Settings2Icon, TerminalIcon } from 'lucide-react';
import { useImperativeHandle, useState } from 'react';
@@ -13,21 +13,6 @@ import { useToolStore } from '@/store/tool';
import { pluginSelectors } from '@/store/tool/selectors';
const styles = createStaticStyles(({ css, cssVar }) => ({
- compactForm: css`
- .ant-form-item {
- margin-block-end: ${cssVar.marginSM};
- }
-
- .ant-form-item-label {
- padding-block-end: ${cssVar.paddingXXS};
-
- label {
- height: auto;
- font-size: ${cssVar.fontSizeSM};
- }
- }
- `,
-
configFormContainer: css`
padding: ${cssVar.paddingLG};
border: 1px solid ${cssVar.colorBorder};
@@ -154,6 +139,16 @@ export interface SettingsRef {
save: () => Promise<void>;
}
+interface ConnectionValues {
+ args?: string[];
+ command?: string;
+ url?: string;
+}
+
+interface EnvValues {
+ env?: Record<string, string>;
+}
+
interface SettingsProps {
hideFooter?: boolean;
identifier: string;
@@ -165,8 +160,6 @@ const Settings = ({
hideFooter,
}: SettingsProps & { ref?: React.RefObject<SettingsRef | null> }) => {
const { t } = useTranslation(['plugin', 'common']);
- const [connectionForm] = AForm.useForm();
- const [envForm] = AForm.useForm();
const [loading, setLoading] = useState(false);
const [connectionLoading, setConnectionLoading] = useState(false);
const [isEditingConnection, setIsEditingConnection] = useState(false);
@@ -176,32 +169,20 @@ const Settings = ({
s.updateInstallMcpPlugin,
]);
- useImperativeHandle(ref, () => ({
- reset: () => {
- connectionForm.resetFields();
- envForm.resetFields();
- setIsEditingConnection(false);
- },
- save: async () => {
- if (isEditingConnection) {
- await connectionForm.submit();
- }
- await envForm.submit();
- },
- }));
-
// Get installed plugin info
const installedPlugin = useToolStore(pluginSelectors.getInstalledPluginById(identifier));
const pluginSettings = useToolStore(pluginSelectors.getPluginSettingsById(identifier));
- if (!installedPlugin) {
- return null;
- }
-
- const customParams = installedPlugin.customParams?.mcp;
+ const customParams = installedPlugin?.customParams?.mcp;
const isStdioType = customParams?.type === 'stdio';
- const handleConnectionSubmit = async (values: any) => {
+ const getConnectionValues = (): ConnectionValues => ({
+ args: customParams?.args,
+ command: customParams?.command,
+ url: customParams?.url,
+ });
+
+ const handleConnectionSubmit = async (values: ConnectionValues) => {
setConnectionLoading(true);
try {
await updateInstallPlugin(identifier!, values);
@@ -216,12 +197,7 @@ const Settings = ({
}
};
- const handleCancelEdit = () => {
- connectionForm.resetFields();
- setIsEditingConnection(false);
- };
-
- const handleEnvSubmit = async (values: { env?: Record<string, string> }) => {
+ const handleEnvSubmit = async (values: EnvValues) => {
setLoading(true);
try {
await updatePluginSettings(identifier!, values.env || {}, { override: true });
@@ -234,6 +210,45 @@ const Settings = ({
}
};
+ const connectionForm = useForm<ConnectionValues>({
+ initialValues: getConnectionValues(),
+ onSubmit: handleConnectionSubmit,
+ });
+ const envForm = useForm<EnvValues>({
+ initialValues: { env: pluginSettings },
+ onSubmit: handleEnvSubmit,
+ });
+
+ const resetEnvForm = () => envForm.reset({ env: pluginSettings });
+
+ const handleStartEdit = () => {
+ connectionForm.reset(getConnectionValues());
+ setIsEditingConnection(true);
+ };
+
+ const handleCancelEdit = () => {
+ connectionForm.reset(getConnectionValues());
+ setIsEditingConnection(false);
+ };
+
+ useImperativeHandle(ref, () => ({
+ reset: () => {
+ connectionForm.reset(getConnectionValues());
+ resetEnvForm();
+ setIsEditingConnection(false);
+ },
+ save: async () => {
+ if (isEditingConnection) {
+ await connectionForm.submit();
+ }
+ await envForm.submit();
+ },
+ }));
+
+ if (!installedPlugin) {
+ return null;
+ }
+
return (
<Flexbox paddingBlock={8} paddingInline={12}>
<Flexbox gap={24}>
@@ -247,7 +262,7 @@ const Settings = ({
icon={<EditIcon size={12} />}
size="small"
type="text"
- onClick={() => setIsEditingConnection(true)}
+ onClick={handleStartEdit}
>
{t('settings.edit')}
</Button>
@@ -297,49 +312,40 @@ const Settings = ({
) : (
// Edit mode
<div className={styles.connectionForm}>
- <AForm
- className={styles.compactForm}
- form={connectionForm}
- initialValues={customParams}
- layout="vertical"
- onFinish={handleConnectionSubmit}
- >
+ <Form form={connectionForm} layout="vertical">
{customParams?.type === 'http' && (
- <AForm.Item
+ <Form.Field
label={t('settings.connection.url')}
name={'url'}
- rules={[{ message: t('settings.rules.urlRequired'), required: true }]}
+ required={t('settings.rules.urlRequired')}
>
<Input placeholder="https://mcp.example.com/server" size="small" />
- </AForm.Item>
+ </Form.Field>
)}
{customParams?.type === 'stdio' && (
<>
- <AForm.Item
+ <Form.Field
label={t('settings.connection.command')}
name={'command'}
- rules={[{ message: t('settings.rules.commandRequired'), required: true }]}
+ required={t('settings.rules.commandRequired')}
>
<MCPStdioCommandInput
placeholder="npx, uv, python..."
onParsedArgs={(args) => {
- const existing: string[] = connectionForm.getFieldValue('args') ?? [];
- connectionForm.setFieldValue('args', [
- ...args,
- ...existing.filter(Boolean),
- ]);
+ const existing: string[] = connectionForm.getValue('args') ?? [];
+ connectionForm.setValue('args', [...args, ...existing.filter(Boolean)]);
}}
/>
- </AForm.Item>
+ </Form.Field>
- <AForm.Item
+ <Form.Field
label={t('settings.connection.args')}
name={'args'}
- rules={[{ message: t('settings.rules.argsRequired'), required: true }]}
+ required={t('settings.rules.argsRequired')}
>
<ArgsInput placeholder="e.g: mcp-hello-world" />
- </AForm.Item>
+ </Form.Field>
</>
)}
<Flexbox horizontal className={styles.footer} gap={8}>
@@ -348,7 +354,7 @@ const Settings = ({
</Button>
<Button onClick={handleCancelEdit}>{t('common:cancel')}</Button>
</Flexbox>
- </AForm>
+ </Form>
</div>
)}
</Flexbox>
@@ -363,27 +369,22 @@ const Settings = ({
<Text style={{ fontSize: 12 }} type="secondary">
{t('settings.envConfigDescription')}
</Text>
- <AForm
- form={envForm}
- initialValues={{ env: pluginSettings }}
- layout="vertical"
- onFinish={handleEnvSubmit}
- >
- <AForm.Item name="env" style={{ marginBottom: 0 }}>
+ <Form form={envForm} layout="vertical">
+ <Form.Field bare name="env">
<KeyValueEditor
addButtonText={t('dev.mcp.env.add')}
keyPlaceholder="VARIABLE_NAME"
/>
- </AForm.Item>
+ </Form.Field>
{!hideFooter && (
<Flexbox horizontal className={styles.footer} gap={8}>
<Button htmlType="submit" loading={loading} type="primary">
{t('common:save')}
</Button>
- <Button onClick={() => envForm.resetFields()}>{t('common:reset')}</Button>
+ <Button onClick={resetEnvForm}>{t('common:reset')}</Button>
</Flexbox>
)}
- </AForm>
+ </Form>
</Flexbox>
)}
diff --git a/src/features/ModelSwitchPanel/components/ControlsForm/ControlsForm.tsx b/src/features/ModelSwitchPanel/components/ControlsForm/ControlsForm.tsx
index b491d42e115..ff963654341 100644
--- a/src/features/ModelSwitchPanel/components/ControlsForm/ControlsForm.tsx
+++ b/src/features/ModelSwitchPanel/components/ControlsForm/ControlsForm.tsx
@@ -1,8 +1,7 @@
import type { LobeAgentChatConfig } from '@lobechat/types';
-import { type FormItemProps } from '@lobehub/ui';
-import { Flexbox, Form } from '@lobehub/ui';
+import { Flexbox } from '@lobehub/ui';
import { Switch } from '@lobehub/ui/base-ui';
-import { Form as AntdForm } from 'antd';
+import { Form, type FormFieldProps, useForm, useWatch } from '@lobehub/ui/base-ui/form';
import isEqual from 'fast-deep-equal';
import { MODEL_REASONING_EXTEND_PARAMS } from 'model-bank/aiModel';
import type { ReactNode } from 'react';
@@ -128,8 +127,6 @@ const ControlsForm = memo<ControlsFormProps>(
]);
const model = modelProp ?? agentModel;
const provider = providerProp ?? agentProvider;
- const [form] = Form.useForm();
-
const storeConfig = useAgentStore(
(s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s),
isEqual,
@@ -151,12 +148,26 @@ const ControlsForm = memo<ControlsFormProps>(
};
}, [config, model]);
+ const form = useForm<LobeAgentChatConfig>({
+ initialValues,
+ onValuesChange: async (values) => {
+ if (disabled) return;
+ onUpdatingChange?.(true);
+ try {
+ await (onChatConfigChange ?? updateAgentChatConfig)(
+ values as Partial<LobeAgentChatConfig>,
+ );
+ } finally {
+ onUpdatingChange?.(false);
+ }
+ },
+ });
+
useEffect(() => {
- form.setFieldsValue(initialValues);
+ form.setValues(initialValues);
}, [form, initialValues]);
- const enableReasoningValue =
- AntdForm.useWatch(['enableReasoning'], form) ?? initialValues.enableReasoning;
+ const enableReasoningValue = useWatch(form, 'enableReasoning') ?? initialValues.enableReasoning;
const gpt52ReasoningEffortDefaultValue = model === 'gpt-5.5' ? 'medium' : 'none';
const thinkingLevelDefaultValue = resolveDefaultThinkingLevelForModel(model);
@@ -628,7 +639,7 @@ const ControlsForm = memo<ControlsFormProps>(
paddingBottom: 0,
},
},
- ].filter(Boolean) as FormItemProps[];
+ ].filter(Boolean) as FormFieldProps<LobeAgentChatConfig>[];
return (
<div
@@ -639,26 +650,15 @@ const ControlsForm = memo<ControlsFormProps>(
>
<Form
form={form}
- initialValues={initialValues}
itemsType={'flat'}
- size={'small'}
style={{ fontSize: 12 }}
variant={'borderless'}
items={
(modelExtendParams || [])
.filter((item: any) => !(hideReasoningParams && REASONING_PARAMS_SET.has(item)))
.map((item: any) => items.find((i) => i.name === item))
- .filter(Boolean) as FormItemProps[]
+ .filter(Boolean) as FormFieldProps<LobeAgentChatConfig>[]
}
- onValuesChange={async (values) => {
- if (disabled) return;
- onUpdatingChange?.(true);
- try {
- await (onChatConfigChange ?? updateAgentChatConfig)(values);
- } finally {
- onUpdatingChange?.(false);
- }
- }}
/>
</div>
);
diff --git a/src/features/ModelSwitchPanel/components/ControlsForm/__tests__/ControlsForm.test.tsx b/src/features/ModelSwitchPanel/components/ControlsForm/__tests__/ControlsForm.test.tsx
index 89f55566056..2980502c2b8 100644
--- a/src/features/ModelSwitchPanel/components/ControlsForm/__tests__/ControlsForm.test.tsx
+++ b/src/features/ModelSwitchPanel/components/ControlsForm/__tests__/ControlsForm.test.tsx
@@ -23,28 +23,16 @@ const testState = vi.hoisted(() => ({
aiState: {
extendParams: ['enableReasoning'],
} as TestAiState,
- setFieldsValue: vi.fn(),
+ setValues: vi.fn(),
updateAgentChatConfig: vi.fn(),
}));
-vi.mock('@lobehub/ui', async (importOriginal) => {
- const MockForm = () => <div data-testid="controls-form" />;
- MockForm.useForm = () => [{ setFieldsValue: testState.setFieldsValue }];
-
- return {
- ...(await importOriginal<object>()),
- Form: MockForm,
- };
-});
-
-vi.mock('antd', async (importOriginal) => {
- const antd = await importOriginal<{ Form: object }>();
-
- return {
- ...antd,
- Form: { ...antd.Form, useWatch: vi.fn(() => undefined) },
- };
-});
+vi.mock('@lobehub/ui/base-ui/form', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ Form: () => <div data-testid="controls-form" />,
+ useForm: () => ({ setValues: testState.setValues }),
+ useWatch: vi.fn(() => undefined),
+}));
vi.mock('react-i18next', () => {
return {
@@ -102,7 +90,7 @@ describe('ControlsForm', () => {
const { unmount } = render(<ControlsForm model="gpt-4" provider="openai" />);
- expect(testState.setFieldsValue).toHaveBeenLastCalledWith({
+ expect(testState.setValues).toHaveBeenLastCalledWith({
enableReasoning: false,
thinking: 'disabled',
});
@@ -116,7 +104,7 @@ describe('ControlsForm', () => {
render(<ControlsForm model="gpt-4" provider="openai" />);
- expect(testState.setFieldsValue).toHaveBeenLastCalledWith({
+ expect(testState.setValues).toHaveBeenLastCalledWith({
enableReasoning: true,
thinking: 'enabled',
});
@@ -128,7 +116,7 @@ describe('ControlsForm', () => {
render(<ControlsForm model="claude-sonnet-5" provider="lobehub" />);
- expect(testState.setFieldsValue).toHaveBeenLastCalledWith(
+ expect(testState.setValues).toHaveBeenLastCalledWith(
expect.objectContaining({
enableAdaptiveThinking: true,
}),
@@ -144,7 +132,7 @@ describe('ControlsForm', () => {
render(<ControlsForm model="claude-sonnet-5" provider="lobehub" />);
- expect(testState.setFieldsValue).toHaveBeenLastCalledWith(
+ expect(testState.setValues).toHaveBeenLastCalledWith(
expect.objectContaining({
enableAdaptiveThinking: false,
}),
diff --git a/src/features/PluginDevModal/MCPManifestForm/QuickImportSection.tsx b/src/features/PluginDevModal/MCPManifestForm/QuickImportSection.tsx
index 50238d6699a..db12c5ab751 100644
--- a/src/features/PluginDevModal/MCPManifestForm/QuickImportSection.tsx
+++ b/src/features/PluginDevModal/MCPManifestForm/QuickImportSection.tsx
@@ -1,6 +1,7 @@
+import { type LobeToolCustomPlugin } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
import { Alert, Button, TextArea } from '@lobehub/ui/base-ui';
-import { type FormInstance } from 'antd';
+import { type FormInstance } from '@lobehub/ui/base-ui/form';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -12,7 +13,7 @@ import { electronStylish } from '@/styles/electron';
import { parseMcpInput } from './utils';
interface QuickImportSectionProps {
- form: FormInstance;
+ form: FormInstance<LobeToolCustomPlugin>;
isEditMode?: boolean;
onClearConnectionError?: () => void;
}
@@ -66,25 +67,25 @@ const QuickImportSection = ({
// Check for duplicate identifier (only in create mode)
if (!isEditMode && pluginIds.includes(identifier)) {
// Update form fields even if duplicate, so user sees the pasted values
- form.setFieldsValue({
+ form.setValues({
customParams: { mcp: mcpConfig },
identifier,
});
// Trigger validation to show Form.Item error
- form.validateFields(['identifier']);
+ form.validate(['identifier']);
setIsImportModalVisible(false); // Close modal even on duplicate error
setJsonInput(''); // Clear modal input
return;
}
// All checks passed, fill the form
- form.setFieldsValue({
+ form.setValues({
customParams: { mcp: mcpConfig },
identifier,
});
// Clear potential old validation error on identifier field
- form.setFields([{ errors: [], name: 'identifier' }]);
+ form.setErrors({ identifier: undefined });
// Clear modal state and close (or rather, hide the import UI)
setIsImportModalVisible(false);
diff --git a/src/features/PluginDevModal/MCPManifestForm/index.tsx b/src/features/PluginDevModal/MCPManifestForm/index.tsx
index a07899e3780..38a4a1b1dcf 100644
--- a/src/features/PluginDevModal/MCPManifestForm/index.tsx
+++ b/src/features/PluginDevModal/MCPManifestForm/index.tsx
@@ -1,7 +1,7 @@
-import { Flexbox, FormItem } from '@lobehub/ui';
+import { type LobeToolCustomPlugin } from '@lobechat/types';
+import { Flexbox } from '@lobehub/ui';
import { Alert, Button, Divider, Input, InputPassword, RadioGroup } from '@lobehub/ui/base-ui';
-import { type FormInstance } from 'antd';
-import { Form } from 'antd';
+import { type FieldPath, Form, type FormInstance, useWatch } from '@lobehub/ui/base-ui/form';
import isEqual from 'fast-deep-equal';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -12,7 +12,7 @@ import ErrorDetails from '@/features/MCP/MCPInstallProgress/InstallError/ErrorDe
import { lambdaClient } from '@/libs/trpc/client';
import { useToolStore } from '@/store/tool';
import { mcpStoreSelectors, pluginSelectors } from '@/store/tool/selectors';
-import { type MCPErrorInfoMetadata } from '@/types/plugins';
+import { type McpConnectionParams, type MCPErrorInfoMetadata } from '@/types/plugins';
import ArgsInput from './ArgsInput';
import CollapsibleSection from './CollapsibleSection';
@@ -26,7 +26,7 @@ interface MCPManifestFormProps {
* the plain custom-plugin DevModal callers (editing plugins, agent tools, …).
*/
enableOAuth?: boolean;
- form: FormInstance;
+ form: FormInstance<LobeToolCustomPlugin>;
isEditMode?: boolean;
/**
* Run the connector OAuth authorize flow. Called instead of the token-less
@@ -36,19 +36,19 @@ interface MCPManifestFormProps {
onAuthorizeOAuth?: () => void;
}
-const HTTP_URL_KEY = ['customParams', 'mcp', 'url'];
-const STDIO_COMMAND = ['customParams', 'mcp', 'command'];
-const STDIO_ARGS = ['customParams', 'mcp', 'args'];
-const STDIO_ENV = ['customParams', 'mcp', 'env'];
-const MCP_TYPE = ['customParams', 'mcp', 'type'];
-const DESC_TYPE = ['customParams', 'description'];
+const HTTP_URL_KEY = 'customParams.mcp.url';
+const STDIO_COMMAND = 'customParams.mcp.command';
+const STDIO_ARGS = 'customParams.mcp.args';
+const STDIO_ENV = 'customParams.mcp.env';
+const MCP_TYPE = 'customParams.mcp.type';
+const DESC_TYPE = 'customParams.description';
// Authentication-related constants
-const AUTH_TYPE = ['customParams', 'mcp', 'auth', 'type'];
-const AUTH_TOKEN = ['customParams', 'mcp', 'auth', 'token'];
-const AUTH_CLIENT_ID = ['customParams', 'mcp', 'auth', 'clientId'];
-const AUTH_CLIENT_SECRET = ['customParams', 'mcp', 'auth', 'clientSecret'];
+const AUTH_TYPE = 'customParams.mcp.auth.type';
+const AUTH_TOKEN = 'customParams.mcp.auth.token';
+const AUTH_CLIENT_ID = 'customParams.mcp.auth.clientId';
+const AUTH_CLIENT_SECRET = 'customParams.mcp.auth.clientSecret';
// Headers-related constants
-const HEADERS = ['customParams', 'mcp', 'headers'];
+const HEADERS = 'customParams.mcp.headers';
const MCPManifestForm = ({
form,
@@ -57,8 +57,8 @@ const MCPManifestForm = ({
onAuthorizeOAuth,
}: MCPManifestFormProps) => {
const { t } = useTranslation('plugin');
- const mcpType = Form.useWatch(MCP_TYPE, form);
- const authType = Form.useWatch(AUTH_TYPE, form);
+ const mcpType = useWatch(form, MCP_TYPE);
+ const authType = useWatch(form, AUTH_TYPE);
// For OAuth servers there is no token to test with — "testing" the connection
// means running the authorize flow instead.
const isOAuth = enableOAuth && mcpType === 'http' && authType === 'oauth2';
@@ -84,8 +84,7 @@ const MCPManifestForm = ({
const testMcpConnection = useToolStore((s) => s.testMcpConnection);
// Use identifier to track test state (if present in the form)
- const formValues = form.getFieldsValue();
- const identifier = formValues?.identifier || 'temp-test-id';
+ const identifier = form.getValue('identifier') || 'temp-test-id';
const testState = useToolStore(mcpStoreSelectors.getMCPConnectionTestState(identifier), isEqual);
const [connectionError, setConnectionError] = useState<string | null>(null);
@@ -97,34 +96,27 @@ const MCPManifestForm = ({
setErrorMetadata(null);
// Manually trigger validation for fields needed for the test
- let isValid = false;
- try {
- const fieldsToValidate = [
- ...(mcpType === 'http' ? [HTTP_URL_KEY] : [STDIO_COMMAND, STDIO_ARGS]),
- ];
+ const fieldsToValidate: FieldPath<LobeToolCustomPlugin>[] =
+ mcpType === 'http' ? [HTTP_URL_KEY] : [STDIO_COMMAND, STDIO_ARGS];
- // For HTTP type, also validate authentication fields
- if (mcpType === 'http') {
- fieldsToValidate.push(AUTH_TYPE);
- const currentAuthType = form.getFieldValue(AUTH_TYPE);
- if (currentAuthType === 'bearer') {
- fieldsToValidate.push(AUTH_TOKEN);
- }
+ // For HTTP type, also validate authentication fields
+ if (mcpType === 'http') {
+ fieldsToValidate.push(AUTH_TYPE);
+ const currentAuthType = form.getValue(AUTH_TYPE);
+ if (currentAuthType === 'bearer') {
+ fieldsToValidate.push(AUTH_TOKEN);
}
-
- await form.validateFields(fieldsToValidate);
- isValid = true;
- } catch {
- // no-thing
}
- if (!isValid) {
+ const { valid } = await form.validate(fieldsToValidate);
+
+ if (!valid) {
setIsTesting(false);
return;
}
try {
- const values = form.getFieldsValue();
+ const values = form.getValues();
const id = values.identifier;
const mcp = values.customParams?.mcp;
const description = values.customParams?.description;
@@ -132,7 +124,7 @@ const MCPManifestForm = ({
// Use mcpStore's testMcpConnection method
const result = await testMcpConnection({
- connection: mcp,
+ connection: mcp as McpConnectionParams['connection'],
identifier: id,
metadata: { avatar, description },
});
@@ -140,7 +132,7 @@ const MCPManifestForm = ({
if (result.success && result.manifest) {
// Optionally update form if manifest ID differs or to store the fetched manifest
// Be careful about overwriting user input if not desired
- form.setFieldsValue({ manifest: result.manifest });
+ form.setValues({ manifest: result.manifest });
setConnectionError(null); // Clear local error state
setErrorMetadata(null);
} else if (result.error) {
@@ -190,66 +182,45 @@ const MCPManifestForm = ({
/>
<Form form={form} layout={'vertical'}>
<Flexbox>
- <Form.Item
- initialValue={'http'}
- label={t('dev.mcp.type.title')}
- name={['customParams', 'mcp', 'type']}
- rules={[{ required: true }]}
- >
+ <Form.Field required label={t('dev.mcp.type.title')} name={MCP_TYPE}>
<MCPTypeSelect />
- </Form.Item>
- <FormItem
+ </Form.Field>
+ <Form.Field
desc={t('dev.mcp.identifier.desc')}
label={t('dev.mcp.identifier.label')}
name={'identifier'}
+ required={t('dev.mcp.identifier.required')}
tag={'identifier'}
- rules={[
- { message: t('dev.mcp.identifier.required'), required: true },
- {
- message: t('dev.mcp.identifier.invalid'),
- pattern: /^[\w-]+$/,
- },
- isEditMode
- ? {}
- : {
- message: t('dev.meta.identifier.errorDuplicate'),
- validator: async () => {
- const id = form.getFieldValue('identifier');
- if (!id) return true;
- if (pluginIds.includes(id)) {
- throw new Error('Duplicate');
- }
- },
- },
- ]}
+ validate={(value?: string) => {
+ if (!value) return;
+ if (!/^[\w-]+$/.test(value)) return t('dev.mcp.identifier.invalid');
+ if (!isEditMode && pluginIds.includes(value))
+ return t('dev.meta.identifier.errorDuplicate');
+ }}
>
<Input placeholder={t('dev.mcp.identifier.placeholder')} />
- </FormItem>
+ </Form.Field>
{mcpType === 'http' && (
<>
- <FormItem
+ <Form.Field
desc={t('dev.mcp.url.desc')}
label={t('dev.mcp.url.label')}
name={HTTP_URL_KEY}
+ required={t('dev.mcp.url.required')}
tag={'url'}
- rules={[
- { message: t('dev.mcp.url.required'), required: true },
- {
- message: t('dev.mcp.url.invalid'),
- validator: async (_, value) => {
- if (!value) return true;
-
- // Throws automatically if the value is not a valid URL
- new URL(value);
- },
- },
- ]}
+ validate={(value?: string) => {
+ if (!value) return;
+ try {
+ new URL(value);
+ } catch {
+ return t('dev.mcp.url.invalid');
+ }
+ }}
>
<Input placeholder="https://mcp.higress.ai/mcp-github/xxxxx" />
- </FormItem>
- <FormItem
+ </Form.Field>
+ <Form.Field
desc={t('dev.mcp.auth.desc')}
- initialValue={'none'}
label={t('dev.mcp.auth.label')}
name={AUTH_TYPE}
>
@@ -274,30 +245,30 @@ const MCPManifestForm = ({
: []),
]}
/>
- </FormItem>
+ </Form.Field>
{authType === 'bearer' && (
- <FormItem
+ <Form.Field
desc={t('dev.mcp.auth.token.desc')}
label={t('dev.mcp.auth.token.label')}
name={AUTH_TOKEN}
- rules={[{ message: t('dev.mcp.auth.token.required'), required: true }]}
+ required={t('dev.mcp.auth.token.required')}
>
<InputPassword
autoComplete="new-password"
placeholder={t('dev.mcp.auth.token.placeholder')}
/>
- </FormItem>
+ </Form.Field>
)}
{enableOAuth && authType === 'oauth2' && (
<>
- <FormItem
+ <Form.Field
desc={t('dev.mcp.auth.oauth.clientId.desc')}
label={t('dev.mcp.auth.oauth.clientId.label')}
name={AUTH_CLIENT_ID}
>
<Input placeholder={t('dev.mcp.auth.oauth.clientId.placeholder')} />
- </FormItem>
- <FormItem
+ </Form.Field>
+ <Form.Field
desc={t('dev.mcp.auth.oauth.clientSecret.desc')}
label={t('dev.mcp.auth.oauth.clientSecret.label')}
name={AUTH_CLIENT_SECRET}
@@ -306,7 +277,7 @@ const MCPManifestForm = ({
autoComplete="new-password"
placeholder={t('dev.mcp.auth.oauth.clientSecret.placeholder')}
/>
- </FormItem>
+ </Form.Field>
<div
style={{
color: 'var(--lobe-colors-textDescription)',
@@ -321,43 +292,43 @@ const MCPManifestForm = ({
</>
)}
<CollapsibleSection title={t('dev.mcp.advanced.title')}>
- <FormItem
+ <Form.Field
desc={t('dev.mcp.headers.desc')}
label={t('dev.mcp.headers.label')}
name={HEADERS}
>
<KeyValueEditor addButtonText={t('dev.mcp.headers.add')} />
- </FormItem>
+ </Form.Field>
</CollapsibleSection>
</>
)}
{mcpType === 'stdio' && (
<>
- <FormItem
+ <Form.Field
desc={t('dev.mcp.command.desc')}
label={t('dev.mcp.command.label')}
name={STDIO_COMMAND}
- rules={[{ message: t('dev.mcp.command.required'), required: true }]}
+ required={t('dev.mcp.command.required')}
tag={'command'}
>
<MCPStdioCommandInput
placeholder={t('dev.mcp.command.placeholder')}
onParsedArgs={(args) => {
- const existing: string[] = form.getFieldValue(STDIO_ARGS) ?? [];
- form.setFieldValue(STDIO_ARGS, [...args, ...existing.filter(Boolean)]);
+ const existing = form.getValue(STDIO_ARGS) ?? [];
+ form.setValue(STDIO_ARGS, [...args, ...existing.filter(Boolean)]);
}}
/>
- </FormItem>
- <FormItem
+ </Form.Field>
+ <Form.Field
desc={t('dev.mcp.args.desc')}
label={t('dev.mcp.args.label')}
name={STDIO_ARGS}
- rules={[{ message: t('dev.mcp.args.required'), required: true }]}
+ required={t('dev.mcp.args.required')}
tag={'args'}
>
<ArgsInput placeholder={t('dev.mcp.args.placeholder')} />
- </FormItem>
- <FormItem
+ </Form.Field>
+ <Form.Field
extra={t('dev.mcp.env.desc')}
label={t('dev.mcp.env.label')}
name={STDIO_ENV}
@@ -367,10 +338,10 @@ const MCPManifestForm = ({
addButtonText={t('dev.mcp.env.add')}
keyPlaceholder="VARIABLE_NAME"
/>
- </FormItem>
+ </Form.Field>
</>
)}
- <FormItem colon={false} label={t('dev.mcp.testConnectionTip')} layout={'horizontal'}>
+ <Form.Field label={t('dev.mcp.testConnectionTip')} layout={'horizontal'}>
<Flexbox horizontal align={'center'} gap={8} justify={'flex-end'}>
<Button
loading={isTesting}
@@ -380,7 +351,7 @@ const MCPManifestForm = ({
{isOAuth ? t('dev.mcp.auth.oauth.authorize') : t('dev.mcp.testConnection')}
</Button>
</Flexbox>
- </FormItem>
+ </Form.Field>
{(connectionError || testState.error) && (
<Alert
closable
@@ -394,23 +365,18 @@ const MCPManifestForm = ({
}}
/>
)}
- <FormItem noStyle name={'manifest'} />
<Divider style={{ marginBlock: 24 }} />
- <FormItem
+ <Form.Field
desc={t('dev.mcp.desc.desc')}
label={t('dev.mcp.desc.label')}
name={DESC_TYPE}
tag={'description'}
>
<Input placeholder={t('dev.mcp.desc.placeholder')} />
- </FormItem>
- <FormItem
- label={t('dev.mcp.avatar.label')}
- name={['customParams', 'avatar']}
- tag={'avatar'}
- >
+ </Form.Field>
+ <Form.Field label={t('dev.mcp.avatar.label')} name={'customParams.avatar'} tag={'avatar'}>
<Input placeholder={'https://plugin-avatar.com'} />
- </FormItem>
+ </Form.Field>
</Flexbox>
</Form>
</>
diff --git a/src/features/PluginDevModal/PluginPreview/index.tsx b/src/features/PluginDevModal/PluginPreview/index.tsx
index 67423158c2b..a45385648ba 100644
--- a/src/features/PluginDevModal/PluginPreview/index.tsx
+++ b/src/features/PluginDevModal/PluginPreview/index.tsx
@@ -1,8 +1,7 @@
-import { type ToolManifest } from '@lobechat/types';
+import { type LobeToolCustomPlugin } from '@lobechat/types';
import { Block, Flexbox, Icon } from '@lobehub/ui';
import { Button, Text } from '@lobehub/ui/base-ui';
-import { type FormInstance } from 'antd';
-import { Form as AForm } from 'antd';
+import { type FormInstance, useWatch } from '@lobehub/ui/base-ui/form';
import { cssVar } from 'antd-style';
import { FileCode } from 'lucide-react';
import { memo } from 'react';
@@ -16,9 +15,9 @@ import { pluginHelpers } from '@/store/tool';
import ApiVisualizer from './ApiVisualizer';
import PluginEmptyState from './EmptyState';
-const PluginPreview = memo<{ form: FormInstance }>(({ form }) => {
+const PluginPreview = memo<{ form: FormInstance<LobeToolCustomPlugin> }>(({ form }) => {
const { t } = useTranslation('plugin');
- const manifest: ToolManifest = AForm.useWatch(['manifest'], form);
+ const manifest = useWatch(form, 'manifest');
const meta = manifest?.meta;
if (!manifest)
diff --git a/src/features/PluginDevModal/index.tsx b/src/features/PluginDevModal/index.tsx
index ae3028ddc4d..77ba940d6d6 100644
--- a/src/features/PluginDevModal/index.tsx
+++ b/src/features/PluginDevModal/index.tsx
@@ -3,7 +3,7 @@ import { TITLE_BAR_HEIGHT } from '@lobechat/desktop-bridge';
import { type LobeToolCustomPlugin } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
import { Button, confirmModal, Drawer, toast } from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { useForm, useWatch } from '@lobehub/ui/base-ui/form';
import { useResponsive } from 'antd-style';
import { memo, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -14,6 +14,10 @@ import MCPManifestForm from './MCPManifestForm';
import PluginPreview from './PluginPreview';
import { getSaveErrorToast } from './saveErrorToast';
+const INITIAL_VALUES = {
+ customParams: { mcp: { auth: { type: 'none' }, type: 'http' } },
+} as LobeToolCustomPlugin;
+
interface DevModalProps {
/** Enable the connector-backed OAuth auth type in the MCP form (see MCPManifestForm). */
enableOAuth?: boolean;
@@ -46,8 +50,16 @@ const DevModal = memo<DevModalProps>(
const [submitting, setSubmitting] = useState(false);
const { mobile } = useResponsive();
- const [form] = Form.useForm();
- const authType = Form.useWatch(['customParams', 'mcp', 'auth', 'type'], form);
+ const form = useForm<LobeToolCustomPlugin>({
+ initialValues: INITIAL_VALUES,
+ onSubmit: async (values) => {
+ await doSave(values);
+ },
+ onValuesChange: (_, values) => {
+ onValueChange?.(values);
+ },
+ });
+ const authType = useWatch(form, 'customParams.mcp.auth.type');
// Seed the form once per modal open, waiting for `value` to arrive (it may
// be undefined initially while edit-mode credentials are being fetched).
@@ -58,7 +70,7 @@ const DevModal = memo<DevModalProps>(
return;
}
if (value !== undefined && !seededRef.current) {
- form.setFieldsValue(value);
+ form.setValues(value);
seededRef.current = true;
}
}, [open, value]);
@@ -102,12 +114,12 @@ const DevModal = memo<DevModalProps>(
toast.error(t('dev.oauthError.blocked'));
return;
}
- try {
- const values = (await form.validateFields()) as LobeToolCustomPlugin;
- await doSave(values, { oauthPopup: popup });
- } catch {
+ const { valid } = await form.validate();
+ if (!valid) {
popup?.close();
+ return;
}
+ await doSave(form.getValues(), { oauthPopup: popup });
};
const handlePrimaryClick = () => {
@@ -116,7 +128,7 @@ const DevModal = memo<DevModalProps>(
};
useEffect(() => {
- if (mode === 'create' && !open) form.resetFields();
+ if (mode === 'create' && !open) form.reset(INITIAL_VALUES);
}, [open]);
const buttonStyle = mobile ? { flex: 1 } : { margin: 0 };
@@ -168,53 +180,44 @@ const DevModal = memo<DevModalProps>(
);
return (
- <Form.Provider
- onFormChange={() => {
- onValueChange?.(form.getFieldsValue());
+ <Drawer
+ containerMaxWidth={'auto'}
+ footer={footer}
+ height={isDesktop ? `calc(100vh - ${TITLE_BAR_HEIGHT}px)` : '100vh'}
+ open={open}
+ placement={'bottom'}
+ push={false}
+ title={t(isEditMode ? 'dev.title.skillSettings' : 'dev.title.create')}
+ width={mobile ? '100%' : 800}
+ styles={{
+ bodyContent: {
+ height: '100%',
+ padding: 0,
+ },
}}
- onFormFinish={async (_, info) => {
- await doSave(info.values as LobeToolCustomPlugin);
+ onClose={() => {
+ onOpenChange(false);
}}
>
- <Drawer
- containerMaxWidth={'auto'}
- footer={footer}
- height={isDesktop ? `calc(100vh - ${TITLE_BAR_HEIGHT}px)` : '100vh'}
- open={open}
- placement={'bottom'}
- push={false}
- title={t(isEditMode ? 'dev.title.skillSettings' : 'dev.title.create')}
- width={mobile ? '100%' : 800}
- styles={{
- bodyContent: {
- height: '100%',
- padding: 0,
- },
- }}
- onClose={() => {
- onOpenChange(false);
+ <Flexbox
+ horizontal
+ gap={0}
+ height={'100%'}
+ onClick={(e) => {
+ e.stopPropagation();
}}
>
- <Flexbox
- horizontal
- gap={0}
- height={'100%'}
- onClick={(e) => {
- e.stopPropagation();
- }}
- >
- <Flexbox flex={3} gap={16} padding={24} style={{ overflowY: 'auto' }}>
- <MCPManifestForm
- enableOAuth={enableOAuth}
- form={form}
- isEditMode={isEditMode}
- onAuthorizeOAuth={runOAuthFlow}
- />
- </Flexbox>
- <PluginPreview form={form} />
+ <Flexbox flex={3} gap={16} padding={24} style={{ overflowY: 'auto' }}>
+ <MCPManifestForm
+ enableOAuth={enableOAuth}
+ form={form}
+ isEditMode={isEditMode}
+ onAuthorizeOAuth={runOAuthFlow}
+ />
</Flexbox>
- </Drawer>
- </Form.Provider>
+ <PluginPreview form={form} />
+ </Flexbox>
+ </Drawer>
);
},
);
diff --git a/src/features/PluginSettings/index.tsx b/src/features/PluginSettings/index.tsx
index d1b04278c44..13cacddbcc9 100644
--- a/src/features/PluginSettings/index.tsx
+++ b/src/features/PluginSettings/index.tsx
@@ -1,6 +1,6 @@
import { type ToolManifestSettings } from '@lobechat/types';
-import { Form, Markdown } from '@lobehub/ui';
-import { Form as AForm } from 'antd';
+import { Markdown } from '@lobehub/ui';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import { createStaticStyles } from 'antd-style';
import isEqual from 'fast-deep-equal';
import { memo } from 'react';
@@ -43,7 +43,12 @@ const PluginSettingsConfig = memo<PluginSettingsConfigProps>(({ schema, id }) =>
const [updatePluginSettings] = useToolStore((s) => [s.updatePluginSettings]);
const pluginSetting = useToolStore(pluginSelectors.getPluginSettingsById(id), isEqual);
- const [form] = AForm.useForm();
+ const form = useForm({
+ initialValues: pluginSetting,
+ onSubmit: async (v) => {
+ await updatePluginSettings(id, v);
+ },
+ });
const items = transformPluginSettings(schema);
@@ -52,7 +57,6 @@ const PluginSettingsConfig = memo<PluginSettingsConfigProps>(({ schema, id }) =>
footer={<Form.SubmitFooter />}
form={form}
gap={16}
- initialValues={pluginSetting}
itemsType={'flat'}
layout={'vertical'}
variant={'borderless'}
@@ -71,15 +75,10 @@ const PluginSettingsConfig = memo<PluginSettingsConfigProps>(({ schema, id }) =>
{item.desc as string}
</Markdown>
),
- key: item.label,
label: item.label,
name: item.name,
tag: item.tag,
- valuePropName: item.type === 'boolean' ? 'checked' : undefined,
}))}
- onFinish={async (v) => {
- await updatePluginSettings(id, v);
- }}
/>
);
});
diff --git a/src/features/ResourcePermission/ResourceAccessPage.tsx b/src/features/ResourcePermission/ResourceAccessPage.tsx
index 98aa3af8c72..2b071313c96 100644
--- a/src/features/ResourcePermission/ResourceAccessPage.tsx
+++ b/src/features/ResourcePermission/ResourceAccessPage.tsx
@@ -1,8 +1,8 @@
'use client';
-import type { FormGroupItemType } from '@lobehub/ui';
-import { Flexbox, Form, Icon } from '@lobehub/ui';
+import { Flexbox, Icon } from '@lobehub/ui';
import { Alert, Breadcrumb, Text, toast } from '@lobehub/ui/base-ui';
+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import { createStaticStyles } from 'antd-style';
import { ChevronRight, InfoIcon, UsersIcon } from 'lucide-react';
import { memo, useEffect } from 'react';
@@ -105,6 +105,7 @@ const ResourceAccessPage = memo<ResourceAccessPageProps>(
isPrivate,
resourceType,
});
+ const form = useForm();
// Managing member access is a manager-only surface, like Agent's page: a
// non-manager (or a private resource that is not the caller's) gets a
@@ -117,7 +118,7 @@ const ResourceAccessPage = memo<ResourceAccessPageProps>(
navigate(redirectPath, { replace: true });
}, [isDenied, navigate, redirectPath, t]);
- const accessGroup: FormGroupItemType = {
+ const accessGroup: FormGroupItem = {
children: [
{
avatar: (
@@ -140,7 +141,7 @@ const ResourceAccessPage = memo<ResourceAccessPageProps>(
title: t('permission.page.memberGroup'),
};
- const formGroups: FormGroupItemType[] = [accessGroup];
+ const formGroups: FormGroupItem[] = [accessGroup];
if (showCollaborators) {
formGroups.push({
children: <CollaboratorList resourceId={resourceId} resourceType={resourceType} />,
@@ -206,7 +207,7 @@ const ResourceAccessPage = memo<ResourceAccessPageProps>(
type={'info'}
/>
) : null}
- <Form items={formGroups} itemsType={'group'} {...FORM_STYLE} />
+ <Form form={form} items={formGroups} itemsType={'group'} {...FORM_STYLE} />
</>
)}
</Flexbox>
diff --git a/src/features/ServiceModel/ModelAssignmentsForm.tsx b/src/features/ServiceModel/ModelAssignmentsForm.tsx
index 8f23c5fb144..9b399569493 100644
--- a/src/features/ServiceModel/ModelAssignmentsForm.tsx
+++ b/src/features/ServiceModel/ModelAssignmentsForm.tsx
@@ -1,8 +1,8 @@
'use client';
-import type { FormGroupItemType, FormItemProps } from '@lobehub/ui';
-import { Flexbox, Form, Tooltip } from '@lobehub/ui';
+import { Flexbox, Tooltip } from '@lobehub/ui';
import { InputNumber, Switch, TextArea } from '@lobehub/ui/base-ui';
+import { Form, type FormFieldProps, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import isEqual from 'fast-deep-equal';
import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -19,8 +19,6 @@ import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
import type { SystemAgentItem, UserServiceModelConfigKey } from '@/types/user/settings';
-import { serviceModelFormStyles as styles } from './styles';
-
type ModelAssignmentItemKey = Exclude<
UserServiceModelConfigKey,
'asr' | 'onboardingTaskRecommender' | 'onboardingUnderstanding'
@@ -84,6 +82,7 @@ const ModelAssignmentsForm = memo(() => {
// shared save-state — the write-side counterpart to the read-side AsyncError above.
const [savingGroup, setSavingGroup] = useState<SavingGroup>();
const { status: saveStatus, lastSavedAt, save, retry } = useSaveState();
+ const form = useForm();
useEffect(() => {
if (loadingKey === 'defaultAgent') setLoadingKey(undefined);
@@ -141,8 +140,7 @@ const ModelAssignmentsForm = memo(() => {
}
};
- const defaultAgentItem: FormItemProps = {
- className: styles.centeredLabel,
+ const defaultAgentItem: FormFieldProps = {
children: (
<Tooltip title={reason}>
<Flexbox
@@ -167,11 +165,10 @@ const ModelAssignmentsForm = memo(() => {
label: t('defaultAgent.title'),
};
- const systemModelItems: FormItemProps[] = SYSTEM_AGENT_MODEL_ITEMS.map(({ key }) => {
+ const systemModelItems: FormFieldProps[] = SYSTEM_AGENT_MODEL_ITEMS.map(({ key }) => {
const value = systemAgentSettings[key];
return {
- className: styles.centeredLabel,
children: (
<Tooltip title={reason}>
<Flexbox
@@ -191,10 +188,10 @@ const ModelAssignmentsForm = memo(() => {
</Tooltip>
),
label: t(`systemAgent.${key}.title`),
- } satisfies FormItemProps;
+ } satisfies FormFieldProps;
});
- const memoryModelItems: FormItemProps[] = MEMORY_MODEL_ITEMS.map(
+ const memoryModelItems: FormFieldProps[] = MEMORY_MODEL_ITEMS.map(
({ contextLimit, key, modelType }) => {
const value = systemAgentSettings[key];
@@ -232,11 +229,11 @@ const ModelAssignmentsForm = memo(() => {
),
desc: t(`systemAgent.${key}.modelDesc`),
label: t(`systemAgent.${key}.title`),
- } satisfies FormItemProps;
+ } satisfies FormFieldProps;
},
);
- const optionalFeatureItems: FormItemProps[] = OPTIONAL_FEATURE_ITEMS.map(({ key }) => {
+ const optionalFeatureItems: FormFieldProps[] = OPTIONAL_FEATURE_ITEMS.map(({ key }) => {
const value = systemAgentSettings[key];
const featureDisabled = value.enabled === false;
@@ -291,11 +288,11 @@ const ModelAssignmentsForm = memo(() => {
{t(`systemAgent.${key}.title`)}
</span>
),
- } satisfies FormItemProps;
+ } satisfies FormFieldProps;
});
const asrValue = systemAgentSettings.asr;
- const asrItem: FormItemProps = {
+ const asrItem: FormFieldProps = {
children: (
<Tooltip title={reason}>
<Flexbox
@@ -328,7 +325,7 @@ const ModelAssignmentsForm = memo(() => {
<AutoSaveHint lastUpdatedTime={lastSavedAt} saveStatus={saveStatus} onRetry={retry} />
);
- const modelAssignments: FormGroupItemType = {
+ const modelAssignments: FormGroupItem = {
children: [defaultAgentItem, ...systemModelItems],
extra: renderSaveHint('assignments'),
title: (
@@ -338,7 +335,7 @@ const ModelAssignmentsForm = memo(() => {
),
};
- const optionalFeatures: FormGroupItemType = {
+ const optionalFeatures: FormGroupItem = {
children: [...optionalFeatureItems, asrItem],
extra: renderSaveHint('optional'),
title: (
@@ -348,7 +345,7 @@ const ModelAssignmentsForm = memo(() => {
),
};
- const memoryModels: FormGroupItemType = {
+ const memoryModels: FormGroupItem = {
children: memoryModelItems,
extra: renderSaveHint('memory'),
title: (
@@ -361,6 +358,7 @@ const ModelAssignmentsForm = memo(() => {
return (
<Form
collapsible={false}
+ form={form}
items={[modelAssignments, memoryModels, optionalFeatures]}
itemsType={'group'}
variant={'filled'}
diff --git a/src/features/ServiceModel/styles.ts b/src/features/ServiceModel/styles.ts
deleted file mode 100644
index 399c0160b6e..00000000000
--- a/src/features/ServiceModel/styles.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { createStaticStyles } from 'antd-style';
-
-export const serviceModelFormStyles = createStaticStyles(({ css }) => ({
- // antd pins the label to `controlHeight` at the top of the row, which reads
- // fine under a two-line label but leaves a lone title floating above its
- // control. Rows without a subtitle need the label to stretch and center
- // itself against the control instead.
- centeredLabel: css`
- .ant-form-item-label > label {
- align-items: center;
- block-size: 100%;
- min-block-size: 36px;
- }
- `,
-}));
diff --git a/src/features/Settings/about/features/About.tsx b/src/features/Settings/about/features/About.tsx
index 597c1c24a9c..dd381b6c276 100644
--- a/src/features/Settings/about/features/About.tsx
+++ b/src/features/Settings/about/features/About.tsx
@@ -2,8 +2,9 @@
import { SiDiscord, SiGithub, SiRss, SiX, SiYoutube } from '@icons-pack/react-simple-icons';
import { BRANDING_EMAIL, BRANDING_NAME, SOCIAL_URL } from '@lobechat/business-const';
-import { Flexbox, Form } from '@lobehub/ui';
+import { Flexbox } from '@lobehub/ui';
import { Divider } from '@lobehub/ui/base-ui';
+import { Form } from '@lobehub/ui/base-ui/form';
import { createStaticStyles } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -29,7 +30,6 @@ const About = memo<{ mobile?: boolean }>(({ mobile }) => {
return (
<Form.Group
collapsible={false}
- gap={16}
style={{ maxWidth: '1024px', width: '100%' }}
title={`${t('about')} ${BRANDING_NAME}`}
variant={'filled'}
diff --git a/src/features/Settings/about/features/Analytics.tsx b/src/features/Settings/about/features/Analytics.tsx
index 462287d3aa7..72323cdf23f 100644
--- a/src/features/Settings/about/features/Analytics.tsx
+++ b/src/features/Settings/about/features/Analytics.tsx
@@ -1,9 +1,8 @@
'use client';
import { BRANDING_NAME } from '@lobechat/business-const';
-import { type FormGroupItemType } from '@lobehub/ui';
-import { Form } from '@lobehub/ui';
import { Switch } from '@lobehub/ui/base-ui';
+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -15,8 +14,9 @@ const Analytics = memo(() => {
const { t } = useTranslation('setting');
const checked = useUserStore(userGeneralSettingsSelectors.telemetry);
const updateGeneralConfig = useUserStore((s) => s.updateGeneralConfig);
+ const form = useForm();
- const items: FormGroupItemType = {
+ const items: FormGroupItem = {
children: [
{
children: (
@@ -30,7 +30,6 @@ const Analytics = memo(() => {
desc: t('analytics.telemetry.desc', { appName: BRANDING_NAME }),
label: t('analytics.telemetry.title'),
minWidth: undefined,
- valuePropName: 'checked',
},
],
title: t('analytics.title'),
@@ -39,6 +38,7 @@ const Analytics = memo(() => {
return (
<Form
collapsible={false}
+ form={form}
items={[items]}
itemsType={'group'}
variant={'filled'}
diff --git a/src/features/Settings/advanced/index.tsx b/src/features/Settings/advanced/index.tsx
index 02cb9d3d864..f88a220e6d7 100644
--- a/src/features/Settings/advanced/index.tsx
+++ b/src/features/Settings/advanced/index.tsx
@@ -1,10 +1,8 @@
'use client';
import { isDesktop } from '@lobechat/const';
-import { type FormGroupItemType, type FormItemProps } from '@lobehub/ui';
-import { Form } from '@lobehub/ui';
import { Select, Skeleton, Spin, Switch } from '@lobehub/ui/base-ui';
-import { createStaticStyles } from 'antd-style';
+import { Form, type FormFieldProps, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import isEqual from 'fast-deep-equal';
import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -17,17 +15,10 @@ import { autoUpdateService } from '@/services/electron/autoUpdate';
import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
+import { type UserGeneralConfig } from '@/types/user/settings';
type UpdateChannelValue = 'canary' | 'stable';
-const styles = createStaticStyles(({ css }) => ({
- labItem: css`
- .ant-form-item-row {
- align-items: center !important;
- }
- `,
-}));
-
const Page = memo(() => {
const { t } = useTranslation('setting');
@@ -44,6 +35,15 @@ const Page = memo(() => {
s.refreshUserState,
]);
const [loading, setLoading] = useState(false);
+ const form = useForm({
+ initialValues: general,
+ values: general,
+ onValuesChange: async (v) => {
+ setLoading(true);
+ await setSettings({ general: v });
+ setLoading(false);
+ },
+ });
const enableGatewayMode = useServerConfigStore(serverConfigSelectors.enableGatewayMode);
@@ -85,7 +85,7 @@ const Page = memo(() => {
return <Skeleton.Text rows={5} />;
}
- const advancedGroup: FormGroupItemType = {
+ const advancedGroup: FormGroupItem<UserGeneralConfig> = {
children: [
{
children: <Switch />,
@@ -97,7 +97,6 @@ const Page = memo(() => {
),
minWidth: undefined,
name: 'isDevMode',
- valuePropName: 'checked',
},
...(enableGatewayMode
? [
@@ -108,7 +107,6 @@ const Page = memo(() => {
onChange={handleGatewayModeChange}
/>
),
- className: styles.labItem,
desc: t('tab.advanced.gatewayMode.desc'),
label: (
<SettingsSearchAnchor id={'advanced-gateway-mode'}>
@@ -116,7 +114,7 @@ const Page = memo(() => {
</SettingsSearchAnchor>
),
minWidth: undefined,
- } satisfies FormItemProps,
+ } satisfies FormFieldProps<UserGeneralConfig>,
]
: []),
],
@@ -129,7 +127,7 @@ const Page = memo(() => {
{ label: t('tab.advanced.updateChannel.canary'), value: 'canary' as const },
];
- const updateChannelGroup: FormGroupItemType = {
+ const updateChannelGroup: FormGroupItem<UserGeneralConfig> = {
children: [
{
children: (
@@ -153,15 +151,10 @@ const Page = memo(() => {
<SettingHeader title={t('tab.advanced')} />
<Form
collapsible={false}
- initialValues={general}
+ form={form}
items={items}
itemsType={'group'}
variant={'filled'}
- onValuesChange={async (v) => {
- setLoading(true);
- await setSettings({ general: v });
- setLoading(false);
- }}
{...FORM_STYLE}
/>
</>
diff --git a/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx b/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx
index 5e9023faf70..5ce1e73145a 100644
--- a/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx
+++ b/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx
@@ -2,7 +2,7 @@
import { CopyButton, Flexbox, Icon } from '@lobehub/ui';
import { Button, Input, Select, Text, useModalContext } from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import { createStaticStyles } from 'antd-style';
import { type Dayjs } from 'dayjs';
import dayjs from 'dayjs';
@@ -60,7 +60,6 @@ export interface ApiKeyModalContentProps {
const ApiKeyModalContent: FC<ApiKeyModalContentProps> = ({ onSubmit }) => {
const { t } = useTranslation('auth');
const { close } = useModalContext();
- const [form] = Form.useForm<FormValues>();
const [loading, setLoading] = useState(false);
const [fullAccess, setFullAccess] = useState(true);
const [selectedScopes, setSelectedScopes] = useState<ApiKeyScope[]>([]);
@@ -101,6 +100,8 @@ const ApiKeyModalContent: FC<ApiKeyModalContentProps> = ({ onSubmit }) => {
}
};
+ const form = useForm<FormValues>({ onSubmit: handleFinish });
+
if (createdKey) {
return (
<Flexbox gap={16}>
@@ -122,21 +123,21 @@ const ApiKeyModalContent: FC<ApiKeyModalContentProps> = ({ onSubmit }) => {
);
}
- const itemStyle = { marginBottom: 0 };
+ const itemStyle = { paddingBlock: 0 };
return (
- <Form colon={false} form={form} layout={'vertical'} onFinish={handleFinish}>
+ <Form form={form} layout={'vertical'}>
<Flexbox gap={16}>
- <Form.Item
+ <Form.Field
+ required
label={t('apikey.form.fields.name.label')}
name={'name'}
- rules={[{ required: true }]}
style={itemStyle}
>
<Input placeholder={t('apikey.form.fields.name.placeholder')} />
- </Form.Item>
+ </Form.Field>
- <Form.Item label={t('apikey.form.fields.expiresAt.label')} style={itemStyle}>
+ <Form.Field label={t('apikey.form.fields.expiresAt.label')} style={itemStyle}>
<Flexbox gap={8}>
<Select
value={expiryPreset}
@@ -155,13 +156,18 @@ const ApiKeyModalContent: FC<ApiKeyModalContentProps> = ({ onSubmit }) => {
/>
)}
</Flexbox>
- </Form.Item>
+ </Form.Field>
- <Form.Item
- help={scopeMissing ? t('apikey.form.fields.scopes.required') : undefined}
+ <Form.Field
label={t('apikey.form.fields.scopes.label')}
style={itemStyle}
- validateStatus={scopeMissing ? 'error' : undefined}
+ extra={
+ scopeMissing ? (
+ <Text style={{ fontSize: 12 }} type={'danger'}>
+ {t('apikey.form.fields.scopes.required')}
+ </Text>
+ ) : undefined
+ }
>
<ScopeSelector
fullAccess={fullAccess}
@@ -169,7 +175,7 @@ const ApiKeyModalContent: FC<ApiKeyModalContentProps> = ({ onSubmit }) => {
onFullAccessChange={setFullAccess}
onSelectedChange={setSelectedScopes}
/>
- </Form.Item>
+ </Form.Field>
<Button
block
diff --git a/src/features/Settings/appearance/features/Desktop.tsx b/src/features/Settings/appearance/features/Desktop.tsx
index 7e8b73558ed..2a85cc34a11 100644
--- a/src/features/Settings/appearance/features/Desktop.tsx
+++ b/src/features/Settings/appearance/features/Desktop.tsx
@@ -1,9 +1,8 @@
'use client';
import { isDesktop } from '@lobechat/const';
-import { type FormGroupItemType } from '@lobehub/ui';
-import { Form } from '@lobehub/ui';
import { Switch } from '@lobehub/ui/base-ui';
+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -14,6 +13,7 @@ import { useElectronStore } from '@/store/electron';
const Desktop = memo(() => {
const { t } = useTranslation('setting');
const [loading, setLoading] = useState(false);
+ const form = useForm();
const [appTrayVisible, setAppTrayVisible, useGetAppTrayVisible] = useElectronStore((s) => [
s.appTrayVisible,
s.setAppTrayVisible,
@@ -24,7 +24,7 @@ const Desktop = memo(() => {
if (!isDesktop) return null;
- const desktop: FormGroupItemType = {
+ const desktop: FormGroupItem = {
children: [
{
children: (
@@ -55,6 +55,7 @@ const Desktop = memo(() => {
return (
<Form
collapsible={false}
+ form={form}
items={[desktop]}
itemsType={'group'}
variant={'filled'}
diff --git a/src/features/Settings/appearance/features/Font/index.tsx b/src/features/Settings/appearance/features/Font/index.tsx
index 172b6963daa..fc2bb0b021a 100644
--- a/src/features/Settings/appearance/features/Font/index.tsx
+++ b/src/features/Settings/appearance/features/Font/index.tsx
@@ -1,9 +1,9 @@
'use client';
import { isDesktop } from '@lobechat/const';
-import type { FormGroupItemType } from '@lobehub/ui';
-import { Flexbox, Form } from '@lobehub/ui';
+import { Flexbox } from '@lobehub/ui';
import { Select, Skeleton, Switch } from '@lobehub/ui/base-ui';
+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -19,13 +19,6 @@ import FallbackFontList from './FallbackFontList';
import { FontSizeControl } from './FontSize';
import { joinFontStack, parseFontStack } from './fontStack';
-const wrapperCol = {
- style: {
- maxWidth: '100%',
- width: '100%',
- },
-};
-
const loadingTextStyle = { marginBlock: 1.5 };
const FontSettings = memo(() => {
@@ -40,6 +33,7 @@ const FontSettings = memo(() => {
const setSettings = useUserStore((s) => s.setSettings);
const isUserStateInit = useUserStore((s) => s.isUserStateInit);
const { status: saveStatus, lastSavedAt, save, retry } = useSaveState();
+ const form = useForm();
const interfaceStack = useMemo(() => parseFontStack(fontFamily), [fontFamily]);
const monospaceStack = useMemo(() => parseFontStack(monospaceFontFamily), [monospaceFontFamily]);
@@ -64,7 +58,7 @@ const FontSettings = memo(() => {
save(() => updatePreference({ terminalFontFamily: joinFontStack(stack) }));
if (!isUserStateInit) {
- const loadingFont: FormGroupItemType = {
+ const loadingFont: FormGroupItem = {
children: [
...(isDesktop
? [
@@ -102,7 +96,6 @@ const FontSettings = memo(() => {
label: <Skeleton height={16} style={loadingTextStyle} width={72} />,
layout: 'vertical',
minWidth: '100%',
- wrapperCol,
},
],
extra: <Skeleton height={16} width={136} />,
@@ -113,6 +106,7 @@ const FontSettings = memo(() => {
<Form
aria-busy
collapsible={false}
+ form={form}
items={[loadingFont]}
itemsType={'group'}
variant={'filled'}
@@ -121,7 +115,7 @@ const FontSettings = memo(() => {
);
}
- const font: FormGroupItemType = {
+ const font: FormGroupItem = {
children: [
...(isDesktop
? [
@@ -249,7 +243,6 @@ const FontSettings = memo(() => {
),
layout: 'vertical',
minWidth: '100%',
- wrapperCol,
},
],
extra: <AutoSaveHint lastUpdatedTime={lastSavedAt} saveStatus={saveStatus} onRetry={retry} />,
@@ -259,6 +252,7 @@ const FontSettings = memo(() => {
return (
<Form
collapsible={false}
+ form={form}
items={[font]}
itemsType={'group'}
variant={'filled'}
diff --git a/src/features/Settings/chat-appearance/features/ChatAppearance/index.tsx b/src/features/Settings/chat-appearance/features/ChatAppearance/index.tsx
index 6f39cff380c..5a252c4a564 100644
--- a/src/features/Settings/chat-appearance/features/ChatAppearance/index.tsx
+++ b/src/features/Settings/chat-appearance/features/ChatAppearance/index.tsx
@@ -1,7 +1,8 @@
'use client';
-import { Flexbox, Form, FormGroup, highlighterThemes, mermaidThemes } from '@lobehub/ui';
+import { Flexbox, highlighterThemes, mermaidThemes } from '@lobehub/ui';
import { Select, Switch, Tabs } from '@lobehub/ui/base-ui';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import isEqual from 'fast-deep-equal';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -24,6 +25,7 @@ const ChatAppearance = memo(() => {
const [setSettings, isUserStateInit] = useUserStore((s) => [s.setSettings, s.isUserStateInit]);
const { status: saveStatus, lastSavedAt, save, retry } = useSaveState();
const [savingKey, setSavingKey] = useState<string>();
+ const form = useForm();
if (!isUserStateInit) return <SettingsSectionSkeleton />;
@@ -40,9 +42,8 @@ const ChatAppearance = memo(() => {
return (
<>
- <FormGroup
+ <Form.Group
collapsible={false}
- gap={16}
title={t('settingChatAppearance.transitionMode.title')}
variant={'filled'}
extra={
@@ -70,10 +71,11 @@ const ChatAppearance = memo(() => {
}
>
<ChatTransitionPreview key={general.transitionMode} mode={general.transitionMode} />
- </FormGroup>
+ </Form.Group>
<Form
collapsible={false}
+ form={form}
itemsType={'group'}
variant={'filled'}
items={[
@@ -126,9 +128,8 @@ const ChatAppearance = memo(() => {
{...FORM_STYLE}
/>
- <FormGroup
+ <Form.Group
collapsible={false}
- gap={16}
title={t('settingChatAppearance.highlighterTheme.title')}
variant={'filled'}
extra={
@@ -149,10 +150,9 @@ const ChatAppearance = memo(() => {
}
>
<HighlighterPreview key={general.highlighterTheme} theme={general.highlighterTheme} />
- </FormGroup>
+ </Form.Group>
- <FormGroup
- gap={16}
+ <Form.Group
title={t('settingChatAppearance.mermaidTheme.title')}
variant={'filled'}
extra={
@@ -173,7 +173,7 @@ const ChatAppearance = memo(() => {
}
>
<MermaidPreview key={general.mermaidTheme} theme={general.mermaidTheme} />
- </FormGroup>
+ </Form.Group>
</>
);
});
diff --git a/src/features/Settings/common/features/Appearance/index.tsx b/src/features/Settings/common/features/Appearance/index.tsx
index c8a260445e1..cae0ca0ed09 100644
--- a/src/features/Settings/common/features/Appearance/index.tsx
+++ b/src/features/Settings/common/features/Appearance/index.tsx
@@ -1,7 +1,6 @@
'use client';
-import { type FormGroupItemType } from '@lobehub/ui';
-import { Form } from '@lobehub/ui';
+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import isEqual from 'fast-deep-equal';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -13,6 +12,7 @@ import { SettingsSearchAnchor } from '@/features/SettingsSearch/anchor';
import { useSaveState } from '@/hooks/useSaveState';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/slices/settings/selectors';
+import { type UserGeneralConfig } from '@/types/user/settings';
import Preview from './Preview';
import { ThemeSwatchesNeutral, ThemeSwatchesPrimary } from './ThemeSwatches';
@@ -22,10 +22,15 @@ const Appearance = memo(() => {
const { general } = useUserStore(settingsSelectors.currentSettings, isEqual);
const [setSettings, isUserStateInit] = useUserStore((s) => [s.setSettings, s.isUserStateInit]);
const { status: saveStatus, lastSavedAt, save, retry } = useSaveState();
+ const form = useForm({
+ initialValues: general,
+ values: general,
+ onValuesChange: (value) => save(() => setSettings({ general: value })),
+ });
if (!isUserStateInit) return <SettingsSectionSkeleton />;
- const theme: FormGroupItemType = {
+ const theme: FormGroupItem<UserGeneralConfig> = {
children: [
{
children: <Preview />,
@@ -60,11 +65,10 @@ const Appearance = memo(() => {
return (
<Form
collapsible={false}
- initialValues={general}
+ form={form}
items={[theme]}
itemsType={'group'}
variant={'filled'}
- onValuesChange={(value) => save(() => setSettings({ general: value }))}
{...FORM_STYLE}
/>
);
diff --git a/src/features/Settings/common/features/Common/Common.tsx b/src/features/Settings/common/features/Common/Common.tsx
index 61c5acca3ce..2a4f39c5622 100644
--- a/src/features/Settings/common/features/Common/Common.tsx
+++ b/src/features/Settings/common/features/Common/Common.tsx
@@ -1,8 +1,8 @@
'use client';
-import { type FormGroupItemType } from '@lobehub/ui';
-import { Flexbox, Form, Icon, ImageSelect } from '@lobehub/ui';
+import { Flexbox, Icon, ImageSelect } from '@lobehub/ui';
import { Select, Skeleton, Tabs } from '@lobehub/ui/base-ui';
+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import isEqual from 'fast-deep-equal';
import { Ban, Gauge, Monitor, Moon, Mouse, Sun, Waves } from 'lucide-react';
import { useTheme as useNextThemesTheme } from 'next-themes';
@@ -21,6 +21,7 @@ import { systemStatusSelectors } from '@/store/global/selectors';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
import { type LocaleMode } from '@/types/locale';
+import { type UserGeneralConfig } from '@/types/user/settings';
import { preloadLang } from '@/utils/client/preloadLang';
const Common = memo(() => {
@@ -32,6 +33,11 @@ const Common = memo(() => {
const [setSettings, isUserStateInit] = useUserStore((s) => [s.setSettings, s.isUserStateInit]);
const [switchLocale, isStatusInit] = useGlobalStore((s) => [s.switchLocale, s.isStatusInit]);
const { status: saveStatus, lastSavedAt, save, retry } = useSaveState();
+ const form = useForm({
+ initialValues: general,
+ values: general,
+ onValuesChange: (v) => save(() => setSettings({ general: v })),
+ });
// Use the theme value from next-themes, default to 'system'
const currentTheme = theme || 'system';
@@ -42,7 +48,7 @@ const Common = memo(() => {
if (!(isStatusInit && isUserStateInit)) return <Skeleton.Text rows={5} />;
- const themeFormGroup: FormGroupItemType = {
+ const themeFormGroup: FormGroupItem<UserGeneralConfig> = {
children: [
{
children: (
@@ -145,7 +151,7 @@ const Common = memo(() => {
),
minWidth: undefined,
name: 'animationMode',
- valuePropName: 'activeKey',
+ valueProp: 'activeKey',
},
{
children: (
@@ -171,7 +177,7 @@ const Common = memo(() => {
),
minWidth: undefined,
name: 'contextMenuMode',
- valuePropName: 'activeKey',
+ valueProp: 'activeKey',
},
{
@@ -205,11 +211,10 @@ const Common = memo(() => {
return (
<Form
collapsible={false}
- initialValues={general}
+ form={form}
items={[themeFormGroup]}
itemsType={'group'}
variant={'filled'}
- onValuesChange={(v) => save(() => setSettings({ general: v }))}
{...FORM_STYLE}
/>
);
diff --git a/src/features/Settings/creds/features/CreateCredModal/FileCredForm.tsx b/src/features/Settings/creds/features/CreateCredModal/FileCredForm.tsx
index 5242b9dd0a5..16bf5d5a5cf 100644
--- a/src/features/Settings/creds/features/CreateCredModal/FileCredForm.tsx
+++ b/src/features/Settings/creds/features/CreateCredModal/FileCredForm.tsx
@@ -1,8 +1,8 @@
'use client';
import { Button, Input, TextArea, toast, Upload } from '@lobehub/ui/base-ui';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import { useMutation } from '@tanstack/react-query';
-import { Form } from 'antd';
import { createStaticStyles } from 'antd-style';
import { type FC, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -33,7 +33,7 @@ interface FormValues {
const FileCredForm: FC<FileCredFormProps> = ({ credsApi, disabled, onBack, onSuccess }) => {
const { t } = useTranslation(['setting', 'common']);
- const [form] = Form.useForm<FormValues>();
+ const form = useForm<FormValues>({ onSubmit: (values) => handleSubmit(values) });
const [fileHashId, setFileHashId] = useState<string | null>(null);
const [fileName, setFileName] = useState<string>('');
const [isUploading, setIsUploading] = useState(false);
@@ -103,8 +103,8 @@ const FileCredForm: FC<FileCredFormProps> = ({ credsApi, disabled, onBack, onSuc
};
return (
- <Form<FormValues> form={form} layout="vertical" onFinish={handleSubmit}>
- <Form.Item required label={t('creds.form.file')}>
+ <Form form={form} layout="vertical">
+ <Form.Field required label={t('creds.form.file')}>
<Upload
dragger
description={t('creds.form.uploadDesc')}
@@ -130,34 +130,30 @@ const FileCredForm: FC<FileCredFormProps> = ({ credsApi, disabled, onBack, onSuc
</Button>
</div>
)}
- </Form.Item>
+ </Form.Field>
- <Form.Item
+ <Form.Field
label={t('creds.form.key')}
name="key"
- rules={[
- { required: true, message: t('creds.form.keyRequired') },
- { pattern: /^[\w-]+$/, message: t('creds.form.keyPattern') },
- ]}
+ required={t('creds.form.keyRequired')}
+ validate={(value?: string) =>
+ value && !/^[\w-]+$/.test(value) ? t('creds.form.keyPattern') : undefined
+ }
>
<Input disabled={disabled} placeholder="e.g., gcp-service-account" />
- </Form.Item>
+ </Form.Field>
- <Form.Item
- label={t('creds.form.name')}
- name="name"
- rules={[{ required: true, message: t('creds.form.nameRequired') }]}
- >
+ <Form.Field label={t('creds.form.name')} name="name" required={t('creds.form.nameRequired')}>
<Input disabled={disabled} placeholder="e.g., GCP Service Account" />
- </Form.Item>
+ </Form.Field>
- <Form.Item label={t('creds.form.description')} name="description">
+ <Form.Field label={t('creds.form.description')} name="description">
<TextArea
disabled={disabled}
placeholder={t('creds.form.descriptionPlaceholder')}
rows={2}
/>
- </Form.Item>
+ </Form.Field>
<div className={styles.footer}>
<Button onClick={onBack}>{t('creds.form.back')}</Button>
diff --git a/src/features/Settings/creds/features/CreateCredModal/KVCredForm.tsx b/src/features/Settings/creds/features/CreateCredModal/KVCredForm.tsx
index c75cbb48b7d..8bc1d9cd288 100644
--- a/src/features/Settings/creds/features/CreateCredModal/KVCredForm.tsx
+++ b/src/features/Settings/creds/features/CreateCredModal/KVCredForm.tsx
@@ -2,8 +2,8 @@
import { Flexbox } from '@lobehub/ui';
import { Button, Input, InputPassword, TextArea } from '@lobehub/ui/base-ui';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import { useMutation } from '@tanstack/react-query';
-import { Form } from 'antd';
import { createStaticStyles } from 'antd-style';
import { Minus, Plus } from 'lucide-react';
import { type FC } from 'react';
@@ -42,7 +42,10 @@ interface FormValues {
const KVCredForm: FC<KVCredFormProps> = ({ credsApi, type, disabled, onBack, onSuccess }) => {
const { t } = useTranslation('setting');
- const [form] = Form.useForm<FormValues>();
+ const form = useForm<FormValues>({
+ initialValues: { kvPairs: [{ key: '', value: '' }] } as FormValues,
+ onSubmit: (values) => handleSubmit(values),
+ });
const createMutation = useMutation({
mutationFn: async (values: FormValues) => {
@@ -79,65 +82,52 @@ const KVCredForm: FC<KVCredFormProps> = ({ credsApi, type, disabled, onBack, onS
};
return (
- <Form<FormValues>
- form={form}
- initialValues={{ kvPairs: [{ key: '', value: '' }] }}
- layout="vertical"
- onFinish={handleSubmit}
- >
- <Form.Item
+ <Form form={form} layout="vertical">
+ <Form.Field
label={t('creds.form.key')}
name="key"
- rules={[
- { required: true, message: t('creds.form.keyRequired') },
- { pattern: /^[\w-]+$/, message: t('creds.form.keyPattern') },
- ]}
+ required={t('creds.form.keyRequired')}
+ validate={(value?: string) =>
+ value && !/^[\w-]+$/.test(value) ? t('creds.form.keyPattern') : undefined
+ }
>
<Input disabled={disabled} placeholder="e.g., openai" />
- </Form.Item>
+ </Form.Field>
- <Form.Item
- label={t('creds.form.name')}
- name="name"
- rules={[{ required: true, message: t('creds.form.nameRequired') }]}
- >
+ <Form.Field label={t('creds.form.name')} name="name" required={t('creds.form.nameRequired')}>
<Input disabled={disabled} placeholder="e.g., OpenAI API Key" />
- </Form.Item>
+ </Form.Field>
- <Form.Item label={t('creds.form.values')}>
+ <Form.Field label={t('creds.form.values')}>
<Form.List name="kvPairs">
- {(fields, { add, remove }) => (
+ {({ fields, add, remove }) => (
<Flexbox gap={8}>
- {fields.map(({ key, name, ...restField }) => (
+ {fields.map(({ key, index }) => (
<div className={styles.kvPair} key={key}>
- <Form.Item
- {...restField}
- name={[name, 'key']}
- style={{ flex: 1, marginBottom: 0 }}
- >
- <Input
- disabled={disabled}
- placeholder={type === 'kv-env' ? 'ENV_VAR_NAME' : 'Header-Name'}
- />
- </Form.Item>
- <Form.Item
- {...restField}
- name={[name, 'value']}
- style={{ flex: 2, marginBottom: 0 }}
- >
- <InputPassword
- autoComplete="new-password"
- disabled={disabled}
- placeholder={t('creds.form.valuePlaceholder')}
- />
- </Form.Item>
+ <div style={{ flex: 1 }}>
+ <Form.Field bare name={`kvPairs.${index}.key`}>
+ <Input
+ disabled={disabled}
+ placeholder={type === 'kv-env' ? 'ENV_VAR_NAME' : 'Header-Name'}
+ />
+ </Form.Field>
+ </div>
+ <div style={{ flex: 2 }}>
+ <Form.Field bare name={`kvPairs.${index}.value`}>
+ <InputPassword
+ autoComplete="new-password"
+ disabled={disabled}
+ placeholder={t('creds.form.valuePlaceholder')}
+ />
+ </Form.Field>
+ </div>
{fields.length > 1 && (
<Button
disabled={disabled}
icon={Minus}
size="small"
type="text"
- onClick={() => remove(name)}
+ onClick={() => remove(index)}
/>
)}
</div>
@@ -154,15 +144,15 @@ const KVCredForm: FC<KVCredFormProps> = ({ credsApi, type, disabled, onBack, onS
</Flexbox>
)}
</Form.List>
- </Form.Item>
+ </Form.Field>
- <Form.Item label={t('creds.form.description')} name="description">
+ <Form.Field label={t('creds.form.description')} name="description">
<TextArea
disabled={disabled}
placeholder={t('creds.form.descriptionPlaceholder')}
rows={2}
/>
- </Form.Item>
+ </Form.Field>
<div className={styles.footer}>
<Button onClick={onBack}>{t('creds.form.back')}</Button>
diff --git a/src/features/Settings/creds/features/CreateCredModal/OAuthCredForm.tsx b/src/features/Settings/creds/features/CreateCredModal/OAuthCredForm.tsx
index af046edc302..bd6bb10251d 100644
--- a/src/features/Settings/creds/features/CreateCredModal/OAuthCredForm.tsx
+++ b/src/features/Settings/creds/features/CreateCredModal/OAuthCredForm.tsx
@@ -2,8 +2,8 @@
import { Empty, Flexbox } from '@lobehub/ui';
import { Avatar, Button, Input, Select, Spin, TextArea } from '@lobehub/ui/base-ui';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import { useMutation } from '@tanstack/react-query';
-import { Form } from 'antd';
import { createStaticStyles } from 'antd-style';
import { type FC } from 'react';
import { useTranslation } from 'react-i18next';
@@ -46,7 +46,7 @@ interface FormValues {
const OAuthCredForm: FC<OAuthCredFormProps> = ({ credsApi, disabled, onBack, onSuccess }) => {
const { t } = useTranslation('setting');
- const [form] = Form.useForm<FormValues>();
+ const form = useForm<FormValues>({ onSubmit: (values) => handleSubmit(values) });
const { data: connectionsData, isLoading } = credsApi.query.listOAuthConnections.useQuery();
@@ -112,45 +112,41 @@ const OAuthCredForm: FC<OAuthCredFormProps> = ({ credsApi, disabled, onBack, onS
}
return (
- <Form<FormValues> form={form} layout="vertical" onFinish={handleSubmit}>
- <Form.Item
+ <Form form={form} layout="vertical">
+ <Form.Field
label={t('creds.form.selectConnection')}
name="oauthConnectionId"
- rules={[{ required: true, message: t('creds.form.connectionRequired') }]}
+ required={t('creds.form.connectionRequired')}
>
<Select
disabled={disabled}
options={connectionOptions}
placeholder={t('creds.form.selectConnectionPlaceholder')}
/>
- </Form.Item>
+ </Form.Field>
- <Form.Item
+ <Form.Field
label={t('creds.form.key')}
name="key"
- rules={[
- { required: true, message: t('creds.form.keyRequired') },
- { pattern: /^[\w-]+$/, message: t('creds.form.keyPattern') },
- ]}
+ required={t('creds.form.keyRequired')}
+ validate={(value?: string) =>
+ value && !/^[\w-]+$/.test(value) ? t('creds.form.keyPattern') : undefined
+ }
>
<Input disabled={disabled} placeholder="e.g., github-oauth" />
- </Form.Item>
+ </Form.Field>
- <Form.Item
- label={t('creds.form.name')}
- name="name"
- rules={[{ required: true, message: t('creds.form.nameRequired') }]}
- >
+ <Form.Field label={t('creds.form.name')} name="name" required={t('creds.form.nameRequired')}>
<Input disabled={disabled} placeholder="e.g., GitHub Connection" />
- </Form.Item>
+ </Form.Field>
- <Form.Item label={t('creds.form.description')} name="description">
+ <Form.Field label={t('creds.form.description')} name="description">
<TextArea
disabled={disabled}
placeholder={t('creds.form.descriptionPlaceholder')}
rows={2}
/>
- </Form.Item>
+ </Form.Field>
<div className={styles.footer}>
<Button onClick={onBack}>{t('creds.form.back')}</Button>
diff --git a/src/features/Settings/creds/features/EditCredModal/EditKVForm.tsx b/src/features/Settings/creds/features/EditCredModal/EditKVForm.tsx
index 6b0913edfa5..125ef643748 100644
--- a/src/features/Settings/creds/features/EditCredModal/EditKVForm.tsx
+++ b/src/features/Settings/creds/features/EditCredModal/EditKVForm.tsx
@@ -3,8 +3,8 @@
import { type UserCredSummary } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
import { Button, Input, InputPassword, Spin, TextArea } from '@lobehub/ui/base-ui';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import { useMutation } from '@tanstack/react-query';
-import { Form } from 'antd';
import { createStaticStyles } from 'antd-style';
import { Minus, Plus } from 'lucide-react';
import { type FC, useEffect, useState } from 'react';
@@ -44,7 +44,7 @@ interface FormValues {
const EditKVForm: FC<EditKVFormProps> = ({ cred, credsApi, onCancel, onSuccess }) => {
const { t } = useTranslation('setting');
const { allowed: canManageCredentials } = usePermission('manage_provider_key');
- const [form] = Form.useForm<FormValues>();
+ const form = useForm<FormValues>({ onSubmit: (values) => handleSubmit(values) });
const [isLoading, setIsLoading] = useState(true);
// Fetch decrypted values on mount
@@ -68,14 +68,14 @@ const EditKVForm: FC<EditKVFormProps> = ({ cred, credsApi, onCancel, onSuccess }
value: value as string,
}));
- form.setFieldsValue({
+ form.setValues({
description: cred.description,
kvPairs: kvPairs.length > 0 ? kvPairs : [{ key: '', value: '' }],
name: cred.name,
});
} catch {
// If decryption fails, just show empty values
- form.setFieldsValue({
+ form.setValues({
description: cred.description,
kvPairs: [{ key: '', value: '' }],
name: cred.name,
@@ -130,49 +130,41 @@ const EditKVForm: FC<EditKVFormProps> = ({ cred, credsApi, onCancel, onSuccess }
}
return (
- <Form<FormValues> form={form} layout="vertical" onFinish={handleSubmit}>
- <Form.Item
- label={t('creds.form.name')}
- name="name"
- rules={[{ required: true, message: t('creds.form.nameRequired') }]}
- >
+ <Form form={form} layout="vertical">
+ <Form.Field label={t('creds.form.name')} name="name" required={t('creds.form.nameRequired')}>
<Input disabled={!canManageCredentials} />
- </Form.Item>
+ </Form.Field>
- <Form.Item label={t('creds.form.values')}>
+ <Form.Field label={t('creds.form.values')}>
<Form.List name="kvPairs">
- {(fields, { add, remove }) => (
+ {({ fields, add, remove }) => (
<Flexbox gap={8}>
- {fields.map(({ key, name, ...restField }) => (
+ {fields.map(({ key, index }) => (
<div className={styles.kvPair} key={key}>
- <Form.Item
- {...restField}
- name={[name, 'key']}
- style={{ flex: 1, marginBottom: 0 }}
- >
- <Input
- disabled={!canManageCredentials}
- placeholder={cred.type === 'kv-env' ? 'ENV_VAR_NAME' : 'Header-Name'}
- />
- </Form.Item>
- <Form.Item
- {...restField}
- name={[name, 'value']}
- style={{ flex: 2, marginBottom: 0 }}
- >
- <InputPassword
- autoComplete="new-password"
- disabled={!canManageCredentials}
- placeholder={t('creds.form.valuePlaceholder')}
- />
- </Form.Item>
+ <div style={{ flex: 1 }}>
+ <Form.Field bare name={`kvPairs.${index}.key`}>
+ <Input
+ disabled={!canManageCredentials}
+ placeholder={cred.type === 'kv-env' ? 'ENV_VAR_NAME' : 'Header-Name'}
+ />
+ </Form.Field>
+ </div>
+ <div style={{ flex: 2 }}>
+ <Form.Field bare name={`kvPairs.${index}.value`}>
+ <InputPassword
+ autoComplete="new-password"
+ disabled={!canManageCredentials}
+ placeholder={t('creds.form.valuePlaceholder')}
+ />
+ </Form.Field>
+ </div>
{fields.length > 1 && (
<Button
disabled={!canManageCredentials}
icon={Minus}
size="small"
type="text"
- onClick={() => remove(name)}
+ onClick={() => remove(index)}
/>
)}
</div>
@@ -189,15 +181,15 @@ const EditKVForm: FC<EditKVFormProps> = ({ cred, credsApi, onCancel, onSuccess }
</Flexbox>
)}
</Form.List>
- </Form.Item>
+ </Form.Field>
- <Form.Item label={t('creds.form.description')} name="description">
+ <Form.Field label={t('creds.form.description')} name="description">
<TextArea
disabled={!canManageCredentials}
placeholder={t('creds.form.descriptionPlaceholder')}
rows={2}
/>
- </Form.Item>
+ </Form.Field>
<div className={styles.footer}>
<Button onClick={onCancel}>{t('creds.form.cancel')}</Button>
diff --git a/src/features/Settings/creds/features/EditCredModal/EditMetaForm.tsx b/src/features/Settings/creds/features/EditCredModal/EditMetaForm.tsx
index 05abe2c9cad..802bca81445 100644
--- a/src/features/Settings/creds/features/EditCredModal/EditMetaForm.tsx
+++ b/src/features/Settings/creds/features/EditCredModal/EditMetaForm.tsx
@@ -2,8 +2,8 @@
import { type UserCredSummary } from '@lobechat/types';
import { Button, Input, TextArea } from '@lobehub/ui/base-ui';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import { useMutation } from '@tanstack/react-query';
-import { Form } from 'antd';
import { createStaticStyles } from 'antd-style';
import { type FC } from 'react';
import { useTranslation } from 'react-i18next';
@@ -36,7 +36,13 @@ interface FormValues {
const EditMetaForm: FC<EditMetaFormProps> = ({ cred, credsApi, onCancel, onSuccess }) => {
const { t } = useTranslation('setting');
const { allowed: canManageCredentials } = usePermission('manage_provider_key');
- const [form] = Form.useForm<FormValues>();
+ const form = useForm<FormValues>({
+ initialValues: {
+ description: cred.description,
+ name: cred.name,
+ },
+ onSubmit: (values) => handleSubmit(values),
+ });
const updateMutation = useMutation({
mutationFn: async (values: FormValues) => {
@@ -60,30 +66,18 @@ const EditMetaForm: FC<EditMetaFormProps> = ({ cred, credsApi, onCancel, onSucce
};
return (
- <Form<FormValues>
- form={form}
- layout="vertical"
- initialValues={{
- description: cred.description,
- name: cred.name,
- }}
- onFinish={handleSubmit}
- >
- <Form.Item
- label={t('creds.form.name')}
- name="name"
- rules={[{ required: true, message: t('creds.form.nameRequired') }]}
- >
+ <Form form={form} layout="vertical">
+ <Form.Field label={t('creds.form.name')} name="name" required={t('creds.form.nameRequired')}>
<Input disabled={!canManageCredentials} />
- </Form.Item>
+ </Form.Field>
- <Form.Item label={t('creds.form.description')} name="description">
+ <Form.Field label={t('creds.form.description')} name="description">
<TextArea
disabled={!canManageCredentials}
placeholder={t('creds.form.descriptionPlaceholder')}
rows={2}
/>
- </Form.Item>
+ </Form.Field>
<div className={styles.footer}>
<Button onClick={onCancel}>{t('creds.form.cancel')}</Button>
diff --git a/src/features/Settings/devices/KeepAwake.tsx b/src/features/Settings/devices/KeepAwake.tsx
index 4a0c22c8341..3ffe1cd9d44 100644
--- a/src/features/Settings/devices/KeepAwake.tsx
+++ b/src/features/Settings/devices/KeepAwake.tsx
@@ -1,8 +1,7 @@
'use client';
-import { type FormGroupItemType } from '@lobehub/ui';
-import { Form } from '@lobehub/ui';
import { Switch } from '@lobehub/ui/base-ui';
+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -16,8 +15,9 @@ import { useGatewayKeepAwake } from '@/features/Electron/connection/useGatewayKe
const KeepAwake = memo(() => {
const { t } = useTranslation('setting');
const { enabled, isLoading, setKeepAwake } = useGatewayKeepAwake();
+ const form = useForm();
- const items: FormGroupItemType = {
+ const items: FormGroupItem = {
children: [
{
children: (
@@ -30,7 +30,6 @@ const KeepAwake = memo(() => {
desc: t('devices.keepAwake.desc'),
label: t('devices.keepAwake.title'),
minWidth: undefined,
- valuePropName: 'checked',
},
],
title: t('devices.thisComputer'),
@@ -39,6 +38,7 @@ const KeepAwake = memo(() => {
return (
<Form
collapsible={false}
+ form={form}
items={[items]}
itemsType={'group'}
variant={'filled'}
diff --git a/src/features/Settings/devices/index.tsx b/src/features/Settings/devices/index.tsx
index fd403487ee3..b7d002c1152 100644
--- a/src/features/Settings/devices/index.tsx
+++ b/src/features/Settings/devices/index.tsx
@@ -1,8 +1,9 @@
'use client';
import { isDesktop } from '@lobechat/const';
-import { Flexbox, Form, Icon } from '@lobehub/ui';
+import { Flexbox, Icon } from '@lobehub/ui';
import { ActionIcon, Button, Text } from '@lobehub/ui/base-ui';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import { createStaticStyles } from 'antd-style';
import { MonitorUpIcon, RefreshCwIcon } from 'lucide-react';
import { memo, useState } from 'react';
@@ -24,11 +25,10 @@ import KeepAwake from './KeepAwake';
const styles = createStaticStyles(({ css }) => ({
// The device rows carry their own padding and hover fill; a thin, even inset
- // keeps that fill the same distance from every edge of the card. The Form
- // zeroes the group body's block padding with !important, hence the override.
+ // keeps that fill the same distance from every edge of the card.
listGroup: css`
- .ant-collapse-body {
- padding: 4px !important;
+ [data-form-group-body] {
+ padding: 4px;
}
`,
}));
@@ -42,6 +42,7 @@ const Page = memo<PageProps>(({ mobile }) => {
const [open, setOpen] = useState(false);
const [initialTab, setInitialTab] = useState<'cli' | 'desktop'>();
const [selectedDeviceId, setSelectedDeviceId] = useState<string>();
+ const form = useForm();
// Shares DeviceManager's SWR entry, so the header actions drive the list it
// renders — the same wiring the workspace devices page uses.
const { data, isValidating, mutate } = useDeviceList();
@@ -68,6 +69,7 @@ const Page = memo<PageProps>(({ mobile }) => {
<Form
classNames={{ group: styles.listGroup }}
collapsible={false}
+ form={form}
itemsType={'group'}
variant={'filled'}
items={[
diff --git a/src/features/Settings/hotkey/features/Conversation.tsx b/src/features/Settings/hotkey/features/Conversation.tsx
index 6e98b74b461..e85e0964ab2 100644
--- a/src/features/Settings/hotkey/features/Conversation.tsx
+++ b/src/features/Settings/hotkey/features/Conversation.tsx
@@ -1,9 +1,9 @@
'use client';
import { HotkeyGroupEnum } from '@lobechat/const/hotkeys';
-import { type FormGroupItemType } from '@lobehub/ui';
-import { Form, HotkeyInput } from '@lobehub/ui';
+import { HotkeyInput } from '@lobehub/ui';
import { Skeleton } from '@lobehub/ui/base-ui';
+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import isEqual from 'fast-deep-equal';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -16,23 +16,25 @@ import { useSaveState } from '@/hooks/useSaveState';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
import { type HotkeyItem } from '@/types/hotkey';
-
-import { hotkeyFormStyles } from './styles';
+import { type UserHotkeyConfig } from '@/types/user/settings';
const HotkeySetting = memo(() => {
const { t } = useTranslation(['setting', 'hotkey']);
- const [form] = Form.useForm();
-
const { hotkey } = useUserStore(settingsSelectors.currentSettings, isEqual);
const [setSettings, isUserStateInit] = useUserStore((s) => [s.setSettings, s.isUserStateInit]);
const { status: saveStatus, lastSavedAt, save, retry } = useSaveState();
+ const form = useForm({
+ initialValues: hotkey,
+ values: hotkey,
+ onValuesChange: (values) => save(() => setSettings({ hotkey: values })),
+ });
if (!isUserStateInit) return <Skeleton.Text rows={5} />;
const clearHotkeyBinding = (id: HotkeyItem['id']) => {
if (!hotkey[id]) return;
- form.setFieldValue(id, '');
+ form.setValue(id, '');
save(() => setSettings({ hotkey: { [id]: '' } }));
};
@@ -61,7 +63,7 @@ const HotkeySetting = memo(() => {
};
};
- const conversation: FormGroupItemType = {
+ const conversation: FormGroupItem<UserHotkeyConfig> = {
children: HOTKEYS_REGISTRATION.filter(
(item) => item.group === HotkeyGroupEnum.Conversation,
).map((item) => mapHotkeyItem(item)),
@@ -78,14 +80,11 @@ const HotkeySetting = memo(() => {
return (
<Form
- classNames={{ item: hotkeyFormStyles.item }}
collapsible={false}
form={form}
- initialValues={hotkey}
items={[conversation]}
itemsType={'group'}
variant={'filled'}
- onValuesChange={(values) => save(() => setSettings({ hotkey: values }))}
{...FORM_STYLE}
/>
);
diff --git a/src/features/Settings/hotkey/features/Desktop.tsx b/src/features/Settings/hotkey/features/Desktop.tsx
index 5f899ab0b96..9b34b4bc50d 100644
--- a/src/features/Settings/hotkey/features/Desktop.tsx
+++ b/src/features/Settings/hotkey/features/Desktop.tsx
@@ -1,8 +1,8 @@
'use client';
-import { type FormGroupItemType } from '@lobehub/ui';
-import { Form, HotkeyInput } from '@lobehub/ui';
+import { HotkeyInput } from '@lobehub/ui';
import { Skeleton, Spin, toast } from '@lobehub/ui/base-ui';
+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import isEqual from 'fast-deep-equal';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -12,15 +12,12 @@ import { FORM_STYLE } from '@/const/layoutTokens';
import { SettingsSearchAnchor } from '@/features/SettingsSearch/anchor';
import { useElectronStore } from '@/store/electron';
import { desktopHotkeysSelectors } from '@/store/electron/selectors';
-import { type DesktopHotkeyItem } from '@/types/hotkey';
-
-import { hotkeyFormStyles } from './styles';
+import { type DesktopHotkeyConfig, type DesktopHotkeyItem } from '@/types/hotkey';
const HotkeySetting = memo(() => {
const { t } = useTranslation(['setting', 'hotkey']);
- const [form] = Form.useForm();
-
const hotkeys = useElectronStore(desktopHotkeysSelectors.hotkeys, isEqual);
+ const form = useForm({ initialValues: hotkeys, values: hotkeys });
const [isHotkeysInit, updateDesktopHotkey, useFetchDesktopHotkeys] = useElectronStore((s) => [
desktopHotkeysSelectors.isHotkeysInit(s),
@@ -68,7 +65,7 @@ const HotkeySetting = memo(() => {
name: item.id,
});
- const desktop: FormGroupItemType = {
+ const desktop: FormGroupItem<DesktopHotkeyConfig> = {
children: DESKTOP_HOTKEYS_REGISTRATION.map((item) => mapHotkeyItem(item)),
extra: loading && <Spin size="small" style={{ opacity: 0.5 }} />,
title: (
@@ -78,10 +75,8 @@ const HotkeySetting = memo(() => {
return (
<Form
- classNames={{ item: hotkeyFormStyles.item }}
collapsible={false}
form={form}
- initialValues={hotkeys}
items={[desktop]}
itemsType={'group'}
variant={'filled'}
diff --git a/src/features/Settings/hotkey/features/Essential.tsx b/src/features/Settings/hotkey/features/Essential.tsx
index 6c8f646b367..f038fe5d9cf 100644
--- a/src/features/Settings/hotkey/features/Essential.tsx
+++ b/src/features/Settings/hotkey/features/Essential.tsx
@@ -1,9 +1,9 @@
'use client';
import { HotkeyGroupEnum } from '@lobechat/const/hotkeys';
-import { type FormGroupItemType } from '@lobehub/ui';
-import { Form, HotkeyInput } from '@lobehub/ui';
+import { HotkeyInput } from '@lobehub/ui';
import { Skeleton } from '@lobehub/ui/base-ui';
+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import isEqual from 'fast-deep-equal';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -16,23 +16,25 @@ import { useSaveState } from '@/hooks/useSaveState';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
import { type HotkeyItem } from '@/types/hotkey';
-
-import { hotkeyFormStyles } from './styles';
+import { type UserHotkeyConfig } from '@/types/user/settings';
const HotkeySetting = memo(() => {
const { t } = useTranslation(['setting', 'hotkey']);
- const [form] = Form.useForm();
-
const { hotkey } = useUserStore(settingsSelectors.currentSettings, isEqual);
const [setSettings, isUserStateInit] = useUserStore((s) => [s.setSettings, s.isUserStateInit]);
const { status: saveStatus, lastSavedAt, save, retry } = useSaveState();
+ const form = useForm({
+ initialValues: hotkey,
+ values: hotkey,
+ onValuesChange: (values) => save(() => setSettings({ hotkey: values })),
+ });
if (!isUserStateInit) return <Skeleton.Text rows={5} />;
const clearHotkeyBinding = (id: HotkeyItem['id']) => {
if (!hotkey[id]) return;
- form.setFieldValue(id, '');
+ form.setValue(id, '');
save(() => setSettings({ hotkey: { [id]: '' } }));
};
@@ -61,7 +63,7 @@ const HotkeySetting = memo(() => {
};
};
- const essential: FormGroupItemType = {
+ const essential: FormGroupItem<UserHotkeyConfig> = {
children: HOTKEYS_REGISTRATION.filter((item) => item.group === HotkeyGroupEnum.Essential).map(
(item) => mapHotkeyItem(item),
),
@@ -78,14 +80,11 @@ const HotkeySetting = memo(() => {
return (
<Form
- classNames={{ item: hotkeyFormStyles.item }}
collapsible={false}
form={form}
- initialValues={hotkey}
items={[essential]}
itemsType={'group'}
variant={'filled'}
- onValuesChange={(values) => save(() => setSettings({ hotkey: values }))}
{...FORM_STYLE}
/>
);
diff --git a/src/features/Settings/hotkey/features/styles.ts b/src/features/Settings/hotkey/features/styles.ts
deleted file mode 100644
index ac3b3d94c0f..00000000000
--- a/src/features/Settings/hotkey/features/styles.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { createStaticStyles } from 'antd-style';
-
-export const hotkeyFormStyles = createStaticStyles(({ css }) => ({
- item: css`
- .ant-form-item-label > label {
- align-items: center;
- min-block-size: 36px;
- }
- `,
-}));
diff --git a/src/features/Settings/image/features/Image.tsx b/src/features/Settings/image/features/Image.tsx
index 92b3ce759a0..1e726c10a83 100644
--- a/src/features/Settings/image/features/Image.tsx
+++ b/src/features/Settings/image/features/Image.tsx
@@ -1,9 +1,10 @@
'use client';
import { type UserImageConfig } from '@lobechat/types';
-import { type FormGroupItemType } from '@lobehub/ui';
-import { Form } from '@lobehub/ui';
+import { Flexbox, Icon, Tooltip } from '@lobehub/ui';
import { Skeleton, Spin } from '@lobehub/ui/base-ui';
+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
+import { CircleHelpIcon } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -18,32 +19,55 @@ import { settingsSelectors } from '@/store/user/slices/settings/selectors';
const ImageSettings = memo(() => {
const { t } = useTranslation('setting');
const { allowed: canManageServiceModel, reason } = usePermission('manage_settings');
- const [form] = Form.useForm<UserImageConfig>();
const [isUpdating, setIsUpdating] = useState(false);
const imageSettings = useUserStore(settingsSelectors.currentImageSettings);
const [setSettings, isUserStateInit] = useUserStore((s) => [s.setSettings, s.isUserStateInit]);
+ const form = useForm<UserImageConfig>({
+ initialValues: imageSettings,
+ values: imageSettings,
+ onValuesChange: async (values) => {
+ if (!canManageServiceModel) return;
+
+ setIsUpdating(true);
+ try {
+ await setSettings({ image: values });
+ } finally {
+ setIsUpdating(false);
+ }
+ },
+ });
if (!isUserStateInit) {
return <Skeleton.Text rows={1} />;
}
- const items: FormGroupItemType[] = [
+ const items: FormGroupItem<UserImageConfig>[] = [
{
children: [
{
- children: (
+ desc: t('settingImage.defaultCount.desc'),
+ label: (
+ <Flexbox horizontal align={'center'} gap={4}>
+ {t('settingImage.defaultCount.label')}
+ {reason && (
+ <Tooltip title={reason}>
+ <Icon icon={CircleHelpIcon} size={14} style={{ cursor: 'help' }} />
+ </Tooltip>
+ )}
+ </Flexbox>
+ ),
+ name: 'defaultImageNum',
+ render: ({ value, onChange }) => (
<FormSliderWithInput
disabled={isUpdating || !canManageServiceModel}
max={MAX_DEFAULT_IMAGE_NUM}
min={MIN_DEFAULT_IMAGE_NUM}
step={1}
+ value={value}
+ onChange={onChange}
/>
),
- desc: t('settingImage.defaultCount.desc'),
- label: t('settingImage.defaultCount.label'),
- name: 'defaultImageNum',
- tooltip: reason,
},
],
extra: isUpdating ? <Spin size="small" style={{ opacity: 0.6 }} /> : undefined,
@@ -59,20 +83,9 @@ const ImageSettings = memo(() => {
<Form
collapsible={false}
form={form}
- initialValues={imageSettings}
items={items}
itemsType={'group'}
variant={'filled'}
- onValuesChange={async (values) => {
- if (!canManageServiceModel) return;
-
- setIsUpdating(true);
- try {
- await setSettings({ image: values });
- } finally {
- setIsUpdating(false);
- }
- }}
{...FORM_STYLE}
/>
);
diff --git a/src/features/Settings/labs/index.tsx b/src/features/Settings/labs/index.tsx
index 1b33777ca3a..b99d96ad19c 100644
--- a/src/features/Settings/labs/index.tsx
+++ b/src/features/Settings/labs/index.tsx
@@ -1,10 +1,9 @@
'use client';
import { isDesktop } from '@lobechat/const';
-import { type FormGroupItemType, type FormItemProps } from '@lobehub/ui';
-import { Flexbox, Form, Tooltip } from '@lobehub/ui';
+import { Flexbox, Tooltip } from '@lobehub/ui';
import { Alert, Skeleton, Switch, Tag } from '@lobehub/ui/base-ui';
-import { createStaticStyles } from 'antd-style';
+import { Form, type FormFieldProps, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import { FlaskConicalIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -18,14 +17,6 @@ import { labPreferSelectors, preferenceSelectors } from '@/store/user/selectors'
import { LAB_FEATURES, type LabFeatureItem, type LabStage } from './features';
-const styles = createStaticStyles(({ css }) => ({
- labItem: css`
- .ant-form-item-row {
- align-items: center !important;
- }
- `,
-}));
-
const StageTag = memo<{ stage: LabStage }>(({ stage }) => {
const { t } = useTranslation('labs');
@@ -52,6 +43,7 @@ const LabsForm = memo(() => {
const labChecked = useUserStore((s) =>
LAB_FEATURES.map(({ flag }) => labPreferSelectors[flag](s)),
);
+ const form = useForm();
if (!isUserStateInit) {
// A failed user-state init must show error + Retry, not a permanent skeleton
@@ -70,7 +62,7 @@ const LabsForm = memo(() => {
LAB_FEATURES.map(({ flag }, index) => [flag, labChecked[index]]),
);
- const toFormItem = ({ flag, i18nKey, stage }: LabFeatureItem): FormItemProps => ({
+ const toFormItem = ({ flag, i18nKey, stage }: LabFeatureItem): FormFieldProps => ({
children: (
<Switch
checked={checkedByFlag[flag]}
@@ -78,7 +70,6 @@ const LabsForm = memo(() => {
onChange={(next: boolean) => updateLab({ [flag]: next })}
/>
),
- className: styles.labItem,
desc: tLabs(`features.${i18nKey}.desc`),
label: (
<SettingsSearchAnchor id={`labs-${flag}`}>
@@ -98,7 +89,7 @@ const LabsForm = memo(() => {
// in-app browser (renderer-retained Electron webviews).
const desktopItems = LAB_FEATURES.filter((feature) => feature.desktopOnly);
- const items: FormGroupItemType[] = [
+ const items: FormGroupItem[] = [
{
children: generalItems.map((item) => toFormItem(item)),
title: tLabs('group.general'),
@@ -117,6 +108,7 @@ const LabsForm = memo(() => {
return (
<Form
collapsible={false}
+ form={form}
items={items}
itemsType={'group'}
variant={'filled'}
diff --git a/src/features/Settings/memory/features/Memory.tsx b/src/features/Settings/memory/features/Memory.tsx
index 67db99d53cb..84d9d4ac365 100644
--- a/src/features/Settings/memory/features/Memory.tsx
+++ b/src/features/Settings/memory/features/Memory.tsx
@@ -1,10 +1,11 @@
'use client';
-import { type UserMemoryEffort } from '@lobechat/types';
-import { type FormGroupItemType } from '@lobehub/ui';
-import { Form, Tooltip } from '@lobehub/ui';
+import { type UserMemoryEffort, type UserMemorySettings } from '@lobechat/types';
+import { Flexbox, Icon, Tooltip } from '@lobehub/ui';
import { Skeleton, Switch } from '@lobehub/ui/base-ui';
+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import isEqual from 'fast-deep-equal';
+import { CircleHelpIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -21,25 +22,41 @@ const MEMORY_EFFORT_LEVELS: readonly UserMemoryEffort[] = ['low', 'medium', 'hig
const MemorySetting = memo(() => {
const { t } = useTranslation('setting');
const { allowed: canManageMemory, reason } = usePermission('manage_settings');
- const [form] = Form.useForm();
const memory = useUserStore(settingsSelectors.currentMemorySettings, isEqual);
const memoryEnabled = useUserStore(settingsSelectors.memoryEnabled);
const [setSettings, isUserStateInit] = useUserStore((s) => [s.setSettings, s.isUserStateInit]);
const { status: saveStatus, lastSavedAt, save, retry } = useSaveState();
+ const memoryValues: UserMemorySettings = { ...memory, enabled: memoryEnabled };
+ const form = useForm({
+ initialValues: memoryValues,
+ values: memoryValues,
+ onValuesChange: (values) => {
+ if (!canManageMemory) return;
+
+ save(() => setSettings({ memory: values }));
+ },
+ });
if (!isUserStateInit) return <Skeleton.Text rows={3} />;
- const memorySettings: FormGroupItemType = {
+ const memorySettings: FormGroupItem<UserMemorySettings> = {
children: [
{
children: <Switch disabled={!canManageMemory} />,
desc: t('memory.enabled.desc'),
- label: t('memory.enabled.title'),
+ label: (
+ <Flexbox horizontal align={'center'} gap={4}>
+ {t('memory.enabled.title')}
+ {reason && (
+ <Tooltip title={reason}>
+ <Icon icon={CircleHelpIcon} size={14} style={{ cursor: 'help' }} />
+ </Tooltip>
+ )}
+ </Flexbox>
+ ),
layout: 'horizontal',
minWidth: undefined,
name: 'enabled',
- tooltip: reason,
- valuePropName: 'checked',
},
{
children: (
@@ -77,15 +94,9 @@ const MemorySetting = memo(() => {
<Form
collapsible={false}
form={form}
- initialValues={{ ...memory, enabled: memoryEnabled }}
items={[memorySettings]}
itemsType={'group'}
variant={'filled'}
- onValuesChange={(values) => {
- if (!canManageMemory) return;
-
- save(() => setSettings({ memory: values }));
- }}
{...FORM_STYLE}
/>
);
diff --git a/src/features/Settings/notification/index.tsx b/src/features/Settings/notification/index.tsx
index 81bd161b738..cae30f2bc23 100644
--- a/src/features/Settings/notification/index.tsx
+++ b/src/features/Settings/notification/index.tsx
@@ -2,8 +2,9 @@ import {
COMPLETION_BUILTIN_SOUNDS,
type CompletionSoundSettings,
} from '@lobechat/electron-client-ipc';
-import { Flexbox, Form } from '@lobehub/ui';
+import { Flexbox } from '@lobehub/ui';
import { Alert, Button, Segmented, Select, Skeleton, Slider, Switch } from '@lobehub/ui/base-ui';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import { Play } from 'lucide-react';
import { useCallback, useEffect, useId, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -25,6 +26,7 @@ export const DesktopNotificationSettings = () => {
const [settings, setSettings] = useState<CompletionSoundSettings>();
const [busy, setBusy] = useState(false);
const [error, setError] = useState(false);
+ const form = useForm();
const report = useCallback(async (action: () => Promise<CompletionSoundSettings | void>) => {
setError(false);
@@ -83,6 +85,7 @@ export const DesktopNotificationSettings = () => {
) : (
<Form
collapsible={false}
+ form={form}
itemMinWidth={FORM_STYLE.itemMinWidth}
itemsType={'group'}
style={FORM_STYLE.style}
@@ -92,19 +95,17 @@ export const DesktopNotificationSettings = () => {
children: [
{
children: (
- <Flexbox horizontal justify={'flex-end'}>
- <Switch
- checked={settings.enabled}
- disabled={busy}
- id={soundToggleId}
- onChange={(enabled) =>
- run(() => completionSoundService.setSettings({ enabled }))
- }
- />
- </Flexbox>
+ <Switch
+ checked={settings.enabled}
+ disabled={busy}
+ id={soundToggleId}
+ style={{ alignSelf: 'flex-end' }}
+ onChange={(enabled) =>
+ run(() => completionSoundService.setSettings({ enabled }))
+ }
+ />
),
desc: t('completionSound.desc'),
- htmlFor: soundToggleId,
label: (
<SettingsSearchAnchor id={'notification-completion-sound'}>
{t('completionSound.enabled')}
diff --git a/src/features/Settings/oauth-apps/features/AppDetail/BasicInfoCard.tsx b/src/features/Settings/oauth-apps/features/AppDetail/BasicInfoCard.tsx
index 5c7cc29ff4a..deba28b00ab 100644
--- a/src/features/Settings/oauth-apps/features/AppDetail/BasicInfoCard.tsx
+++ b/src/features/Settings/oauth-apps/features/AppDetail/BasicInfoCard.tsx
@@ -2,7 +2,7 @@
import { Flexbox } from '@lobehub/ui';
import { Button, Input, Text, TextArea } from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import { PencilIcon } from 'lucide-react';
import { type FC, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -26,8 +26,8 @@ interface BasicInfoCardProps {
/**
* Name, logo and description, read-only until the user asks to edit. The edit
- * form mounts fresh from the saved values each time, so cancelling needs no
- * reset and a half-typed change never lingers into the next edit.
+ * form is reset to the saved values each time editing starts, so cancelling
+ * needs no reset and a half-typed change never lingers into the next edit.
*/
const BasicInfoCard: FC<BasicInfoCardProps> = ({ canEdit, detail, onSubmit }) => {
const { t } = useTranslation('auth');
@@ -40,7 +40,10 @@ const BasicInfoCard: FC<BasicInfoCardProps> = ({ canEdit, detail, onSubmit }) =>
const [logoChanged, setLogoChanged] = useState(false);
const { upload: uploadLogo, uploading: logoUploading } = useLogoUpload();
+ const form = useForm<BasicInfoValues>({ onSubmit: (values) => handleFinish(values) });
+
const startEditing = () => {
+ form.reset({ description: detail.description ?? '', name: detail.name });
setLogoUri(detail.logoUri ?? null);
setLogoChanged(false);
setEditing(true);
@@ -72,7 +75,7 @@ const BasicInfoCard: FC<BasicInfoCardProps> = ({ canEdit, detail, onSubmit }) =>
}
};
- const itemStyle = { marginBottom: 0 };
+ const itemStyle = { paddingBlock: 0 };
return (
<SectionCard
@@ -91,14 +94,9 @@ const BasicInfoCard: FC<BasicInfoCardProps> = ({ canEdit, detail, onSubmit }) =>
}
>
{editing ? (
- <Form
- colon={false}
- initialValues={{ description: detail.description ?? '', name: detail.name }}
- layout={'vertical'}
- onFinish={handleFinish}
- >
+ <Form form={form} layout={'vertical'}>
<Flexbox gap={16}>
- <Form.Item label={t('oauthApp.form.logo.label')} style={itemStyle}>
+ <Form.Field label={t('oauthApp.form.logo.label')} style={itemStyle}>
<AvatarUpload
allowDelete={!!logoUri}
loading={logoUploading}
@@ -107,24 +105,24 @@ const BasicInfoCard: FC<BasicInfoCardProps> = ({ canEdit, detail, onSubmit }) =>
onDelete={handleDeleteLogo}
onUpload={handleUpload}
/>
- </Form.Item>
+ </Form.Field>
- <Form.Item
+ <Form.Field
label={t('oauthApp.form.name.label')}
name={'name'}
- rules={[{ message: t('oauthApp.validation.nameRequired'), required: true }]}
+ required={t('oauthApp.validation.nameRequired')}
style={itemStyle}
>
<Input placeholder={t('oauthApp.form.name.placeholder')} />
- </Form.Item>
+ </Form.Field>
- <Form.Item
+ <Form.Field
label={t('oauthApp.form.description.label')}
name={'description'}
style={itemStyle}
>
<TextArea placeholder={t('oauthApp.form.description.placeholder')} rows={3} />
- </Form.Item>
+ </Form.Field>
<Flexbox horizontal gap={8} justify={'flex-end'}>
<Button onClick={() => setEditing(false)}>{t('oauthApp.detail.cancel')}</Button>
diff --git a/src/features/Settings/oauth-apps/features/AppDetail/RedirectUrisCard.tsx b/src/features/Settings/oauth-apps/features/AppDetail/RedirectUrisCard.tsx
index 12ec93ed403..4b03d283d0c 100644
--- a/src/features/Settings/oauth-apps/features/AppDetail/RedirectUrisCard.tsx
+++ b/src/features/Settings/oauth-apps/features/AppDetail/RedirectUrisCard.tsx
@@ -2,7 +2,7 @@
import { Flexbox } from '@lobehub/ui';
import { ActionIcon, Alert, Button, Input, Text } from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import { createStaticStyles } from 'antd-style';
import { PencilIcon, PlusIcon, Trash2Icon } from 'lucide-react';
import { type FC, useState } from 'react';
@@ -19,8 +19,10 @@ import {
import SectionCard from './SectionCard';
const styles = createStaticStyles(({ css, cssVar }) => ({
- // antd's ErrorList only picks up error styling inside a Form.Item that has an
- // error status; the list-level message sits outside one, so it is colored here.
+ fieldError: css`
+ font-size: 12px;
+ color: ${cssVar.colorError};
+ `,
listError: css`
font-size: 14px;
line-height: 1.5;
@@ -70,6 +72,13 @@ const RedirectUrisCard: FC<RedirectUrisCardProps> = ({ canEdit, detail, onSubmit
}
};
+ const form = useForm<RedirectUrisValues>({ onSubmit: handleFinish });
+
+ const startEditing = () => {
+ form.reset({ redirectUris: saved.length > 0 ? saved : [''] });
+ setEditing(true);
+ };
+
return (
<SectionCard
title={t('oauthApp.redirectUris.title')}
@@ -79,7 +88,7 @@ const RedirectUrisCard: FC<RedirectUrisCardProps> = ({ canEdit, detail, onSubmit
disabled={!canEdit}
icon={<PencilIcon size={14} />}
size={'small'}
- onClick={() => setEditing(true)}
+ onClick={startEditing}
>
{t(saved.length > 0 ? 'oauthApp.detail.edit' : 'oauthApp.redirectUris.configure')}
</Button>
@@ -87,58 +96,60 @@ const RedirectUrisCard: FC<RedirectUrisCardProps> = ({ canEdit, detail, onSubmit
}
>
{editing ? (
- <Form
- colon={false}
- initialValues={{ redirectUris: saved.length > 0 ? saved : [''] }}
- layout={'vertical'}
- onFinish={handleFinish}
- >
+ <Form form={form} layout={'vertical'}>
<Flexbox gap={12}>
<Text style={{ fontSize: 12 }} type={'secondary'}>
{t('oauthApp.form.redirectUris.extra')}
</Text>
- <Form.List
- name={'redirectUris'}
- rules={[
- {
- validator: async (_, values?: (string | undefined)[]) => {
- const messageKey = redirectUriListMessageKey(values);
- if (messageKey)
- throw new Error(t(messageKey, { count: MAX_OAUTH_REDIRECT_URIS }));
- },
- },
- ]}
- >
- {(fields, { add, remove }, { errors }) => (
+ <Form.List name={'redirectUris'}>
+ {({ fields, add, remove }) => (
<Flexbox gap={8}>
{fields.map((field) => (
<Flexbox horizontal align={'flex-start'} gap={8} key={field.key}>
- <Form.Item
- name={field.name}
- style={{ flex: 1, marginBottom: 0 }}
- rules={[
- {
- validator: async (_, value?: string) => {
- const messageKey = redirectUriMessageKey(value);
- if (messageKey) throw new Error(t(messageKey));
- },
- },
- ]}
- >
- <Input placeholder={t('oauthApp.form.redirectUris.placeholder')} />
- </Form.Item>
+ <Form.Field
+ bare
+ name={`redirectUris.${field.index}`}
+ render={({ error, onBlur, onChange, value }) => (
+ <Flexbox flex={1} gap={4}>
+ <Input
+ aria-invalid={error ? true : undefined}
+ placeholder={t('oauthApp.form.redirectUris.placeholder')}
+ value={value}
+ onBlur={onBlur}
+ onChange={(e) => onChange(e.target.value)}
+ />
+ {error && <div className={styles.fieldError}>{error}</div>}
+ </Flexbox>
+ )}
+ validate={(value?: string) => {
+ const messageKey = redirectUriMessageKey(value);
+ return messageKey ? t(messageKey) : undefined;
+ }}
+ />
<ActionIcon
aria-label={t('oauthApp.redirectUris.remove')}
icon={Trash2Icon}
style={{ marginTop: 4 }}
title={t('oauthApp.redirectUris.remove')}
- onClick={() => remove(field.name)}
+ onClick={() => remove(field.index)}
/>
</Flexbox>
))}
- {errors.length > 0 && <div className={styles.listError}>{errors}</div>}
+ <Form.Field
+ bare
+ name={'redirectUris'}
+ render={({ error }) =>
+ error ? <div className={styles.listError}>{error}</div> : null
+ }
+ validate={(values?: (string | undefined)[]) => {
+ const messageKey = redirectUriListMessageKey(values);
+ return messageKey
+ ? t(messageKey, { count: MAX_OAUTH_REDIRECT_URIS })
+ : undefined;
+ }}
+ />
<Button
block
diff --git a/src/features/Settings/oauth-apps/features/CreateAppModal/Content.tsx b/src/features/Settings/oauth-apps/features/CreateAppModal/Content.tsx
index a7ff11015da..3e61f20b4ea 100644
--- a/src/features/Settings/oauth-apps/features/CreateAppModal/Content.tsx
+++ b/src/features/Settings/oauth-apps/features/CreateAppModal/Content.tsx
@@ -3,7 +3,7 @@
import { type OAuthAppType } from '@lobechat/types';
import { Flexbox, Icon } from '@lobehub/ui';
import { Button, Input, Text, TextArea, useModalContext } from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form, useForm, useWatch } from '@lobehub/ui/base-ui/form';
import { createStaticStyles, cx } from 'antd-style';
import { CheckIcon, GlobeIcon, type LucideIcon, TerminalIcon } from 'lucide-react';
import { type FC, useState } from 'react';
@@ -134,8 +134,6 @@ export interface CreateAppModalContentProps {
const CreateAppModalContent: FC<CreateAppModalContentProps> = ({ onSubmit }) => {
const { t } = useTranslation('auth');
const { close, setCanDismissByClickOutside } = useModalContext();
- const [form] = Form.useForm<CreateAppFormValues>();
- const type = Form.useWatch('type', form);
const [loading, setLoading] = useState(false);
const [logoUri, setLogoUri] = useState<string>();
@@ -143,6 +141,13 @@ const CreateAppModalContent: FC<CreateAppModalContentProps> = ({ onSubmit }) =>
// silently drop the user's input); the explicit ✕/ESC close still works.
const markDirty = () => setCanDismissByClickOutside(false);
+ const form = useForm<CreateAppFormValues>({
+ initialValues: { type: 'device' } as CreateAppFormValues,
+ onSubmit: (values) => handleFinish(values),
+ onValuesChange: markDirty,
+ });
+ const type = useWatch(form, 'type');
+
const { upload: uploadLogo, uploading: logoUploading } = useLogoUpload();
const handleUpload = async (file: File) => {
@@ -170,19 +175,12 @@ const CreateAppModalContent: FC<CreateAppModalContentProps> = ({ onSubmit }) =>
}
};
- const itemStyle = { marginBottom: 0 };
+ const itemStyle = { paddingBlock: 0 };
return (
- <Form
- colon={false}
- form={form}
- initialValues={{ type: 'device' }}
- layout={'vertical'}
- onFinish={handleFinish}
- onValuesChange={markDirty}
- >
+ <Form form={form} layout={'vertical'}>
<Flexbox gap={16}>
- <Form.Item label={t('oauthApp.form.logo.label')} style={itemStyle}>
+ <Form.Field label={t('oauthApp.form.logo.label')} style={itemStyle}>
<AvatarUpload
allowDelete={!!logoUri}
loading={logoUploading}
@@ -191,18 +189,18 @@ const CreateAppModalContent: FC<CreateAppModalContentProps> = ({ onSubmit }) =>
onDelete={() => setLogoUri(undefined)}
onUpload={handleUpload}
/>
- </Form.Item>
+ </Form.Field>
- <Form.Item
+ <Form.Field
label={t('oauthApp.form.name.label')}
name={'name'}
- rules={[{ message: t('oauthApp.validation.nameRequired'), required: true }]}
+ required={t('oauthApp.validation.nameRequired')}
style={itemStyle}
>
<Input placeholder={t('oauthApp.form.name.placeholder')} />
- </Form.Item>
+ </Form.Field>
- <Form.Item
+ <Form.Field
label={t('oauthApp.form.type.label')}
name={'type'}
style={itemStyle}
@@ -229,15 +227,15 @@ const CreateAppModalContent: FC<CreateAppModalContentProps> = ({ onSubmit }) =>
},
]}
/>
- </Form.Item>
+ </Form.Field>
- <Form.Item
+ <Form.Field
label={t('oauthApp.form.description.label')}
name={'description'}
style={itemStyle}
>
<TextArea placeholder={t('oauthApp.form.description.placeholder')} rows={3} />
- </Form.Item>
+ </Form.Field>
<Button
block
diff --git a/src/features/Settings/oauth-apps/features/SecretModal/index.tsx b/src/features/Settings/oauth-apps/features/SecretModal/index.tsx
index dbda30cd22a..c8b28e616d2 100644
--- a/src/features/Settings/oauth-apps/features/SecretModal/index.tsx
+++ b/src/features/Settings/oauth-apps/features/SecretModal/index.tsx
@@ -9,8 +9,8 @@ import { useTranslation } from 'react-i18next';
const styles = createStaticStyles(({ css, cssVar }) => ({
secret: css`
- padding-block: 8px;
- padding-inline: 12px;
+ padding-block: 4px;
+ padding-inline: 12px 4px;
border-radius: ${cssVar.borderRadius};
font-family: ${cssVar.fontFamilyCode};
@@ -31,8 +31,8 @@ const ClientSecretContent: FC<ClientSecretContentProps> = ({ clientSecret }) =>
return (
<Flexbox gap={12}>
<Alert message={t('oauthApp.secret.onceWarning')} type={'warning'} />
- <div className={styles.secret}>{clientSecret}</div>
- <Flexbox horizontal justify={'flex-end'}>
+ <Flexbox horizontal align={'center'} className={styles.secret} gap={8}>
+ <Flexbox flex={1}>{clientSecret}</Flexbox>
<CopyButton content={clientSecret} title={t('oauthApp.secret.copy')} />
</Flexbox>
<Text style={{ fontSize: 12 }} type={'secondary'}>
diff --git a/src/features/Settings/profile/index.tsx b/src/features/Settings/profile/index.tsx
index fd9611f4f32..8be8a2ad7de 100644
--- a/src/features/Settings/profile/index.tsx
+++ b/src/features/Settings/profile/index.tsx
@@ -1,8 +1,9 @@
'use client';
import { isDesktop } from '@lobechat/const';
-import { Flexbox, FormGroup } from '@lobehub/ui';
+import { Flexbox } from '@lobehub/ui';
import { Divider } from '@lobehub/ui/base-ui';
+import { Form } from '@lobehub/ui/base-ui/form';
import { useEffect } from 'react';
import { useTranslation } from 'react-i18next';
@@ -66,7 +67,7 @@ const ProfileSetting = ({ showSettingHeader = true }: ProfileSettingProps) => {
return (
<>
{showSettingHeader && <SettingHeader title={t('profile.title')} />}
- <FormGroup collapsible={false} gap={16} title={t('profile.account')} variant={'filled'}>
+ <Form.Group collapsible={false} title={t('profile.account')} variant={'filled'}>
<Flexbox style={{ display: isLoading ? 'flex' : 'none' }}>
<SettingsProfileRowSkeleton />
<Divider style={{ margin: 0 }} />
@@ -126,7 +127,7 @@ const ProfileSetting = ({ showSettingHeader = true }: ProfileSettingProps) => {
</>
)}
</Flexbox>
- </FormGroup>
+ </Form.Group>
</>
);
};
diff --git a/src/features/Settings/provider/detail/azure/index.tsx b/src/features/Settings/provider/detail/azure/index.tsx
index d6c093589c8..78bb4596cd7 100644
--- a/src/features/Settings/provider/detail/azure/index.tsx
+++ b/src/features/Settings/provider/detail/azure/index.tsx
@@ -41,7 +41,7 @@ const useProviderCard = (): ProviderItem => {
),
desc: t('azure.token.desc'),
label: t('azure.token.title'),
- name: [KeyVaultsConfigKey, LLMProviderApiTokenKey],
+ name: `${KeyVaultsConfigKey}.${LLMProviderApiTokenKey}`,
},
{
children: isLoading ? (
@@ -51,7 +51,7 @@ const useProviderCard = (): ProviderItem => {
),
desc: t('azure.endpoint.desc'),
label: t('azure.endpoint.title'),
- name: [KeyVaultsConfigKey, LLMProviderBaseUrlKey],
+ name: `${KeyVaultsConfigKey}.${LLMProviderBaseUrlKey}`,
},
],
checkModel,
diff --git a/src/features/Settings/provider/detail/azureai/index.tsx b/src/features/Settings/provider/detail/azureai/index.tsx
index 0a797f70a84..ad8336ec6b4 100644
--- a/src/features/Settings/provider/detail/azureai/index.tsx
+++ b/src/features/Settings/provider/detail/azureai/index.tsx
@@ -33,7 +33,7 @@ const useProviderCard = (): ProviderItem => {
),
desc: t('azureai.token.desc'),
label: t('azureai.token.title'),
- name: [KeyVaultsConfigKey, LLMProviderApiTokenKey],
+ name: `${KeyVaultsConfigKey}.${LLMProviderApiTokenKey}`,
},
{
children: isLoading ? (
@@ -43,7 +43,7 @@ const useProviderCard = (): ProviderItem => {
),
desc: t('azureai.endpoint.desc'),
label: t('azureai.endpoint.title'),
- name: [KeyVaultsConfigKey, LLMProviderBaseUrlKey],
+ name: `${KeyVaultsConfigKey}.${LLMProviderBaseUrlKey}`,
},
],
};
diff --git a/src/features/Settings/provider/detail/bedrock/index.tsx b/src/features/Settings/provider/detail/bedrock/index.tsx
index f1792ff6cd9..30fd2665c2c 100644
--- a/src/features/Settings/provider/detail/bedrock/index.tsx
+++ b/src/features/Settings/provider/detail/bedrock/index.tsx
@@ -122,8 +122,7 @@ const useBedrockCard = (): ProviderItem => {
),
desc: t(`${providerKey}.apiKey.desc`),
label: t(`${providerKey}.apiKey.title`),
- name: [KeyVaultsConfigKey, 'apiKey'],
- preserve: false,
+ name: `${KeyVaultsConfigKey}.apiKey`,
};
const awsCredentialItems = [
@@ -138,8 +137,7 @@ const useBedrockCard = (): ProviderItem => {
),
desc: t(`${providerKey}.accessKeyId.desc`),
label: t(`${providerKey}.accessKeyId.title`),
- name: [KeyVaultsConfigKey, 'accessKeyId'],
- preserve: false,
+ name: `${KeyVaultsConfigKey}.accessKeyId`,
},
{
children: isLoading ? (
@@ -152,8 +150,7 @@ const useBedrockCard = (): ProviderItem => {
),
desc: t(`${providerKey}.secretAccessKey.desc`),
label: t(`${providerKey}.secretAccessKey.title`),
- name: [KeyVaultsConfigKey, 'secretAccessKey'],
- preserve: false,
+ name: `${KeyVaultsConfigKey}.secretAccessKey`,
},
{
children: isLoading ? (
@@ -166,8 +163,7 @@ const useBedrockCard = (): ProviderItem => {
),
desc: t(`${providerKey}.sessionToken.desc`),
label: t(`${providerKey}.sessionToken.title`),
- name: [KeyVaultsConfigKey, 'sessionToken'],
- preserve: false,
+ name: `${KeyVaultsConfigKey}.sessionToken`,
},
];
@@ -207,7 +203,7 @@ const useBedrockCard = (): ProviderItem => {
),
desc: t(`${providerKey}.region.desc`),
label: t(`${providerKey}.region.title`),
- name: [KeyVaultsConfigKey, 'region'],
+ name: `${KeyVaultsConfigKey}.region`,
},
],
normalizeConfigValues: normalizeBedrockConfigValues(authMode),
diff --git a/src/features/Settings/provider/detail/cloudflare/index.tsx b/src/features/Settings/provider/detail/cloudflare/index.tsx
index 314b6b3f47a..355ce7f4432 100644
--- a/src/features/Settings/provider/detail/cloudflare/index.tsx
+++ b/src/features/Settings/provider/detail/cloudflare/index.tsx
@@ -33,7 +33,7 @@ const useProviderCard = (): ProviderItem => {
),
desc: t(`${providerKey}.apiKey.desc`),
label: t(`${providerKey}.apiKey.title`),
- name: [KeyVaultsConfigKey, 'apiKey'],
+ name: `${KeyVaultsConfigKey}.apiKey`,
},
{
children: isLoading ? (
@@ -43,7 +43,7 @@ const useProviderCard = (): ProviderItem => {
),
desc: t(`${providerKey}.baseURLOrAccountID.desc`),
label: t(`${providerKey}.baseURLOrAccountID.title`),
- name: [KeyVaultsConfigKey, 'baseURLOrAccountID'],
+ name: `${KeyVaultsConfigKey}.baseURLOrAccountID`,
},
],
};
diff --git a/src/features/Settings/provider/detail/comfyui/index.tsx b/src/features/Settings/provider/detail/comfyui/index.tsx
index b630970bfed..b906a477d6a 100644
--- a/src/features/Settings/provider/detail/comfyui/index.tsx
+++ b/src/features/Settings/provider/detail/comfyui/index.tsx
@@ -42,7 +42,7 @@ const useComfyUICard = (): ProviderItem => {
),
desc: t('comfyui.baseURL.desc'),
label: t('comfyui.baseURL.title'),
- name: [KeyVaultsConfigKey, 'baseURL'],
+ name: `${KeyVaultsConfigKey}.baseURL`,
},
// Authentication Type Selector - Always shown
@@ -58,7 +58,7 @@ const useComfyUICard = (): ProviderItem => {
),
desc: t('comfyui.authType.desc'),
label: t('comfyui.authType.title'),
- name: [KeyVaultsConfigKey, 'authType'],
+ name: `${KeyVaultsConfigKey}.authType`,
},
];
@@ -73,7 +73,7 @@ const useComfyUICard = (): ProviderItem => {
),
desc: t('comfyui.username.desc'),
label: t('comfyui.username.title'),
- name: [KeyVaultsConfigKey, 'username'],
+ name: `${KeyVaultsConfigKey}.username`,
},
{
children: isLoading ? (
@@ -86,7 +86,7 @@ const useComfyUICard = (): ProviderItem => {
),
desc: t('comfyui.password.desc'),
label: t('comfyui.password.title'),
- name: [KeyVaultsConfigKey, 'password'],
+ name: `${KeyVaultsConfigKey}.password`,
},
);
}
@@ -100,7 +100,7 @@ const useComfyUICard = (): ProviderItem => {
),
desc: t('comfyui.apiKey.desc'),
label: t('comfyui.apiKey.title'),
- name: [KeyVaultsConfigKey, 'apiKey'],
+ name: `${KeyVaultsConfigKey}.apiKey`,
});
}
@@ -119,7 +119,7 @@ const useComfyUICard = (): ProviderItem => {
),
desc: t('comfyui.customHeaders.desc'),
label: t('comfyui.customHeaders.title'),
- name: [KeyVaultsConfigKey, 'customHeaders'],
+ name: `${KeyVaultsConfigKey}.customHeaders`,
});
}
diff --git a/src/features/Settings/provider/detail/github/index.tsx b/src/features/Settings/provider/detail/github/index.tsx
index 9ef79dad698..4a7e27e784f 100644
--- a/src/features/Settings/provider/detail/github/index.tsx
+++ b/src/features/Settings/provider/detail/github/index.tsx
@@ -51,7 +51,7 @@ const useProviderCard = (): ProviderItem => {
</Markdown>
),
label: t('github.personalAccessToken.title'),
- name: [KeyVaultsConfigKey, LLMProviderApiTokenKey],
+ name: `${KeyVaultsConfigKey}.${LLMProviderApiTokenKey}`,
},
],
};
diff --git a/src/features/Settings/provider/detail/vertexai/index.tsx b/src/features/Settings/provider/detail/vertexai/index.tsx
index 8d5660dae39..b9321d9ef91 100644
--- a/src/features/Settings/provider/detail/vertexai/index.tsx
+++ b/src/features/Settings/provider/detail/vertexai/index.tsx
@@ -94,7 +94,7 @@ const useProviderCard = (): ProviderItem => {
</Markdown>
),
label: t('vertexai.apiKey.title'),
- name: [KeyVaultsConfigKey, LLMProviderApiTokenKey],
+ name: `${KeyVaultsConfigKey}.${LLMProviderApiTokenKey}`,
},
{
children: isLoading ? (
@@ -115,7 +115,7 @@ const useProviderCard = (): ProviderItem => {
</Markdown>
),
label: t('vertexai.region.title'),
- name: [KeyVaultsConfigKey, 'region'],
+ name: `${KeyVaultsConfigKey}.region`,
},
],
};
diff --git a/src/features/Settings/provider/features/CreateNewProvider/Content.tsx b/src/features/Settings/provider/features/CreateNewProvider/Content.tsx
index ee8c232a141..881c9b5acf5 100644
--- a/src/features/Settings/provider/features/CreateNewProvider/Content.tsx
+++ b/src/features/Settings/provider/features/CreateNewProvider/Content.tsx
@@ -11,7 +11,7 @@ import {
toast,
useModalContext,
} from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import { AiProviderBaseURLSchema } from 'model-bank/aiProvider';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -33,7 +33,6 @@ const SectionTitle = memo<{ children: React.ReactNode }>(({ children }) => (
const CreateNewProviderContent = memo(() => {
const { t } = useTranslation('modelProvider');
- const [form] = Form.useForm<CreateAiProviderParams>();
const [loading, setLoading] = useState(false);
const createNewAiProvider = useAiInfraStore((s) => s.createNewAiProvider);
@@ -63,54 +62,40 @@ const CreateNewProviderContent = memo(() => {
}
};
- const itemStyle = { marginBottom: 0 };
+ const form = useForm<CreateAiProviderParams>({ onSubmit: onFinish });
+
+ const itemStyle = { paddingBlock: 0 };
return (
- <Form
- colon={false}
- form={form}
- layout={'vertical'}
- scrollToFirstError={{ behavior: 'instant', block: 'end', focus: true }}
- onFinish={onFinish}
- >
+ <Form form={form} layout={'vertical'}>
<Flexbox gap={16}>
<SectionTitle>{t('createNewAiProvider.basicTitle')}</SectionTitle>
- <Form.Item
+ <Form.Field
extra={t('createNewAiProvider.id.desc')}
label={t('createNewAiProvider.id.title')}
name={'id'}
+ required={t('createNewAiProvider.id.required')}
style={itemStyle}
- rules={[
- { message: t('createNewAiProvider.id.required'), required: true },
- {
- message: t('createNewAiProvider.id.format'),
- pattern: /^[\d_a-z-]+$/,
- },
- {
- message: t('createNewAiProvider.id.duplicate'),
- validator: (_, value: string) => {
- const list = useAiInfraStore.getState().aiProviderList;
- if (value && list.some((p) => p.id === value)) {
- return Promise.reject();
- }
- return Promise.resolve();
- },
- },
- ]}
+ validate={(value?: string) => {
+ if (!value) return;
+ if (!/^[\d_a-z-]+$/.test(value)) return t('createNewAiProvider.id.format');
+ const list = useAiInfraStore.getState().aiProviderList;
+ if (list.some((p) => p.id === value)) return t('createNewAiProvider.id.duplicate');
+ }}
>
<Input
autoFocus
placeholder={t('createNewAiProvider.id.placeholder')}
variant={'filled'}
/>
- </Form.Item>
+ </Form.Field>
- <Form.Item label={t('createNewAiProvider.name.title')} name={'name'} style={itemStyle}>
+ <Form.Field label={t('createNewAiProvider.name.title')} name={'name'} style={itemStyle}>
<Input placeholder={t('createNewAiProvider.name.placeholder')} variant={'filled'} />
- </Form.Item>
+ </Form.Field>
- <Form.Item
+ <Form.Field
label={t('createNewAiProvider.description.title')}
name={'description'}
style={itemStyle}
@@ -120,24 +105,24 @@ const CreateNewProviderContent = memo(() => {
style={{ minHeight: 72 }}
variant={'filled'}
/>
- </Form.Item>
+ </Form.Field>
- <Form.Item label={t('createNewAiProvider.logo.title')} name={'logo'} style={itemStyle}>
+ <Form.Field label={t('createNewAiProvider.logo.title')} name={'logo'} style={itemStyle}>
<Input
allowClear
placeholder={t('createNewAiProvider.logo.placeholder')}
variant={'filled'}
/>
- </Form.Item>
+ </Form.Field>
<div style={{ marginBlockStart: 8 }}>
<SectionTitle>{t('createNewAiProvider.configTitle')}</SectionTitle>
</div>
- <Form.Item
+ <Form.Field
label={t('createNewAiProvider.sdkType.title')}
- name={['settings', 'sdkType']}
- rules={[{ message: t('createNewAiProvider.sdkType.required'), required: true }]}
+ name={'settings.sdkType'}
+ required={t('createNewAiProvider.sdkType.required')}
style={itemStyle}
>
<Select
@@ -154,32 +139,29 @@ const CreateNewProviderContent = memo(() => {
);
}}
/>
- </Form.Item>
+ </Form.Field>
- <Form.Item
+ <Form.Field
label={t('createNewAiProvider.proxyUrl.title')}
- name={[KeyVaultsConfigKey, LLMProviderBaseUrlKey]}
+ name={`${KeyVaultsConfigKey}.${LLMProviderBaseUrlKey}`}
+ required={t('createNewAiProvider.proxyUrl.required')}
style={itemStyle}
- rules={[
- { message: t('createNewAiProvider.proxyUrl.required'), required: true },
- {
- validator: (_, value: string) =>
- !value || AiProviderBaseURLSchema.safeParse(value).success
- ? Promise.resolve()
- : Promise.reject(t('providerModels.config.baseURL.invalid')),
- },
- ]}
+ validate={(value?: string) =>
+ !value || AiProviderBaseURLSchema.safeParse(value).success
+ ? undefined
+ : t('providerModels.config.baseURL.invalid')
+ }
>
<Input
allowClear
placeholder={t('createNewAiProvider.proxyUrl.placeholder')}
variant={'filled'}
/>
- </Form.Item>
+ </Form.Field>
- <Form.Item
+ <Form.Field
label={t('createNewAiProvider.apiKey.title')}
- name={[KeyVaultsConfigKey, LLMProviderApiTokenKey]}
+ name={`${KeyVaultsConfigKey}.${LLMProviderApiTokenKey}`}
style={itemStyle}
>
<InputPassword
@@ -187,7 +169,7 @@ const CreateNewProviderContent = memo(() => {
placeholder={t('createNewAiProvider.apiKey.placeholder')}
variant={'filled'}
/>
- </Form.Item>
+ </Form.Field>
<Button block htmlType={'submit'} loading={loading} type={'primary'}>
{t('createNewAiProvider.confirm')}
diff --git a/src/features/Settings/provider/features/ModelList/CreateNewModelModal/Content.tsx b/src/features/Settings/provider/features/ModelList/CreateNewModelModal/Content.tsx
index bcc2006467b..75b6d2a3d58 100644
--- a/src/features/Settings/provider/features/ModelList/CreateNewModelModal/Content.tsx
+++ b/src/features/Settings/provider/features/ModelList/CreateNewModelModal/Content.tsx
@@ -1,6 +1,6 @@
'use client';
-import type { FormInstance } from 'antd';
+import type { FormInstance } from '@lobehub/ui/base-ui/form';
import { memo } from 'react';
import ModelConfigForm from './Form';
diff --git a/src/features/Settings/provider/features/ModelList/CreateNewModelModal/Footer.tsx b/src/features/Settings/provider/features/ModelList/CreateNewModelModal/Footer.tsx
index 9b1abb4ab2c..b35cba1e093 100644
--- a/src/features/Settings/provider/features/ModelList/CreateNewModelModal/Footer.tsx
+++ b/src/features/Settings/provider/features/ModelList/CreateNewModelModal/Footer.tsx
@@ -1,7 +1,8 @@
'use client';
import { Button, ModalFooter, useModalContext } from '@lobehub/ui/base-ui';
-import type { FormInstance } from 'antd';
+import type { FormInstance } from '@lobehub/ui/base-ui/form';
+import { type CreateAiModelParams } from 'model-bank';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -33,8 +34,12 @@ const CreateNewModelFooter = memo<CreateNewModelFooterProps>(({ formRef }) => {
setLoading(true);
try {
- await form.validateFields();
- const data = form.getFieldsValue();
+ const { valid } = await form.validate();
+ if (!valid) {
+ setLoading(false);
+ return;
+ }
+ const data = form.getValues() as Omit<CreateAiModelParams, 'providerId'>;
await createNewAiModel({ ...data, providerId: editingProvider });
setLoading(false);
close();
diff --git a/src/features/Settings/provider/features/ModelList/CreateNewModelModal/Form.tsx b/src/features/Settings/provider/features/ModelList/CreateNewModelModal/Form.tsx
index c33a010aac3..14a9e5a769c 100644
--- a/src/features/Settings/provider/features/ModelList/CreateNewModelModal/Form.tsx
+++ b/src/features/Settings/provider/features/ModelList/CreateNewModelModal/Form.tsx
@@ -1,12 +1,10 @@
import { Checkbox, Input, Select } from '@lobehub/ui/base-ui';
-import type { FormInstance } from 'antd';
-import { Form } from 'antd';
+import { Form, type FormInstance, type FormValues, useForm } from '@lobehub/ui/base-ui/form';
import type { AiModelType } from 'model-bank';
import { memo, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import MaxTokenSlider from '@/components/MaxTokenSlider';
-import { useIsMobile } from '@/hooks/useIsMobile';
import { type ChatModelCard } from '@/types/llm';
import ExtendParamsSelect from './ExtendParamsSelect';
@@ -33,9 +31,7 @@ const ModelConfigForm = memo<ModelConfigFormProps>(
}) => {
const { t } = useTranslation('modelProvider');
- const [formInstance] = Form.useForm();
-
- const isMobile = useIsMobile();
+ const formInstance = useForm<FormValues>({ initialValues });
const modelTypeOptions = useMemo(
() =>
@@ -63,123 +59,118 @@ const ModelConfigForm = memo<ModelConfigFormProps>(
e.stopPropagation();
}}
>
- <Form
- colon={false}
- disabled={disabled}
- form={formInstance}
- initialValues={initialValues}
- labelCol={{ span: 4 }}
- style={{ marginTop: 16 }}
- wrapperCol={isMobile ? { span: 18 } : { offset: 1, span: 18 }}
- >
- <Form.Item
+ <Form form={formInstance} layout={'vertical'} style={{ marginTop: 16 }}>
+ <Form.Field
+ required
extra={t('providerModels.item.modelConfig.id.extra')}
label={t('providerModels.item.modelConfig.id.title')}
name={'id'}
- rules={[
- { required: true },
- {
- validator: async (_, value?: string) => {
- if (hasDuplicateModelId(value, existingModelIds)) {
- throw new Error(t('providerModels.item.modelConfig.id.duplicate'));
- }
- },
- },
- ]}
+ validate={(value?: string) =>
+ hasDuplicateModelId(value, existingModelIds)
+ ? t('providerModels.item.modelConfig.id.duplicate')
+ : undefined
+ }
>
<Input
disabled={disabled || !idEditable}
placeholder={t('providerModels.item.modelConfig.id.placeholder')}
/>
- </Form.Item>
+ </Form.Field>
{showDeployName && (
- <Form.Item
+ <Form.Field
extra={t('providerModels.item.modelConfig.deployName.extra')}
label={t('providerModels.item.modelConfig.deployName.title')}
- name={['config', 'deploymentName']}
+ name={'config.deploymentName'}
>
- <Input placeholder={t('providerModels.item.modelConfig.deployName.placeholder')} />
- </Form.Item>
+ <Input
+ disabled={disabled}
+ placeholder={t('providerModels.item.modelConfig.deployName.placeholder')}
+ />
+ </Form.Field>
)}
- <Form.Item
+ <Form.Field
label={t('providerModels.item.modelConfig.displayName.title')}
name={'displayName'}
>
- <Input placeholder={t('providerModels.item.modelConfig.displayName.placeholder')} />
- </Form.Item>
- <Form.Item
+ <Input
+ disabled={disabled}
+ placeholder={t('providerModels.item.modelConfig.displayName.placeholder')}
+ />
+ </Form.Field>
+ <Form.Field
extra={t('providerModels.item.modelConfig.tokens.extra')}
label={t('providerModels.item.modelConfig.tokens.title')}
name={'contextWindowTokens'}
>
<MaxTokenSlider />
- </Form.Item>
- <Form.Item
+ </Form.Field>
+ <Form.Field
extra={t('providerModels.item.modelConfig.extendParams.extra')}
label={t('providerModels.item.modelConfig.extendParams.title')}
- name={['settings', 'extendParams']}
+ name={'settings.extendParams'}
>
<ExtendParamsSelect />
- </Form.Item>
- <Form.Item
- extra={t('providerModels.item.modelConfig.functionCall.extra')}
+ </Form.Field>
+ <Form.Field
+ desc={t('providerModels.item.modelConfig.functionCall.extra')}
label={t('providerModels.item.modelConfig.functionCall.title')}
- name={['abilities', 'functionCall']}
- valuePropName={'checked'}
+ layout={'horizontal'}
+ name={'abilities.functionCall'}
>
- <Checkbox />
- </Form.Item>
- <Form.Item
- extra={t('providerModels.item.modelConfig.vision.extra')}
+ <Checkbox disabled={disabled} />
+ </Form.Field>
+ <Form.Field
+ desc={t('providerModels.item.modelConfig.vision.extra')}
label={t('providerModels.item.modelConfig.vision.title')}
- name={['abilities', 'vision']}
- valuePropName={'checked'}
+ layout={'horizontal'}
+ name={'abilities.vision'}
>
- <Checkbox />
- </Form.Item>
- <Form.Item
- extra={t('providerModels.item.modelConfig.reasoning.extra')}
+ <Checkbox disabled={disabled} />
+ </Form.Field>
+ <Form.Field
+ desc={t('providerModels.item.modelConfig.reasoning.extra')}
label={t('providerModels.item.modelConfig.reasoning.title')}
- name={['abilities', 'reasoning']}
- valuePropName={'checked'}
+ layout={'horizontal'}
+ name={'abilities.reasoning'}
>
- <Checkbox />
- </Form.Item>
- <Form.Item
- extra={t('providerModels.item.modelConfig.search.extra')}
+ <Checkbox disabled={disabled} />
+ </Form.Field>
+ <Form.Field
+ desc={t('providerModels.item.modelConfig.search.extra')}
label={t('providerModels.item.modelConfig.search.title')}
- name={['abilities', 'search']}
- valuePropName={'checked'}
+ layout={'horizontal'}
+ name={'abilities.search'}
>
- <Checkbox />
- </Form.Item>
+ <Checkbox disabled={disabled} />
+ </Form.Field>
- <Form.Item
- extra={t('providerModels.item.modelConfig.imageOutput.extra')}
+ <Form.Field
+ desc={t('providerModels.item.modelConfig.imageOutput.extra')}
label={t('providerModels.item.modelConfig.imageOutput.title')}
- name={['abilities', 'imageOutput']}
- valuePropName={'checked'}
+ layout={'horizontal'}
+ name={'abilities.imageOutput'}
>
- <Checkbox />
- </Form.Item>
- <Form.Item
- extra={t('providerModels.item.modelConfig.video.extra')}
+ <Checkbox disabled={disabled} />
+ </Form.Field>
+ <Form.Field
+ desc={t('providerModels.item.modelConfig.video.extra')}
label={t('providerModels.item.modelConfig.video.title')}
- name={['abilities', 'video']}
- valuePropName={'checked'}
+ layout={'horizontal'}
+ name={'abilities.video'}
>
- <Checkbox />
- </Form.Item>
- <Form.Item
+ <Checkbox disabled={disabled} />
+ </Form.Field>
+ <Form.Field
extra={t('providerModels.item.modelConfig.type.extra')}
label={t('providerModels.item.modelConfig.type.title')}
name={'type'}
>
<Select
+ disabled={disabled}
options={modelTypeOptions}
placeholder={t('providerModels.item.modelConfig.type.placeholder')}
/>
- </Form.Item>
+ </Form.Field>
{/*<Form.Item*/}
{/* extra={t('providerModels.item.modelConfig.files.extra')}*/}
{/* label={t('providerModels.item.modelConfig.files.title')}*/}
diff --git a/src/features/Settings/provider/features/ModelList/CreateNewModelModal/index.tsx b/src/features/Settings/provider/features/ModelList/CreateNewModelModal/index.tsx
index 24d89d1dae3..6dec76d63e1 100644
--- a/src/features/Settings/provider/features/ModelList/CreateNewModelModal/index.tsx
+++ b/src/features/Settings/provider/features/ModelList/CreateNewModelModal/index.tsx
@@ -2,7 +2,7 @@
import type { ModalInstance } from '@lobehub/ui/base-ui';
import { createModal } from '@lobehub/ui/base-ui';
-import type { FormInstance } from 'antd';
+import type { FormInstance } from '@lobehub/ui/base-ui/form';
import { t } from 'i18next';
import CreateNewModelContent from './Content';
diff --git a/src/features/Settings/provider/features/ModelList/ModelConfigModal/Content.tsx b/src/features/Settings/provider/features/ModelList/ModelConfigModal/Content.tsx
index 0bd4e05d3e6..77ae2e16f6c 100644
--- a/src/features/Settings/provider/features/ModelList/ModelConfigModal/Content.tsx
+++ b/src/features/Settings/provider/features/ModelList/ModelConfigModal/Content.tsx
@@ -1,6 +1,6 @@
'use client';
-import { type FormInstance } from 'antd';
+import { type FormInstance } from '@lobehub/ui/base-ui/form';
import isEqual from 'fast-deep-equal';
import { memo } from 'react';
diff --git a/src/features/Settings/provider/features/ModelList/ModelConfigModal/Footer.tsx b/src/features/Settings/provider/features/ModelList/ModelConfigModal/Footer.tsx
index b62dd8bcf7e..8ccd9d52f2d 100644
--- a/src/features/Settings/provider/features/ModelList/ModelConfigModal/Footer.tsx
+++ b/src/features/Settings/provider/features/ModelList/ModelConfigModal/Footer.tsx
@@ -1,7 +1,7 @@
'use client';
import { Button, ModalFooter, useModalContext } from '@lobehub/ui/base-ui';
-import { type FormInstance } from 'antd';
+import { type FormInstance } from '@lobehub/ui/base-ui/form';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -30,7 +30,7 @@ const ModelConfigFooter = memo<ModelConfigFooterProps>(({ formRef, id }) => {
onClick={async () => {
const form = formRef.current;
if (!editingProvider || !id || !form) return;
- const data = form.getFieldsValue();
+ const data = form.getValues();
setLoading(true);
await updateAiModelsConfig(id, editingProvider, data);
diff --git a/src/features/Settings/provider/features/ModelList/ModelConfigModal/index.tsx b/src/features/Settings/provider/features/ModelList/ModelConfigModal/index.tsx
index 1e4e2a3439e..0a4ad1e994b 100644
--- a/src/features/Settings/provider/features/ModelList/ModelConfigModal/index.tsx
+++ b/src/features/Settings/provider/features/ModelList/ModelConfigModal/index.tsx
@@ -1,7 +1,7 @@
'use client';
import { createModal, type ModalInstance } from '@lobehub/ui/base-ui';
-import { type FormInstance } from 'antd';
+import { type FormInstance } from '@lobehub/ui/base-ui/form';
import { t } from 'i18next';
import ModelConfigContent from './Content';
diff --git a/src/features/Settings/provider/features/ProviderConfig/UpdateProviderInfo/SettingModal.tsx b/src/features/Settings/provider/features/ProviderConfig/UpdateProviderInfo/SettingModal.tsx
index 7fefe1ceb40..fc5f70c1989 100644
--- a/src/features/Settings/provider/features/ProviderConfig/UpdateProviderInfo/SettingModal.tsx
+++ b/src/features/Settings/provider/features/ProviderConfig/UpdateProviderInfo/SettingModal.tsx
@@ -14,7 +14,7 @@ import {
toast,
useModalContext,
} from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import { cssVar } from 'antd-style';
import { t as i18nT } from 'i18next';
import { BrainIcon } from 'lucide-react';
@@ -42,12 +42,11 @@ const SectionTitle = memo<{ children: ReactNode }>(({ children }) => (
SectionTitle.displayName = 'SectionTitle';
-const itemStyle = { marginBottom: 0 };
+const itemStyle = { paddingBlock: 0 };
const SettingContent = memo<SettingContentProps>(({ initialValues, id }) => {
const { t } = useTranslation(['modelProvider', 'common']);
const [loading, setLoading] = useState(false);
- const [form] = Form.useForm<UpdateAiProviderParams>();
const [updateAiProvider, deleteAiProvider] = useAiInfraStore((s) => [
s.updateAiProvider,
s.deleteAiProvider,
@@ -90,6 +89,12 @@ const SettingContent = memo<SettingContentProps>(({ initialValues, id }) => {
}
};
+ const form = useForm<UpdateAiProviderParams>({
+ initialValues: initialValues as UpdateAiProviderParams,
+ onSubmit: ({ description, logo, name, settings }) =>
+ onFinish({ description, logo, name, settings }),
+ });
+
const handleDelete = () => {
confirmModal({
content: t('updateAiProvider.confirmDeleteDescription'),
@@ -107,31 +112,24 @@ const SettingContent = memo<SettingContentProps>(({ initialValues, id }) => {
return (
<Flexbox>
- <Form
- colon={false}
- form={form}
- initialValues={initialValues}
- layout={'vertical'}
- scrollToFirstError={{ behavior: 'instant', block: 'end', focus: true }}
- onFinish={onFinish}
- >
+ <Form form={form} layout={'vertical'}>
<Flexbox gap={16}>
<SectionTitle>{t('createNewAiProvider.basicTitle')}</SectionTitle>
- <Form.Item label={t('createNewAiProvider.id.title')} style={itemStyle}>
+ <Form.Field label={t('createNewAiProvider.id.title')} style={itemStyle}>
<Text type={'secondary'}>{initialValues.id}</Text>
- </Form.Item>
+ </Form.Field>
- <Form.Item
+ <Form.Field
label={t('createNewAiProvider.name.title')}
name={'name'}
- rules={[{ message: t('createNewAiProvider.name.required'), required: true }]}
+ required={t('createNewAiProvider.name.required')}
style={itemStyle}
>
<Input placeholder={t('createNewAiProvider.name.placeholder')} variant={'filled'} />
- </Form.Item>
+ </Form.Field>
- <Form.Item
+ <Form.Field
label={t('createNewAiProvider.description.title')}
name={'description'}
style={itemStyle}
@@ -141,20 +139,20 @@ const SettingContent = memo<SettingContentProps>(({ initialValues, id }) => {
style={{ minHeight: 72 }}
variant={'filled'}
/>
- </Form.Item>
+ </Form.Field>
- <Form.Item label={t('createNewAiProvider.logo.title')} name={'logo'} style={itemStyle}>
+ <Form.Field label={t('createNewAiProvider.logo.title')} name={'logo'} style={itemStyle}>
<Input allowClear placeholder={'https://logo-url'} variant={'filled'} />
- </Form.Item>
+ </Form.Field>
<div style={{ marginBlockStart: 8 }}>
<SectionTitle>{t('createNewAiProvider.configTitle')}</SectionTitle>
</div>
- <Form.Item
+ <Form.Field
label={t('createNewAiProvider.sdkType.title')}
- name={['settings', 'sdkType']}
- rules={[{ message: t('createNewAiProvider.sdkType.required'), required: true }]}
+ name={'settings.sdkType'}
+ required={t('createNewAiProvider.sdkType.required')}
style={itemStyle}
>
<Select
@@ -171,7 +169,7 @@ const SettingContent = memo<SettingContentProps>(({ initialValues, id }) => {
);
}}
/>
- </Form.Item>
+ </Form.Field>
</Flexbox>
</Form>
<ModalFooter
diff --git a/src/features/Settings/provider/features/ProviderConfig/index.tsx b/src/features/Settings/provider/features/ProviderConfig/index.tsx
index 0ee64365d2f..da63d0930d3 100644
--- a/src/features/Settings/provider/features/ProviderConfig/index.tsx
+++ b/src/features/Settings/provider/features/ProviderConfig/index.tsx
@@ -2,12 +2,19 @@
import { BRANDING_PROVIDER } from '@lobechat/business-const';
import { AES_GCM_URL, BASE_PROVIDER_DOC_URL, FORM_STYLE } from '@lobechat/const';
-import { type FormGroupItemType, type FormItemProps } from '@lobehub/ui';
-import { Center, Flexbox, Form, Icon, stopPropagation, Tooltip } from '@lobehub/ui';
+import { Center, Flexbox, Icon, stopPropagation, Tooltip } from '@lobehub/ui';
import { Avatar, Skeleton, Spin, Switch } from '@lobehub/ui/base-ui';
+import {
+ Form,
+ type FormFieldProps,
+ type FormGroupItem,
+ type FormValues,
+ useForm,
+ useWatch,
+} from '@lobehub/ui/base-ui/form';
import { useDebounceFn } from 'ahooks';
-import { Form as AntdForm } from 'antd';
import { createStaticStyles, cssVar, cx, responsive } from 'antd-style';
+import { get, set } from 'es-toolkit/compat';
import { InfoIcon, LockIcon } from 'lucide-react';
import { AiProviderBaseURLSchema } from 'model-bank/aiProvider';
import { type ReactNode } from 'react';
@@ -37,46 +44,27 @@ import EnableSwitch from './EnableSwitch';
import OAuthDeviceFlowAuth from './OAuthDeviceFlowAuth';
import UpdateProviderInfo from './UpdateProviderInfo';
-const prefixCls = 'ant';
-
const styles = createStaticStyles(({ css, cssVar }) => ({
aceGcm: css`
- padding-block: 0 !important;
- .${prefixCls}-form-item-label {
- display: none;
- }
- .${prefixCls}-form-item-control {
- width: 100%;
+ width: 100%;
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
- text-align: center;
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ text-align: center;
- opacity: 0.66;
+ opacity: 0.66;
- transition: opacity 0.2s ${cssVar.motionEaseInOut};
+ transition: opacity 0.2s ${cssVar.motionEaseInOut};
- &:hover {
- opacity: 1;
- }
+ &:hover {
+ opacity: 1;
}
`,
form: css`
- /* The group header is the first thing on the page, so its own top padding
- reads as dead space under the nav bar. The page inset is enough. */
- .${prefixCls}-collapse-header {
- padding-block-start: 0 !important;
- }
- .${prefixCls}-form-item-control:has(.${prefixCls}-input,.${prefixCls}-select) {
- flex: none;
- }
${responsive.sm} {
width: 100%;
min-width: unset !important;
}
- .${prefixCls}-select-selection-overflow-item {
- font-size: 12px;
- }
`,
help: css`
border-radius: 50%;
@@ -101,7 +89,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
export interface ProviderConfigProps extends Omit<AiProviderDetailItem, 'enabled' | 'source'> {
- apiKeyItems?: FormItemProps[];
+ apiKeyItems?: FormFieldProps[];
apiKeyUrl?: string;
canDeactivate?: boolean;
checkErrorRender?: CheckErrorRender;
@@ -149,7 +137,9 @@ const ProviderConfig = memo<ProviderConfigProps>(
supportResponsesApi,
} = settings || {};
const { t } = useTranslation('modelProvider');
- const [form] = Form.useForm();
+ const form = useForm({
+ onValuesChange: (_, values) => handleFormValuesChange(values),
+ });
const { allowed: canManageProvider } = usePermission('manage_provider_key');
const isOAuthProvider = authType === 'oauthDeviceFlow';
@@ -182,14 +172,14 @@ const ProviderConfig = memo<ProviderConfigProps>(
// Watch form values in real-time to show/hide switches immediately
// Watch nested form values for endpoints
- const formBaseURL = AntdForm.useWatch(['keyVaults', 'baseURL'], form);
- const formEndpoint = AntdForm.useWatch(['keyVaults', 'endpoint'], form);
+ const formBaseURL = useWatch(form, 'keyVaults.baseURL');
+ const formEndpoint = useWatch(form, 'keyVaults.endpoint');
// Watch all possible credential fields for different providers
- const formApiKey = AntdForm.useWatch(['keyVaults', 'apiKey'], form);
- const formAccessKeyId = AntdForm.useWatch(['keyVaults', 'accessKeyId'], form);
- const formSecretAccessKey = AntdForm.useWatch(['keyVaults', 'secretAccessKey'], form);
- const formUsername = AntdForm.useWatch(['keyVaults', 'username'], form);
- const formPassword = AntdForm.useWatch(['keyVaults', 'password'], form);
+ const formApiKey = useWatch(form, 'keyVaults.apiKey');
+ const formAccessKeyId = useWatch(form, 'keyVaults.accessKeyId');
+ const formSecretAccessKey = useWatch(form, 'keyVaults.secretAccessKey');
+ const formUsername = useWatch(form, 'keyVaults.username');
+ const formPassword = useWatch(form, 'keyVaults.password');
// Check if provider has endpoint and apiKey based on runtime config
// Fallback to data.keyVaults if runtime config is not yet loaded
@@ -232,11 +222,9 @@ const ProviderConfig = memo<ProviderConfigProps>(
...(providerRuntimeConfig?.config && { config: providerRuntimeConfig.config }),
};
- // Clear the previous provider's field state first so omitted keys do not
+ // Replace the previous provider's field state so omitted keys do not
// leak old values when the next provider has empty credentials.
- form.resetFields();
- // Set form values and mark as initialized
- form.setFieldsValue(mergedData);
+ form.reset(mergedData);
lastInitializedIdRef.current = id;
}, [isLoading, id, data, providerRuntimeConfig, form]);
@@ -274,7 +262,7 @@ const ProviderConfig = memo<ProviderConfigProps>(
await useAiInfraStore.getState().refreshAiProviderRuntimeState();
}, []);
- const apiKeyItem: FormItemProps[] =
+ const apiKeyItem: FormFieldProps[] =
!showApiKey || isOAuthProvider
? []
: (apiKeyItems ?? [
@@ -284,6 +272,7 @@ const ProviderConfig = memo<ProviderConfigProps>(
) : (
<FormPassword
autoComplete={'new-password'}
+ disabled={!canManageProvider}
placeholder={t('providerModels.config.apiKey.placeholder', { name })}
suffix={
configUpdating && (
@@ -308,13 +297,14 @@ const ProviderConfig = memo<ProviderConfigProps>(
t(`providerModels.config.apiKey.desc`, { name })
),
label: t(`providerModels.config.apiKey.title`),
- name: [KeyVaultsConfigKey, LLMProviderApiTokenKey],
+ name: `${KeyVaultsConfigKey}.${LLMProviderApiTokenKey}`,
},
]);
- const aceGcmItem: FormItemProps = {
+ const aceGcmItem: FormFieldProps = {
+ bare: true,
children: (
- <>
+ <div className={styles.aceGcm}>
<Icon icon={LockIcon} style={{ marginRight: 4 }} />
<Trans
i18nKey="providerModels.config.aesGcm"
@@ -330,21 +320,20 @@ const ProviderConfig = memo<ProviderConfigProps>(
/>,
]}
/>
- </>
+ </div>
),
- className: styles.aceGcm,
- minWidth: undefined,
};
const showEndpoint = !!proxyUrl || isCustom;
- const endpointItem = showEndpoint
+ const endpointItem: FormFieldProps | undefined = showEndpoint
? {
children: isLoading ? (
<SkeletonInput />
) : (
<FormInput
allowClear
+ disabled={!canManageProvider}
placeholder={
(!!proxyUrl && proxyUrl?.placeholder) ||
t('providerModels.config.baseURL.placeholder')
@@ -356,18 +345,11 @@ const ProviderConfig = memo<ProviderConfigProps>(
),
desc: (!!proxyUrl && proxyUrl?.desc) || t('providerModels.config.baseURL.desc'),
label: (!!proxyUrl && proxyUrl?.title) || t('providerModels.config.baseURL.title'),
- name: [KeyVaultsConfigKey, LLMProviderBaseUrlKey],
- rules: [
- {
- validator: (_: any, value: string) => {
- if (!value) return;
-
- return AiProviderBaseURLSchema.safeParse(value).error
- ? Promise.reject(t('providerModels.config.baseURL.invalid'))
- : Promise.resolve();
- },
- },
- ],
+ name: `${KeyVaultsConfigKey}.${LLMProviderBaseUrlKey}`,
+ validate: (value?: string) =>
+ value && AiProviderBaseURLSchema.safeParse(value).error
+ ? t('providerModels.config.baseURL.invalid')
+ : undefined,
}
: undefined;
@@ -384,9 +366,13 @@ const ProviderConfig = memo<ProviderConfigProps>(
(showEndpoint && isProviderEndpointNotEmpty) ||
(showApiKey && isProviderApiKeyNotEmpty));
- const clientFetchItem = showClientFetch
+ const clientFetchItem: FormFieldProps | undefined = showClientFetch
? {
- children: isLoading ? <SkeletonSwitch /> : <Switch loading={configUpdating} />,
+ children: isLoading ? (
+ <SkeletonSwitch />
+ ) : (
+ <Switch disabled={!canManageProvider} loading={configUpdating} />
+ ),
desc: t('providerModels.config.fetchOnClient.desc'),
label: t('providerModels.config.fetchOnClient.title'),
minWidth: undefined,
@@ -402,11 +388,15 @@ const ProviderConfig = memo<ProviderConfigProps>(
endpointItem,
showResponsesApiSwitch
? {
- children: isLoading ? <Skeleton height={36} /> : <Switch loading={configUpdating} />,
+ children: isLoading ? (
+ <Skeleton height={36} />
+ ) : (
+ <Switch disabled={!canManageProvider} loading={configUpdating} />
+ ),
desc: t('providerModels.config.responsesApi.desc'),
label: t('providerModels.config.responsesApi.title'),
minWidth: undefined,
- name: ['config', 'enableResponseApi'],
+ name: 'config.enableResponseApi',
}
: undefined,
clientFetchItem,
@@ -424,16 +414,16 @@ const ProviderConfig = memo<ProviderConfigProps>(
isCheckingConnection.current = false;
}}
onBeforeCheck={async () => {
- try {
- await form.validateFields();
- } catch {
- return false;
- }
+ const { valid } = await form.validate();
+ if (!valid) return false;
// Set connection test state to prevent duplicate requests from onValuesChange
isCheckingConnection.current = true;
// Proactively save the latest form values to ensure fetchAiProviderRuntimeState retrieves up-to-date data
- await updateAiProviderConfig(id, normalizeValues(form.getFieldsValue()));
+ await updateAiProviderConfig(
+ id,
+ normalizeValues(pickFieldValues(form.getValues())),
+ );
return true;
}}
@@ -444,7 +434,23 @@ const ProviderConfig = memo<ProviderConfigProps>(
}
: undefined,
showAceGcm && aceGcmItem,
- ].filter(Boolean) as FormItemProps[];
+ ].filter(Boolean) as FormFieldProps[];
+
+ const pickFieldValues = (values: FormValues): UpdateAiProviderConfigParams =>
+ configItems.reduce<UpdateAiProviderConfigParams>((acc, item) => {
+ if (item.name && !item.hidden) set(acc, item.name, get(values, item.name));
+ return acc;
+ }, {});
+
+ const handleFormValuesChange = (values: FormValues) => {
+ if (!canManageProvider) return;
+
+ cancelDebouncedHandleValueChange();
+ const baseURL = values.keyVaults?.baseURL;
+ if (baseURL && !AiProviderBaseURLSchema.safeParse(baseURL).success) return;
+
+ debouncedHandleValueChange(id, normalizeValues(pickFieldValues(values)));
+ };
const logoUrl = data?.logo ?? logo;
@@ -534,7 +540,7 @@ const ProviderConfig = memo<ProviderConfigProps>(
</Flexbox>
);
- const model: FormGroupItemType = {
+ const model: FormGroupItem = {
children: configItems,
defaultActive: true,
extra: isOAuthProvider ? undefined : headerExtra,
@@ -560,19 +566,9 @@ const ProviderConfig = memo<ProviderConfigProps>(
{shouldShowForm && (
<Form
className={cx(styles.form, className)}
- disabled={!canManageProvider}
form={form}
items={[model]}
variant={'borderless'}
- onValuesChange={(_, values) => {
- if (!canManageProvider) return;
-
- cancelDebouncedHandleValueChange();
- const baseURL = values.keyVaults?.baseURL;
- if (baseURL && !AiProviderBaseURLSchema.safeParse(baseURL).success) return;
-
- debouncedHandleValueChange(id, normalizeValues(values));
- }}
{...FORM_STYLE}
/>
)}
diff --git a/src/features/Settings/proxy/features/ProxyForm.test.tsx b/src/features/Settings/proxy/features/ProxyForm.test.tsx
index 90f95dc443f..58d027acbdd 100644
--- a/src/features/Settings/proxy/features/ProxyForm.test.tsx
+++ b/src/features/Settings/proxy/features/ProxyForm.test.tsx
@@ -101,8 +101,8 @@ describe('ProxyForm', () => {
await waitFor(() => {
expect(setProxySettingsMock).not.toHaveBeenCalled();
- expect(screen.getByText('proxy.validation.serverRequired')).toBeInTheDocument();
- expect(screen.getByText('proxy.validation.portRequired')).toBeInTheDocument();
+ expect(screen.getAllByText('proxy.validation.serverRequired')).toHaveLength(2);
+ expect(screen.getAllByText('proxy.validation.portRequired')).toHaveLength(2);
});
});
@@ -116,8 +116,8 @@ describe('ProxyForm', () => {
await waitFor(() => {
expect(testProxyConfigMock).not.toHaveBeenCalled();
- expect(screen.getByText('proxy.validation.serverRequired')).toBeInTheDocument();
- expect(screen.getByText('proxy.validation.portRequired')).toBeInTheDocument();
+ expect(screen.getAllByText('proxy.validation.serverRequired')).toHaveLength(2);
+ expect(screen.getAllByText('proxy.validation.portRequired')).toHaveLength(2);
});
expect(toastErrorMock).not.toHaveBeenCalled();
diff --git a/src/features/Settings/proxy/features/ProxyForm.tsx b/src/features/Settings/proxy/features/ProxyForm.tsx
index 40eacb6709e..8de8932a355 100644
--- a/src/features/Settings/proxy/features/ProxyForm.tsx
+++ b/src/features/Settings/proxy/features/ProxyForm.tsx
@@ -1,8 +1,7 @@
'use client';
import { type NetworkProxySettings } from '@lobechat/electron-client-ipc';
-import { type FormGroupItemType } from '@lobehub/ui';
-import { Flexbox, Form } from '@lobehub/ui';
+import { Flexbox } from '@lobehub/ui';
import {
Button,
Input,
@@ -12,7 +11,7 @@ import {
Switch,
toast,
} from '@lobehub/ui/base-ui';
-import { Form as AntdForm } from 'antd';
+import { Form, type FormGroupItem, useForm, useWatch } from '@lobehub/ui/base-ui/form';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -28,12 +27,6 @@ const PROXY_TYPES = ['http', 'https', 'socks5'] as const;
const IP_HOST_REGEX = /^(?:\d{1,3}\.){3}\d{1,3}$/;
const DOMAIN_HOST_REGEX = /^[\dA-Z](?:[\dA-Z-]*[\dA-Z])?(?:\.[\dA-Z](?:[\dA-Z-]*[\dA-Z])?)*$/i;
-const isFormValidationError = (
- error: unknown,
-): error is {
- errorFields: unknown[];
-} => typeof error === 'object' && error !== null && 'errorFields' in error;
-
const isSupportedProxyType = (value?: string): value is (typeof PROXY_TYPES)[number] =>
PROXY_TYPES.includes(value as (typeof PROXY_TYPES)[number]);
@@ -61,86 +54,82 @@ const isCompleteProxyConfig = (config: Partial<NetworkProxySettings>) => {
const ProxyForm = () => {
const { t } = useTranslation('electron');
- const [form] = Form.useForm();
const [testUrl, setTestUrl] = useState('https://www.google.com');
const [isTesting, setIsTesting] = useState(false);
const [isSaving, setIsSaving] = useState(false);
- const isEnableProxy = AntdForm.useWatch('enableProxy', form);
- const proxyRequireAuth = AntdForm.useWatch('proxyRequireAuth', form);
-
const [setProxySettings, useGetProxySettings] = useElectronStore((s) => [
s.setProxySettings,
s.useGetProxySettings,
]);
const { data: proxySettings, isLoading } = useGetProxySettings();
+ const form = useForm<NetworkProxySettings>({
+ initialValues: proxySettings,
+ onValuesChange: (changed, values) => handleValuesChange(changed, values),
+ });
+
+ const isEnableProxy = useWatch(form, 'enableProxy');
+ const proxyRequireAuth = useWatch(form, 'proxyRequireAuth');
+
const { isDirty } = useProxyDirty(form, proxySettings);
const initializedRef = useRef(false);
useEffect(() => {
if (proxySettings && !initializedRef.current) {
- form.setFieldsValue(proxySettings);
+ form.setValues(proxySettings);
initializedRef.current = true;
}
}, [form, proxySettings]);
const validateProxyType = useCallback(
- async (_: unknown, value?: string) => {
+ (value?: string) => {
if (!isEnableProxy || isSupportedProxyType(value)) return;
- throw new Error(t('proxy.validation.typeRequired'));
+ return t('proxy.validation.typeRequired');
},
[isEnableProxy, t],
);
const validateProxyServer = useCallback(
- async (_: unknown, value?: string) => {
+ (value?: string) => {
if (!isEnableProxy) return;
const proxyServer = value?.trim();
- if (!proxyServer) {
- throw new Error(t('proxy.validation.serverRequired'));
- }
+ if (!proxyServer) return t('proxy.validation.serverRequired');
- if (!isValidProxyHost(proxyServer)) {
- throw new Error(t('proxy.validation.serverInvalid'));
- }
+ if (!isValidProxyHost(proxyServer)) return t('proxy.validation.serverInvalid');
},
[isEnableProxy, t],
);
const validateProxyPort = useCallback(
- async (_: unknown, value?: string) => {
+ (value?: string) => {
if (!isEnableProxy) return;
const proxyPort = value?.trim();
- if (!proxyPort) {
- throw new Error(t('proxy.validation.portRequired'));
- }
+ if (!proxyPort) return t('proxy.validation.portRequired');
const port = Number.parseInt(proxyPort, 10);
- if (Number.isNaN(port) || port < 1 || port > 65_535) {
- throw new Error(t('proxy.validation.portInvalid'));
- }
+ if (Number.isNaN(port) || port < 1 || port > 65_535) return t('proxy.validation.portInvalid');
},
[isEnableProxy, t],
);
const validateProxyUsername = useCallback(
- async (_: unknown, value?: string) => {
+ (value?: string) => {
if (!isEnableProxy || !proxyRequireAuth || value?.trim()) return;
- throw new Error(t('proxy.validation.usernameRequired'));
+ return t('proxy.validation.usernameRequired');
},
[isEnableProxy, proxyRequireAuth, t],
);
const validateProxyPassword = useCallback(
- async (_: unknown, value?: string) => {
+ (value?: string) => {
if (!isEnableProxy || !proxyRequireAuth || value?.trim()) return;
- throw new Error(t('proxy.validation.passwordRequired'));
+ return t('proxy.validation.passwordRequired');
},
[isEnableProxy, proxyRequireAuth, t],
);
@@ -154,7 +143,7 @@ const ProxyForm = () => {
const valuesToSave = next ? allValues : { enableProxy: false };
setProxySettings(valuesToSave).catch((error) => {
- form.setFieldsValue({ enableProxy: !next });
+ form.setValue('enableProxy', !next);
const message = error instanceof Error ? error.message : String(error);
toast.error(t('proxy.saveFailed', { error: message }));
});
@@ -164,13 +153,10 @@ const ProxyForm = () => {
);
const handleSave = useCallback(async () => {
- let values: NetworkProxySettings;
- try {
- values = await form.validateFields();
- } catch {
- // Validation error — fields surface their own inline messages.
- return;
- }
+ const { valid } = await form.validate();
+ // Validation error — fields surface their own inline messages.
+ if (!valid) return;
+ const values = form.getValues();
try {
setIsSaving(true);
@@ -185,14 +171,16 @@ const ProxyForm = () => {
}, [form, setProxySettings, t]);
const handleReset = useCallback(() => {
- if (proxySettings) form.setFieldsValue(proxySettings);
+ if (proxySettings) form.reset(proxySettings);
}, [form, proxySettings]);
const handleTest = useCallback(async () => {
try {
setIsTesting(true);
- const values = await form.validateFields();
+ const { valid } = await form.validate();
+ if (!valid) return;
+ const values = form.getValues();
const config: NetworkProxySettings = {
...proxySettings,
...values,
@@ -205,8 +193,6 @@ const ProxyForm = () => {
toast.error(`${t('proxy.testFailed')}: ${result.message ?? ''}`);
}
} catch (error) {
- if (isFormValidationError(error)) return;
-
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
toast.error(`${t('proxy.testFailed')}: ${errorMessage}`);
} finally {
@@ -216,7 +202,7 @@ const ProxyForm = () => {
if (isLoading) return <Skeleton.Text rows={5} />;
- const enableProxyGroup: FormGroupItemType = {
+ const enableProxyGroup: FormGroupItem<NetworkProxySettings> = {
children: [
{
children: <Switch />,
@@ -225,13 +211,12 @@ const ProxyForm = () => {
layout: 'horizontal',
minWidth: undefined,
name: 'enableProxy',
- valuePropName: 'checked',
},
],
title: t('proxy.enable'),
};
- const basicSettingsGroup: FormGroupItemType = {
+ const basicSettingsGroup: FormGroupItem<NetworkProxySettings> = {
children: [
{
children: (
@@ -243,27 +228,27 @@ const ProxyForm = () => {
label: t('proxy.type'),
minWidth: undefined,
name: 'proxyType',
- rules: [{ validator: validateProxyType }],
+ validate: validateProxyType,
},
{
children: <Input disabled={!isEnableProxy} placeholder="127.0.0.1" />,
desc: t('proxy.validation.serverRequired'),
label: t('proxy.server'),
name: 'proxyServer',
- rules: [{ validator: validateProxyServer }],
+ validate: validateProxyServer,
},
{
children: <Input disabled={!isEnableProxy} placeholder="7890" style={{ width: 120 }} />,
desc: t('proxy.validation.portRequired'),
label: t('proxy.port'),
name: 'proxyPort',
- rules: [{ validator: validateProxyPort }],
+ validate: validateProxyPort,
},
],
title: t('proxy.basicSettings'),
};
- const authGroup: FormGroupItemType = {
+ const authGroup: FormGroupItem<NetworkProxySettings> = {
children: [
{
children: <Switch disabled={!isEnableProxy} />,
@@ -272,15 +257,14 @@ const ProxyForm = () => {
layout: 'horizontal',
minWidth: undefined,
name: 'proxyRequireAuth',
- valuePropName: 'checked',
},
...(proxyRequireAuth && isEnableProxy
? [
{
children: <Input placeholder={t('proxy.username_placeholder')} />,
label: t('proxy.username'),
- name: 'proxyUsername',
- rules: [{ validator: validateProxyUsername }],
+ name: 'proxyUsername' as const,
+ validate: validateProxyUsername,
},
{
children: (
@@ -290,8 +274,8 @@ const ProxyForm = () => {
/>
),
label: t('proxy.password'),
- name: 'proxyPassword',
- rules: [{ validator: validateProxyPassword }],
+ name: 'proxyPassword' as const,
+ validate: validateProxyPassword,
},
]
: []),
@@ -299,7 +283,7 @@ const ProxyForm = () => {
title: t('proxy.authSettings'),
};
- const testGroup: FormGroupItemType = {
+ const testGroup: FormGroupItem<NetworkProxySettings> = {
children: [
{
children: (
@@ -328,11 +312,9 @@ const ProxyForm = () => {
<Form
collapsible={false}
form={form}
- initialValues={proxySettings}
items={[enableProxyGroup, basicSettingsGroup, authGroup, testGroup]}
itemsType={'group'}
variant={'filled'}
- onValuesChange={handleValuesChange}
{...FORM_STYLE}
/>
<SaveBar isDirty={isDirty} isSaving={isSaving} onReset={handleReset} onSave={handleSave} />
diff --git a/src/features/Settings/proxy/features/useProxyDirty.ts b/src/features/Settings/proxy/features/useProxyDirty.ts
index b1aee4b60ed..728fac3887d 100644
--- a/src/features/Settings/proxy/features/useProxyDirty.ts
+++ b/src/features/Settings/proxy/features/useProxyDirty.ts
@@ -1,5 +1,5 @@
import { type NetworkProxySettings } from '@lobechat/electron-client-ipc';
-import { Form as AntdForm, type FormInstance } from 'antd';
+import { type FormInstance, useWatch } from '@lobehub/ui/base-ui/form';
import { useMemo } from 'react';
const WATCH_FIELDS: readonly (keyof NetworkProxySettings)[] = [
@@ -15,10 +15,10 @@ const WATCH_FIELDS: readonly (keyof NetworkProxySettings)[] = [
const normalize = (v: unknown) => (v === undefined || v === null ? '' : v);
export const useProxyDirty = (
- form: FormInstance,
+ form: FormInstance<NetworkProxySettings>,
saved: NetworkProxySettings | undefined,
): { isDirty: boolean } => {
- const values = AntdForm.useWatch([], form);
+ const values = useWatch(form, (v) => v);
const isDirty = useMemo(() => {
if (!saved || !values) return false;
diff --git a/src/features/Settings/stats/features/overview/ShareButton/ShareModal.tsx b/src/features/Settings/stats/features/overview/ShareButton/ShareModal.tsx
index ad1e06c698e..afd0785185c 100644
--- a/src/features/Settings/stats/features/overview/ShareButton/ShareModal.tsx
+++ b/src/features/Settings/stats/features/overview/ShareButton/ShareModal.tsx
@@ -1,10 +1,8 @@
'use client';
-import { type FormItemProps, type FormModalProps } from '@lobehub/ui';
-import { FormModal } from '@lobehub/ui';
-import { Skeleton, Tabs } from '@lobehub/ui/base-ui';
-import { createStaticStyles } from 'antd-style';
-import { memo, useState } from 'react';
+import { Button, Modal, Skeleton, Tabs } from '@lobehub/ui/base-ui';
+import { Form, type FormFieldProps, useForm, useWatch } from '@lobehub/ui/base-ui/form';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { ImageType, imageTypeOptions, useScreenshot } from '@/hooks/useScreenshot';
@@ -14,16 +12,6 @@ const Preview = dynamic(() => import('./Preview'), {
loading: () => <Skeleton height={400} width={'100%'} />,
});
-const prefixCls = 'ant';
-
-const styles = createStaticStyles(({ css }) => ({
- preview: css`
- .${prefixCls}-form-item-label {
- display: none;
- }
- `,
-}));
-
type FieldType = {
imageType: ImageType;
};
@@ -32,48 +20,51 @@ const DEFAULT_FIELD_VALUE: FieldType = {
imageType: ImageType.JPG,
};
-const ShareModal = memo<FormModalProps & { mobile?: boolean }>(({ open, onCancel, mobile }) => {
+interface ShareModalProps {
+ mobile?: boolean;
+ onCancel?: () => void;
+ open?: boolean;
+}
+
+const ShareModal = memo<ShareModalProps>(({ open, onCancel, mobile }) => {
const { t } = useTranslation(['chat', 'common']);
- const [fieldValue, setFieldValue] = useState<FieldType>(DEFAULT_FIELD_VALUE);
+ const form = useForm<FieldType>({ initialValues: DEFAULT_FIELD_VALUE });
+ const imageType = useWatch(form, 'imageType');
const { loading, onDownload } = useScreenshot({
- imageType: fieldValue.imageType,
+ imageType,
title: 'stats',
width: mobile ? 440 : undefined,
});
- const items: FormItemProps[] = [
+ const items: FormFieldProps<FieldType>[] = [
{
+ bare: true,
children: <Preview />,
- className: styles.preview,
- divider: false,
- minWidth: '100%',
},
{
children: <Tabs items={imageTypeOptions} />,
divider: false,
label: t('shareModal.imageType'),
- minWidth: undefined,
name: 'imageType',
- valuePropName: 'activeKey',
+ valueProp: 'activeKey',
},
];
return (
- <FormModal
+ <Modal
allowFullscreen
- footer={null}
- initialValues={DEFAULT_FIELD_VALUE}
- items={items}
- itemsType={'flat'}
open={open}
- submitLoading={loading}
- submitText={t('shareModal.download')}
title={t('share', { ns: 'common' })}
width={480}
+ footer={
+ <Button block loading={loading} type={'primary'} onClick={onDownload}>
+ {t('shareModal.download')}
+ </Button>
+ }
onCancel={onCancel}
- onFinish={onDownload}
- onValuesChange={(_, v) => setFieldValue(v)}
- />
+ >
+ <Form form={form} gap={24} items={items} itemsType={'flat'} />
+ </Modal>
);
});
diff --git a/src/features/Settings/stats/index.tsx b/src/features/Settings/stats/index.tsx
index b1b5ff1a908..9e07477f320 100644
--- a/src/features/Settings/stats/index.tsx
+++ b/src/features/Settings/stats/index.tsx
@@ -1,7 +1,8 @@
'use client';
-import { FormGroup, Grid, Icon } from '@lobehub/ui';
+import { Grid, Icon } from '@lobehub/ui';
import { DatePicker, Divider, Tabs } from '@lobehub/ui/base-ui';
+import { Form } from '@lobehub/ui/base-ui/form';
import { ProviderIcon } from '@lobehub/ui/icons';
import dayjs from 'dayjs';
import { Brain, UserIcon } from 'lucide-react';
@@ -78,10 +79,9 @@ const StatsSetting = memo<StatsSettingProps>(
<>
{showSettingHeader && <SettingHeader title={t('tab.stats')} />}
{/* ========== Header Section ========== */}
- <FormGroup
+ <Form.Group
collapsible={false}
extra={headerNode === undefined ? <ShareButton /> : undefined}
- gap={16}
variant={'filled'}
title={
headerNode === undefined ? (
@@ -105,11 +105,10 @@ const StatsSetting = memo<StatsSettingProps>(
<AssistantsRank mobile={mobile} />
<TopicsRank mobile={mobile} />
</Grid>
- </FormGroup>
- <FormGroup
+ </Form.Group>
+ <Form.Group
collapsible={false}
- gap={16}
- title={t('tab.usage')}
+ title={<span style={{ lineHeight: '35px' }}>{t('tab.usage')}</span>}
variant={'filled'}
extra={
<>
@@ -147,9 +146,6 @@ const StatsSetting = memo<StatsSettingProps>(
/>
</>
}
- styles={{
- title: { lineHeight: '35px' },
- }}
>
<AsyncBoundary data={data} error={error} errorVariant={'block'} onRetry={() => mutate()}>
<UsageCards
@@ -168,7 +164,7 @@ const StatsSetting = memo<StatsSettingProps>(
</AsyncBoundary>
<div style={{ height: 24 }} />
<UsageTable dateStrings={dateStrings} />
- </FormGroup>
+ </Form.Group>
</>
);
},
diff --git a/src/features/Settings/storage/features/Advanced.tsx b/src/features/Settings/storage/features/Advanced.tsx
index 63828c90d69..01fec1be70a 100644
--- a/src/features/Settings/storage/features/Advanced.tsx
+++ b/src/features/Settings/storage/features/Advanced.tsx
@@ -1,9 +1,9 @@
'use client';
import { BRANDING_NAME } from '@lobechat/business-const';
-import type { FormGroupItemType } from '@lobehub/ui';
-import { Form, Icon } from '@lobehub/ui';
+import { Icon } from '@lobehub/ui';
import { Button, confirmModal, Switch, toast } from '@lobehub/ui/base-ui';
+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import { HardDriveDownload, HardDriveUpload } from 'lucide-react';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -28,6 +28,7 @@ const AdvancedActions = () => {
const transferAgentsFormItems = useTransferAgentsFormItem();
const resetSettings = useUserStore((s) => s.resetSettings);
const updateGeneralConfig = useUserStore((s) => s.updateGeneralConfig);
+ const form = useForm();
const handleReset = useCallback(() => {
confirmModal({
@@ -65,7 +66,7 @@ const AdvancedActions = () => {
} as const;
};
- const system: FormGroupItemType = {
+ const system: FormGroupItem = {
children: [
{
children: (
@@ -103,7 +104,7 @@ const AdvancedActions = () => {
title: t('storage.actions.title'),
};
- const analytics: FormGroupItemType = {
+ const analytics: FormGroupItem = {
children: [
{
children: (
@@ -121,13 +122,12 @@ const AdvancedActions = () => {
</SettingsSearchAnchor>
),
minWidth: undefined,
- valuePropName: 'checked',
},
],
title: t('analytics.title'),
};
- const dataMigration: FormGroupItemType | undefined = transferAgentsFormItems
+ const dataMigration: FormGroupItem | undefined = transferAgentsFormItems
? {
children: transferAgentsFormItems,
title: t('storage.migration.title'),
@@ -138,6 +138,7 @@ const AdvancedActions = () => {
<>
<Form
collapsible={false}
+ form={form}
itemsType={'group'}
variant={'filled'}
items={[
diff --git a/src/features/Settings/storage/index.tsx b/src/features/Settings/storage/index.tsx
index b4a7f9d81a4..5aa88b2443f 100644
--- a/src/features/Settings/storage/index.tsx
+++ b/src/features/Settings/storage/index.tsx
@@ -1,6 +1,7 @@
'use client';
-import { Flexbox, FormGroup } from '@lobehub/ui';
+import { Flexbox } from '@lobehub/ui';
+import { Form } from '@lobehub/ui/base-ui/form';
import { useTranslation } from 'react-i18next';
import { ArticleSkeleton } from '@/components/Skeleton';
@@ -26,9 +27,9 @@ const Page = ({ showSettingHeader = true }: PageProps) => {
<>
{showSettingHeader && <SettingHeader title={t('tab.storage')} />}
<Flexbox style={{ display: isLoading ? 'flex' : 'none' }}>
- <FormGroup collapsible={false} title={t('storage.actions.title')} variant="filled">
+ <Form.Group collapsible={false} title={t('storage.actions.title')} variant="filled">
<ArticleSkeleton rows={4} />
- </FormGroup>
+ </Form.Group>
</Flexbox>
<Flexbox style={{ display: isLoading ? 'none' : 'flex' }}>
<Advanced />
diff --git a/src/features/Settings/system-tools/features/AppEnvironmentSection.tsx b/src/features/Settings/system-tools/features/AppEnvironmentSection.tsx
index b985db0c469..91237e33c14 100644
--- a/src/features/Settings/system-tools/features/AppEnvironmentSection.tsx
+++ b/src/features/Settings/system-tools/features/AppEnvironmentSection.tsx
@@ -1,8 +1,8 @@
'use client';
-import { type FormGroupItemType } from '@lobehub/ui';
-import { Flexbox, Form } from '@lobehub/ui';
+import { Flexbox } from '@lobehub/ui';
import { Tag, Text } from '@lobehub/ui/base-ui';
+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -29,8 +29,9 @@ const APP_ENVIRONMENT_ITEMS = [
const AppEnvironmentSection = memo(() => {
const { t } = useTranslation('setting');
const lobeEnv = window.lobeEnv;
+ const form = useForm();
- const formItems: FormGroupItemType[] = [
+ const formItems: FormGroupItem[] = [
{
children: APP_ENVIRONMENT_ITEMS.map((item) => {
const version = lobeEnv?.[item.versionKey];
@@ -58,6 +59,7 @@ const AppEnvironmentSection = memo(() => {
return (
<Form
collapsible={false}
+ form={form}
items={formItems}
itemsType={'group'}
variant={'filled'}
diff --git a/src/features/Settings/system-tools/features/ShellSection.tsx b/src/features/Settings/system-tools/features/ShellSection.tsx
index 3d849ab3144..8ae018a1248 100644
--- a/src/features/Settings/system-tools/features/ShellSection.tsx
+++ b/src/features/Settings/system-tools/features/ShellSection.tsx
@@ -1,9 +1,8 @@
'use client';
import { type WindowsShellMode } from '@lobechat/electron-client-ipc';
-import { type FormGroupItemType } from '@lobehub/ui';
-import { Form } from '@lobehub/ui';
import { Select, Text } from '@lobehub/ui/base-ui';
+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import useSWR from 'swr';
@@ -21,6 +20,7 @@ import { getPlatform } from '@/utils/platform';
const ShellSection = memo(() => {
const { t } = useTranslation('setting');
const [updating, setUpdating] = useState(false);
+ const form = useForm();
const { data, mutate } = useSWR(
'desktop-shell-settings',
@@ -49,7 +49,7 @@ const ShellSection = memo(() => {
: []),
];
- const shellGroup: FormGroupItemType = {
+ const shellGroup: FormGroupItem = {
children: [
{
children: (
@@ -87,6 +87,7 @@ const ShellSection = memo(() => {
return (
<Form
collapsible={false}
+ form={form}
items={[shellGroup]}
itemsType={'group'}
variant={'filled'}
diff --git a/src/features/Settings/system-tools/features/ToolDetectorSection.tsx b/src/features/Settings/system-tools/features/ToolDetectorSection.tsx
index 0f368891808..a89ed1ab81d 100644
--- a/src/features/Settings/system-tools/features/ToolDetectorSection.tsx
+++ b/src/features/Settings/system-tools/features/ToolDetectorSection.tsx
@@ -1,9 +1,9 @@
'use client';
import { type BinaryStatus } from '@lobechat/electron-client-ipc';
-import { type FormGroupItemType } from '@lobehub/ui';
-import { CopyButton, Flexbox, Form, Icon, Tooltip } from '@lobehub/ui';
+import { CopyButton, Flexbox, Icon, Tooltip } from '@lobehub/ui';
import { Button, Spin, Tag, Text } from '@lobehub/ui/base-ui';
+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import { CheckCircle2, RefreshCw, XCircle } from 'lucide-react';
import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -133,6 +133,7 @@ const ToolDetectorSection = memo(() => {
// rendered as "not detected" — a failure masquerading as an all-missing
// environment. Track it so we can render a failure + Retry instead (ux Read §1.1).
const [detectError, setDetectError] = useState<unknown>();
+ const form = useForm();
const detectTools = useCallback(async (force = false) => {
try {
@@ -156,31 +157,29 @@ const ToolDetectorSection = memo(() => {
detectTools(true);
}, [detectTools]);
- const formItems: FormGroupItemType[] = Object.entries(TOOL_CATEGORIES).map(
- ([, categoryConfig]) => ({
- children: categoryConfig.tools.map((tool) => {
- const status = toolStatuses[tool.name];
- const label = (
- <Flexbox horizontal align="center" gap={8}>
- <Text>{tool.name}</Text>
- {status?.version && (
- <Tag color="processing" style={{ marginInlineStart: 0 }}>
- {status.version}
- </Tag>
- )}
- </Flexbox>
- );
- return {
- children: <ToolStatusDisplay isDetecting={detecting} status={status} />,
- desc: t(tool.descKey),
- label,
- minWidth: undefined,
- };
- }),
- desc: t(categoryConfig.descKey),
- title: t(categoryConfig.titleKey),
+ const formItems: FormGroupItem[] = Object.entries(TOOL_CATEGORIES).map(([, categoryConfig]) => ({
+ children: categoryConfig.tools.map((tool) => {
+ const status = toolStatuses[tool.name];
+ const label = (
+ <Flexbox horizontal align="center" gap={8}>
+ <Text>{tool.name}</Text>
+ {status?.version && (
+ <Tag color="processing" style={{ marginInlineStart: 0 }}>
+ {status.version}
+ </Tag>
+ )}
+ </Flexbox>
+ );
+ return {
+ children: <ToolStatusDisplay isDetecting={detecting} status={status} />,
+ desc: t(tool.descKey),
+ label,
+ minWidth: undefined,
+ };
}),
- );
+ desc: t(categoryConfig.descKey),
+ title: t(categoryConfig.titleKey),
+ }));
// Nothing detected AND the scan errored → a real failure, not an empty
// environment. Show the reason + Retry rather than a wall of "not detected".
@@ -191,6 +190,7 @@ const ToolDetectorSection = memo(() => {
return (
<Form
collapsible={false}
+ form={form}
items={formItems}
itemsType={'group'}
variant={'filled'}
diff --git a/src/features/ShareModal/ShareImage/index.tsx b/src/features/ShareModal/ShareImage/index.tsx
index 618d7cac214..552ed323bdf 100644
--- a/src/features/ShareModal/ShareImage/index.tsx
+++ b/src/features/ShareModal/ShareImage/index.tsx
@@ -1,6 +1,6 @@
-import { type FormItemProps } from '@lobehub/ui';
-import { Flexbox, Form } from '@lobehub/ui';
+import { Flexbox } from '@lobehub/ui';
import { Button, Switch, Tabs } from '@lobehub/ui/base-ui';
+import { Form, type FormFieldProps, useForm } from '@lobehub/ui/base-ui/form';
import { CopyIcon } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -30,6 +30,10 @@ const DEFAULT_FIELD_VALUE: FieldType = {
const ShareImage = memo<{ mobile?: boolean }>(() => {
const currentAgentTitle = useAgentStore(agentSelectors.currentAgentDisplayName);
const [fieldValue, setFieldValue] = useState<FieldType>(DEFAULT_FIELD_VALUE);
+ const form = useForm({
+ initialValues: DEFAULT_FIELD_VALUE,
+ onValuesChange: (_, v) => setFieldValue(v),
+ });
const { t } = useTranslation(['chat', 'common']);
const { context, dbMessages } = useShareData();
const { loading, onDownload, title } = useScreenshot({
@@ -43,14 +47,14 @@ const ShareImage = memo<{ mobile?: boolean }>(() => {
{ key: WidthMode.Narrow, label: t('shareModal.widthMode.narrow') },
];
- const settings: FormItemProps[] = [
+ const settings: FormFieldProps<FieldType>[] = [
{
children: <Tabs items={widthModeOptions} />,
label: t('shareModal.widthMode.label'),
layout: 'horizontal',
minWidth: undefined,
name: 'widthMode',
- valuePropName: 'activeKey',
+ valueProp: 'activeKey',
},
{
children: <Switch />,
@@ -58,7 +62,6 @@ const ShareImage = memo<{ mobile?: boolean }>(() => {
layout: 'horizontal',
minWidth: undefined,
name: 'withSystemRole',
- valuePropName: 'checked',
},
{
children: <Switch />,
@@ -66,7 +69,6 @@ const ShareImage = memo<{ mobile?: boolean }>(() => {
layout: 'horizontal',
minWidth: undefined,
name: 'withFooter',
- valuePropName: 'checked',
},
{
children: <Tabs items={imageTypeOptions} />,
@@ -74,7 +76,7 @@ const ShareImage = memo<{ mobile?: boolean }>(() => {
layout: 'vertical',
minWidth: undefined,
name: 'imageType',
- valuePropName: 'activeKey',
+ valueProp: 'activeKey',
},
];
@@ -103,13 +105,7 @@ const ShareImage = memo<{ mobile?: boolean }>(() => {
<Flexbox className={styles.body} gap={16} horizontal={!isMobile}>
<Preview context={context} messages={dbMessages} title={title} {...fieldValue} />
<Flexbox className={styles.sidebar} gap={12}>
- <Form
- initialValues={DEFAULT_FIELD_VALUE}
- items={settings}
- itemsType={'flat'}
- onValuesChange={(_, v) => setFieldValue(v)}
- {...FORM_STYLE}
- />
+ <Form form={form} items={settings} itemsType={'flat'} {...FORM_STYLE} />
{!isMobile && button}
</Flexbox>
</Flexbox>
diff --git a/src/features/ShareModal/ShareJSON/index.tsx b/src/features/ShareModal/ShareJSON/index.tsx
index 2a8f9e6b647..7fb20bcace1 100644
--- a/src/features/ShareModal/ShareJSON/index.tsx
+++ b/src/features/ShareModal/ShareJSON/index.tsx
@@ -1,9 +1,9 @@
import { FORM_STYLE } from '@lobechat/const';
import { type TopicExportMode } from '@lobechat/types';
import { exportFile } from '@lobechat/utils/client';
-import { type FormItemProps } from '@lobehub/ui';
-import { copyToClipboard, Flexbox, Form } from '@lobehub/ui';
+import { copyToClipboard, Flexbox } from '@lobehub/ui';
import { Button, Switch, Tabs, toast } from '@lobehub/ui/base-ui';
+import { Form, type FormFieldProps, useForm } from '@lobehub/ui/base-ui/form';
import { CopyIcon } from 'lucide-react';
import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -26,6 +26,10 @@ const DEFAULT_FIELD_VALUE: FieldType = {
const ShareJSON = memo(() => {
const [fieldValue, setFieldValue] = useState(DEFAULT_FIELD_VALUE);
+ const form = useForm({
+ initialValues: DEFAULT_FIELD_VALUE,
+ onValuesChange: (_, v) => setFieldValue(v),
+ });
const { t } = useTranslation(['chat', 'common']);
const exportModeOptions = useMemo(
@@ -36,7 +40,7 @@ const ShareJSON = memo(() => {
[t],
);
- const settings: FormItemProps[] = [
+ const settings: FormFieldProps<FieldType>[] = [
{
children: (
<Tabs
@@ -62,7 +66,6 @@ const ShareJSON = memo(() => {
layout: 'horizontal',
minWidth: undefined,
name: 'withSystemRole',
- valuePropName: 'checked',
},
];
@@ -128,13 +131,7 @@ const ShareJSON = memo(() => {
<Flexbox className={styles.body} gap={16} horizontal={!isMobile}>
<Preview content={content} />
<Flexbox className={styles.sidebar} gap={12}>
- <Form
- initialValues={DEFAULT_FIELD_VALUE}
- items={settings}
- itemsType={'flat'}
- onValuesChange={(_, v) => setFieldValue(v)}
- {...FORM_STYLE}
- />
+ <Form form={form} items={settings} itemsType={'flat'} {...FORM_STYLE} />
{!isMobile && button}
</Flexbox>
</Flexbox>
diff --git a/src/features/ShareModal/SharePdf/index.tsx b/src/features/ShareModal/SharePdf/index.tsx
index bf11b0abbc2..367bb539b9a 100644
--- a/src/features/ShareModal/SharePdf/index.tsx
+++ b/src/features/ShareModal/SharePdf/index.tsx
@@ -1,7 +1,7 @@
import { type UIChatMessage } from '@lobechat/types';
-import { type FormItemProps } from '@lobehub/ui';
-import { Flexbox, Form } from '@lobehub/ui';
+import { Flexbox } from '@lobehub/ui';
import { Button, Switch, toast } from '@lobehub/ui/base-ui';
+import { Form, type FormFieldProps, useForm } from '@lobehub/ui/base-ui/form';
import { cx } from 'antd-style';
import { DownloadIcon, FileText } from 'lucide-react';
import { memo, useState } from 'react';
@@ -29,19 +29,22 @@ const DEFAULT_FIELD_VALUE: FieldType = {
const SharePdf = memo((props: { message?: UIChatMessage }) => {
const [fieldValue, setFieldValue] = useState(DEFAULT_FIELD_VALUE);
+ const form = useForm({
+ initialValues: DEFAULT_FIELD_VALUE,
+ onValuesChange: (_, allValues) => setFieldValue(allValues),
+ });
const { t } = useTranslation(['chat', 'common']);
const { message: outerMessage } = props;
const isMobile = useIsMobile();
- const settings: FormItemProps[] = [
+ const settings: FormFieldProps<FieldType>[] = [
{
children: <Switch />,
label: t('shareModal.withSystemRole'),
layout: 'horizontal',
minWidth: undefined,
name: 'withSystemRole',
- valuePropName: 'checked',
},
{
children: <Switch />,
@@ -49,7 +52,6 @@ const SharePdf = memo((props: { message?: UIChatMessage }) => {
layout: 'horizontal',
minWidth: undefined,
name: 'withRole',
- valuePropName: 'checked',
},
{
children: <Switch />,
@@ -57,7 +59,6 @@ const SharePdf = memo((props: { message?: UIChatMessage }) => {
layout: 'horizontal',
minWidth: undefined,
name: 'includeUser',
- valuePropName: 'checked',
},
{
children: <Switch />,
@@ -65,7 +66,6 @@ const SharePdf = memo((props: { message?: UIChatMessage }) => {
layout: 'horizontal',
minWidth: undefined,
name: 'includeTool',
- valuePropName: 'checked',
},
];
@@ -97,11 +97,6 @@ const SharePdf = memo((props: { message?: UIChatMessage }) => {
}
};
- // Update configuration when form changes
- const handleConfigChange = (_changedValues: any, allValues: FieldType) => {
- setFieldValue(allValues);
- };
-
const handleDownload = async () => {
if (pdfData) {
try {
@@ -156,13 +151,7 @@ const SharePdf = memo((props: { message?: UIChatMessage }) => {
</div>
<Flexbox className={styles.sidebar} gap={12}>
<div>{t('shareModal.pdfErrorDescription')}</div>
- <Form
- initialValues={DEFAULT_FIELD_VALUE}
- items={settings}
- itemsType={'flat'}
- onValuesChange={handleConfigChange}
- {...FORM_STYLE}
- />
+ <Form form={form} items={settings} itemsType={'flat'} {...FORM_STYLE} />
{generateButton}
</Flexbox>
</Flexbox>
@@ -173,13 +162,7 @@ const SharePdf = memo((props: { message?: UIChatMessage }) => {
<Flexbox className={styles.body} gap={16} horizontal={!isMobile}>
<PdfPreview loading={loading} pdfData={pdfData} onGeneratePdf={handleGeneratePdf} />
<Flexbox className={styles.sidebar} gap={12}>
- <Form
- initialValues={DEFAULT_FIELD_VALUE}
- items={settings}
- itemsType={'flat'}
- onValuesChange={handleConfigChange}
- {...FORM_STYLE}
- />
+ <Form form={form} items={settings} itemsType={'flat'} {...FORM_STYLE} />
{pdfData && generateButton}
{downloadButton}
</Flexbox>
diff --git a/src/features/ShareModal/ShareText/index.tsx b/src/features/ShareModal/ShareText/index.tsx
index f6aef18b61a..47143f9edd3 100644
--- a/src/features/ShareModal/ShareText/index.tsx
+++ b/src/features/ShareModal/ShareText/index.tsx
@@ -1,8 +1,8 @@
import { FORM_STYLE } from '@lobechat/const';
import { exportFile } from '@lobechat/utils/client';
-import { type FormItemProps } from '@lobehub/ui';
-import { copyToClipboard, Flexbox, Form } from '@lobehub/ui';
+import { copyToClipboard, Flexbox } from '@lobehub/ui';
import { Button, Switch, toast } from '@lobehub/ui/base-ui';
+import { Form, type FormFieldProps, useForm } from '@lobehub/ui/base-ui/form';
import { CopyIcon } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -25,16 +25,19 @@ const DEFAULT_FIELD_VALUE: FieldType = {
const ShareText = memo(() => {
const [fieldValue, setFieldValue] = useState(DEFAULT_FIELD_VALUE);
+ const form = useForm({
+ initialValues: DEFAULT_FIELD_VALUE,
+ onValuesChange: (_, v) => setFieldValue(v),
+ });
const { t } = useTranslation(['chat', 'common']);
- const settings: FormItemProps[] = [
+ const settings: FormFieldProps<FieldType>[] = [
{
children: <Switch />,
label: t('shareModal.withSystemRole'),
layout: 'horizontal',
minWidth: undefined,
name: 'withSystemRole',
- valuePropName: 'checked',
},
{
children: <Switch />,
@@ -42,7 +45,6 @@ const ShareText = memo(() => {
layout: 'horizontal',
minWidth: undefined,
name: 'withRole',
- valuePropName: 'checked',
},
{
children: <Switch />,
@@ -50,7 +52,6 @@ const ShareText = memo(() => {
layout: 'horizontal',
minWidth: undefined,
name: 'includeUser',
- valuePropName: 'checked',
},
{
children: <Switch />,
@@ -58,7 +59,6 @@ const ShareText = memo(() => {
layout: 'horizontal',
minWidth: undefined,
name: 'includeTool',
- valuePropName: 'checked',
},
];
@@ -113,13 +113,7 @@ const ShareText = memo(() => {
<Flexbox className={styles.body} gap={16} horizontal={!isMobile}>
<Preview content={content} />
<Flexbox className={styles.sidebar} gap={12}>
- <Form
- initialValues={DEFAULT_FIELD_VALUE}
- items={settings}
- itemsType={'flat'}
- onValuesChange={(_, v) => setFieldValue(v)}
- {...FORM_STYLE}
- />
+ <Form form={form} items={settings} itemsType={'flat'} {...FORM_STYLE} />
{!isMobile && button}
</Flexbox>
</Flexbox>
diff --git a/src/features/WorkspaceSetting/Storage/index.tsx b/src/features/WorkspaceSetting/Storage/index.tsx
index e2f9d7d3cf7..860d2781039 100644
--- a/src/features/WorkspaceSetting/Storage/index.tsx
+++ b/src/features/WorkspaceSetting/Storage/index.tsx
@@ -1,9 +1,9 @@
'use client';
import { BRANDING_NAME } from '@lobechat/business-const';
-import type { FormGroupItemType } from '@lobehub/ui';
-import { Form, Icon } from '@lobehub/ui';
+import { Icon } from '@lobehub/ui';
import { Button, Switch } from '@lobehub/ui/base-ui';
+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/base-ui/form';
import { HardDriveDownload, HardDriveUpload } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -14,21 +14,21 @@ import { FORM_STYLE } from '@/const/layoutTokens';
const WorkspaceStorageContent = memo(() => {
const { t } = useTranslation('setting');
const transferAgentsFormItems = useTransferAgentsFormItem();
+ const form = useForm();
- const analytics: FormGroupItemType = {
+ const analytics: FormGroupItem = {
children: [
{
children: <Switch disabled />,
desc: t('workspaceSetting.storage.telemetry.desc', { appName: BRANDING_NAME }),
label: t('workspaceSetting.storage.telemetry.title'),
minWidth: undefined,
- valuePropName: 'checked',
},
],
title: t('analytics.title'),
};
- const system: FormGroupItemType = {
+ const system: FormGroupItem = {
children: [
{
children: (
@@ -56,7 +56,7 @@ const WorkspaceStorageContent = memo(() => {
title: t('storage.actions.title'),
};
- const dataMigration: FormGroupItemType | undefined = transferAgentsFormItems
+ const dataMigration: FormGroupItem | undefined = transferAgentsFormItems
? {
children: transferAgentsFormItems,
title: t('storage.migration.title'),
@@ -66,6 +66,7 @@ const WorkspaceStorageContent = memo(() => {
return (
<Form
collapsible={false}
+ form={form}
items={[analytics, ...(dataMigration ? [dataMigration] : []), system]}
itemsType={'group'}
variant={'filled'}
diff --git a/src/layout/AuthProvider/MarketAuth/ProfileSetupModal.tsx b/src/layout/AuthProvider/MarketAuth/ProfileSetupModal.tsx
index 057e8ad90a8..e8d50508206 100644
--- a/src/layout/AuthProvider/MarketAuth/ProfileSetupModal.tsx
+++ b/src/layout/AuthProvider/MarketAuth/ProfileSetupModal.tsx
@@ -2,11 +2,12 @@
import { Center, Flexbox, Icon, Tooltip } from '@lobehub/ui';
import { confirmModal, Input, Text, TextArea, toast, Upload } from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form, useForm, useWatch } from '@lobehub/ui/base-ui/form';
import { cssVar } from 'antd-style';
import { CircleHelp, Globe, ImagePlus, Trash2 } from 'lucide-react';
import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { z } from 'zod';
import EmojiPicker from '@/components/EmojiPicker';
import ImperativeModal from '@/components/ImperativeModal';
@@ -71,9 +72,11 @@ const ProfileSetupModal = memo<ProfileSetupModalProps>(
}) => {
const { t } = useTranslation('marketAuth');
- const [form] = Form.useForm<FormValues>();
- const displayName = Form.useWatch('displayName', form);
- const userName = Form.useWatch('userName', form);
+ const form = useForm<FormValues>({
+ initialValues: { description: '', displayName: '', userName: '', website: '' },
+ });
+ const displayName = useWatch(form, 'displayName');
+ const userName = useWatch(form, 'userName');
const [loading, setLoading] = useState(false);
const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);
@@ -144,7 +147,7 @@ const ProfileSetupModal = memo<ProfileSetupModalProps>(
.replaceAll(/[^\w-]/g, '')
.slice(0, 32);
- form.setFieldsValue({
+ form.setValues({
description: userProfile?.description || '',
displayName: existingDisplayName,
userName: existingUserName || generatedUserName,
@@ -229,7 +232,9 @@ const ProfileSetupModal = memo<ProfileSetupModalProps>(
}
try {
- const values = await form.validateFields();
+ const { valid } = await form.validate();
+ if (!valid) return;
+ const values = form.getValues();
setLoading(true);
// Build socialLinks from OAuth profiles and website input
@@ -323,7 +328,9 @@ const ProfileSetupModal = memo<ProfileSetupModalProps>(
const handleSubmit = useCallback(async () => {
try {
- const values = await form.validateFields();
+ const { valid } = await form.validate();
+ if (!valid) return;
+ const values = form.getValues();
const oldUserName = userProfile?.userName;
// If userName changed and it's not first-time setup, show confirmation
@@ -381,28 +388,28 @@ const ProfileSetupModal = memo<ProfileSetupModalProps>(
onCancel={handleCancel}
onOk={handleSubmit}
>
- <Form form={form} layout="vertical">
+ <Form form={form} gap={0} layout="vertical">
<Flexbox horizontal gap={24}>
<Flexbox flex={1}>
- <Form.Item
+ <Form.Field
label={t('profileSetup.fields.displayName.label')}
name="displayName"
- rules={[
- { message: t('profileSetup.fields.displayName.required'), required: true },
- {
- max: 50,
- message: t('profileSetup.fields.displayName.maxLength'),
- },
- ]}
+ required={t('profileSetup.fields.displayName.required')}
+ validate={(value?: string) =>
+ value && value.length > 50
+ ? t('profileSetup.fields.displayName.maxLength')
+ : undefined
+ }
>
<Input
maxLength={50}
placeholder={t('profileSetup.fields.displayName.placeholder')}
suffix={`${displayName?.length ?? 0} / 50`}
/>
- </Form.Item>
- <Form.Item
+ </Form.Field>
+ <Form.Field
name="userName"
+ required={t('profileSetup.fields.userName.required')}
label={
<Flexbox horizontal align="center" gap={4}>
{t('profileSetup.fields.userName.label')}
@@ -411,21 +418,12 @@ const ProfileSetupModal = memo<ProfileSetupModalProps>(
</Tooltip>
</Flexbox>
}
- rules={[
- { message: t('profileSetup.fields.userName.required'), required: true },
- {
- message: t('profileSetup.fields.userName.pattern'),
- pattern: /^[\w-]+$/,
- },
- {
- max: 32,
- message: t('profileSetup.fields.userName.maxLength'),
- },
- {
- message: t('profileSetup.fields.userName.minLength'),
- min: 3,
- },
- ]}
+ validate={(value?: string) => {
+ if (!value) return;
+ if (!/^[\w-]+$/.test(value)) return t('profileSetup.fields.userName.pattern');
+ if (value.length > 32) return t('profileSetup.fields.userName.maxLength');
+ if (value.length < 3) return t('profileSetup.fields.userName.minLength');
+ }}
>
<Input
maxLength={32}
@@ -433,10 +431,10 @@ const ProfileSetupModal = memo<ProfileSetupModalProps>(
prefix="@"
suffix={`${userName?.length ?? 0} / 32`}
/>
- </Form.Item>
+ </Form.Field>
</Flexbox>
{/* Avatar Section */}
- <Form.Item>
+ <Form.Field>
<EmojiPicker
allowDelete={!!avatarUrl}
loading={avatarUploading}
@@ -451,17 +449,16 @@ const ProfileSetupModal = memo<ProfileSetupModalProps>(
onDelete={handleAvatarDelete}
onUpload={handleAvatarUpload}
/>
- </Form.Item>
+ </Form.Field>
</Flexbox>
- <Form.Item
+ <Form.Field
label={t('profileSetup.fields.description.label')}
name="description"
- rules={[
- {
- max: 200,
- message: t('profileSetup.fields.description.maxLength'),
- },
- ]}
+ validate={(value?: string) =>
+ value && value.length > 200
+ ? t('profileSetup.fields.description.maxLength')
+ : undefined
+ }
>
<TextArea
showCount
@@ -469,13 +466,13 @@ const ProfileSetupModal = memo<ProfileSetupModalProps>(
placeholder={t('profileSetup.fields.description.placeholder')}
rows={3}
/>
- </Form.Item>
+ </Form.Field>
{/* Only show banner and social links in edit mode, not first-time setup */}
{!isFirstTimeSetup && (
<>
{/* Banner Upload Section */}
- <Form.Item
+ <Form.Field
label={
<Flexbox horizontal align="center" gap={4}>
{t('profileSetup.fields.bannerUrl.label')}
@@ -561,7 +558,7 @@ const ProfileSetupModal = memo<ProfileSetupModalProps>(
</Flexbox>
)}
</Flexbox>
- </Form.Item>
+ </Form.Field>
<Text style={{ display: 'block', marginBottom: 12 }} type="secondary">
{t('profileSetup.socialLinks.title')}
@@ -592,14 +589,13 @@ const ProfileSetupModal = memo<ProfileSetupModalProps>(
</Flexbox>
{/* Website - Manual Input */}
- <Form.Item
+ <Form.Field
name="website"
- rules={[
- {
- message: t('profileSetup.fields.website.invalidUrl'),
- type: 'url',
- },
- ]}
+ validate={(value?: string) =>
+ value && !z.url().safeParse(value).success
+ ? t('profileSetup.fields.website.invalidUrl')
+ : undefined
+ }
>
<Input
placeholder={t('profileSetup.fields.website.placeholder')}
@@ -611,7 +607,7 @@ const ProfileSetupModal = memo<ProfileSetupModalProps>(
/>
}
/>
- </Form.Item>
+ </Form.Field>
</>
)}
</Form>
diff --git a/src/routes/(main)/agent/channel/detail/Body.tsx b/src/routes/(main)/agent/channel/detail/Body.tsx
index 0dde50e1ce6..28fedd4b330 100644
--- a/src/routes/(main)/agent/channel/detail/Body.tsx
+++ b/src/routes/(main)/agent/channel/detail/Body.tsx
@@ -1,10 +1,10 @@
'use client';
import { isMaskedBotCredential } from '@lobechat/const';
-import { Block, Flexbox, Form, FormGroup, FormItem, Icon } from '@lobehub/ui';
+import { Block, Flexbox, Icon } from '@lobehub/ui';
import type { SelectOption } from '@lobehub/ui/base-ui';
import { Button, confirmModal, InputNumber, Select, Switch, Tag, Text } from '@lobehub/ui/base-ui';
-import { Form as AntdForm, type FormInstance } from 'antd';
+import { Form, type FormInstance, useFormInstance, useWatch } from '@lobehub/ui/base-ui/form';
import { createStaticStyles } from 'antd-style';
import {
Fingerprint,
@@ -19,7 +19,6 @@ import {
Trash2,
UsersRound,
} from 'lucide-react';
-import type { MouseEvent } from 'react';
import { Fragment, memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -38,48 +37,10 @@ import {
import { extractSettingsDefaults } from './formState';
import type { ChannelFormValues } from './index';
-const prefixCls = 'ant';
-
const styles = createStaticStyles(({ css, cssVar }) => ({
advancedGroup: css`
border-block-start: 1px solid ${cssVar.colorBorderSecondary};
border-radius: 0 !important;
-
- .${prefixCls}-collapse-item {
- border-radius: 0 !important;
- }
-
- .${prefixCls}-collapse-header {
- align-items: center !important;
-
- margin-inline: -16px;
- padding-block: 10px !important;
- padding-inline: 16px !important;
- border-block-end: 0 !important;
-
- color: ${cssVar.colorTextSecondary} !important;
-
- transition: background-color ${cssVar.motionDurationFast} ${cssVar.motionEaseInOut};
-
- &:hover {
- background: ${cssVar.colorBgTextHover};
- }
- }
-
- .${prefixCls}-collapse-expand-icon {
- align-self: center;
- color: ${cssVar.colorTextSecondary} !important;
- }
-
- .${prefixCls}-collapse-title {
- display: flex;
- flex: 1 !important;
- align-items: center;
- }
-
- .${prefixCls}-collapse-content-box {
- padding-inline: 0 !important;
- }
`,
advancedTitle: css`
font-size: 13px;
@@ -98,73 +59,48 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
align-self: center;
color: ${cssVar.colorTextSecondary};
`,
- form: css`
- .${prefixCls}-form-item-label {
- display: flex;
- align-items: center;
- }
-
- .${prefixCls}-form-item-label > label {
- align-items: center;
- width: 100%;
- }
-
- .${prefixCls}-form-item-required::before {
- align-self: center !important;
- }
-
- .${prefixCls}-form-item-control {
- flex: 0 0 50% !important;
- width: 50%;
- }
- `,
}));
// --------------- Validation rules builder ---------------
-export function buildRules(field: FieldSchema, t: (key: string) => string) {
- const rules: any[] = [];
-
- if (field.required) {
- rules.push({ message: t(field.label), required: true });
- }
-
- // Format constraint declared by the platform schema. Empty stays valid, so an
- // untouched optional field does not trip it, and so does the placeholder the
- // server returns in place of a stored secret — the save path swaps that back
- // for the real value, and holding it to the platform's format here would make
- // every unrelated edit demand the secret be retyped.
- if (field.pattern) {
- const pattern = new RegExp(field.pattern);
- const message = field.patternMessage ? t(field.patternMessage) : t(field.label);
-
- rules.push({
- validator: (_: unknown, value: unknown) => {
- if (typeof value !== 'string' || !value) return Promise.resolve();
- if (isMaskedBotCredential(value)) return Promise.resolve();
- return pattern.test(value) ? Promise.resolve() : Promise.reject(new Error(message));
- },
- });
- }
-
- if (field.type === 'number' || field.type === 'integer') {
- if (typeof field.minimum === 'number') {
- rules.push({
- message: `${t(field.label)} ≥ ${field.minimum}`,
- min: field.minimum,
- type: 'number' as const,
- });
+const isEmptyValue = (value: unknown) =>
+ value === undefined || value === null || value === '' || (Array.isArray(value) && !value.length);
+
+export function buildValidate(field: FieldSchema, t: (key: string) => string) {
+ const pattern = field.pattern ? new RegExp(field.pattern) : undefined;
+ const isNumber = field.type === 'number' || field.type === 'integer';
+ const { maximum, minimum } = field;
+
+ if (
+ !field.required &&
+ !pattern &&
+ !(isNumber && (typeof minimum === 'number' || typeof maximum === 'number'))
+ )
+ return undefined;
+
+ return (value: unknown) => {
+ if (isEmptyValue(value)) return field.required ? t(field.label) : undefined;
+
+ // Format constraint declared by the platform schema. Empty stays valid, so an
+ // untouched optional field does not trip it, and so does the placeholder the
+ // server returns in place of a stored secret — the save path swaps that back
+ // for the real value, and holding it to the platform's format here would make
+ // every unrelated edit demand the secret be retyped.
+ if (
+ pattern &&
+ typeof value === 'string' &&
+ !isMaskedBotCredential(value) &&
+ !pattern.test(value)
+ )
+ return field.patternMessage ? t(field.patternMessage) : t(field.label);
+
+ if (isNumber && typeof value === 'number') {
+ if (typeof minimum === 'number' && value < minimum) return `${t(field.label)} ≥ ${minimum}`;
+ if (typeof maximum === 'number' && value > maximum) return `${t(field.label)} ≤ ${maximum}`;
}
- if (typeof field.maximum === 'number') {
- rules.push({
- message: `${t(field.label)} ≤ ${field.maximum}`,
- max: field.maximum,
- type: 'number' as const,
- });
- }
- }
- return rules.length > 0 ? rules : undefined;
+ return undefined;
+ };
}
// --------------- Single field component (memo'd) ---------------
@@ -225,8 +161,9 @@ const SchemaField = memo<SchemaFieldProps>(
const disabled = formDisabled || featureLocked;
// Conditional visibility: watch the sibling field specified by visibleWhen
- const watchedValue = AntdForm.useWatch(
- field.visibleWhen ? [parentKey, field.visibleWhen.field] : [],
+ const form = useFormInstance();
+ const watchedValue = useWatch(form, (values) =>
+ field.visibleWhen ? values[parentKey]?.[field.visibleWhen.field] : undefined,
);
if (field.visibleWhen) {
// An array matches any of its entries, so one field can be shared by
@@ -243,7 +180,7 @@ const SchemaField = memo<SchemaFieldProps>(
const label = renderFieldLabel(field, t);
// Array of objects (e.g. user / channel allowlist) — needs Form.List, can't
- // be expressed as a single control inside a name-bound FormItem.
+ // be expressed as a single control inside a name-bound Form.Field.
if (field.type === 'array' && field.items?.type === 'object') {
return (
<ObjectListField
@@ -342,19 +279,17 @@ const SchemaField = memo<SchemaFieldProps>(
}
return (
- <FormItem
+ <Form.Field
avatar={renderFieldIcon(field)}
divider={divider}
- initialValue={field.default}
label={label}
minWidth={'max(50%, 400px)'}
- name={[parentKey, field.key]}
- rules={buildRules(field, t)}
- valuePropName={field.type === 'boolean' ? 'checked' : undefined}
+ name={`${parentKey}.${field.key}`}
+ validate={buildValidate(field, t)}
variant="outlined"
>
{children}
- </FormItem>
+ </Form.Field>
);
},
);
@@ -397,36 +332,31 @@ const ObjectListField = memo<ObjectListFieldProps>(
const removeLabel = t('channel.allowListRemove');
return (
- <FormItem
+ <Form.Field
avatar={icon}
divider={divider}
label={label}
minWidth={'max(50%, 400px)'}
variant="outlined"
>
- <AntdForm.List initialValue={field.default as unknown[]} name={[parentKey, field.key]}>
- {(rows, { add, remove }) => (
+ <Form.List name={`${parentKey}.${field.key}`}>
+ {({ fields: rows, add, remove }) => (
<Flexbox gap={8} style={{ width: '100%' }}>
{rows.length === 0 && (
<Flexbox style={{ fontSize: 12, opacity: 0.6, paddingBlock: 4 }}>
{emptyLabel}
</Flexbox>
)}
- {rows.map(({ key, name }) => (
+ {rows.map(({ index, key, name }) => (
<Flexbox horizontal align="center" gap={8} key={key}>
{itemProps.map((sub) => (
- // `noStyle` skips the antd FormItem chrome that the parent
- // form's 50%-width override targets — without it each cell
- // collapses to half the row, leaving a wide gap between
- // the id and name inputs. The flex:1 wrapper takes over
- // sizing, and `minWidth:0` lets the input actually shrink.
<div key={sub.key} style={{ flex: 1, minWidth: 0 }}>
- <AntdForm.Item
- noStyle
- name={[name, sub.key]}
- rules={
+ <Form.Field
+ bare
+ name={`${name}.${sub.key}`}
+ validate={
sub.required
- ? [{ message: t(sub.label), required: true, whitespace: true }]
+ ? (value?: string) => (value?.trim() ? undefined : t(sub.label))
: undefined
}
>
@@ -438,7 +368,7 @@ const ObjectListField = memo<ObjectListFieldProps>(
: t(sub.label)
}
/>
- </AntdForm.Item>
+ </Form.Field>
</div>
))}
<Button
@@ -446,7 +376,7 @@ const ObjectListField = memo<ObjectListFieldProps>(
disabled={disabled}
icon={<Trash2 size={14} />}
type="text"
- onClick={() => remove(name)}
+ onClick={() => remove(index)}
/>
</Flexbox>
))}
@@ -466,8 +396,8 @@ const ObjectListField = memo<ObjectListFieldProps>(
</Button>
</Flexbox>
)}
- </AntdForm.List>
- </FormItem>
+ </Form.List>
+ </Form.Field>
);
},
);
@@ -480,21 +410,20 @@ const ApplicationIdField = memo<{ disabled?: boolean; divider?: boolean; field:
const t = _t as (key: string) => string;
return (
- <FormItem
+ <Form.Field
avatar={renderFieldIcon(field)}
divider={divider}
- initialValue={field.default}
label={renderFieldLabel(field, t)}
minWidth={'max(50%, 400px)'}
name="applicationId"
- rules={buildRules(field, t)}
+ validate={buildValidate(field, t)}
variant="outlined"
>
<FormInput
disabled={disabled}
placeholder={field.placeholder ? t(field.placeholder) : t(field.label)}
/>
- </FormItem>
+ </Form.Field>
);
},
);
@@ -581,10 +510,10 @@ const Body = memo<BodyProps>(
const [settingsActive, setSettingsActive] = useState(userIdInitiallyMissing);
const handleResetSettings = useCallback(() => {
- form.setFieldsValue({
+ form.setValues({
settings: extractSettingsDefaults(platformDef.schema) as Record<string, {} | undefined>,
});
- onValuesChange?.(form.getFieldsValue(true) as ChannelFormValues);
+ onValuesChange?.(form.getValues());
}, [form, onValuesChange, platformDef.schema]);
// A settings-field helper writes straight into the form, which does not
@@ -592,30 +521,16 @@ const Body = memo<BodyProps>(
// reports its own write. Without this the page never sees the change and
// the unsaved-changes affordances stay hidden.
const handleFieldExtrasFilled = useCallback(() => {
- onValuesChange?.(form.getFieldsValue(true) as ChannelFormValues);
+ onValuesChange?.(form.getValues());
}, [form, onValuesChange]);
- const handleSettingsHeaderClick = useCallback((event: MouseEvent<HTMLDivElement>) => {
- const target = event.target;
- if (!(target instanceof Element)) return;
- if (!target.closest(`.${prefixCls}-collapse-header`)) return;
- if (target.closest(`.${prefixCls}-collapse-extra`)) return;
-
- event.preventDefault();
- event.stopPropagation();
- setSettingsActive((active) => !active);
- }, []);
-
return (
<Form
- className={styles.form}
form={form}
gap={0}
itemMinWidth={'max(50%, 400px)'}
- requiredMark={false}
style={{ maxWidth: 1024, padding: '16px 0', width: '100%' }}
variant={'borderless'}
- onValuesChange={(_, values) => onValuesChange?.(values as ChannelFormValues)}
>
<Block className={styles.container} variant={'outlined'}>
{CustomCredentialBody ? (
@@ -670,67 +585,65 @@ const Body = memo<BodyProps>(
</>
)}
{settingsFields.length > 0 && (
- <div onClickCapture={handleSettingsHeaderClick}>
- <FormGroup
- collapsible
- active={settingsActive}
- className={styles.advancedGroup}
- defaultActive={userIdInitiallyMissing}
- keyValue={`settings-${platformDef.id}`}
- title={<SettingsTitle schema={platformDef.schema} />}
- variant="borderless"
- extra={
- settingsActive ? (
- <Button
+ <Form.Group
+ collapsible
+ active={settingsActive}
+ className={styles.advancedGroup}
+ defaultActive={userIdInitiallyMissing}
+ keyValue={`settings-${platformDef.id}`}
+ title={<SettingsTitle schema={platformDef.schema} />}
+ variant="borderless"
+ extra={
+ settingsActive ? (
+ <Button
+ disabled={disabled}
+ icon={<RotateCcw size={14} />}
+ size="small"
+ type="default"
+ onClick={() =>
+ confirmModal({
+ content: t('channel.settingsResetConfirm'),
+ okText: t('channel.settingsResetDefault'),
+ title: t('channel.settingsResetDefault'),
+ onOk: handleResetSettings,
+ })
+ }
+ >
+ {t('channel.settingsResetDefault')}
+ </Button>
+ ) : undefined
+ }
+ onCollapse={setSettingsActive}
+ >
+ {settingsFields.map((field) => {
+ // Feature-gated fields (e.g. watch keywords) lock when the
+ // resolved access meta reports the feature as not allowed.
+ const featureLocked =
+ !!field.paidFeature &&
+ platformDef.access?.features?.[field.paidFeature]?.allowed === false;
+ const FieldExtras =
+ platformSettingsFieldExtrasMap[`${platformDef.id}:${field.key}`];
+ return (
+ <Fragment key={field.key}>
+ <SchemaField
+ divider
disabled={disabled}
- icon={<RotateCcw size={14} />}
- size="small"
- type="default"
- onClick={() =>
- confirmModal({
- content: t('channel.settingsResetConfirm'),
- okText: t('channel.settingsResetDefault'),
- title: t('channel.settingsResetDefault'),
- onOk: handleResetSettings,
- })
- }
- >
- {t('channel.settingsResetDefault')}
- </Button>
- ) : undefined
- }
- onCollapse={setSettingsActive}
- >
- {settingsFields.map((field) => {
- // Feature-gated fields (e.g. watch keywords) lock when the
- // resolved access meta reports the feature as not allowed.
- const featureLocked =
- !!field.paidFeature &&
- platformDef.access?.features?.[field.paidFeature]?.allowed === false;
- const FieldExtras =
- platformSettingsFieldExtrasMap[`${platformDef.id}:${field.key}`];
- return (
- <Fragment key={field.key}>
- <SchemaField
- divider
- disabled={disabled}
- featureLocked={featureLocked}
- field={field}
- parentKey="settings"
+ featureLocked={featureLocked}
+ field={field}
+ parentKey="settings"
+ />
+ {FieldExtras && (
+ <FieldExtras
+ disabled={disabled || featureLocked}
+ platformId={platformDef.id}
+ savedValue={currentConfig?.settings?.[field.key]}
+ onFilled={handleFieldExtrasFilled}
/>
- {FieldExtras && (
- <FieldExtras
- disabled={disabled || featureLocked}
- platformId={platformDef.id}
- savedValue={currentConfig?.settings?.[field.key]}
- onFilled={handleFieldExtrasFilled}
- />
- )}
- </Fragment>
- );
- })}
- </FormGroup>
- </div>
+ )}
+ </Fragment>
+ );
+ })}
+ </Form.Group>
)}
</Block>
</Form>
diff --git a/src/routes/(main)/agent/channel/detail/Footer.tsx b/src/routes/(main)/agent/channel/detail/Footer.tsx
index 0d62e551933..469c3929dda 100644
--- a/src/routes/(main)/agent/channel/detail/Footer.tsx
+++ b/src/routes/(main)/agent/channel/detail/Footer.tsx
@@ -2,7 +2,7 @@
import { Flexbox } from '@lobehub/ui';
import { Alert, Button, Tag } from '@lobehub/ui/base-ui';
-import { Form as AntdForm, type FormInstance } from 'antd';
+import { type FormInstance, useWatch } from '@lobehub/ui/base-ui/form';
import { createStaticStyles } from 'antd-style';
import { RefreshCw, Trash2 } from 'lucide-react';
import { memo, useEffect, useMemo, useState } from 'react';
@@ -115,9 +115,9 @@ const Footer = memo<FooterProps>(
const { t } = useTranslation('agent');
const origin = useAppOrigin();
const platformId = platformDef.id;
- const applicationId = AntdForm.useWatch('applicationId', form);
+ const applicationId = useWatch(form, 'applicationId');
- const settingsConnectionMode = AntdForm.useWatch(['settings', 'connectionMode'], form);
+ const settingsConnectionMode = useWatch(form, 'settings.connectionMode');
const showWebhookUrl = platformDef.showWebhookUrl || settingsConnectionMode === 'webhook';
@@ -130,8 +130,8 @@ const Footer = memo<FooterProps>(
const settings = platformDef.schema.find((f) => f.key === 'settings');
return settings?.properties?.some((f) => f.key === 'userId') ?? false;
}, [platformDef.schema]);
- const watchedUserId = AntdForm.useWatch(['settings', 'userId'], form);
- // `useWatch` returns `undefined` until antd Form hydrates from the
+ const watchedUserId = useWatch(form, 'settings.userId');
+ // `useWatch` returns `undefined` until the form hydrates from the
// parent's `initialValues`. Fall back to the saved value only during
// that pre-hydration window so we don't flash the alert for every
// saved bot. Once the form has reported a value, trust the watched
diff --git a/src/routes/(main)/agent/channel/detail/buildRules.test.ts b/src/routes/(main)/agent/channel/detail/buildRules.test.ts
index 0c77ff03db4..302359d7c49 100644
--- a/src/routes/(main)/agent/channel/detail/buildRules.test.ts
+++ b/src/routes/(main)/agent/channel/detail/buildRules.test.ts
@@ -1,7 +1,7 @@
import { BOT_CREDENTIAL_MASK } from '@lobechat/const';
import { describe, expect, it } from 'vitest';
-import { buildRules } from './Body';
+import { buildValidate } from './Body';
/** Discord's real bot-token pattern, the one a masked value has to survive. */
const tokenField = {
@@ -11,34 +11,30 @@ const tokenField = {
type: 'password' as const,
};
-type FormRule = { validator?: (rule: unknown, value: unknown) => Promise<void> };
-
const validate = (value: unknown) => {
- const rules = buildRules(tokenField, (k: string) => k) as FormRule[];
- const validator = rules.find((rule) => rule.validator)?.validator;
- if (!validator) throw new Error('buildRules stopped emitting a validator for a patterned field');
+ const validator = buildValidate(tokenField, (k: string) => k);
+ if (!validator)
+ throw new Error('buildValidate stopped emitting a validator for a patterned field');
- return validator(undefined, value);
+ return validator(value);
};
describe('credential format rule', () => {
- it('accepts the placeholder a stored secret is read back as', async () => {
+ it('accepts the placeholder a stored secret is read back as', () => {
// Otherwise saving any unrelated edit on an existing channel would demand
// the secret be retyped, because the form submits what the server gave it.
- await expect(validate(BOT_CREDENTIAL_MASK)).resolves.toBeUndefined();
+ expect(validate(BOT_CREDENTIAL_MASK)).toBeUndefined();
});
- it('still accepts a real token', async () => {
- await expect(
- validate('MTIzNDU2Nzg5MDEyMzQ1Njc4.GhIjKl.SUPERSECRETTOKENVALUE123'),
- ).resolves.toBeUndefined();
+ it('still accepts a real token', () => {
+ expect(validate('MTIzNDU2Nzg5MDEyMzQ1Njc4.GhIjKl.SUPERSECRETTOKENVALUE123')).toBeUndefined();
});
- it('still rejects a malformed token', async () => {
- await expect(validate('nope')).rejects.toThrow();
+ it('still rejects a malformed token', () => {
+ expect(validate('nope')).toBe('botToken');
});
- it('leaves an empty value to the required rule', async () => {
- await expect(validate('')).resolves.toBeUndefined();
+ it('leaves an empty value to the required rule', () => {
+ expect(validate('')).toBeUndefined();
});
});
diff --git a/src/routes/(main)/agent/channel/detail/index.tsx b/src/routes/(main)/agent/channel/detail/index.tsx
index d1b23e76f16..2cabb162ca0 100644
--- a/src/routes/(main)/agent/channel/detail/index.tsx
+++ b/src/routes/(main)/agent/channel/detail/index.tsx
@@ -2,7 +2,7 @@
import { Flexbox } from '@lobehub/ui';
import { Alert, Button, confirmModal, toast } from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { useForm } from '@lobehub/ui/base-ui/form';
import { createStaticStyles } from 'antd-style';
import { ExternalLink } from 'lucide-react';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
@@ -51,6 +51,20 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const omitUndefinedValues = <T extends Record<string, unknown>>(record: T) =>
Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined)) as T;
+const getFormValues = (
+ schema: SerializedPlatformDefinition['schema'],
+ config?: CurrentConfig,
+): ChannelFormValues => {
+ const values = config ? getChannelFormValues(config) : { credentials: {}, settings: {} };
+ return {
+ ...values,
+ settings: mergeSettingsWithDefaults(schema, omitUndefinedValues(values.settings)) as Record<
+ string,
+ {} | undefined
+ >,
+ };
+};
+
export interface CurrentConfig {
applicationId: string;
credentials: Record<string, string>;
@@ -87,7 +101,11 @@ const PlatformDetail = memo<PlatformDetailProps>(
const { t } = useTranslation('agent');
const navigate = useWorkspaceAwareNavigate();
- const [form] = Form.useForm<ChannelFormValues>();
+ const [isDirty, setIsDirty] = useState(false);
+ const form = useForm<ChannelFormValues>({
+ initialValues: getFormValues(platformDef.schema, currentConfig),
+ onValuesChange: () => setIsDirty(true),
+ });
const { allowed: canEdit } = usePermission('edit_own_content');
const activeWorkspaceId = useActiveWorkspaceId();
const readOnly = disabled || !canEdit;
@@ -112,7 +130,6 @@ const PlatformDetail = memo<PlatformDetailProps>(
const [connectResult, setConnectResult] = useState<TestResult>();
const [testing, setTesting] = useState(false);
const [testResult, setTestResult] = useState<TestResult>();
- const [isDirty, setIsDirty] = useState(false);
const connectPollingTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Platform-specific extras (e.g. iMessage's BlueBubbles bridge) register a
@@ -229,20 +246,17 @@ const PlatformDetail = memo<PlatformDetailProps>(
// runtimeStatus — otherwise background status refreshes would wipe
// in-progress form edits and cancel the connect-status polling loop.
useEffect(() => {
- form.resetFields();
setSaveResult(undefined);
setConnectResult(undefined);
setTestResult(undefined);
stopConnectPolling();
- }, [platformDef.id, form, stopConnectPolling]);
+ }, [platformDef.id, stopConnectPolling]);
// Sync form with saved config
useEffect(() => {
- if (currentConfig) {
- form.setFieldsValue(getChannelFormValues(currentConfig));
- }
+ form.reset(getFormValues(platformDef.schema, currentConfig));
setIsDirty(false);
- }, [currentConfig, form]);
+ }, [currentConfig, form, platformDef.schema]);
useEffect(() => {
if (!currentConfig?.enabled) {
@@ -268,8 +282,9 @@ const PlatformDetail = memo<PlatformDetailProps>(
if (writeDisabled) return;
try {
- await form.validateFields();
- const values = form.getFieldsValue(true) as ChannelFormValues;
+ const { valid } = await form.validate();
+ if (!valid) return;
+ const values = form.getValues();
setSaving(true);
setSaveResult(undefined);
@@ -280,7 +295,7 @@ const PlatformDetail = memo<PlatformDetailProps>(
applicationId: formAppId,
credentials: rawCredentials = {},
settings: rawSettings = {},
- } = values as ChannelFormValues;
+ } = values;
// Strip undefined values from credentials (optional fields left empty by antd form)
const credentials = Object.fromEntries(
@@ -327,7 +342,6 @@ const PlatformDetail = memo<PlatformDetailProps>(
// Auto-connect bot after save
await connectCurrentBot(applicationId);
} catch (e: any) {
- if (e?.errorFields) return;
console.error(e);
setSaveResult({ errorDetail: e?.message || String(e), type: 'error' });
setSaving(false);
@@ -356,7 +370,7 @@ const PlatformDetail = memo<PlatformDetailProps>(
const { applicationId, credentials } = params;
const settings = mergeSettingsWithDefaults(
platformDef.schema,
- omitUndefinedValues(form.getFieldValue('settings') || {}),
+ omitUndefinedValues(form.getValue('settings') || {}),
);
if (currentConfig) {
@@ -411,14 +425,14 @@ const PlatformDetail = memo<PlatformDetailProps>(
try {
await deleteBotProvider(currentConfig.id, agentId);
toast.success(t('channel.removed'));
- form.resetFields();
+ form.reset(getFormValues(platformDef.schema));
} catch {
toast.error(t('channel.removeFailed'));
}
},
title: t('channel.removeChannel'),
});
- }, [readOnly, currentConfig, agentId, deleteBotProvider, t, form]);
+ }, [readOnly, currentConfig, agentId, deleteBotProvider, t, form, platformDef.schema]);
const handleTestConnection = useCallback(async () => {
if (writeDisabled) return;
@@ -452,12 +466,11 @@ const PlatformDetail = memo<PlatformDetailProps>(
}, [writeDisabled, currentConfig, platformDef.id, testConnection, t]);
const handleDiscard = useCallback(() => {
- form.resetFields();
- if (currentConfig) form.setFieldsValue(getChannelFormValues(currentConfig));
+ form.reset(getFormValues(platformDef.schema, currentConfig));
setIsDirty(false);
setSaveResult(undefined);
setTestResult(undefined);
- }, [currentConfig, form]);
+ }, [currentConfig, form, platformDef.schema]);
const handleFormValuesChange = useCallback(() => setIsDirty(true), []);
diff --git a/src/routes/(main)/agent/channel/detail/permission.test.tsx b/src/routes/(main)/agent/channel/detail/permission.test.tsx
index 565854316eb..d4220c57f8a 100644
--- a/src/routes/(main)/agent/channel/detail/permission.test.tsx
+++ b/src/routes/(main)/agent/channel/detail/permission.test.tsx
@@ -1,8 +1,8 @@
/**
* @vitest-environment happy-dom
*/
+import { useForm } from '@lobehub/ui/base-ui/form';
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
-import { Form } from 'antd';
import type { ReactNode } from 'react';
import { describe, expect, it, vi } from 'vitest';
@@ -11,7 +11,7 @@ import type { SerializedPlatformDefinition } from '@/server/services/bot/platfor
import Header from '../Header';
import Body from './Body';
import Footer from './Footer';
-import PlatformDetail from './index';
+import PlatformDetail, { type ChannelFormValues } from './index';
const mocks = vi.hoisted(() => ({
activeWorkspaceId: null as string | null,
@@ -232,7 +232,7 @@ const currentConfig = {
};
const BodyHarness = ({ disabled }: { disabled?: boolean }) => {
- const [form] = Form.useForm();
+ const form = useForm<ChannelFormValues>();
return (
<Body
@@ -246,7 +246,7 @@ const BodyHarness = ({ disabled }: { disabled?: boolean }) => {
};
const FooterHarness = ({ disabled }: { disabled?: boolean }) => {
- const [form] = Form.useForm();
+ const form = useForm<ChannelFormValues>();
return (
<Footer
@@ -285,23 +285,21 @@ describe('Agent channel permission gates', () => {
expect(screen.getByRole('button', { name: 'channel.settingsResetDefault' })).toBeDisabled();
});
- it('toggles advanced settings from the full header row', () => {
+ it('toggles advanced settings from the full header row', async () => {
render(<BodyHarness />);
- const header = document.querySelector('.ant-collapse-header') as HTMLElement;
- expect(header).not.toBeNull();
expect(screen.getByRole('textbox', { name: 'channel.charLimit' })).toBeInTheDocument();
-
- const panel = () =>
- screen
- .getByRole('textbox', { hidden: true, name: 'channel.charLimit' })
- .closest('.ant-collapse-panel');
+ const header = screen.getByRole('button', { name: 'channel.settings' });
fireEvent.click(header);
- expect(panel()).toHaveClass('ant-collapse-panel-inactive');
+ await waitFor(() =>
+ expect(screen.queryByRole('textbox', { name: 'channel.charLimit' })).not.toBeInTheDocument(),
+ );
fireEvent.click(header);
- expect(panel()).not.toHaveClass('ant-collapse-panel-inactive');
+ await waitFor(() =>
+ expect(screen.getByRole('textbox', { name: 'channel.charLimit' })).toBeInTheDocument(),
+ );
});
it('disables mutating channel actions when editing is denied', () => {
diff --git a/src/routes/(main)/agent/channel/platform/imessage/CredentialExtras.tsx b/src/routes/(main)/agent/channel/platform/imessage/CredentialExtras.tsx
index 6b952c827ab..75e751d707c 100644
--- a/src/routes/(main)/agent/channel/platform/imessage/CredentialExtras.tsx
+++ b/src/routes/(main)/agent/channel/platform/imessage/CredentialExtras.tsx
@@ -2,9 +2,9 @@
import { isDesktop } from '@lobechat/const';
import type { ImessageBridgeConfig, ImessageBridgeStatus } from '@lobechat/electron-client-ipc';
-import { Flexbox, FormItem, Icon } from '@lobehub/ui';
+import { Flexbox, Icon } from '@lobehub/ui';
import { Button, Switch, Tag, Text, toast } from '@lobehub/ui/base-ui';
-import { Form as AntdForm } from 'antd';
+import { Form, useFormInstance, useWatch } from '@lobehub/ui/base-ui/form';
import { createStaticStyles } from 'antd-style';
import { KeyRound, Link2, Wrench } from 'lucide-react';
import { memo, use, useCallback, useEffect, useState } from 'react';
@@ -69,8 +69,8 @@ const CredentialExtras = memo(() => {
const { t: _t } = useTranslation('agent');
const t = _t as (key: string) => string;
- const form = AntdForm.useFormInstance();
- const applicationId = AntdForm.useWatch('applicationId', form) as string | undefined;
+ const form = useFormInstance();
+ const applicationId = useWatch(form, 'applicationId') as string | undefined;
const appId = applicationId?.trim();
const postSave = use(ChannelPostSaveContext);
@@ -110,20 +110,18 @@ const CredentialExtras = memo(() => {
const fillDesktopDeviceId = useCallback(async () => {
const deviceInfo = await gatewayConnectionService.getDeviceInfo();
- form.setFieldValue(['credentials', 'desktopDeviceId'], deviceInfo.deviceId);
- void form.validateFields([['credentials', 'desktopDeviceId']]).catch(() => undefined);
+ form.setValue('credentials.desktopDeviceId', deviceInfo.deviceId);
+ void form.validate(['credentials.desktopDeviceId']);
}, [form]);
// The webhook secret is shared between the cloud provider and the local
// bridge but is not a user-facing field — generate one on demand and reuse
// whatever is already stored on the form (saved config or a prior generation).
const ensureWebhookSecret = useCallback((): string => {
- const existing = (
- form.getFieldValue(['credentials', 'webhookSecret']) as string | undefined
- )?.trim();
+ const existing = (form.getValue('credentials.webhookSecret') as string | undefined)?.trim();
if (existing) return existing;
const generated = globalThis.crypto.randomUUID();
- form.setFieldValue(['credentials', 'webhookSecret'], generated);
+ form.setValue('credentials.webhookSecret', generated);
return generated;
}, [form]);
@@ -255,7 +253,7 @@ const CredentialExtras = memo(() => {
</Flexbox>
{/* Middle: the credential fields the operator fills in. */}
- <FormItem
+ <Form.Field
avatar={<Icon className={styles.fieldIcon} icon={Link2} size={20} />}
minWidth={'max(50%, 360px)'}
variant="outlined"
@@ -278,8 +276,8 @@ const CredentialExtras = memo(() => {
setTestStatus('idle');
}}
/>
- </FormItem>
- <FormItem
+ </Form.Field>
+ <Form.Field
divider
avatar={<Icon className={styles.fieldIcon} icon={KeyRound} size={20} />}
minWidth={'max(50%, 360px)'}
@@ -300,7 +298,7 @@ const CredentialExtras = memo(() => {
setTestStatus('idle');
}}
/>
- </FormItem>
+ </Form.Field>
{/* Bottom: row 1 — service status + the Enable toggle (write-through);
row 2 — the connection test. */}
diff --git a/src/routes/(main)/agent/channel/platform/line/CredentialExtras.tsx b/src/routes/(main)/agent/channel/platform/line/CredentialExtras.tsx
index ee9cf758117..42d07952326 100644
--- a/src/routes/(main)/agent/channel/platform/line/CredentialExtras.tsx
+++ b/src/routes/(main)/agent/channel/platform/line/CredentialExtras.tsx
@@ -2,7 +2,7 @@
import { isMaskedBotCredential } from '@lobechat/const';
import { Button, toast } from '@lobehub/ui/base-ui';
-import { Form as AntdForm } from 'antd';
+import { useFormInstance, useWatch } from '@lobehub/ui/base-ui/form';
import { Download } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -15,9 +15,8 @@ const CredentialExtras = memo<PlatformCredentialExtrasProps>(({ disabled }) => {
const { t: _t } = useTranslation('agent');
const t = _t as (key: string) => string;
- const form = AntdForm.useFormInstance();
- const channelAccessToken = AntdForm.useWatch(['credentials', 'channelAccessToken'], form) as
- string | undefined;
+ const form = useFormInstance();
+ const channelAccessToken = useWatch(form, 'credentials.channelAccessToken') as string | undefined;
const [loading, setLoading] = useState(false);
const lineFetchBotInfo = useAgentStore((s) => s.lineFetchBotInfo);
@@ -35,10 +34,10 @@ const CredentialExtras = memo<PlatformCredentialExtrasProps>(({ disabled }) => {
setLoading(true);
try {
const info = await lineFetchBotInfo(token);
- form.setFieldValue('applicationId', info.userId);
+ form.setValue('applicationId', info.userId);
// Trigger validation/dirty state on the field so the form save button
// recognises the auto-filled value as a real change.
- form.validateFields(['applicationId']).catch(() => undefined);
+ void form.validate(['applicationId']);
toast.success(
info.displayName
? `${t('channel.line.fetchBotInfoSuccess')} (${info.displayName})`
diff --git a/src/routes/(main)/agent/channel/platform/wechat/ConnectedInfo.tsx b/src/routes/(main)/agent/channel/platform/wechat/ConnectedInfo.tsx
index ee15d18d140..309613d1493 100644
--- a/src/routes/(main)/agent/channel/platform/wechat/ConnectedInfo.tsx
+++ b/src/routes/(main)/agent/channel/platform/wechat/ConnectedInfo.tsx
@@ -1,6 +1,7 @@
'use client';
-import { Flexbox, FormItem, Icon } from '@lobehub/ui';
+import { Flexbox, Icon } from '@lobehub/ui';
+import { Form } from '@lobehub/ui/base-ui/form';
import { createStaticStyles } from 'antd-style';
import type { LucideIcon } from 'lucide-react';
import { Fingerprint, KeyRound, UserRound } from 'lucide-react';
@@ -33,7 +34,7 @@ const ReadOnlyField = memo<{
const InputComponent = password ? FormPassword : FormInput;
return (
- <FormItem
+ <Form.Field
avatar={<Icon className={styles.fieldIcon} icon={icon} size={20} />}
divider={divider}
label={label}
@@ -41,7 +42,7 @@ const ReadOnlyField = memo<{
variant="outlined"
>
<InputComponent readOnly value={value || ''} />
- </FormItem>
+ </Form.Field>
);
});
diff --git a/src/routes/(main)/community/(detail)/user/features/SubmitRepoModal.tsx b/src/routes/(main)/community/(detail)/user/features/SubmitRepoModal.tsx
index 9379d080bf0..f0ed06e2dd8 100644
--- a/src/routes/(main)/community/(detail)/user/features/SubmitRepoModal.tsx
+++ b/src/routes/(main)/community/(detail)/user/features/SubmitRepoModal.tsx
@@ -2,7 +2,7 @@
import { Flexbox } from '@lobehub/ui';
import { Input, Text, toast } from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -22,14 +22,15 @@ export const SubmitRepoModal = memo<SubmitRepoModalProps>(
({ open, onClose, onSuccess, beforeSubmit }) => {
const { t } = useTranslation('discover');
- const [form] = Form.useForm();
+ const form = useForm<{ gitUrl?: string }>();
const [isSubmitting, setIsSubmitting] = useState(false);
const handleSubmit = useCallback(async () => {
try {
- const values = await form.validateFields();
- const gitUrl = values.gitUrl?.trim();
+ const { valid } = await form.validate();
+ if (!valid) return;
+ const gitUrl = form.getValue('gitUrl')?.trim();
if (!gitUrl) {
return;
@@ -48,7 +49,7 @@ export const SubmitRepoModal = memo<SubmitRepoModalProps>(
toast.success(t('user.submitRepoSuccess'));
onSuccess?.();
onClose();
- form.resetFields();
+ form.reset();
} catch (error) {
console.error('[SubmitRepoModal] Failed to submit:', error);
toast.error(error instanceof Error ? error.message : t('user.submitRepoError'));
@@ -58,7 +59,7 @@ export const SubmitRepoModal = memo<SubmitRepoModalProps>(
}, [beforeSubmit, form, t, onSuccess, onClose]);
const handleCancel = useCallback(() => {
- form.resetFields();
+ form.reset();
onClose();
}, [form, onClose]);
@@ -82,19 +83,16 @@ export const SubmitRepoModal = memo<SubmitRepoModalProps>(
</Text>
<Form form={form} layout="vertical">
- <Form.Item
+ <Form.Field
label={t('user.githubUrl')}
name="gitUrl"
- rules={[
- { required: true, message: t('user.githubUrlRequired') },
- {
- pattern: GITHUB_URL_REGEX,
- message: t('user.githubUrlInvalid'),
- },
- ]}
+ required={t('user.githubUrlRequired')}
+ validate={(value: string) =>
+ value && !GITHUB_URL_REGEX.test(value) ? t('user.githubUrlInvalid') : undefined
+ }
>
<Input placeholder="https://github.com/username/repo" />
- </Form.Item>
+ </Form.Field>
</Form>
<Flexbox style={{ marginTop: 8 }}>
diff --git a/src/routes/(main)/community/(detail)/workspace/features/WorkspaceProfileModal/Content.tsx b/src/routes/(main)/community/(detail)/workspace/features/WorkspaceProfileModal/Content.tsx
index a0f08481a09..555548003b5 100644
--- a/src/routes/(main)/community/(detail)/workspace/features/WorkspaceProfileModal/Content.tsx
+++ b/src/routes/(main)/community/(detail)/workspace/features/WorkspaceProfileModal/Content.tsx
@@ -13,7 +13,7 @@ import {
Upload,
useModalContext,
} from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form, useForm, useWatch } from '@lobehub/ui/base-ui/form';
import { cssVar } from 'antd-style';
import { CircleHelp, Globe, ImagePlus, Trash2 } from 'lucide-react';
import { memo, useCallback, useEffect, useMemo, useState } from 'react';
@@ -64,13 +64,22 @@ const NAMESPACE_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
const isNamespaceFormatValid = (value: string) =>
value.length >= 3 && value.length <= 32 && NAMESPACE_PATTERN.test(value);
+const URL_PATTERN = /^(?:(?:[a-z]+:)?\/\/|www\.)\S+$/i;
+
type NamespaceAvailability = 'available' | 'checking' | 'idle' | 'taken';
export const Content = memo<ContentProps>(({ user, onSuccess }) => {
const { t } = useTranslation('discover');
const { close } = useModalContext();
- const [form] = Form.useForm<FormValues>();
+ const form = useForm<FormValues>({
+ initialValues: {
+ description: user.description ?? undefined,
+ displayName: user.displayName ?? user.userName ?? user.namespace,
+ namespace: user.namespace || normalizeNamespace(user.displayName ?? user.userName ?? ''),
+ websiteUrl: user.socialLinks?.website,
+ },
+ });
const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);
const [avatarUrl, setAvatarUrl] = useState<string | null>(user.avatarUrl ?? null);
const [avatarUploading, setAvatarUploading] = useState(false);
@@ -83,8 +92,8 @@ export const Content = memo<ContentProps>(({ user, onSuccess }) => {
// set). Mirrors the workspace create wizard's slug check: debounce, only probe
// a well-formed handle, and treat it purely as a UX hint — the setup mutation
// still rejects a taken handle on submit.
- const namespaceValue = Form.useWatch('namespace', form);
- const displayNameValue = Form.useWatch('displayName', form);
+ const namespaceValue = useWatch(form, 'namespace');
+ const displayNameValue = useWatch(form, 'displayName');
const trimmedNamespace = (namespaceValue ?? '').trim();
const [namespaceAvailability, setNamespaceAvailability] = useState<NamespaceAvailability>('idle');
@@ -183,7 +192,9 @@ export const Content = memo<ContentProps>(({ user, onSuccess }) => {
const handleSave = useCallback(async () => {
if (loading) return;
- const values = await form.validateFields();
+ const { valid } = await form.validate();
+ if (!valid) return;
+ const values = form.getValues();
if (isSetup && namespaceAvailability === 'taken') {
toast.error(t('user.workspaceProfile.fields.namespace.taken'));
@@ -234,18 +245,20 @@ export const Content = memo<ContentProps>(({ user, onSuccess }) => {
const optionalContent = useMemo(
() => (
<>
- <Form.Item
+ <Form.Field
label={t('user.workspaceProfile.fields.websiteUrl')}
name="websiteUrl"
- rules={[{ message: t('user.workspaceProfile.errors.url'), type: 'url' }]}
+ validate={(value?: string) =>
+ value && !URL_PATTERN.test(value) ? t('user.workspaceProfile.errors.url') : undefined
+ }
>
<Input
placeholder={t('user.workspaceProfile.fields.websiteUrl.placeholder')}
prefix={<Icon color={cssVar.colorTextSecondary} icon={Globe} />}
/>
- </Form.Item>
+ </Form.Field>
- <Form.Item
+ <Form.Field
label={
<Flexbox horizontal align="center" gap={4}>
{t('user.workspaceProfile.fields.bannerUrl')}
@@ -331,7 +344,7 @@ export const Content = memo<ContentProps>(({ user, onSuccess }) => {
</Flexbox>
)}
</Flexbox>
- </Form.Item>
+ </Form.Field>
</>
),
[bannerUploading, bannerUrl, handleBannerUpload, t],
@@ -339,61 +352,51 @@ export const Content = memo<ContentProps>(({ user, onSuccess }) => {
return (
<Flexbox gap={20} padding={24}>
- <Form
- form={form}
- layout="vertical"
- initialValues={{
- description: user.description ?? undefined,
- displayName: user.displayName ?? user.userName ?? user.namespace,
- namespace: user.namespace || normalizeNamespace(user.displayName ?? user.userName ?? ''),
- websiteUrl: user.socialLinks?.website,
- }}
- >
+ <Form form={form} layout="vertical">
<Flexbox horizontal gap={24}>
<Flexbox flex={1}>
- <Form.Item
+ <Form.Field
label={t('user.workspaceProfile.fields.displayName')}
name="displayName"
- rules={[
- { message: t('user.workspaceProfile.errors.displayName'), required: true },
- { max: 50, message: t('user.workspaceProfile.fields.displayName.maxLength') },
- ]}
+ required={t('user.workspaceProfile.errors.displayName')}
+ validate={(value?: string) =>
+ value && value.length > 50
+ ? t('user.workspaceProfile.fields.displayName.maxLength')
+ : undefined
+ }
>
<Input
maxLength={50}
placeholder={t('user.workspaceProfile.fields.displayName.placeholder')}
suffix={`${displayNameValue?.length ?? 0} / 50`}
/>
- </Form.Item>
+ </Form.Field>
</Flexbox>
- <Form.Item>
- <AvatarUpload
- allowDelete={!!avatarUrl}
- loading={avatarUploading}
- shape="square"
- size={80}
- value={avatarUrl || undefined}
- onDelete={() => setAvatarUrl(null)}
- onUpload={handleAvatarUpload}
- />
- </Form.Item>
+ <AvatarUpload
+ allowDelete={!!avatarUrl}
+ loading={avatarUploading}
+ shape="square"
+ size={80}
+ value={avatarUrl || undefined}
+ onDelete={() => setAvatarUrl(null)}
+ onUpload={handleAvatarUpload}
+ />
</Flexbox>
{isSetup && (
- <Form.Item
+ <Form.Field
extra={namespaceStatusNode}
label={t('user.workspaceProfile.fields.namespace')}
name="namespace"
- rules={[
- { message: t('user.workspaceProfile.errors.namespace.required'), required: true },
- { max: 32, message: t('user.workspaceProfile.errors.namespace.length') },
- { min: 3, message: t('user.workspaceProfile.errors.namespace.length') },
- {
- message: t('user.workspaceProfile.errors.namespace.pattern'),
- pattern: /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,
- },
- ]}
+ required={t('user.workspaceProfile.errors.namespace.required')}
+ validate={(value?: string) => {
+ if (!value) return;
+ if (value.length < 3 || value.length > 32)
+ return t('user.workspaceProfile.errors.namespace.length');
+ if (!NAMESPACE_PATTERN.test(value))
+ return t('user.workspaceProfile.errors.namespace.pattern');
+ }}
>
<Input
maxLength={32}
@@ -401,13 +404,17 @@ export const Content = memo<ContentProps>(({ user, onSuccess }) => {
prefix={ORGANIZATION_URL_PREFIX}
suffix={`${namespaceValue?.length ?? 0} / 32`}
/>
- </Form.Item>
+ </Form.Field>
)}
- <Form.Item
+ <Form.Field
label={t('user.workspaceProfile.fields.description')}
name="description"
- rules={[{ max: 200, message: t('user.workspaceProfile.fields.description.maxLength') }]}
+ validate={(value?: string) =>
+ value && value.length > 200
+ ? t('user.workspaceProfile.fields.description.maxLength')
+ : undefined
+ }
>
<TextArea
showCount
@@ -415,7 +422,7 @@ export const Content = memo<ContentProps>(({ user, onSuccess }) => {
placeholder={t('user.workspaceProfile.fields.description.placeholder')}
rows={3}
/>
- </Form.Item>
+ </Form.Field>
<Accordion
keepMounted
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx
index 9ef29dc26ee..3a36f933cfd 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunCreateModal/Content.tsx
@@ -13,7 +13,7 @@ import {
toast,
useModalContext,
} from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form, useForm, useWatch } from '@lobehub/ui/base-ui/form';
import { createStaticStyles, cssVar } from 'antd-style';
import { SquareArrowOutUpRight } from 'lucide-react';
import { type FC, useCallback, useEffect, useMemo, useState } from 'react';
@@ -62,6 +62,15 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
+interface RunCreateFormValues {
+ datasetId?: string;
+ k?: number | null;
+ maxSteps?: number | null;
+ name?: string;
+ targetAgentId?: string;
+ timeoutMinutes?: number | null;
+}
+
interface AgentOption {
avatar?: string | null;
backgroundColor?: string | null;
@@ -98,10 +107,16 @@ const RunCreateContent: FC<RunCreateContentProps> = ({
const createRun = useEvalStore((s) => s.createRun);
const startRun = useEvalStore((s) => s.startRun);
const datasetList = useEvalStore((s) => s.datasetList);
- const [form] = Form.useForm();
- const kValue = Form.useWatch('k', form) ?? 1;
-
const isDatasetMode = !!datasetId && !!datasetName;
+ const form = useForm<RunCreateFormValues>({
+ initialValues: {
+ datasetId: datasetId && !isDatasetMode ? datasetId : undefined,
+ k: 1,
+ maxSteps: DEFAULT_MAX_STEPS,
+ timeoutMinutes: DEFAULT_TIMEOUT_MINUTES,
+ },
+ });
+ const kValue = useWatch(form, 'k') ?? 1;
const [agents, setAgents] = useState<AgentOption[]>([]);
const [loadingAgents, setLoadingAgents] = useState(false);
@@ -114,12 +129,6 @@ const RunCreateContent: FC<RunCreateContentProps> = ({
.finally(() => setLoadingAgents(false));
}, []);
- useEffect(() => {
- if (datasetId && !isDatasetMode) {
- form.setFieldsValue({ datasetId });
- }
- }, [datasetId, isDatasetMode, form]);
-
const inboxAgent: AgentOption = useMemo(
() => ({
avatar: DEFAULT_INBOX_AVATAR,
@@ -166,12 +175,9 @@ const RunCreateContent: FC<RunCreateContentProps> = ({
const submit = useCallback(
async (shouldStart: boolean) => {
- let values;
- try {
- values = await form.validateFields();
- } catch {
- return;
- }
+ const { valid } = await form.validate();
+ if (!valid) return;
+ const values = form.getValues();
onLoadingChange?.(true);
try {
const maxSteps = values.maxSteps ?? DEFAULT_MAX_STEPS;
@@ -183,7 +189,7 @@ const RunCreateContent: FC<RunCreateContentProps> = ({
maxSteps,
timeout: timeoutMinutes * 60_000,
},
- datasetId: isDatasetMode ? datasetId : values.datasetId,
+ datasetId: (isDatasetMode ? datasetId : values.datasetId)!,
experimentId,
name: values.name,
targetAgentId: values.targetAgentId,
@@ -231,10 +237,10 @@ const RunCreateContent: FC<RunCreateContentProps> = ({
return (
<Form form={form} layout="vertical">
- <Form.Item
+ <Form.Field
label={t('run.create.name')}
name="name"
- rules={[{ message: t('run.create.name.required'), required: true }]}
+ required={t('run.create.name.required')}
extra={
<Text
className={styles.timestampLink}
@@ -242,7 +248,7 @@ const RunCreateContent: FC<RunCreateContentProps> = ({
onClick={() => {
const now = new Date();
const ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
- form.setFieldsValue({ name: ts });
+ form.setValue('name', ts);
}}
>
{t('run.create.name.useTimestamp')}
@@ -250,12 +256,12 @@ const RunCreateContent: FC<RunCreateContentProps> = ({
}
>
<Input placeholder={t('run.create.name.placeholder')} variant="filled" />
- </Form.Item>
+ </Form.Field>
- <Form.Item
+ <Form.Field
label={t('run.create.agent')}
name="targetAgentId"
- rules={[{ message: t('run.create.agent.required'), required: true }]}
+ required={t('run.create.agent.required')}
>
<Select
allowClear
@@ -283,13 +289,13 @@ const RunCreateContent: FC<RunCreateContentProps> = ({
</span>
)}
/>
- </Form.Item>
+ </Form.Field>
{!isDatasetMode && (
- <Form.Item
+ <Form.Field
label={t('run.create.dataset')}
name="datasetId"
- rules={[{ message: t('run.create.dataset.required'), required: true }]}
+ required={t('run.create.dataset.required')}
>
<Select
placeholder={t('run.create.dataset.placeholder')}
@@ -308,7 +314,7 @@ const RunCreateContent: FC<RunCreateContentProps> = ({
value: ds.id,
}))}
/>
- </Form.Item>
+ </Form.Field>
)}
<Accordion
@@ -320,11 +326,10 @@ const RunCreateContent: FC<RunCreateContentProps> = ({
{
children: (
<Flexbox gap={16} style={{ paddingTop: 8 }}>
- <Form.Item
- initialValue={1}
+ <Form.Field
label={t('run.config.k')}
name="k"
- style={{ marginBottom: 0 }}
+ style={{ paddingBlock: 0 }}
extra={
<span className={styles.hint}>{t('run.config.k.hint', { k: kValue })}</span>
}
@@ -336,13 +341,12 @@ const RunCreateContent: FC<RunCreateContentProps> = ({
style={{ width: '100%' }}
variant="filled"
/>
- </Form.Item>
- <Form.Item
+ </Form.Field>
+ <Form.Field
extra={<span className={styles.hint}>{t('run.config.maxSteps.hint')}</span>}
- initialValue={DEFAULT_MAX_STEPS}
label={t('run.config.maxSteps')}
name="maxSteps"
- style={{ marginBottom: 0 }}
+ style={{ paddingBlock: 0 }}
>
<InputNumber
max={1000}
@@ -351,12 +355,11 @@ const RunCreateContent: FC<RunCreateContentProps> = ({
style={{ width: '100%' }}
variant="filled"
/>
- </Form.Item>
- <Form.Item
- initialValue={DEFAULT_TIMEOUT_MINUTES}
+ </Form.Field>
+ <Form.Field
label={t('run.config.timeout')}
name="timeoutMinutes"
- style={{ marginBottom: 0 }}
+ style={{ paddingBlock: 0 }}
>
<InputNumber
max={MAX_TIMEOUT_MINUTES}
@@ -365,7 +368,7 @@ const RunCreateContent: FC<RunCreateContentProps> = ({
suffix={t('run.config.timeout.unit')}
variant="filled"
/>
- </Form.Item>
+ </Form.Field>
</Flexbox>
),
key: 'advanced',
diff --git a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Content.tsx b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Content.tsx
index dd0222a205d..b0e3607a8f8 100644
--- a/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Content.tsx
+++ b/src/routes/(main)/eval/bench/[benchmarkId]/features/RunEditModal/Content.tsx
@@ -13,7 +13,7 @@ import {
toast,
useModalContext,
} from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form, useForm, useWatch } from '@lobehub/ui/base-ui/form';
import { createStaticStyles, cssVar } from 'antd-style';
import { SquareArrowOutUpRight } from 'lucide-react';
import { type FC, useCallback, useEffect, useMemo, useState } from 'react';
@@ -73,9 +73,6 @@ const RunEditContent: FC<RunEditContentProps> = ({ formId, onLoadingChange, run
const { benchmarkId } = useParams<{ benchmarkId: string }>();
const updateRun = useEvalStore((s) => s.updateRun);
const datasetList = useEvalStore((s) => s.datasetList);
- const [form] = Form.useForm();
- const kValue = Form.useWatch('k', form) ?? 1;
-
const [agents, setAgents] = useState<AgentOption[]>([]);
const [loadingAgents, setLoadingAgents] = useState(false);
@@ -96,18 +93,6 @@ const RunEditContent: FC<RunEditContentProps> = ({ formId, onLoadingChange, run
.finally(() => setLoadingAgents(false));
}, [canChangeConfig]);
- useEffect(() => {
- if (run) {
- form.setFieldsValue({
- k: run.config?.k,
- maxSteps: run.config?.maxSteps,
- name: run.name,
- targetAgentId: run.targetAgentId,
- timeoutMinutes: run.config?.timeout ? run.config.timeout / 60_000 : undefined,
- });
- }
- }, [run, form]);
-
const inboxAgent: AgentOption = useMemo(
() => ({
avatar: DEFAULT_INBOX_AVATAR,
@@ -177,9 +162,21 @@ const RunEditContent: FC<RunEditContentProps> = ({ formId, onLoadingChange, run
}
};
+ const form = useForm({
+ initialValues: {
+ k: run.config?.k,
+ maxSteps: run.config?.maxSteps,
+ name: run.name,
+ targetAgentId: run.targetAgentId,
+ timeoutMinutes: run.config?.timeout ? run.config.timeout / 60_000 : undefined,
+ },
+ onSubmit: handleFinish,
+ });
+ const kValue = useWatch(form, 'k') ?? 1;
+
return (
- <Form form={form} layout="vertical" name={formId} onFinish={handleFinish}>
- <Form.Item label={t('run.create.dataset')}>
+ <Form form={form} id={formId} layout="vertical">
+ <Form.Field label={t('run.create.dataset')}>
<Flexbox horizontal align={'center'} gap={8}>
<span>{currentDataset?.name || run.datasetId}</span>
{currentDataset?.testCaseCount !== undefined && (
@@ -196,17 +193,17 @@ const RunEditContent: FC<RunEditContentProps> = ({ formId, onLoadingChange, run
/>
)}
</Flexbox>
- </Form.Item>
+ </Form.Field>
- <Form.Item label={t('run.create.name')} name="name">
+ <Form.Field label={t('run.create.name')} name="name">
<Input placeholder={t('run.create.name.placeholder')} variant="filled" />
- </Form.Item>
+ </Form.Field>
{canChangeConfig && (
- <Form.Item
+ <Form.Field
label={t('run.create.agent')}
name="targetAgentId"
- rules={[{ message: t('run.create.agent.required'), required: true }]}
+ required={t('run.create.agent.required')}
>
<Select
allowClear
@@ -234,7 +231,7 @@ const RunEditContent: FC<RunEditContentProps> = ({ formId, onLoadingChange, run
</span>
)}
/>
- </Form.Item>
+ </Form.Field>
)}
<Accordion
@@ -246,10 +243,10 @@ const RunEditContent: FC<RunEditContentProps> = ({ formId, onLoadingChange, run
{
children: (
<Flexbox gap={16} style={{ paddingTop: 8 }}>
- <Form.Item
+ <Form.Field
label={t('run.config.k')}
name="k"
- style={{ marginBottom: 0 }}
+ style={{ paddingBlock: 0 }}
extra={
<span className={styles.hint}>{t('run.config.k.hint', { k: kValue })}</span>
}
@@ -262,12 +259,12 @@ const RunEditContent: FC<RunEditContentProps> = ({ formId, onLoadingChange, run
style={{ width: '100%' }}
variant="filled"
/>
- </Form.Item>
- <Form.Item
+ </Form.Field>
+ <Form.Field
extra={<span className={styles.hint}>{t('run.config.maxSteps.hint')}</span>}
label={t('run.config.maxSteps')}
name="maxSteps"
- style={{ marginBottom: 0 }}
+ style={{ paddingBlock: 0 }}
>
<InputNumber
disabled={isFinished}
@@ -277,11 +274,11 @@ const RunEditContent: FC<RunEditContentProps> = ({ formId, onLoadingChange, run
style={{ width: '100%' }}
variant="filled"
/>
- </Form.Item>
- <Form.Item
+ </Form.Field>
+ <Form.Field
label={t('run.config.timeout')}
name="timeoutMinutes"
- style={{ marginBottom: 0 }}
+ style={{ paddingBlock: 0 }}
>
<InputNumber
disabled={isFinished}
@@ -291,7 +288,7 @@ const RunEditContent: FC<RunEditContentProps> = ({ formId, onLoadingChange, run
suffix={t('run.config.timeout.unit')}
variant="filled"
/>
- </Form.Item>
+ </Form.Field>
</Flexbox>
),
key: 'advanced',
diff --git a/src/routes/(main)/eval/features/BenchmarkEditModal/Content.tsx b/src/routes/(main)/eval/features/BenchmarkEditModal/Content.tsx
index d97d65cc051..afc2123bd6e 100644
--- a/src/routes/(main)/eval/features/BenchmarkEditModal/Content.tsx
+++ b/src/routes/(main)/eval/features/BenchmarkEditModal/Content.tsx
@@ -1,7 +1,7 @@
'use client';
import { Input, Select, TextArea, toast, useModalContext } from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form, useForm, useWatch } from '@lobehub/ui/base-ui/form';
import { cssVar } from 'antd-style';
import { type FC, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -38,29 +38,9 @@ const BenchmarkEditContent: FC<BenchmarkEditContentProps> = ({
const { t } = useTranslation('eval');
const { close } = useModalContext();
- const [form] = Form.useForm();
const [identifierTouched, setIdentifierTouched] = useState(false);
const updateBenchmark = useEvalStore((s) => s.updateBenchmark);
- const nameValue = Form.useWatch('name', form);
-
- useEffect(() => {
- if (benchmark) {
- form.setFieldsValue({
- description: benchmark.description || '',
- identifier: benchmark.identifier,
- name: benchmark.name,
- tags: benchmark.tags || [],
- });
- }
- }, [benchmark, form]);
-
- useEffect(() => {
- if (!identifierTouched && nameValue) {
- form.setFieldValue('identifier', toIdentifier(nameValue));
- }
- }, [nameValue, identifierTouched, form]);
-
const handleFinish = async (values: any) => {
onLoadingChange?.(true);
try {
@@ -81,33 +61,50 @@ const BenchmarkEditContent: FC<BenchmarkEditContentProps> = ({
}
};
+ const form = useForm({
+ initialValues: {
+ description: benchmark.description || '',
+ identifier: benchmark.identifier,
+ name: benchmark.name,
+ tags: benchmark.tags || [],
+ },
+ onSubmit: handleFinish,
+ });
+ const nameValue = useWatch(form, 'name');
+
+ useEffect(() => {
+ if (!identifierTouched && nameValue) {
+ form.setValue('identifier', toIdentifier(nameValue));
+ }
+ }, [nameValue, identifierTouched, form]);
+
return (
- <Form form={form} layout="vertical" name={formId} onFinish={handleFinish}>
- <Form.Item
+ <Form form={form} id={formId} layout="vertical">
+ <Form.Field
label={t('benchmark.create.name.label')}
name="name"
- rules={[{ message: t('benchmark.create.nameRequired'), required: true }]}
+ required={t('benchmark.create.nameRequired')}
>
<Input autoFocus placeholder={t('benchmark.create.name.placeholder')} />
- </Form.Item>
+ </Form.Field>
- <Form.Item
+ <Form.Field
label={t('benchmark.create.identifier.label')}
name="identifier"
- rules={[{ message: t('benchmark.create.identifierRequired'), required: true }]}
+ required={t('benchmark.create.identifierRequired')}
>
<Input
placeholder={t('benchmark.create.identifier.placeholder')}
style={{ fontFamily: cssVar.fontFamilyCode }}
onChange={() => setIdentifierTouched(true)}
/>
- </Form.Item>
+ </Form.Field>
- <Form.Item label={t('benchmark.create.description.label')} name="description">
+ <Form.Field label={t('benchmark.create.description.label')} name="description">
<TextArea placeholder={t('benchmark.create.description.placeholder')} rows={3} />
- </Form.Item>
+ </Form.Field>
- <Form.Item label={t('benchmark.create.tags.label')} name="tags" style={{ marginBottom: 0 }}>
+ <Form.Field label={t('benchmark.create.tags.label')} name="tags">
<Select
mode="tags"
open={false}
@@ -115,7 +112,7 @@ const BenchmarkEditContent: FC<BenchmarkEditContentProps> = ({
style={{ width: '100%' }}
tokenSeparators={[',', ',', ' ']}
/>
- </Form.Item>
+ </Form.Field>
</Form>
);
};
diff --git a/src/routes/(main)/eval/features/CreateBenchmarkModal/Content.tsx b/src/routes/(main)/eval/features/CreateBenchmarkModal/Content.tsx
index 1fee8eea5b9..cc00171a0b5 100644
--- a/src/routes/(main)/eval/features/CreateBenchmarkModal/Content.tsx
+++ b/src/routes/(main)/eval/features/CreateBenchmarkModal/Content.tsx
@@ -1,7 +1,7 @@
'use client';
import { Input, Select, TextArea, toast, useModalContext } from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form, useForm, useWatch } from '@lobehub/ui/base-ui/form';
import { cssVar } from 'antd-style';
import { type FC, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -26,18 +26,9 @@ const CreateBenchmarkContent: FC<CreateBenchmarkContentProps> = ({ formId, onLoa
const { close } = useModalContext();
const navigate = useWorkspaceAwareNavigate();
- const [form] = Form.useForm();
const [identifierTouched, setIdentifierTouched] = useState(false);
const createBenchmark = useEvalStore((s) => s.createBenchmark);
- const nameValue = Form.useWatch('name', form);
-
- useEffect(() => {
- if (!identifierTouched && nameValue) {
- form.setFieldValue('identifier', toIdentifier(nameValue));
- }
- }, [nameValue, identifierTouched, form]);
-
const handleFinish = async (values: any) => {
onLoadingChange?.(true);
try {
@@ -59,33 +50,44 @@ const CreateBenchmarkContent: FC<CreateBenchmarkContentProps> = ({ formId, onLoa
}
};
+ const form = useForm({
+ onSubmit: handleFinish,
+ });
+ const nameValue = useWatch(form, 'name');
+
+ useEffect(() => {
+ if (!identifierTouched && nameValue) {
+ form.setValue('identifier', toIdentifier(nameValue));
+ }
+ }, [nameValue, identifierTouched, form]);
+
return (
- <Form form={form} layout="vertical" name={formId} onFinish={handleFinish}>
- <Form.Item
+ <Form form={form} id={formId} layout="vertical">
+ <Form.Field
label={t('benchmark.create.name.label')}
name="name"
- rules={[{ message: t('benchmark.create.nameRequired'), required: true }]}
+ required={t('benchmark.create.nameRequired')}
>
<Input autoFocus placeholder={t('benchmark.create.name.placeholder')} />
- </Form.Item>
+ </Form.Field>
- <Form.Item
+ <Form.Field
label={t('benchmark.create.identifier.label')}
name="identifier"
- rules={[{ message: t('benchmark.create.identifierRequired'), required: true }]}
+ required={t('benchmark.create.identifierRequired')}
>
<Input
placeholder={t('benchmark.create.identifier.placeholder')}
style={{ fontFamily: cssVar.fontFamilyCode }}
onChange={() => setIdentifierTouched(true)}
/>
- </Form.Item>
+ </Form.Field>
- <Form.Item label={t('benchmark.create.description.label')} name="description">
+ <Form.Field label={t('benchmark.create.description.label')} name="description">
<TextArea placeholder={t('benchmark.create.description.placeholder')} rows={3} />
- </Form.Item>
+ </Form.Field>
- <Form.Item label={t('benchmark.create.tags.label')} name="tags" style={{ marginBottom: 0 }}>
+ <Form.Field label={t('benchmark.create.tags.label')} name="tags">
<Select
mode="tags"
open={false}
@@ -93,7 +95,7 @@ const CreateBenchmarkContent: FC<CreateBenchmarkContentProps> = ({ formId, onLoa
style={{ width: '100%' }}
tokenSeparators={[',', ',', ' ']}
/>
- </Form.Item>
+ </Form.Field>
</Form>
);
};
diff --git a/src/routes/(main)/eval/features/DatasetCreateModal/Content.tsx b/src/routes/(main)/eval/features/DatasetCreateModal/Content.tsx
index 486e689efaf..ab9201f2681 100644
--- a/src/routes/(main)/eval/features/DatasetCreateModal/Content.tsx
+++ b/src/routes/(main)/eval/features/DatasetCreateModal/Content.tsx
@@ -2,7 +2,7 @@
import { Center, Flexbox, Icon } from '@lobehub/ui';
import { Input, Select, Text, TextArea, toast, useModalContext } from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form, useForm, useWatch } from '@lobehub/ui/base-ui/form';
import { createStaticStyles, cssVar } from 'antd-style';
import { CheckIcon } from 'lucide-react';
import { type FC, useEffect, useState } from 'react';
@@ -121,26 +121,19 @@ const DatasetCreateContent: FC<DatasetCreateContentProps> = ({
const { t } = useTranslation('eval');
const { close } = useModalContext();
- const [form] = Form.useForm();
const [selectedPreset, setSelectedPreset] = useState<string>('custom');
const [identifierTouched, setIdentifierTouched] = useState(false);
- const nameValue = Form.useWatch('name', form);
- const evalModeValue = Form.useWatch('evalMode', form);
-
- useEffect(() => {
- if (!identifierTouched && nameValue) {
- form.setFieldValue('identifier', toIdentifier(nameValue));
- }
- }, [nameValue, identifierTouched, form]);
-
const handleFinish = async (values: any) => {
onLoadingChange?.(true);
try {
const result = await agentEvalService.createDataset({
benchmarkId,
description: values.description,
- evalConfig: values.evalConfig?.judgePrompt ? values.evalConfig : undefined,
+ evalConfig:
+ values.evalMode === 'llm-rubric' && values.evalConfig?.judgePrompt
+ ? values.evalConfig
+ : undefined,
evalMode: values.evalMode || undefined,
identifier: values.identifier.trim(),
metadata: {
@@ -161,38 +154,48 @@ const DatasetCreateContent: FC<DatasetCreateContentProps> = ({
}
};
+ const form = useForm({ onSubmit: handleFinish });
+ const nameValue = useWatch(form, 'name');
+ const evalModeValue = useWatch(form, 'evalMode');
+
+ useEffect(() => {
+ if (!identifierTouched && nameValue) {
+ form.setValue('identifier', toIdentifier(nameValue));
+ }
+ }, [nameValue, identifierTouched, form]);
+
const presetsByCategory = getPresetsByCategory();
const orderedCategories = Object.entries(presetsByCategory).filter(
([, presets]) => presets.length > 0,
);
return (
- <Form form={form} layout="vertical" name={formId} onFinish={handleFinish}>
- <Form.Item
+ <Form form={form} id={formId} layout="vertical">
+ <Form.Field
label={t('dataset.create.name.label')}
name="name"
- rules={[{ message: t('dataset.create.nameRequired'), required: true }]}
+ required={t('dataset.create.nameRequired')}
>
<Input placeholder={t('dataset.create.name.placeholder')} />
- </Form.Item>
+ </Form.Field>
- <Form.Item
+ <Form.Field
label={t('dataset.create.identifier.label')}
name="identifier"
- rules={[{ message: t('dataset.create.identifierRequired'), required: true }]}
+ required={t('dataset.create.identifierRequired')}
>
<Input
placeholder={t('dataset.create.identifier.placeholder')}
style={{ fontFamily: cssVar.fontFamilyCode }}
onChange={() => setIdentifierTouched(true)}
/>
- </Form.Item>
+ </Form.Field>
- <Form.Item label={t('dataset.create.description.label')} name="description">
+ <Form.Field label={t('dataset.create.description.label')} name="description">
<TextArea placeholder={t('dataset.create.description.placeholder')} rows={3} />
- </Form.Item>
+ </Form.Field>
- <Form.Item extra={t('dataset.evalMode.hint')} label={t('evalMode.label')} name="evalMode">
+ <Form.Field extra={t('dataset.evalMode.hint')} label={t('evalMode.label')} name="evalMode">
<Select
allowClear
placeholder={t('evalMode.placeholder')}
@@ -211,12 +214,12 @@ const DatasetCreateContent: FC<DatasetCreateContentProps> = ({
{ label: t('evalMode.external'), value: 'external' },
]}
/>
- </Form.Item>
+ </Form.Field>
{evalModeValue === 'llm-rubric' && (
- <Form.Item label={t('evalMode.prompt.label')} name={['evalConfig', 'judgePrompt']}>
+ <Form.Field label={t('evalMode.prompt.label')} name="evalConfig.judgePrompt">
<TextArea placeholder={t('evalMode.prompt.placeholder')} rows={3} />
- </Form.Item>
+ </Form.Field>
)}
{/* Preset picker — selectable cards grouped by category, the bold upgrade
diff --git a/src/routes/(main)/eval/features/DatasetEditModal/Content.tsx b/src/routes/(main)/eval/features/DatasetEditModal/Content.tsx
index 82f2632db4c..5173ab10985 100644
--- a/src/routes/(main)/eval/features/DatasetEditModal/Content.tsx
+++ b/src/routes/(main)/eval/features/DatasetEditModal/Content.tsx
@@ -2,10 +2,10 @@
import { Center, Flexbox, Icon } from '@lobehub/ui';
import { Input, Select, Text, TextArea, toast, useModalContext } from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form, useForm, useWatch } from '@lobehub/ui/base-ui/form';
import { createStaticStyles, cssVar } from 'antd-style';
import { CheckIcon } from 'lucide-react';
-import { type FC, useEffect, useState } from 'react';
+import { type FC, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { agentEvalService } from '@/services/agentEval';
@@ -111,21 +111,9 @@ const DatasetEditContent: FC<DatasetEditContentProps> = ({
const { t } = useTranslation('eval');
const { close } = useModalContext();
- const [form] = Form.useForm();
- const [selectedPreset, setSelectedPreset] = useState<string>('custom');
- const evalModeValue = Form.useWatch('evalMode', form);
-
- useEffect(() => {
- if (dataset) {
- form.setFieldsValue({
- description: dataset.description || '',
- evalConfig: (dataset as any).evalConfig,
- evalMode: dataset.evalMode || undefined,
- name: dataset.name,
- });
- setSelectedPreset((dataset.metadata?.preset as string) || 'custom');
- }
- }, [dataset, form]);
+ const [selectedPreset, setSelectedPreset] = useState<string>(
+ () => (dataset.metadata?.preset as string) || 'custom',
+ );
const presetsByCategory = getPresetsByCategory();
const orderedCategories = Object.entries(presetsByCategory).filter(
@@ -137,7 +125,11 @@ const DatasetEditContent: FC<DatasetEditContentProps> = ({
try {
await agentEvalService.updateDataset({
description: values.description?.trim() || undefined,
- evalConfig: values.evalConfig?.judgePrompt ? values.evalConfig : null,
+ evalConfig:
+ (values.evalMode === 'llm-rubric' || values.evalMode === 'answer-relevance') &&
+ values.evalConfig?.judgePrompt
+ ? values.evalConfig
+ : null,
evalMode: values.evalMode || null,
id: dataset.id,
metadata: {
@@ -156,21 +148,39 @@ const DatasetEditContent: FC<DatasetEditContentProps> = ({
}
};
+ const evalConfig = (dataset as any).evalConfig;
+ const form = useForm({
+ initialValues: {
+ description: dataset.description || '',
+ evalConfig: {
+ criteria: evalConfig?.criteria,
+ judgePrompt: evalConfig?.judgePrompt,
+ model: evalConfig?.model ?? 'gpt-5-nano',
+ provider: evalConfig?.provider ?? 'aihubmix',
+ systemRole: evalConfig?.systemRole,
+ },
+ evalMode: dataset.evalMode || undefined,
+ name: dataset.name,
+ },
+ onSubmit: handleFinish,
+ });
+ const evalModeValue = useWatch(form, 'evalMode');
+
return (
- <Form form={form} layout="vertical" name={formId} onFinish={handleFinish}>
- <Form.Item
+ <Form form={form} id={formId} layout="vertical">
+ <Form.Field
label={t('dataset.create.name.label')}
name="name"
- rules={[{ message: t('dataset.create.nameRequired'), required: true }]}
+ required={t('dataset.create.nameRequired')}
>
<Input autoFocus placeholder={t('dataset.create.name.placeholder')} />
- </Form.Item>
+ </Form.Field>
- <Form.Item label={t('dataset.create.description.label')} name="description">
+ <Form.Field label={t('dataset.create.description.label')} name="description">
<TextArea placeholder={t('dataset.create.description.placeholder')} rows={3} />
- </Form.Item>
+ </Form.Field>
- <Form.Item extra={t('dataset.evalMode.hint')} label={t('evalMode.label')} name="evalMode">
+ <Form.Field extra={t('dataset.evalMode.hint')} label={t('evalMode.label')} name="evalMode">
<Select
allowClear
placeholder={t('evalMode.placeholder')}
@@ -190,25 +200,25 @@ const DatasetEditContent: FC<DatasetEditContentProps> = ({
{ label: t('evalMode.external'), value: 'external' },
]}
/>
- </Form.Item>
+ </Form.Field>
{(evalModeValue === 'llm-rubric' || evalModeValue === 'answer-relevance') && (
<>
- <Form.Item initialValue="aihubmix" label={'Provider'} name={['evalConfig', 'provider']}>
+ <Form.Field label={'Provider'} name="evalConfig.provider">
<TextArea placeholder={'LLM provider (e.g. openai, azure)'} rows={1} />
- </Form.Item>
- <Form.Item initialValue="gpt-5-nano" label={'Model'} name={['evalConfig', 'model']}>
+ </Form.Field>
+ <Form.Field label={'Model'} name="evalConfig.model">
<TextArea placeholder={'LLM model to use for evaluation (e.g. gpt-4)'} rows={1} />
- </Form.Item>
- <Form.Item label={'System Prompt'} name={['evalConfig', 'systemRole']}>
+ </Form.Field>
+ <Form.Field label={'System Prompt'} name="evalConfig.systemRole">
<TextArea placeholder={'Optional system prompt for the LLM judge'} rows={3} />
- </Form.Item>
- <Form.Item label={'Eval Prompt'} name={['evalConfig', 'criteria']}>
+ </Form.Field>
+ <Form.Field label={'Eval Prompt'} name="evalConfig.criteria">
<TextArea placeholder={'Prompt template for the LLM judge'} rows={3} />
- </Form.Item>
- <Form.Item label={t('evalMode.prompt.label')} name={['evalConfig', 'judgePrompt']}>
+ </Form.Field>
+ <Form.Field label={t('evalMode.prompt.label')} name="evalConfig.judgePrompt">
<TextArea placeholder={t('evalMode.prompt.placeholder')} rows={3} />
- </Form.Item>
+ </Form.Field>
</>
)}
diff --git a/src/routes/(main)/eval/features/Experiments/ExperimentCreateModal.tsx b/src/routes/(main)/eval/features/Experiments/ExperimentCreateModal.tsx
index d1b776ce0de..a524b56732b 100644
--- a/src/routes/(main)/eval/features/Experiments/ExperimentCreateModal.tsx
+++ b/src/routes/(main)/eval/features/Experiments/ExperimentCreateModal.tsx
@@ -11,9 +11,9 @@ import {
toast,
useModalContext,
} from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form, useForm } from '@lobehub/ui/base-ui/form';
import { t } from 'i18next';
-import { memo, useEffect } from 'react';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { benchmarkSelectors, useEvalStore } from '@/store/eval';
@@ -34,7 +34,6 @@ const ExperimentModalContent = memo<ExperimentModalContentProps>(
const { t } = useTranslation('eval');
const { close } = useModalContext();
- const [form] = Form.useForm();
const createExperiment = useEvalStore((s) => s.createExperiment);
const updateExperiment = useEvalStore((s) => s.updateExperiment);
const useFetchBenchmarks = useEvalStore((s) => s.useFetchBenchmarks);
@@ -42,16 +41,6 @@ const ExperimentModalContent = memo<ExperimentModalContentProps>(
useFetchBenchmarks();
- useEffect(() => {
- if (experiment) {
- form.setFieldsValue({
- benchmarkIds: experiment.benchmarks.map((benchmark) => benchmark.id),
- description: experiment.description || undefined,
- name: experiment.name,
- });
- }
- }, [experiment, form]);
-
const handleSubmit = async (values: {
benchmarkIds: string[];
description?: string;
@@ -79,24 +68,35 @@ const ExperimentModalContent = memo<ExperimentModalContentProps>(
}
};
+ const form = useForm({
+ initialValues: experiment
+ ? {
+ benchmarkIds: experiment.benchmarks.map((benchmark) => benchmark.id),
+ description: experiment.description || undefined,
+ name: experiment.name,
+ }
+ : undefined,
+ onSubmit: handleSubmit,
+ });
+
return (
- <Form form={form} id={formId} layout="vertical" onFinish={handleSubmit}>
- <Form.Item
+ <Form form={form} id={formId} layout="vertical">
+ <Form.Field
label={t('experiment.create.name.label')}
name="name"
- rules={[{ message: t('experiment.create.nameRequired'), required: true }]}
+ required={t('experiment.create.nameRequired')}
>
<Input placeholder={t('experiment.create.name.placeholder')} />
- </Form.Item>
+ </Form.Field>
- <Form.Item label={t('experiment.create.description.label')} name="description">
+ <Form.Field label={t('experiment.create.description.label')} name="description">
<TextArea placeholder={t('experiment.create.description.placeholder')} rows={3} />
- </Form.Item>
+ </Form.Field>
- <Form.Item
+ <Form.Field
label={t('experiment.create.benchmarks.label')}
name="benchmarkIds"
- rules={[{ message: t('experiment.create.benchmarksRequired'), required: true }]}
+ required={t('experiment.create.benchmarksRequired')}
>
<Select
mode="multiple"
@@ -106,7 +106,7 @@ const ExperimentModalContent = memo<ExperimentModalContentProps>(
value: benchmark.id,
}))}
/>
- </Form.Item>
+ </Form.Field>
</Form>
);
},
diff --git a/src/routes/(main)/eval/features/TestCaseCreateModal/Content.tsx b/src/routes/(main)/eval/features/TestCaseCreateModal/Content.tsx
index f3234cf2eff..7fe6c1243be 100644
--- a/src/routes/(main)/eval/features/TestCaseCreateModal/Content.tsx
+++ b/src/routes/(main)/eval/features/TestCaseCreateModal/Content.tsx
@@ -10,7 +10,7 @@ import {
toast,
useModalContext,
} from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form, useForm, useWatch } from '@lobehub/ui/base-ui/form';
import { createStaticStyles, cssVar } from 'antd-style';
import { type FC } from 'react';
import { useTranslation } from 'react-i18next';
@@ -42,9 +42,6 @@ const TestCaseCreateContent: FC<TestCaseCreateContentProps> = ({
const { t } = useTranslation('eval');
const { close } = useModalContext();
- const [form] = Form.useForm();
- const evalModeValue = Form.useWatch('evalMode', form);
-
const handleFinish = async (values: any) => {
onLoadingChange?.(true);
try {
@@ -61,7 +58,10 @@ const TestCaseCreateContent: FC<TestCaseCreateContentProps> = ({
input: values.input,
},
datasetId,
- evalConfig: values.evalConfig?.judgePrompt ? values.evalConfig : undefined,
+ evalConfig:
+ values.evalMode === 'llm-rubric' && values.evalConfig?.judgePrompt
+ ? values.evalConfig
+ : undefined,
evalMode: values.evalMode || undefined,
metadata: {
...(values.difficulty ? { difficulty: values.difficulty } : {}),
@@ -83,29 +83,32 @@ const TestCaseCreateContent: FC<TestCaseCreateContentProps> = ({
}
};
+ const form = useForm({ onSubmit: handleFinish });
+ const evalModeValue = useWatch(form, 'evalMode');
+
return (
- <Form form={form} layout="vertical" name={formId} onFinish={handleFinish}>
+ <Form form={form} id={formId} layout="vertical">
<div className={styles.sectionLabel}>{t('caseDetail.section.testCase')}</div>
- <Form.Item label={t('testCase.create.input.label')} name="input" rules={[{ required: true }]}>
+ <Form.Field required label={t('testCase.create.input.label')} name="input">
<TextArea
autoSize={{ maxRows: 6, minRows: 3 }}
placeholder={t('testCase.create.input.placeholder')}
/>
- </Form.Item>
- <Form.Item
+ </Form.Field>
+ <Form.Field
label={t('testCase.create.expected.label')}
name="expected"
- rules={[{ message: t('testCase.create.expected.required'), required: true }]}
+ required={t('testCase.create.expected.required')}
>
<TextArea
autoSize={{ maxRows: 6, minRows: 2 }}
placeholder={t('testCase.create.expected.placeholder')}
/>
- </Form.Item>
+ </Form.Field>
<div className={styles.sectionLabel} style={{ marginBlockStart: 4 }}>
{t('caseDetail.section.scoring')}
</div>
- <Form.Item label={t('evalMode.label')} name="evalMode">
+ <Form.Field label={t('evalMode.label')} name="evalMode">
<Select
allowClear
placeholder={t('evalMode.placeholder')}
@@ -123,14 +126,14 @@ const TestCaseCreateContent: FC<TestCaseCreateContentProps> = ({
{ label: t('evalMode.llm-rubric'), value: 'llm-rubric' },
]}
/>
- </Form.Item>
+ </Form.Field>
{evalModeValue === 'llm-rubric' && (
- <Form.Item label={t('evalMode.prompt.label')} name={['evalConfig', 'judgePrompt']}>
+ <Form.Field label={t('evalMode.prompt.label')} name="evalConfig.judgePrompt">
<TextArea
autoSize={{ maxRows: 8, minRows: 3 }}
placeholder={t('evalMode.prompt.placeholder')}
/>
- </Form.Item>
+ </Form.Field>
)}
<Accordion
keepMounted
@@ -140,10 +143,10 @@ const TestCaseCreateContent: FC<TestCaseCreateContentProps> = ({
{
children: (
<Flexbox gap={16} style={{ paddingBlockStart: 8 }}>
- <Form.Item
+ <Form.Field
label={t('testCase.create.difficulty.label')}
name="difficulty"
- style={{ marginBottom: 0 }}
+ style={{ paddingBlock: 0 }}
>
<Select
allowClear
@@ -154,14 +157,14 @@ const TestCaseCreateContent: FC<TestCaseCreateContentProps> = ({
{ label: t('difficulty.hard'), value: 'hard' },
]}
/>
- </Form.Item>
- <Form.Item
+ </Form.Field>
+ <Form.Field
label={t('testCase.create.tags.label')}
name="tags"
- style={{ marginBottom: 0 }}
+ style={{ paddingBlock: 0 }}
>
<Input placeholder={t('testCase.create.tags.placeholder')} />
- </Form.Item>
+ </Form.Field>
</Flexbox>
),
key: 'advanced',
diff --git a/src/routes/(main)/eval/features/TestCaseEditModal/Content.tsx b/src/routes/(main)/eval/features/TestCaseEditModal/Content.tsx
index bede68cce4a..519e854a1cb 100644
--- a/src/routes/(main)/eval/features/TestCaseEditModal/Content.tsx
+++ b/src/routes/(main)/eval/features/TestCaseEditModal/Content.tsx
@@ -10,9 +10,9 @@ import {
toast,
useModalContext,
} from '@lobehub/ui/base-ui';
-import { Form } from 'antd';
+import { Form, useForm, useWatch } from '@lobehub/ui/base-ui/form';
import { createStaticStyles, cssVar } from 'antd-style';
-import { type FC, useEffect } from 'react';
+import { type FC } from 'react';
import { useTranslation } from 'react-i18next';
import { agentEvalService } from '@/services/agentEval';
@@ -42,23 +42,6 @@ const TestCaseEditContent: FC<TestCaseEditContentProps> = ({
const { t } = useTranslation('eval');
const { close } = useModalContext();
- const [form] = Form.useForm();
- const evalModeValue = Form.useWatch('evalMode', form);
-
- useEffect(() => {
- if (testCase) {
- form.setFieldsValue({
- category: testCase.content?.category,
- difficulty: testCase.metadata?.difficulty,
- evalConfig: testCase.evalConfig,
- evalMode: testCase.evalMode || undefined,
- expected: testCase.content?.expected,
- input: testCase.content?.input,
- tags: testCase.metadata?.tags?.join(', '),
- });
- }
- }, [testCase, form]);
-
const handleFinish = async (values: any) => {
onLoadingChange?.(true);
try {
@@ -75,7 +58,10 @@ const TestCaseEditContent: FC<TestCaseEditContentProps> = ({
expected: values.expected,
input: values.input,
},
- evalConfig: values.evalConfig?.judgePrompt ? values.evalConfig : null,
+ evalConfig:
+ values.evalMode === 'llm-rubric' && values.evalConfig?.judgePrompt
+ ? values.evalConfig
+ : null,
evalMode: values.evalMode || null,
id: testCase.id,
metadata: {
@@ -94,29 +80,43 @@ const TestCaseEditContent: FC<TestCaseEditContentProps> = ({
}
};
+ const form = useForm({
+ initialValues: {
+ category: testCase.content?.category,
+ difficulty: testCase.metadata?.difficulty,
+ evalConfig: { judgePrompt: testCase.evalConfig?.judgePrompt },
+ evalMode: testCase.evalMode || undefined,
+ expected: testCase.content?.expected,
+ input: testCase.content?.input,
+ tags: testCase.metadata?.tags?.join(', '),
+ },
+ onSubmit: handleFinish,
+ });
+ const evalModeValue = useWatch(form, 'evalMode');
+
return (
- <Form form={form} layout="vertical" name={formId} onFinish={handleFinish}>
+ <Form form={form} id={formId} layout="vertical">
<div className={styles.sectionLabel}>{t('caseDetail.section.testCase')}</div>
- <Form.Item label={t('testCase.create.input.label')} name="input" rules={[{ required: true }]}>
+ <Form.Field required label={t('testCase.create.input.label')} name="input">
<TextArea
autoSize={{ maxRows: 6, minRows: 3 }}
placeholder={t('testCase.create.input.placeholder')}
/>
- </Form.Item>
- <Form.Item
+ </Form.Field>
+ <Form.Field
label={t('testCase.create.expected.label')}
name="expected"
- rules={[{ message: t('testCase.create.expected.required'), required: true }]}
+ required={t('testCase.create.expected.required')}
>
<TextArea
autoSize={{ maxRows: 6, minRows: 2 }}
placeholder={t('testCase.create.expected.placeholder')}
/>
- </Form.Item>
+ </Form.Field>
<div className={styles.sectionLabel} style={{ marginBlockStart: 4 }}>
{t('caseDetail.section.scoring')}
</div>
- <Form.Item label={t('evalMode.label')} name="evalMode">
+ <Form.Field label={t('evalMode.label')} name="evalMode">
<Select
allowClear
placeholder={t('evalMode.placeholder')}
@@ -134,14 +134,14 @@ const TestCaseEditContent: FC<TestCaseEditContentProps> = ({
{ label: t('evalMode.llm-rubric'), value: 'llm-rubric' },
]}
/>
- </Form.Item>
+ </Form.Field>
{evalModeValue === 'llm-rubric' && (
- <Form.Item label={t('evalMode.prompt.label')} name={['evalConfig', 'judgePrompt']}>
+ <Form.Field label={t('evalMode.prompt.label')} name="evalConfig.judgePrompt">
<TextArea
autoSize={{ maxRows: 8, minRows: 3 }}
placeholder={t('evalMode.prompt.placeholder')}
/>
- </Form.Item>
+ </Form.Field>
)}
<Accordion
keepMounted
@@ -151,17 +151,17 @@ const TestCaseEditContent: FC<TestCaseEditContentProps> = ({
{
children: (
<Flexbox gap={16} style={{ paddingBlockStart: 8 }}>
- <Form.Item
+ <Form.Field
label={t('table.columns.category')}
name="category"
- style={{ marginBottom: 0 }}
+ style={{ paddingBlock: 0 }}
>
<Input placeholder={t('dataset.import.categoryDesc')} />
- </Form.Item>
- <Form.Item
+ </Form.Field>
+ <Form.Field
label={t('testCase.create.difficulty.label')}
name="difficulty"
- style={{ marginBottom: 0 }}
+ style={{ paddingBlock: 0 }}
>
<Select
allowClear
@@ -172,14 +172,14 @@ const TestCaseEditContent: FC<TestCaseEditContentProps> = ({
{ label: t('difficulty.hard'), value: 'hard' },
]}
/>
- </Form.Item>
- <Form.Item
+ </Form.Field>
+ <Form.Field
label={t('testCase.create.tags.label')}
name="tags"
- style={{ marginBottom: 0 }}
+ style={{ paddingBlock: 0 }}
>
<Input placeholder={t('testCase.create.tags.placeholder')} />
- </Form.Item>
+ </Form.Field>
</Flexbox>
),
key: 'advanced',