Files
monkey-ai-web/src/pages/WebsiteSettings/index.jsx
T

286 lines
9.2 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useRef, useState } from 'react';
import {
Banner,
Button,
Card,
Form,
Spin,
Tabs,
Typography,
} from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { showError, showSuccess, showWarning } from '../../helpers';
import {
TABS,
emptySettings,
settingsFromConfig,
serializeSettings,
validateField,
validateSettings,
} from './model';
import { getWebsiteSettings, saveWebsiteSettings } from './settingsApi';
import WebsiteField from './WebsiteField';
import QrCodeUpload from './QrCodeUpload';
import InsightsPanel from './InsightsPanel';
import './WebsiteSettings.css';
export default function WebsiteSettings() {
const { t } = useTranslation();
const [activeTab, setActiveTab] = useState('home');
const [values, setValues] = useState(emptySettings);
const [errors, setErrors] = useState({});
const [saving, setSaving] = useState(false);
const [uploading, setUploading] = useState(false);
const [resetVersion, setResetVersion] = useState(0);
const [dirty, setDirty] = useState(false);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState('');
const [loadVersion, setLoadVersion] = useState(0);
const originalConfig = useRef({});
const savePending = useRef(false);
useEffect(() => {
let active = true;
setLoading(true);
setLoadError('');
getWebsiteSettings()
.then((config) => {
if (!active) return;
originalConfig.current = config ?? {};
setValues(settingsFromConfig(config));
setDirty(false);
setErrors({});
})
.catch((error) => {
if (active)
setLoadError(error.message || '官网配置读取失败,请稍后重试');
})
.finally(() => {
if (active) setLoading(false);
});
return () => {
active = false;
};
}, [loadVersion]);
const disabled = saving || loading || Boolean(loadError);
useEffect(() => {
if (!dirty) return;
const warn = (event) => {
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', warn);
return () => window.removeEventListener('beforeunload', warn);
}, [dirty]);
const tab = TABS.find((item) => item.key === activeTab);
const change = (name, value) => {
setDirty(true);
setValues((previous) => ({ ...previous, [name]: value }));
setErrors((previous) =>
previous[name]
? { ...previous, [name]: validateField(name, value) }
: previous,
);
};
const clear = () => {
setDirty(true);
setResetVersion((version) => version + 1);
setValues(emptySettings());
setErrors({});
setUploading(false);
};
const save = async () => {
if (savePending.current || disabled || uploading) return;
const nextErrors = validateSettings(values);
setErrors(nextErrors);
if (Object.keys(nextErrors).length) {
// Keep field errors for every tab; report each hidden invalid tab only once.
for (const item of TABS) {
if (
item.key !== activeTab &&
item.fields.some((name) => nextErrors[name])
) {
showWarning(t(`请完善${item.label}的配置`));
}
}
return;
}
savePending.current = true;
setSaving(true);
try {
const configurationJson = serializeSettings(
values,
originalConfig.current,
);
const result = await saveWebsiteSettings(configurationJson);
originalConfig.current = result.config ?? JSON.parse(configurationJson);
setValues(settingsFromConfig(originalConfig.current));
setDirty(false);
showSuccess(t('官网设置已保存'));
} catch (error) {
showError(t(error.message || '保存失败,请稍后重试'));
} finally {
setSaving(false);
savePending.current = false;
}
};
return (
<div className='website-settings-page' aria-busy={loading || saving}>
<Spin
spinning={loading || saving}
size='large'
style={{
minHeight: 200,
width: '100%',
flex: 1,
display: 'flex',
flexDirection: 'column',
}}
childStyle={{ flex: 1, display: 'flex', flexDirection: 'column' }}
data-testid='website-settings-loading'
>
<Card className='website-settings-card'>
<Typography.Title heading={4} style={{ marginBottom: 8 }}>
{t('官网设置')}
</Typography.Title>
<Typography.Paragraph type='tertiary'>
{t('配置官网展示内容与商务联系信息')}
</Typography.Paragraph>
{loadError ? (
<Banner
type='danger'
closeIcon={null}
description={t(loadError)}
fullMode={false}
>
<Button onClick={() => setLoadVersion((version) => version + 1)}>
{t('重新加载')}
</Button>
</Banner>
) : null}
<Tabs type='line' activeKey={activeTab} onChange={setActiveTab}>
{TABS.map((item) => (
<Tabs.TabPane
key={item.key}
itemKey={item.key}
tab={t(item.label)}
/>
))}
</Tabs>
<Form
onSubmit={save}
className={activeTab === 'insights' ? 'py-5' : 'max-w-4xl py-5'}
autoComplete='off'
>
<Typography.Paragraph
type='tertiary'
className='website-settings-tab-description'
>
{t(tab.description)}
</Typography.Paragraph>
{activeTab === 'insights' ? (
<InsightsPanel
key={resetVersion}
value={values.insights}
onChange={(value) => change('insights', value)}
disabled={disabled}
error={errors.insights}
/>
) : (
<div className='grid grid-cols-1 gap-x-7 md:grid-cols-2'>
{tab.fields.map((name) => (
<div
key={name}
className={name === 'address' ? 'md:col-span-2' : ''}
>
<WebsiteField
name={name}
value={values[name]}
error={errors[name]}
disabled={disabled}
onChange={(value) => change(name, value)}
onBlur={() =>
setErrors((previous) => ({
...previous,
[name]: validateField(name, values[name]),
}))
}
>
{name === 'wechatQrCode' && (
<QrCodeUpload
value={values.wechatQrCode}
onChange={(url) => change(name, url)}
busy={disabled}
onBusyChange={setUploading}
resetVersion={resetVersion}
invalid={Boolean(errors[name])}
/>
)}
</WebsiteField>
{activeTab === 'home' && name === 'teamMembers' && (
<Typography.Text type='tertiary' size='small'>
{t('研发人员占比')}:
{values.researchRatio || t('未配置')}
</Typography.Text>
)}
</div>
))}
</div>
)}
<Banner
type='info'
closeIcon={null}
className='website-settings-notice !rounded-lg'
style={{
marginTop: 10,
marginBottom: 2,
paddingTop: 2,
paddingBottom: 2,
}}
description={t('四个页签共用一份配置,保存时将统一校验并提交。')}
/>
<div
className='flex justify-center gap-2'
style={{ marginTop: 18 }}
>
<Button onClick={clear} disabled={disabled}>
{t('清空')}
</Button>
<Button
theme='solid'
htmlType='submit'
loading={saving}
disabled={disabled || uploading}
>
{t('保存')}
</Button>
</div>
</Form>
</Card>
</Spin>
</div>
);
}