Commit 775b1c45 by QuentinHsu

style(web): format code

parent ad7a64e5
module.exports = require("@so1ve/prettier-config"); module.exports = require('@so1ve/prettier-config');
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -21,9 +21,9 @@ import Chat2Link from './pages/Chat2Link'; ...@@ -21,9 +21,9 @@ import Chat2Link from './pages/Chat2Link';
import { Layout } from '@douyinfe/semi-ui'; import { Layout } from '@douyinfe/semi-ui';
import Midjourney from './pages/Midjourney'; import Midjourney from './pages/Midjourney';
import Pricing from './pages/Pricing/index.js'; import Pricing from './pages/Pricing/index.js';
import Task from "./pages/Task/index.js"; import Task from './pages/Task/index.js';
import Playground from './pages/Playground/Playground.js'; import Playground from './pages/Playground/Playground.js';
import OAuth2Callback from "./components/OAuth2Callback.js"; import OAuth2Callback from './components/OAuth2Callback.js';
import PersonalSetting from './components/PersonalSetting.js'; import PersonalSetting from './components/PersonalSetting.js';
import Setup from './pages/Setup/index.js'; import Setup from './pages/Setup/index.js';
......
...@@ -28,11 +28,7 @@ const FooterBar = () => { ...@@ -28,11 +28,7 @@ const FooterBar = () => {
New API {import.meta.env.VITE_REACT_APP_VERSION}{' '} New API {import.meta.env.VITE_REACT_APP_VERSION}{' '}
</a> </a>
{t('由')}{' '} {t('由')}{' '}
<a <a href='https://github.com/Calcium-Ion' target='_blank' rel='noreferrer'>
href='https://github.com/Calcium-Ion'
target='_blank'
rel='noreferrer'
>
Calcium-Ion Calcium-Ion
</a>{' '} </a>{' '}
{t('开发,基于')}{' '} {t('开发,基于')}{' '}
...@@ -59,10 +55,12 @@ const FooterBar = () => { ...@@ -59,10 +55,12 @@ const FooterBar = () => {
}, []); }, []);
return ( return (
<div style={{ <div
style={{
textAlign: 'center', textAlign: 'center',
paddingBottom: '5px', paddingBottom: '5px',
}}> }}
>
{footer ? ( {footer ? (
<div <div
className='custom-footer' className='custom-footer'
......
...@@ -9,7 +9,11 @@ import { ...@@ -9,7 +9,11 @@ import {
showSuccess, showSuccess,
updateAPI, updateAPI,
} from '../helpers'; } from '../helpers';
import {onGitHubOAuthClicked, onOIDCClicked, onLinuxDOOAuthClicked} from './utils'; import {
onGitHubOAuthClicked,
onOIDCClicked,
onLinuxDOOAuthClicked,
} from './utils';
import Turnstile from 'react-turnstile'; import Turnstile from 'react-turnstile';
import { import {
Button, Button,
...@@ -71,7 +75,6 @@ const LoginForm = () => { ...@@ -71,7 +75,6 @@ const LoginForm = () => {
} }
}, []); }, []);
const onWeChatLoginClicked = () => { const onWeChatLoginClicked = () => {
setShowWeChatLoginModal(true); setShowWeChatLoginModal(true);
}; };
...@@ -223,7 +226,8 @@ const LoginForm = () => { ...@@ -223,7 +226,8 @@ const LoginForm = () => {
}} }}
> >
<Text> <Text>
{t('没有账户?')} <Link to='/register'>{t('点击注册')}</Link> {t('没有账户?')}{' '}
<Link to='/register'>{t('点击注册')}</Link>
</Text> </Text>
<Text> <Text>
{t('忘记密码?')} <Link to='/reset'>{t('点击重置')}</Link> {t('忘记密码?')} <Link to='/reset'>{t('点击重置')}</Link>
...@@ -261,7 +265,10 @@ const LoginForm = () => { ...@@ -261,7 +265,10 @@ const LoginForm = () => {
type='primary' type='primary'
icon={<OIDCIcon />} icon={<OIDCIcon />}
onClick={() => onClick={() =>
onOIDCClicked(status.oidc_authorization_endpoint, status.oidc_client_id) onOIDCClicked(
status.oidc_authorization_endpoint,
status.oidc_client_id,
)
} }
/> />
) : ( ) : (
...@@ -331,7 +338,9 @@ const LoginForm = () => { ...@@ -331,7 +338,9 @@ const LoginForm = () => {
</div> </div>
<div style={{ textAlign: 'center' }}> <div style={{ textAlign: 'center' }}>
<p> <p>
{t('微信扫码关注公众号,输入「验证码」获取验证码(三分钟内有效)')} {t(
'微信扫码关注公众号,输入「验证码」获取验证码(三分钟内有效)',
)}
</p> </p>
</div> </div>
<Form size='large'> <Form size='large'>
......
...@@ -46,7 +46,6 @@ const LogsTable = () => { ...@@ -46,7 +46,6 @@ const LogsTable = () => {
const [isModalOpen, setIsModalOpen] = useState(false); const [isModalOpen, setIsModalOpen] = useState(false);
const [modalContent, setModalContent] = useState(''); const [modalContent, setModalContent] = useState('');
function renderType(type) { function renderType(type) {
switch (type) { switch (type) {
case 'IMAGINE': case 'IMAGINE':
return ( return (
...@@ -154,7 +153,6 @@ const LogsTable = () => { ...@@ -154,7 +153,6 @@ const LogsTable = () => {
} }
function renderCode(code) { function renderCode(code) {
switch (code) { switch (code) {
case 1: case 1:
return ( return (
...@@ -190,7 +188,6 @@ const LogsTable = () => { ...@@ -190,7 +188,6 @@ const LogsTable = () => {
} }
function renderStatus(type) { function renderStatus(type) {
switch (type) { switch (type) {
case 'SUCCESS': case 'SUCCESS':
return ( return (
...@@ -251,7 +248,6 @@ const LogsTable = () => { ...@@ -251,7 +248,6 @@ const LogsTable = () => {
}; };
// 修改renderDuration函数以包含颜色逻辑 // 修改renderDuration函数以包含颜色逻辑
function renderDuration(submit_time, finishTime) { function renderDuration(submit_time, finishTime) {
if (!submit_time || !finishTime) return 'N/A'; if (!submit_time || !finishTime) return 'N/A';
const start = new Date(submit_time); const start = new Date(submit_time);
...@@ -261,7 +257,7 @@ const LogsTable = () => { ...@@ -261,7 +257,7 @@ const LogsTable = () => {
const color = durationSec > 60 ? 'red' : 'green'; const color = durationSec > 60 ? 'red' : 'green';
return ( return (
<Tag color={color} size="large"> <Tag color={color} size='large'>
{durationSec} {t('秒')} {durationSec} {t('秒')}
</Tag> </Tag>
); );
...@@ -560,7 +556,9 @@ const LogsTable = () => { ...@@ -560,7 +556,9 @@ const LogsTable = () => {
{isAdminUser && showBanner ? ( {isAdminUser && showBanner ? (
<Banner <Banner
type='info' type='info'
description={t('当前未开启Midjourney回调,部分项目可能无法获得绘图结果,可在运营设置中开启。')} description={t(
'当前未开启Midjourney回调,部分项目可能无法获得绘图结果,可在运营设置中开启。',
)}
/> />
) : ( ) : (
<></> <></>
...@@ -634,7 +632,7 @@ const LogsTable = () => { ...@@ -634,7 +632,7 @@ const LogsTable = () => {
t('第 {{start}} - {{end}} 条,共 {{total}} 条', { t('第 {{start}} - {{end}} 条,共 {{total}} 条', {
start: page.currentStart, start: page.currentStart,
end: page.currentEnd, end: page.currentEnd,
total: logCount total: logCount,
}), }),
}} }}
loading={loading} loading={loading}
......
...@@ -39,7 +39,7 @@ const ModelPricing = () => { ...@@ -39,7 +39,7 @@ const ModelPricing = () => {
setSelectedRowKeys(selectedRowKeys); setSelectedRowKeys(selectedRowKeys);
}, },
}), }),
[] [],
); );
const handleChange = (value) => { const handleChange = (value) => {
...@@ -96,9 +96,9 @@ const ModelPricing = () => { ...@@ -96,9 +96,9 @@ const ModelPricing = () => {
borderStyle: 'solid', borderStyle: 'solid',
}} }}
> >
<IconVerify style={{ color: 'green' }} size="large" /> <IconVerify style={{ color: 'green' }} size='large' />
</Popover> </Popover>
) );
} }
const columns = [ const columns = [
...@@ -145,7 +145,6 @@ const ModelPricing = () => { ...@@ -145,7 +145,6 @@ const ModelPricing = () => {
title: t('可用分组'), title: t('可用分组'),
dataIndex: 'enable_groups', dataIndex: 'enable_groups',
render: (text, record, index) => { render: (text, record, index) => {
// enable_groups is a string array // enable_groups is a string array
return ( return (
<Space> <Space>
...@@ -153,11 +152,7 @@ const ModelPricing = () => { ...@@ -153,11 +152,7 @@ const ModelPricing = () => {
if (usableGroup[group]) { if (usableGroup[group]) {
if (group === selectedGroup) { if (group === selectedGroup) {
return ( return (
<Tag <Tag color='blue' size='large' prefixIcon={<IconVerify />}>
color='blue'
size='large'
prefixIcon={<IconVerify />}
>
{group} {group}
</Tag> </Tag>
); );
...@@ -168,10 +163,12 @@ const ModelPricing = () => { ...@@ -168,10 +163,12 @@ const ModelPricing = () => {
size='large' size='large'
onClick={() => { onClick={() => {
setSelectedGroup(group); setSelectedGroup(group);
showInfo(t('当前查看的分组为:{{group}},倍率为:{{ratio}}', { showInfo(
t('当前查看的分组为:{{group}},倍率为:{{ratio}}', {
group: group, group: group,
ratio: groupRatio[group] ratio: groupRatio[group],
})); }),
);
}} }}
> >
{group} {group}
...@@ -186,12 +183,13 @@ const ModelPricing = () => { ...@@ -186,12 +183,13 @@ const ModelPricing = () => {
}, },
{ {
title: () => ( title: () => (
<span style={{'display':'flex','alignItems':'center'}}> <span style={{ display: 'flex', alignItems: 'center' }}>
{t('倍率')} {t('倍率')}
<Popover <Popover
content={ content={
<div style={{ padding: 8 }}> <div style={{ padding: 8 }}>
{t('倍率是为了方便换算不同价格的模型')}<br/> {t('倍率是为了方便换算不同价格的模型')}
<br />
{t('点击查看倍率说明')} {t('点击查看倍率说明')}
</div> </div>
} }
...@@ -219,11 +217,18 @@ const ModelPricing = () => { ...@@ -219,11 +217,18 @@ const ModelPricing = () => {
let completionRatio = parseFloat(record.completion_ratio.toFixed(3)); let completionRatio = parseFloat(record.completion_ratio.toFixed(3));
content = ( content = (
<> <>
<Text>{t('模型倍率')}{record.quota_type === 0 ? text : t('无')}</Text> <Text>
{t('模型倍率')}{record.quota_type === 0 ? text : t('无')}
</Text>
<br /> <br />
<Text>{t('补全倍率')}{record.quota_type === 0 ? completionRatio : t('无')}</Text> <Text>
{t('补全倍率')}
{record.quota_type === 0 ? completionRatio : t('无')}
</Text>
<br /> <br />
<Text>{t('分组倍率')}{groupRatio[selectedGroup]}</Text> <Text>
{t('分组倍率')}{groupRatio[selectedGroup]}
</Text>
</> </>
); );
return <div>{content}</div>; return <div>{content}</div>;
...@@ -236,21 +241,31 @@ const ModelPricing = () => { ...@@ -236,21 +241,31 @@ const ModelPricing = () => {
let content = text; let content = text;
if (record.quota_type === 0) { if (record.quota_type === 0) {
// 这里的 *2 是因为 1倍率=0.002刀,请勿删除 // 这里的 *2 是因为 1倍率=0.002刀,请勿删除
let inputRatioPrice = record.model_ratio * 2 * groupRatio[selectedGroup]; let inputRatioPrice =
record.model_ratio * 2 * groupRatio[selectedGroup];
let completionRatioPrice = let completionRatioPrice =
record.model_ratio * record.model_ratio *
record.completion_ratio * 2 * record.completion_ratio *
2 *
groupRatio[selectedGroup]; groupRatio[selectedGroup];
content = ( content = (
<> <>
<Text>{t('提示')} ${inputRatioPrice} / 1M tokens</Text> <Text>
{t('提示')} ${inputRatioPrice} / 1M tokens
</Text>
<br /> <br />
<Text>{t('补全')} ${completionRatioPrice} / 1M tokens</Text> <Text>
{t('补全')} ${completionRatioPrice} / 1M tokens
</Text>
</> </>
); );
} else { } else {
let price = parseFloat(text) * groupRatio[selectedGroup]; let price = parseFloat(text) * groupRatio[selectedGroup];
content = <>${t('模型价格')}${price}</>; content = (
<>
${t('模型价格')}${price}
</>
);
} }
return <div>{content}</div>; return <div>{content}</div>;
}, },
...@@ -300,7 +315,7 @@ const ModelPricing = () => { ...@@ -300,7 +315,7 @@ const ModelPricing = () => {
if (success) { if (success) {
setGroupRatio(group_ratio); setGroupRatio(group_ratio);
setUsableGroup(usable_group); setUsableGroup(usable_group);
setSelectedGroup(userState.user ? userState.user.group : 'default') setSelectedGroup(userState.user ? userState.user.group : 'default');
setModelsFormat(data, group_ratio); setModelsFormat(data, group_ratio);
} else { } else {
showError(message); showError(message);
...@@ -330,32 +345,38 @@ const ModelPricing = () => { ...@@ -330,32 +345,38 @@ const ModelPricing = () => {
<Layout> <Layout>
{userState.user ? ( {userState.user ? (
<Banner <Banner
type="success" type='success'
fullMode={false} fullMode={false}
closeIcon="null" closeIcon='null'
description={t('您的默认分组为:{{group}},分组倍率为:{{ratio}}', { description={t('您的默认分组为:{{group}},分组倍率为:{{ratio}}', {
group: userState.user.group, group: userState.user.group,
ratio: groupRatio[userState.user.group] ratio: groupRatio[userState.user.group],
})} })}
/> />
) : ( ) : (
<Banner <Banner
type='warning' type='warning'
fullMode={false} fullMode={false}
closeIcon="null" closeIcon='null'
description={t('您还未登陆,显示的价格为默认分组倍率: {{ratio}}', { description={t('您还未登陆,显示的价格为默认分组倍率: {{ratio}}', {
ratio: groupRatio['default'] ratio: groupRatio['default'],
})} })}
/> />
)} )}
<br/> <br />
<Banner <Banner
type="info" type='info'
fullMode={false} fullMode={false}
description={<div>{t('按量计费费用 = 分组倍率 × 模型倍率 × (提示token数 + 补全token数 × 补全倍率)/ 500000 (单位:美元)')}</div>} description={
closeIcon="null" <div>
{t(
'按量计费费用 = 分组倍率 × 模型倍率 × (提示token数 + 补全token数 × 补全倍率)/ 500000 (单位:美元)',
)}
</div>
}
closeIcon='null'
/> />
<br/> <br />
<Space style={{ marginBottom: 16 }}> <Space style={{ marginBottom: 16 }}>
<Input <Input
placeholder={t('模糊搜索模型名称')} placeholder={t('模糊搜索模型名称')}
...@@ -368,11 +389,11 @@ const ModelPricing = () => { ...@@ -368,11 +389,11 @@ const ModelPricing = () => {
<Button <Button
theme='light' theme='light'
type='tertiary' type='tertiary'
style={{width: 150}} style={{ width: 150 }}
onClick={() => { onClick={() => {
copyText(selectedRowKeys); copyText(selectedRowKeys);
}} }}
disabled={selectedRowKeys == ""} disabled={selectedRowKeys == ''}
> >
{t('复制选中模型')} {t('复制选中模型')}
</Button> </Button>
...@@ -387,7 +408,7 @@ const ModelPricing = () => { ...@@ -387,7 +408,7 @@ const ModelPricing = () => {
t('第 {{start}} - {{end}} 条,共 {{total}} 条', { t('第 {{start}} - {{end}} 条,共 {{total}} 条', {
start: page.currentStart, start: page.currentStart,
end: page.currentEnd, end: page.currentEnd,
total: models.length total: models.length,
}), }),
pageSize: models.length, pageSize: models.length,
showSizeChanger: false, showSizeChanger: false,
......
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { Card, Spin, Tabs } from '@douyinfe/semi-ui'; import { Card, Spin, Tabs } from '@douyinfe/semi-ui';
import { API, showError, showSuccess } from '../helpers'; import { API, showError, showSuccess } from '../helpers';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import SettingGeminiModel from '../pages/Setting/Model/SettingGeminiModel.js'; import SettingGeminiModel from '../pages/Setting/Model/SettingGeminiModel.js';
...@@ -31,14 +30,12 @@ const ModelSetting = () => { ...@@ -31,14 +30,12 @@ const ModelSetting = () => {
if ( if (
item.key === 'gemini.safety_settings' || item.key === 'gemini.safety_settings' ||
item.key === 'gemini.version_settings' || item.key === 'gemini.version_settings' ||
item.key === 'claude.model_headers_settings'|| item.key === 'claude.model_headers_settings' ||
item.key === 'claude.default_max_tokens' item.key === 'claude.default_max_tokens'
) { ) {
item.value = JSON.stringify(JSON.parse(item.value), null, 2); item.value = JSON.stringify(JSON.parse(item.value), null, 2);
} }
if ( if (item.key.endsWith('Enabled') || item.key.endsWith('enabled')) {
item.key.endsWith('Enabled') || item.key.endsWith('enabled')
) {
newInputs[item.key] = item.value === 'true' ? true : false; newInputs[item.key] = item.value === 'true' ? true : false;
} else { } else {
newInputs[item.key] = item.value; newInputs[item.key] = item.value;
......
...@@ -15,7 +15,9 @@ const OAuth2Callback = (props) => { ...@@ -15,7 +15,9 @@ const OAuth2Callback = (props) => {
let navigate = useNavigate(); let navigate = useNavigate();
const sendCode = async (code, state, count) => { const sendCode = async (code, state, count) => {
const res = await API.get(`/api/oauth/${props.type}?code=${code}&state=${state}`); const res = await API.get(
`/api/oauth/${props.type}?code=${code}&state=${state}`,
);
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
if (message === 'bind') { if (message === 'bind') {
...@@ -25,7 +27,7 @@ const OAuth2Callback = (props) => { ...@@ -25,7 +27,7 @@ const OAuth2Callback = (props) => {
userDispatch({ type: 'login', payload: data }); userDispatch({ type: 'login', payload: data });
localStorage.setItem('user', JSON.stringify(data)); localStorage.setItem('user', JSON.stringify(data));
setUserData(data); setUserData(data);
updateAPI() updateAPI();
showSuccess('登录成功!'); showSuccess('登录成功!');
navigate('/token'); navigate('/token');
} }
......
...@@ -4,14 +4,30 @@ import { Icon } from '@douyinfe/semi-ui'; ...@@ -4,14 +4,30 @@ import { Icon } from '@douyinfe/semi-ui';
const OIDCIcon = (props) => { const OIDCIcon = (props) => {
function CustomIcon() { function CustomIcon() {
return ( return (
<svg t="1723135116886" className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" <svg
p-id="10969" width="1em" height="1em"> t='1723135116886'
className='icon'
viewBox='0 0 1024 1024'
version='1.1'
xmlns='http://www.w3.org/2000/svg'
p-id='10969'
width='1em'
height='1em'
>
<path <path
d="M512 960C265 960 64 759 64 512S265 64 512 64s448 201 448 448-201 448-448 448z m0-882.6c-239.7 0-434.6 195-434.6 434.6s195 434.6 434.6 434.6 434.6-195 434.6-434.6S751.7 77.4 512 77.4z" d='M512 960C265 960 64 759 64 512S265 64 512 64s448 201 448 448-201 448-448 448z m0-882.6c-239.7 0-434.6 195-434.6 434.6s195 434.6 434.6 434.6 434.6-195 434.6-434.6S751.7 77.4 512 77.4z'
p-id="10970" fill="#2c2c2c" stroke="#2c2c2c" stroke-width="60"></path> p-id='10970'
fill='#2c2c2c'
stroke='#2c2c2c'
stroke-width='60'
></path>
<path <path
d="M197.7 512c0-78.3 31.6-98.8 87.2-98.8 56.2 0 87.2 20.5 87.2 98.8s-31 98.8-87.2 98.8c-55.7 0-87.2-20.5-87.2-98.8z m130.4 0c0-46.8-7.8-64.5-43.2-64.5-35.2 0-42.9 17.7-42.9 64.5 0 47.1 7.8 63.7 42.9 63.7 35.4 0 43.2-16.6 43.2-63.7zM409.7 415.9h42.1V608h-42.1V415.9zM653.9 512c0 74.2-37.1 96.1-93.6 96.1h-65.9V415.9h65.9c56.5 0 93.6 16.1 93.6 96.1z m-43.5 0c0-49.3-17.7-60.6-52.3-60.6h-21.6v120.7h21.6c35.4 0 52.3-13.3 52.3-60.1zM686.5 512c0-74.2 36.3-98.8 92.7-98.8 18.3 0 33.2 2.2 44.8 6.4v36.3c-11.9-4.2-26-6.6-42.1-6.6-34.6 0-49.8 15.5-49.8 62.6 0 50.1 15.2 62.6 49.3 62.6 15.8 0 30.2-2.2 44.8-7.5v36c-11.3 4.7-28.5 8-46.8 8-56.1-0.2-92.9-18.7-92.9-99z" d='M197.7 512c0-78.3 31.6-98.8 87.2-98.8 56.2 0 87.2 20.5 87.2 98.8s-31 98.8-87.2 98.8c-55.7 0-87.2-20.5-87.2-98.8z m130.4 0c0-46.8-7.8-64.5-43.2-64.5-35.2 0-42.9 17.7-42.9 64.5 0 47.1 7.8 63.7 42.9 63.7 35.4 0 43.2-16.6 43.2-63.7zM409.7 415.9h42.1V608h-42.1V415.9zM653.9 512c0 74.2-37.1 96.1-93.6 96.1h-65.9V415.9h65.9c56.5 0 93.6 16.1 93.6 96.1z m-43.5 0c0-49.3-17.7-60.6-52.3-60.6h-21.6v120.7h21.6c35.4 0 52.3-13.3 52.3-60.1zM686.5 512c0-74.2 36.3-98.8 92.7-98.8 18.3 0 33.2 2.2 44.8 6.4v36.3c-11.9-4.2-26-6.6-42.1-6.6-34.6 0-49.8 15.5-49.8 62.6 0 50.1 15.2 62.6 49.3 62.6 15.8 0 30.2-2.2 44.8-7.5v36c-11.3 4.7-28.5 8-46.8 8-56.1-0.2-92.9-18.7-92.9-99z'
p-id="10971" fill="#2c2c2c" stroke="#2c2c2c" stroke-width="20"></path> p-id='10971'
fill='#2c2c2c'
stroke='#2c2c2c'
stroke-width='20'
></path>
</svg> </svg>
); );
} }
......
...@@ -11,7 +11,6 @@ import ModelSettingsVisualEditor from '../pages/Setting/Operation/ModelSettingsV ...@@ -11,7 +11,6 @@ import ModelSettingsVisualEditor from '../pages/Setting/Operation/ModelSettingsV
import GroupRatioSettings from '../pages/Setting/Operation/GroupRatioSettings.js'; import GroupRatioSettings from '../pages/Setting/Operation/GroupRatioSettings.js';
import ModelRatioSettings from '../pages/Setting/Operation/ModelRatioSettings.js'; import ModelRatioSettings from '../pages/Setting/Operation/ModelRatioSettings.js';
import { API, showError, showSuccess } from '../helpers'; import { API, showError, showSuccess } from '../helpers';
import SettingsChats from '../pages/Setting/Operation/SettingsChats.js'; import SettingsChats from '../pages/Setting/Operation/SettingsChats.js';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
...@@ -58,7 +57,7 @@ const OperationSetting = () => { ...@@ -58,7 +57,7 @@ const OperationSetting = () => {
DataExportInterval: 5, DataExportInterval: 5,
DefaultCollapseSidebar: false, // 默认折叠侧边栏 DefaultCollapseSidebar: false, // 默认折叠侧边栏
RetryTimes: 0, RetryTimes: 0,
Chats: "[]", Chats: '[]',
DemoSiteEnabled: false, DemoSiteEnabled: false,
SelfUseModeEnabled: false, SelfUseModeEnabled: false,
AutomaticDisableKeywords: '', AutomaticDisableKeywords: '',
...@@ -154,14 +153,14 @@ const OperationSetting = () => { ...@@ -154,14 +153,14 @@ const OperationSetting = () => {
</Card> </Card>
{/* 合并模型倍率设置和可视化倍率设置 */} {/* 合并模型倍率设置和可视化倍率设置 */}
<Card style={{ marginTop: '10px' }}> <Card style={{ marginTop: '10px' }}>
<Tabs type="line"> <Tabs type='line'>
<Tabs.TabPane tab={t('模型倍率设置')} itemKey="model"> <Tabs.TabPane tab={t('模型倍率设置')} itemKey='model'>
<ModelRatioSettings options={inputs} refresh={onRefresh} /> <ModelRatioSettings options={inputs} refresh={onRefresh} />
</Tabs.TabPane> </Tabs.TabPane>
<Tabs.TabPane tab={t('可视化倍率设置')} itemKey="visual"> <Tabs.TabPane tab={t('可视化倍率设置')} itemKey='visual'>
<ModelSettingsVisualEditor options={inputs} refresh={onRefresh} /> <ModelSettingsVisualEditor options={inputs} refresh={onRefresh} />
</Tabs.TabPane> </Tabs.TabPane>
<Tabs.TabPane tab={t('未设置倍率模型')} itemKey="unset_models"> <Tabs.TabPane tab={t('未设置倍率模型')} itemKey='unset_models'>
<ModelRatioNotSetEditor options={inputs} refresh={onRefresh} /> <ModelRatioNotSetEditor options={inputs} refresh={onRefresh} />
</Tabs.TabPane> </Tabs.TabPane>
</Tabs> </Tabs>
......
import React, { useContext, useEffect, useRef, useState } from 'react'; import React, { useContext, useEffect, useRef, useState } from 'react';
import { Banner, Button, Col, Form, Row, Modal, Space } from '@douyinfe/semi-ui'; import {
Banner,
Button,
Col,
Form,
Row,
Modal,
Space,
} from '@douyinfe/semi-ui';
import { API, showError, showSuccess, timestamp2string } from '../helpers'; import { API, showError, showSuccess, timestamp2string } from '../helpers';
import { marked } from 'marked'; import { marked } from 'marked';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
...@@ -46,7 +54,7 @@ const OtherSetting = () => { ...@@ -46,7 +54,7 @@ const OtherSetting = () => {
HomePageContent: false, HomePageContent: false,
About: false, About: false,
Footer: false, Footer: false,
CheckUpdate: false CheckUpdate: false,
}); });
const handleInputChange = async (value, e) => { const handleInputChange = async (value, e) => {
const name = e.target.id; const name = e.target.id;
...@@ -151,7 +159,10 @@ const OtherSetting = () => { ...@@ -151,7 +159,10 @@ const OtherSetting = () => {
const checkUpdate = async () => { const checkUpdate = async () => {
try { try {
setLoadingInput((loadingInput) => ({ ...loadingInput, CheckUpdate: true })); setLoadingInput((loadingInput) => ({
...loadingInput,
CheckUpdate: true,
}));
// Use a CORS proxy to avoid direct cross-origin requests to GitHub API // Use a CORS proxy to avoid direct cross-origin requests to GitHub API
// Option 1: Use a public CORS proxy service // Option 1: Use a public CORS proxy service
// const proxyUrl = 'https://cors-anywhere.herokuapp.com/'; // const proxyUrl = 'https://cors-anywhere.herokuapp.com/';
...@@ -164,13 +175,13 @@ const OtherSetting = () => { ...@@ -164,13 +175,13 @@ const OtherSetting = () => {
'https://api.github.com/repos/Calcium-Ion/new-api/releases/latest', 'https://api.github.com/repos/Calcium-Ion/new-api/releases/latest',
{ {
headers: { headers: {
'Accept': 'application/json', Accept: 'application/json',
'Content-Type': 'application/json', 'Content-Type': 'application/json',
// Adding User-Agent which is often required by GitHub API // Adding User-Agent which is often required by GitHub API
'User-Agent': 'new-api-update-checker' 'User-Agent': 'new-api-update-checker',
} },
} },
).then(response => response.json()); ).then((response) => response.json());
// Option 3: Use a local proxy endpoint // Option 3: Use a local proxy endpoint
// Create a cached version of the response to avoid frequent GitHub API calls // Create a cached version of the response to avoid frequent GitHub API calls
...@@ -190,7 +201,10 @@ const OtherSetting = () => { ...@@ -190,7 +201,10 @@ const OtherSetting = () => {
console.error('Failed to check for updates:', error); console.error('Failed to check for updates:', error);
showError('检查更新失败,请稍后再试'); showError('检查更新失败,请稍后再试');
} finally { } finally {
setLoadingInput((loadingInput) => ({ ...loadingInput, CheckUpdate: false })); setLoadingInput((loadingInput) => ({
...loadingInput,
CheckUpdate: false,
}));
} }
}; };
const getOptions = async () => { const getOptions = async () => {
...@@ -217,7 +231,10 @@ const OtherSetting = () => { ...@@ -217,7 +231,10 @@ const OtherSetting = () => {
// Function to open GitHub release page // Function to open GitHub release page
const openGitHubRelease = () => { const openGitHubRelease = () => {
window.open(`https://github.com/Calcium-Ion/new-api/releases/tag/${updateData.tag_name}`, '_blank'); window.open(
`https://github.com/Calcium-Ion/new-api/releases/tag/${updateData.tag_name}`,
'_blank',
);
}; };
const getStartTimeString = () => { const getStartTimeString = () => {
...@@ -237,7 +254,11 @@ const OtherSetting = () => { ...@@ -237,7 +254,11 @@ const OtherSetting = () => {
<Text> <Text>
{t('当前版本')}{statusState?.status?.version || t('未知')} {t('当前版本')}{statusState?.status?.version || t('未知')}
</Text> </Text>
<Button type="primary" onClick={checkUpdate} loading={loadingInput['CheckUpdate']}> <Button
type='primary'
onClick={checkUpdate}
loading={loadingInput['CheckUpdate']}
>
{t('检查更新')} {t('检查更新')}
</Button> </Button>
</Space> </Space>
...@@ -245,7 +266,9 @@ const OtherSetting = () => { ...@@ -245,7 +266,9 @@ const OtherSetting = () => {
</Row> </Row>
<Row> <Row>
<Col span={16}> <Col span={16}>
<Text>{t('启动时间')}{getStartTimeString()}</Text> <Text>
{t('启动时间')}{getStartTimeString()}
</Text>
</Col> </Col>
</Row> </Row>
</Form.Section> </Form.Section>
...@@ -300,7 +323,9 @@ const OtherSetting = () => { ...@@ -300,7 +323,9 @@ const OtherSetting = () => {
</Button> </Button>
<Form.TextArea <Form.TextArea
label={t('首页内容')} label={t('首页内容')}
placeholder={t('在此输入首页内容,支持 Markdown & HTML 代码,设置后首页的状态信息将不再显示。如果输入的是一个链接,则会使用该链接作为 iframe 的 src 属性,这允许你设置任意网页作为首页')} placeholder={t(
'在此输入首页内容,支持 Markdown & HTML 代码,设置后首页的状态信息将不再显示。如果输入的是一个链接,则会使用该链接作为 iframe 的 src 属性,这允许你设置任意网页作为首页',
)}
field={'HomePageContent'} field={'HomePageContent'}
onChange={handleInputChange} onChange={handleInputChange}
style={{ fontFamily: 'JetBrains Mono, Consolas' }} style={{ fontFamily: 'JetBrains Mono, Consolas' }}
...@@ -314,7 +339,9 @@ const OtherSetting = () => { ...@@ -314,7 +339,9 @@ const OtherSetting = () => {
</Button> </Button>
<Form.TextArea <Form.TextArea
label={t('关于')} label={t('关于')}
placeholder={t('在此输入新的关于内容,支持 Markdown & HTML 代码。如果输入的是一个链接,则会使用该链接作为 iframe 的 src 属性,这允许你设置任意网页作为关于页面')} placeholder={t(
'在此输入新的关于内容,支持 Markdown & HTML 代码。如果输入的是一个链接,则会使用该链接作为 iframe 的 src 属性,这允许你设置任意网页作为关于页面',
)}
field={'About'} field={'About'}
onChange={handleInputChange} onChange={handleInputChange}
style={{ fontFamily: 'JetBrains Mono, Consolas' }} style={{ fontFamily: 'JetBrains Mono, Consolas' }}
...@@ -327,13 +354,17 @@ const OtherSetting = () => { ...@@ -327,13 +354,17 @@ const OtherSetting = () => {
<Banner <Banner
fullMode={false} fullMode={false}
type='info' type='info'
description={t('移除 One API 的版权标识必须首先获得授权,项目维护需要花费大量精力,如果本项目对你有意义,请主动支持本项目')} description={t(
'移除 One API 的版权标识必须首先获得授权,项目维护需要花费大量精力,如果本项目对你有意义,请主动支持本项目',
)}
closeIcon={null} closeIcon={null}
style={{ marginTop: 15 }} style={{ marginTop: 15 }}
/> />
<Form.Input <Form.Input
label={t('页脚')} label={t('页脚')}
placeholder={t('在此输入新的页脚,留空则使用默认页脚,支持 HTML 代码')} placeholder={t(
'在此输入新的页脚,留空则使用默认页脚,支持 HTML 代码',
)}
field={'Footer'} field={'Footer'}
onChange={handleInputChange} onChange={handleInputChange}
/> />
...@@ -349,15 +380,15 @@ const OtherSetting = () => { ...@@ -349,15 +380,15 @@ const OtherSetting = () => {
onCancel={() => setShowUpdateModal(false)} onCancel={() => setShowUpdateModal(false)}
footer={[ footer={[
<Button <Button
key="details" key='details'
type="primary" type='primary'
onClick={() => { onClick={() => {
setShowUpdateModal(false); setShowUpdateModal(false);
openGitHubRelease(); openGitHubRelease();
}} }}
> >
{t('详情')} {t('详情')}
</Button> </Button>,
]} ]}
> >
<div dangerouslySetInnerHTML={{ __html: updateData.content }}></div> <div dangerouslySetInnerHTML={{ __html: updateData.content }}></div>
......
...@@ -13,7 +13,6 @@ import { UserContext } from '../context/User/index.js'; ...@@ -13,7 +13,6 @@ import { UserContext } from '../context/User/index.js';
import { StatusContext } from '../context/Status/index.js'; import { StatusContext } from '../context/Status/index.js';
const { Sider, Content, Header, Footer } = Layout; const { Sider, Content, Header, Footer } = Layout;
const PageLayout = () => { const PageLayout = () => {
const [userState, userDispatch] = useContext(UserContext); const [userState, userDispatch] = useContext(UserContext);
const [statusState, statusDispatch] = useContext(StatusContext); const [statusState, statusDispatch] = useContext(StatusContext);
...@@ -68,16 +67,20 @@ const PageLayout = () => { ...@@ -68,16 +67,20 @@ const PageLayout = () => {
}, [i18n]); }, [i18n]);
// 获取侧边栏折叠状态 // 获取侧边栏折叠状态
const isSidebarCollapsed = localStorage.getItem('default_collapse_sidebar') === 'true'; const isSidebarCollapsed =
localStorage.getItem('default_collapse_sidebar') === 'true';
return ( return (
<Layout style={{ <Layout
style={{
height: '100vh', height: '100vh',
display: 'flex', display: 'flex',
flexDirection: 'column', flexDirection: 'column',
overflow: styleState.isMobile ? 'visible' : 'hidden' overflow: styleState.isMobile ? 'visible' : 'hidden',
}}> }}
<Header style={{ >
<Header
style={{
padding: 0, padding: 0,
height: 'auto', height: 'auto',
lineHeight: 'normal', lineHeight: 'normal',
...@@ -85,19 +88,23 @@ const PageLayout = () => { ...@@ -85,19 +88,23 @@ const PageLayout = () => {
width: '100%', width: '100%',
top: 0, top: 0,
zIndex: 100, zIndex: 100,
boxShadow: '0 1px 6px rgba(0, 0, 0, 0.08)' boxShadow: '0 1px 6px rgba(0, 0, 0, 0.08)',
}}> }}
>
<HeaderBar /> <HeaderBar />
</Header> </Header>
<Layout style={{ <Layout
style={{
marginTop: styleState.isMobile ? '0' : '56px', marginTop: styleState.isMobile ? '0' : '56px',
height: styleState.isMobile ? 'auto' : 'calc(100vh - 56px)', height: styleState.isMobile ? 'auto' : 'calc(100vh - 56px)',
overflow: styleState.isMobile ? 'visible' : 'auto', overflow: styleState.isMobile ? 'visible' : 'auto',
display: 'flex', display: 'flex',
flexDirection: 'column' flexDirection: 'column',
}}> }}
>
{styleState.showSider && ( {styleState.showSider && (
<Sider style={{ <Sider
style={{
position: 'fixed', position: 'fixed',
left: 0, left: 0,
top: '56px', top: '56px',
...@@ -107,40 +114,51 @@ const PageLayout = () => { ...@@ -107,40 +114,51 @@ const PageLayout = () => {
border: 'none', border: 'none',
paddingRight: '0', paddingRight: '0',
height: 'calc(100vh - 56px)', height: 'calc(100vh - 56px)',
}}> }}
>
<SiderBar /> <SiderBar />
</Sider> </Sider>
)} )}
<Layout style={{ <Layout
marginLeft: styleState.isMobile ? '0' : (styleState.showSider ? (styleState.siderCollapsed ? '60px' : '200px') : '0'), style={{
marginLeft: styleState.isMobile
? '0'
: styleState.showSider
? styleState.siderCollapsed
? '60px'
: '200px'
: '0',
transition: 'margin-left 0.3s ease', transition: 'margin-left 0.3s ease',
flex: '1 1 auto', flex: '1 1 auto',
display: 'flex', display: 'flex',
flexDirection: 'column' flexDirection: 'column',
}}> }}
>
<Content <Content
style={{ style={{
flex: '1 0 auto', flex: '1 0 auto',
overflowY: styleState.isMobile ? 'visible' : 'auto', overflowY: styleState.isMobile ? 'visible' : 'auto',
WebkitOverflowScrolling: 'touch', WebkitOverflowScrolling: 'touch',
padding: styleState.shouldInnerPadding? '24px': '0', padding: styleState.shouldInnerPadding ? '24px' : '0',
position: 'relative', position: 'relative',
marginTop: styleState.isMobile ? '2px' : '0', marginTop: styleState.isMobile ? '2px' : '0',
}} }}
> >
<App /> <App />
</Content> </Content>
<Layout.Footer style={{ <Layout.Footer
style={{
flex: '0 0 auto', flex: '0 0 auto',
width: '100%' width: '100%',
}}> }}
>
<FooterBar /> <FooterBar />
</Layout.Footer> </Layout.Footer>
</Layout> </Layout>
</Layout> </Layout>
<ToastContainer /> <ToastContainer />
</Layout> </Layout>
) );
} };
export default PageLayout; export default PageLayout;
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { Card, Spin, Tabs } from '@douyinfe/semi-ui'; import { Card, Spin, Tabs } from '@douyinfe/semi-ui';
import { API, showError, showSuccess } from '../helpers'; import { API, showError, showSuccess } from '../helpers';
import SettingsChats from '../pages/Setting/Operation/SettingsChats.js'; import SettingsChats from '../pages/Setting/Operation/SettingsChats.js';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
...@@ -24,9 +23,7 @@ const RateLimitSetting = () => { ...@@ -24,9 +23,7 @@ const RateLimitSetting = () => {
if (success) { if (success) {
let newInputs = {}; let newInputs = {};
data.forEach((item) => { data.forEach((item) => {
if ( if (item.key.endsWith('Enabled')) {
item.key.endsWith('Enabled')
) {
newInputs[item.key] = item.value === 'true' ? true : false; newInputs[item.key] = item.value === 'true' ? true : false;
} else { } else {
newInputs[item.key] = item.value; newInputs[item.key] = item.value;
......
...@@ -10,7 +10,8 @@ import { ...@@ -10,7 +10,8 @@ import {
import { ITEMS_PER_PAGE } from '../constants'; import { ITEMS_PER_PAGE } from '../constants';
import { renderQuota } from '../helpers/render'; import { renderQuota } from '../helpers/render';
import { import {
Button, Divider, Button,
Divider,
Form, Form,
Modal, Modal,
Popconfirm, Popconfirm,
...@@ -193,7 +194,9 @@ const RedemptionsTable = () => { ...@@ -193,7 +194,9 @@ const RedemptionsTable = () => {
}; };
const loadRedemptions = async (startIdx, pageSize) => { const loadRedemptions = async (startIdx, pageSize) => {
const res = await API.get(`/api/redemption/?p=${startIdx}&page_size=${pageSize}`); const res = await API.get(
`/api/redemption/?p=${startIdx}&page_size=${pageSize}`,
);
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
const newPageData = data.items; const newPageData = data.items;
...@@ -286,7 +289,9 @@ const RedemptionsTable = () => { ...@@ -286,7 +289,9 @@ const RedemptionsTable = () => {
return; return;
} }
setSearching(true); setSearching(true);
const res = await API.get(`/api/redemption/search?keyword=${keyword}&p=${page}&page_size=${pageSize}`); const res = await API.get(
`/api/redemption/search?keyword=${keyword}&p=${page}&page_size=${pageSize}`,
);
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
const newPageData = data.items; const newPageData = data.items;
...@@ -355,9 +360,11 @@ const RedemptionsTable = () => { ...@@ -355,9 +360,11 @@ const RedemptionsTable = () => {
visiable={showEdit} visiable={showEdit}
handleClose={closeEdit} handleClose={closeEdit}
></EditRedemption> ></EditRedemption>
<Form onSubmit={()=> { <Form
onSubmit={() => {
searchRedemptions(searchKeyword, activePage, pageSize).then(); searchRedemptions(searchKeyword, activePage, pageSize).then();
}}> }}
>
<Form.Input <Form.Input
label={t('搜索关键字')} label={t('搜索关键字')}
field='keyword' field='keyword'
...@@ -369,7 +376,7 @@ const RedemptionsTable = () => { ...@@ -369,7 +376,7 @@ const RedemptionsTable = () => {
onChange={handleKeywordChange} onChange={handleKeywordChange}
/> />
</Form> </Form>
<Divider style={{margin:'5px 0 15px 0'}}/> <Divider style={{ margin: '5px 0 15px 0' }} />
<div> <div>
<Button <Button
theme='light' theme='light'
...@@ -394,7 +401,8 @@ const RedemptionsTable = () => { ...@@ -394,7 +401,8 @@ const RedemptionsTable = () => {
} }
let keys = ''; let keys = '';
for (let i = 0; i < selectedKeys.length; i++) { for (let i = 0; i < selectedKeys.length; i++) {
keys += selectedKeys[i].name + ' ' + selectedKeys[i].key + '\n'; keys +=
selectedKeys[i].name + ' ' + selectedKeys[i].key + '\n';
} }
await copyText(keys); await copyText(keys);
}} }}
...@@ -417,7 +425,7 @@ const RedemptionsTable = () => { ...@@ -417,7 +425,7 @@ const RedemptionsTable = () => {
t('第 {{start}} - {{end}} 条,共 {{total}} 条', { t('第 {{start}} - {{end}} 条,共 {{total}} 条', {
start: page.currentStart, start: page.currentStart,
end: page.currentEnd, end: page.currentEnd,
total: tokenCount total: tokenCount,
}), }),
onPageSizeChange: (size) => { onPageSizeChange: (size) => {
setPageSize(size); setPageSize(size);
......
import React, { useContext, useEffect, useState } from 'react'; import React, { useContext, useEffect, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom'; import { Link, useNavigate } from 'react-router-dom';
import { API, getLogo, showError, showInfo, showSuccess, updateAPI } from '../helpers'; import {
API,
getLogo,
showError,
showInfo,
showSuccess,
updateAPI,
} from '../helpers';
import Turnstile from 'react-turnstile'; import Turnstile from 'react-turnstile';
import { Button, Card, Divider, Form, Icon, Layout, Modal } from '@douyinfe/semi-ui'; import {
Button,
Card,
Divider,
Form,
Icon,
Layout,
Modal,
} from '@douyinfe/semi-ui';
import Title from '@douyinfe/semi-ui/lib/es/typography/title'; import Title from '@douyinfe/semi-ui/lib/es/typography/title';
import Text from '@douyinfe/semi-ui/lib/es/typography/text'; import Text from '@douyinfe/semi-ui/lib/es/typography/text';
import { IconGithubLogo } from '@douyinfe/semi-icons'; import { IconGithubLogo } from '@douyinfe/semi-icons';
import {onGitHubOAuthClicked, onLinuxDOOAuthClicked, onOIDCClicked} from './utils.js'; import {
import OIDCIcon from "./OIDCIcon.js"; onGitHubOAuthClicked,
onLinuxDOOAuthClicked,
onOIDCClicked,
} from './utils.js';
import OIDCIcon from './OIDCIcon.js';
import LinuxDoIcon from './LinuxDoIcon.js'; import LinuxDoIcon from './LinuxDoIcon.js';
import WeChatIcon from './WeChatIcon.js'; import WeChatIcon from './WeChatIcon.js';
import TelegramLoginButton from 'react-telegram-login/src'; import TelegramLoginButton from 'react-telegram-login/src';
...@@ -22,7 +41,7 @@ const RegisterForm = () => { ...@@ -22,7 +41,7 @@ const RegisterForm = () => {
password: '', password: '',
password2: '', password2: '',
email: '', email: '',
verification_code: '' verification_code: '',
}); });
const { username, password, password2 } = inputs; const { username, password, password2 } = inputs;
const [showEmailVerification, setShowEmailVerification] = useState(false); const [showEmailVerification, setShowEmailVerification] = useState(false);
...@@ -54,7 +73,6 @@ const RegisterForm = () => { ...@@ -54,7 +73,6 @@ const RegisterForm = () => {
} }
}); });
const onWeChatLoginClicked = () => { const onWeChatLoginClicked = () => {
setShowWeChatLoginModal(true); setShowWeChatLoginModal(true);
}; };
...@@ -106,7 +124,7 @@ const RegisterForm = () => { ...@@ -106,7 +124,7 @@ const RegisterForm = () => {
inputs.aff_code = affCode; inputs.aff_code = affCode;
const res = await API.post( const res = await API.post(
`/api/user/register?turnstile=${turnstileToken}`, `/api/user/register?turnstile=${turnstileToken}`,
inputs inputs,
); );
const { success, message } = res.data; const { success, message } = res.data;
if (success) { if (success) {
...@@ -127,7 +145,7 @@ const RegisterForm = () => { ...@@ -127,7 +145,7 @@ const RegisterForm = () => {
} }
setLoading(true); setLoading(true);
const res = await API.get( const res = await API.get(
`/api/verification?email=${inputs.email}&turnstile=${turnstileToken}` `/api/verification?email=${inputs.email}&turnstile=${turnstileToken}`,
); );
const { success, message } = res.data; const { success, message } = res.data;
if (success) { if (success) {
...@@ -169,7 +187,6 @@ const RegisterForm = () => { ...@@ -169,7 +187,6 @@ const RegisterForm = () => {
} }
}; };
return ( return (
<div> <div>
<Layout> <Layout>
...@@ -179,7 +196,7 @@ const RegisterForm = () => { ...@@ -179,7 +196,7 @@ const RegisterForm = () => {
style={{ style={{
justifyContent: 'center', justifyContent: 'center',
display: 'flex', display: 'flex',
marginTop: 120 marginTop: 120,
}} }}
> >
<div style={{ width: 500 }}> <div style={{ width: 500 }}>
...@@ -187,28 +204,28 @@ const RegisterForm = () => { ...@@ -187,28 +204,28 @@ const RegisterForm = () => {
<Title heading={2} style={{ textAlign: 'center' }}> <Title heading={2} style={{ textAlign: 'center' }}>
{t('新用户注册')} {t('新用户注册')}
</Title> </Title>
<Form size="large"> <Form size='large'>
<Form.Input <Form.Input
field={'username'} field={'username'}
label={t('用户名')} label={t('用户名')}
placeholder={t('用户名')} placeholder={t('用户名')}
name="username" name='username'
onChange={(value) => handleChange('username', value)} onChange={(value) => handleChange('username', value)}
/> />
<Form.Input <Form.Input
field={'password'} field={'password'}
label={t('密码')} label={t('密码')}
placeholder={t('输入密码,最短 8 位,最长 20 位')} placeholder={t('输入密码,最短 8 位,最长 20 位')}
name="password" name='password'
type="password" type='password'
onChange={(value) => handleChange('password', value)} onChange={(value) => handleChange('password', value)}
/> />
<Form.Input <Form.Input
field={'password2'} field={'password2'}
label={t('确认密码')} label={t('确认密码')}
placeholder={t('确认密码')} placeholder={t('确认密码')}
name="password2" name='password2'
type="password" type='password'
onChange={(value) => handleChange('password2', value)} onChange={(value) => handleChange('password2', value)}
/> />
{showEmailVerification ? ( {showEmailVerification ? (
...@@ -218,10 +235,13 @@ const RegisterForm = () => { ...@@ -218,10 +235,13 @@ const RegisterForm = () => {
label={t('邮箱')} label={t('邮箱')}
placeholder={t('输入邮箱地址')} placeholder={t('输入邮箱地址')}
onChange={(value) => handleChange('email', value)} onChange={(value) => handleChange('email', value)}
name="email" name='email'
type="email" type='email'
suffix={ suffix={
<Button onClick={sendVerificationCode} disabled={loading}> <Button
onClick={sendVerificationCode}
disabled={loading}
>
{t('获取验证码')} {t('获取验证码')}
</Button> </Button>
} }
...@@ -230,8 +250,10 @@ const RegisterForm = () => { ...@@ -230,8 +250,10 @@ const RegisterForm = () => {
field={'verification_code'} field={'verification_code'}
label={t('验证码')} label={t('验证码')}
placeholder={t('输入验证码')} placeholder={t('输入验证码')}
onChange={(value) => handleChange('verification_code', value)} onChange={(value) =>
name="verification_code" handleChange('verification_code', value)
}
name='verification_code'
/> />
</> </>
) : ( ) : (
...@@ -252,14 +274,12 @@ const RegisterForm = () => { ...@@ -252,14 +274,12 @@ const RegisterForm = () => {
style={{ style={{
display: 'flex', display: 'flex',
justifyContent: 'space-between', justifyContent: 'space-between',
marginTop: 20 marginTop: 20,
}} }}
> >
<Text> <Text>
{t('已有账户?')} {t('已有账户?')}
<Link to="/login"> <Link to='/login'>{t('点击登录')}</Link>
{t('点击登录')}
</Link>
</Text> </Text>
</div> </div>
{status.github_oauth || {status.github_oauth ||
...@@ -294,7 +314,10 @@ const RegisterForm = () => { ...@@ -294,7 +314,10 @@ const RegisterForm = () => {
type='primary' type='primary'
icon={<OIDCIcon />} icon={<OIDCIcon />}
onClick={() => onClick={() =>
onOIDCClicked(status.oidc_authorization_endpoint, status.oidc_client_id) onOIDCClicked(
status.oidc_authorization_endpoint,
status.oidc_client_id,
)
} }
/> />
) : ( ) : (
...@@ -365,7 +388,9 @@ const RegisterForm = () => { ...@@ -365,7 +388,9 @@ const RegisterForm = () => {
</div> </div>
<div style={{ textAlign: 'center' }}> <div style={{ textAlign: 'center' }}>
<p> <p>
{t('微信扫码关注公众号,输入「验证码」获取验证码(三分钟内有效)')} {t(
'微信扫码关注公众号,输入「验证码」获取验证码(三分钟内有效)',
)}
</p> </p>
</div> </div>
<Form size='large'> <Form size='large'>
......
...@@ -15,10 +15,13 @@ import { ...@@ -15,10 +15,13 @@ import {
import '../index.css'; import '../index.css';
import { import {
IconCalendarClock, IconChecklistStroked, IconCalendarClock,
IconComment, IconCommentStroked, IconChecklistStroked,
IconComment,
IconCommentStroked,
IconCreditCard, IconCreditCard,
IconGift, IconHelpCircle, IconGift,
IconHelpCircle,
IconHistogram, IconHistogram,
IconHome, IconHome,
IconImage, IconImage,
...@@ -26,9 +29,16 @@ import { ...@@ -26,9 +29,16 @@ import {
IconLayers, IconLayers,
IconPriceTag, IconPriceTag,
IconSetting, IconSetting,
IconUser IconUser,
} from '@douyinfe/semi-icons'; } from '@douyinfe/semi-icons';
import { Avatar, Dropdown, Layout, Nav, Switch, Divider } from '@douyinfe/semi-ui'; import {
Avatar,
Dropdown,
Layout,
Nav,
Switch,
Divider,
} from '@douyinfe/semi-ui';
import { setStatusData } from '../helpers/data.js'; import { setStatusData } from '../helpers/data.js';
import { stringToColor } from '../helpers/render.js'; import { stringToColor } from '../helpers/render.js';
import { useSetTheme, useTheme } from '../context/Theme/index.js'; import { useSetTheme, useTheme } from '../context/Theme/index.js';
...@@ -44,21 +54,23 @@ const navItemStyle = { ...@@ -44,21 +54,23 @@ const navItemStyle = {
// 自定义侧边栏按钮悬停样式 // 自定义侧边栏按钮悬停样式
const navItemHoverStyle = { const navItemHoverStyle = {
backgroundColor: 'var(--semi-color-primary-light-default)', backgroundColor: 'var(--semi-color-primary-light-default)',
color: 'var(--semi-color-primary)' color: 'var(--semi-color-primary)',
}; };
// 自定义侧边栏按钮选中样式 // 自定义侧边栏按钮选中样式
const navItemSelectedStyle = { const navItemSelectedStyle = {
backgroundColor: 'var(--semi-color-primary-light-default)', backgroundColor: 'var(--semi-color-primary-light-default)',
color: 'var(--semi-color-primary)', color: 'var(--semi-color-primary)',
fontWeight: '600' fontWeight: '600',
}; };
// 自定义图标样式 // 自定义图标样式
const iconStyle = (itemKey, selectedKeys) => { const iconStyle = (itemKey, selectedKeys) => {
return { return {
fontSize: '18px', fontSize: '18px',
color: selectedKeys.includes(itemKey) ? 'var(--semi-color-primary)' : 'var(--semi-color-text-2)', color: selectedKeys.includes(itemKey)
? 'var(--semi-color-primary)'
: 'var(--semi-color-text-2)',
}; };
}; };
...@@ -99,8 +111,24 @@ const SiderBar = () => { ...@@ -99,8 +111,24 @@ const SiderBar = () => {
// 预先计算所有可能的图标样式 // 预先计算所有可能的图标样式
const allItemKeys = useMemo(() => { const allItemKeys = useMemo(() => {
const keys = ['home', 'channel', 'token', 'redemption', 'topup', 'user', 'log', 'midjourney', const keys = [
'setting', 'about', 'chat', 'detail', 'pricing', 'task', 'playground', 'personal']; 'home',
'channel',
'token',
'redemption',
'topup',
'user',
'log',
'midjourney',
'setting',
'about',
'chat',
'detail',
'pricing',
'task',
'playground',
'personal',
];
// 添加聊天项的keys // 添加聊天项的keys
for (let i = 0; i < chatItems.length; i++) { for (let i = 0; i < chatItems.length; i++) {
keys.push('chat' + i); keys.push('chat' + i);
...@@ -111,7 +139,7 @@ const SiderBar = () => { ...@@ -111,7 +139,7 @@ const SiderBar = () => {
// 使用useMemo一次性计算所有图标样式 // 使用useMemo一次性计算所有图标样式
const iconStyles = useMemo(() => { const iconStyles = useMemo(() => {
const styles = {}; const styles = {};
allItemKeys.forEach(key => { allItemKeys.forEach((key) => {
styles[key] = iconStyle(key, selectedKeys); styles[key] = iconStyle(key, selectedKeys);
}); });
return styles; return styles;
...@@ -157,10 +185,8 @@ const SiderBar = () => { ...@@ -157,10 +185,8 @@ const SiderBar = () => {
to: '/task', to: '/task',
icon: <IconChecklistStroked />, icon: <IconChecklistStroked />,
className: className:
localStorage.getItem('enable_task') === 'true' localStorage.getItem('enable_task') === 'true' ? '' : 'tableHiddle',
? '' },
: 'tableHiddle',
}
], ],
[ [
localStorage.getItem('enable_data_export'), localStorage.getItem('enable_data_export'),
...@@ -276,7 +302,7 @@ const SiderBar = () => { ...@@ -276,7 +302,7 @@ const SiderBar = () => {
} }
} catch (e) { } catch (e) {
console.error(e); console.error(e);
showError('聊天数据解析失败') showError('聊天数据解析失败');
} }
} }
}, []); }, []);
...@@ -284,7 +310,9 @@ const SiderBar = () => { ...@@ -284,7 +310,9 @@ const SiderBar = () => {
// Update the useEffect for route selection // Update the useEffect for route selection
useEffect(() => { useEffect(() => {
const currentPath = location.pathname; const currentPath = location.pathname;
let matchingKey = Object.keys(routerMapState).find(key => routerMapState[key] === currentPath); let matchingKey = Object.keys(routerMapState).find(
(key) => routerMapState[key] === currentPath,
);
// Handle chat routes // Handle chat routes
if (!matchingKey && currentPath.startsWith('/chat/')) { if (!matchingKey && currentPath.startsWith('/chat/')) {
...@@ -325,7 +353,7 @@ const SiderBar = () => { ...@@ -325,7 +353,7 @@ const SiderBar = () => {
return ( return (
<> <>
<Nav <Nav
className="custom-sidebar-nav" className='custom-sidebar-nav'
style={{ style={{
width: isCollapsed ? '60px' : '200px', width: isCollapsed ? '60px' : '200px',
boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)', boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)',
...@@ -351,7 +379,9 @@ const SiderBar = () => { ...@@ -351,7 +379,9 @@ const SiderBar = () => {
// 确保在收起侧边栏时有选中的项目,避免不必要的计算 // 确保在收起侧边栏时有选中的项目,避免不必要的计算
if (selectedKeys.length === 0) { if (selectedKeys.length === 0) {
const currentPath = location.pathname; const currentPath = location.pathname;
const matchingKey = Object.keys(routerMapState).find(key => routerMapState[key] === currentPath); const matchingKey = Object.keys(routerMapState).find(
(key) => routerMapState[key] === currentPath,
);
if (matchingKey) { if (matchingKey) {
setSelectedKeys([matchingKey]); setSelectedKeys([matchingKey]);
...@@ -385,7 +415,7 @@ const SiderBar = () => { ...@@ -385,7 +415,7 @@ const SiderBar = () => {
// 如果点击的是已经展开的子菜单的父项,则收起子菜单 // 如果点击的是已经展开的子菜单的父项,则收起子菜单
if (openedKeys.includes(key.itemKey)) { if (openedKeys.includes(key.itemKey)) {
setOpenedKeys(openedKeys.filter(k => k !== key.itemKey)); setOpenedKeys(openedKeys.filter((k) => k !== key.itemKey));
} }
setSelectedKeys([key.itemKey]); setSelectedKeys([key.itemKey]);
...@@ -403,7 +433,9 @@ const SiderBar = () => { ...@@ -403,7 +433,9 @@ const SiderBar = () => {
key={item.itemKey} key={item.itemKey}
itemKey={item.itemKey} itemKey={item.itemKey}
text={item.text} text={item.text}
icon={React.cloneElement(item.icon, { style: iconStyles[item.itemKey] })} icon={React.cloneElement(item.icon, {
style: iconStyles[item.itemKey],
})}
> >
{item.items.map((subItem) => ( {item.items.map((subItem) => (
<Nav.Item <Nav.Item
...@@ -420,7 +452,9 @@ const SiderBar = () => { ...@@ -420,7 +452,9 @@ const SiderBar = () => {
key={item.itemKey} key={item.itemKey}
itemKey={item.itemKey} itemKey={item.itemKey}
text={item.text} text={item.text}
icon={React.cloneElement(item.icon, { style: iconStyles[item.itemKey] })} icon={React.cloneElement(item.icon, {
style: iconStyles[item.itemKey],
})}
/> />
); );
} }
...@@ -436,7 +470,9 @@ const SiderBar = () => { ...@@ -436,7 +470,9 @@ const SiderBar = () => {
key={item.itemKey} key={item.itemKey}
itemKey={item.itemKey} itemKey={item.itemKey}
text={item.text} text={item.text}
icon={React.cloneElement(item.icon, { style: iconStyles[item.itemKey] })} icon={React.cloneElement(item.icon, {
style: iconStyles[item.itemKey],
})}
className={item.className} className={item.className}
/> />
))} ))}
...@@ -453,7 +489,9 @@ const SiderBar = () => { ...@@ -453,7 +489,9 @@ const SiderBar = () => {
key={item.itemKey} key={item.itemKey}
itemKey={item.itemKey} itemKey={item.itemKey}
text={item.text} text={item.text}
icon={React.cloneElement(item.icon, { style: iconStyles[item.itemKey] })} icon={React.cloneElement(item.icon, {
style: iconStyles[item.itemKey],
})}
className={item.className} className={item.className}
/> />
))} ))}
...@@ -470,7 +508,9 @@ const SiderBar = () => { ...@@ -470,7 +508,9 @@ const SiderBar = () => {
key={item.itemKey} key={item.itemKey}
itemKey={item.itemKey} itemKey={item.itemKey}
text={item.text} text={item.text}
icon={React.cloneElement(item.icon, { style: iconStyles[item.itemKey] })} icon={React.cloneElement(item.icon, {
style: iconStyles[item.itemKey],
})}
className={item.className} className={item.className}
/> />
))} ))}
...@@ -480,14 +520,12 @@ const SiderBar = () => { ...@@ -480,14 +520,12 @@ const SiderBar = () => {
paddingBottom: styleState?.isMobile ? '112px' : '', paddingBottom: styleState?.isMobile ? '112px' : '',
}} }}
collapseButton={true} collapseButton={true}
collapseText={(collapsed)=> collapseText={(collapsed) => {
{ if (collapsed) {
if(collapsed){ return t('展开侧边栏');
return t('展开侧边栏')
}
return t('收起侧边栏')
}
} }
return t('收起侧边栏');
}}
/> />
</Nav> </Nav>
</> </>
......
...@@ -8,14 +8,16 @@ import { ...@@ -8,14 +8,16 @@ import {
} from '../helpers'; } from '../helpers';
import { ITEMS_PER_PAGE } from '../constants'; import { ITEMS_PER_PAGE } from '../constants';
import {renderGroup, renderQuota} from '../helpers/render'; import { renderGroup, renderQuota } from '../helpers/render';
import { import {
Button, Divider, Button,
Divider,
Dropdown, Dropdown,
Form, Form,
Modal, Modal,
Popconfirm, Popconfirm,
Popover, Space, Popover,
Space,
SplitButtonGroup, SplitButtonGroup,
Table, Table,
Tag, Tag,
...@@ -30,7 +32,6 @@ function renderTimestamp(timestamp) { ...@@ -30,7 +32,6 @@ function renderTimestamp(timestamp) {
} }
const TokensTable = () => { const TokensTable = () => {
const { t } = useTranslation(); const { t } = useTranslation();
const renderStatus = (status, model_limits_enabled = false) => { const renderStatus = (status, model_limits_enabled = false) => {
...@@ -86,12 +87,14 @@ const TokensTable = () => { ...@@ -86,12 +87,14 @@ const TokensTable = () => {
dataIndex: 'status', dataIndex: 'status',
key: 'status', key: 'status',
render: (text, record, index) => { render: (text, record, index) => {
return <div> return (
<div>
<Space> <Space>
{renderStatus(text, record.model_limits_enabled)} {renderStatus(text, record.model_limits_enabled)}
{renderGroup(record.group)} {renderGroup(record.group)}
</Space> </Space>
</div>; </div>
);
}, },
}, },
{ {
...@@ -143,7 +146,7 @@ const TokensTable = () => { ...@@ -143,7 +146,7 @@ const TokensTable = () => {
dataIndex: 'operate', dataIndex: 'operate',
render: (text, record, index) => { render: (text, record, index) => {
let chats = localStorage.getItem('chats'); let chats = localStorage.getItem('chats');
let chatsArray = [] let chatsArray = [];
let shouldUseCustom = true; let shouldUseCustom = true;
if (shouldUseCustom) { if (shouldUseCustom) {
...@@ -153,7 +156,7 @@ const TokensTable = () => { ...@@ -153,7 +156,7 @@ const TokensTable = () => {
// check chats is array // check chats is array
if (Array.isArray(chats)) { if (Array.isArray(chats)) {
for (let i = 0; i < chats.length; i++) { for (let i = 0; i < chats.length; i++) {
let chat = {} let chat = {};
chat.node = 'item'; chat.node = 'item';
// c is a map // c is a map
// chat.key = chats[i].name; // chat.key = chats[i].name;
...@@ -164,13 +167,12 @@ const TokensTable = () => { ...@@ -164,13 +167,12 @@ const TokensTable = () => {
chat.name = key; chat.name = key;
chat.onClick = () => { chat.onClick = () => {
onOpenLink(key, chats[i][key], record); onOpenLink(key, chats[i][key], record);
} };
} }
} }
chatsArray.push(chat); chatsArray.push(chat);
} }
} }
} catch (e) { } catch (e) {
console.log(e); console.log(e);
showError(t('聊天链接配置错误,请联系管理员')); showError(t('聊天链接配置错误,请联系管理员'));
...@@ -208,7 +210,11 @@ const TokensTable = () => { ...@@ -208,7 +210,11 @@ const TokensTable = () => {
if (chatsArray.length === 0) { if (chatsArray.length === 0) {
showError(t('请联系管理员配置聊天链接')); showError(t('请联系管理员配置聊天链接'));
} else { } else {
onOpenLink('default', chats[0][Object.keys(chats[0])[0]], record); onOpenLink(
'default',
chats[0][Object.keys(chats[0])[0]],
record,
);
} }
}} }}
> >
...@@ -539,7 +545,7 @@ const TokensTable = () => { ...@@ -539,7 +545,7 @@ const TokensTable = () => {
{t('查询')} {t('查询')}
</Button> </Button>
</Form> </Form>
<Divider style={{margin:'15px 0'}}/> <Divider style={{ margin: '15px 0' }} />
<div> <div>
<Button <Button
theme='light' theme='light'
...@@ -588,7 +594,7 @@ const TokensTable = () => { ...@@ -588,7 +594,7 @@ const TokensTable = () => {
t('第 {{start}} - {{end}} 条,共 {{total}} 条', { t('第 {{start}} - {{end}} 条,共 {{total}} 条', {
start: page.currentStart, start: page.currentStart,
end: page.currentEnd, end: page.currentEnd,
total: tokens.length total: tokens.length,
}), }),
onPageSizeChange: (size) => { onPageSizeChange: (size) => {
setPageSize(size); setPageSize(size);
......
...@@ -167,7 +167,11 @@ const UsersTable = () => { ...@@ -167,7 +167,11 @@ const UsersTable = () => {
manageUser(record.id, 'demote', record); manageUser(record.id, 'demote', record);
}} }}
> >
<Button theme='light' type='secondary' style={{ marginRight: 1 }}> <Button
theme='light'
type='secondary'
style={{ marginRight: 1 }}
>
{t('降级')} {t('降级')}
</Button> </Button>
</Popconfirm> </Popconfirm>
...@@ -261,7 +265,7 @@ const UsersTable = () => { ...@@ -261,7 +265,7 @@ const UsersTable = () => {
users[i].key = users[i].id; users[i].key = users[i].id;
} }
setUsers(users); setUsers(users);
} };
const loadUsers = async (startIdx, pageSize) => { const loadUsers = async (startIdx, pageSize) => {
const res = await API.get(`/api/user/?p=${startIdx}&page_size=${pageSize}`); const res = await API.get(`/api/user/?p=${startIdx}&page_size=${pageSize}`);
...@@ -277,7 +281,6 @@ const UsersTable = () => { ...@@ -277,7 +281,6 @@ const UsersTable = () => {
setLoading(false); setLoading(false);
}; };
useEffect(() => { useEffect(() => {
loadUsers(0, pageSize) loadUsers(0, pageSize)
.then() .then()
...@@ -327,14 +330,21 @@ const UsersTable = () => { ...@@ -327,14 +330,21 @@ const UsersTable = () => {
} }
}; };
const searchUsers = async (startIdx, pageSize, searchKeyword, searchGroup) => { const searchUsers = async (
startIdx,
pageSize,
searchKeyword,
searchGroup,
) => {
if (searchKeyword === '' && searchGroup === '') { if (searchKeyword === '' && searchGroup === '') {
// if keyword is blank, load files instead. // if keyword is blank, load files instead.
await loadUsers(startIdx, pageSize); await loadUsers(startIdx, pageSize);
return; return;
} }
setSearching(true); setSearching(true);
const res = await API.get(`/api/user/search?keyword=${searchKeyword}&group=${searchGroup}&p=${startIdx}&page_size=${pageSize}`); const res = await API.get(
`/api/user/search?keyword=${searchKeyword}&group=${searchGroup}&p=${startIdx}&page_size=${pageSize}`,
);
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
const newPageData = data.items; const newPageData = data.items;
...@@ -372,7 +382,7 @@ const UsersTable = () => { ...@@ -372,7 +382,7 @@ const UsersTable = () => {
}; };
const refresh = async () => { const refresh = async () => {
setActivePage(1) setActivePage(1);
if (searchKeyword === '') { if (searchKeyword === '') {
await loadUsers(activePage, pageSize); await loadUsers(activePage, pageSize);
} else { } else {
...@@ -431,7 +441,9 @@ const UsersTable = () => { ...@@ -431,7 +441,9 @@ const UsersTable = () => {
> >
<div style={{ display: 'flex' }}> <div style={{ display: 'flex' }}>
<Space> <Space>
<Tooltip content={t('支持搜索用户的 ID、用户名、显示名称和邮箱地址')}> <Tooltip
content={t('支持搜索用户的 ID、用户名、显示名称和邮箱地址')}
>
<Form.Input <Form.Input
label={t('搜索关键字')} label={t('搜索关键字')}
icon='search' icon='search'
...@@ -482,7 +494,7 @@ const UsersTable = () => { ...@@ -482,7 +494,7 @@ const UsersTable = () => {
t('第 {{start}} - {{end}} 条,共 {{total}} 条', { t('第 {{start}} - {{end}} 条,共 {{total}} 条', {
start: page.currentStart, start: page.currentStart,
end: page.currentEnd, end: page.currentEnd,
total: users.length total: users.length,
}), }),
currentPage: activePage, currentPage: activePage,
pageSize: pageSize, pageSize: pageSize,
......
import { Input, Typography } from '@douyinfe/semi-ui'; import { Input, Typography } from '@douyinfe/semi-ui';
import React from 'react'; import React from 'react';
const TextInput = ({ label, name, value, onChange, placeholder, type = 'text' }) => { const TextInput = ({
label,
name,
value,
onChange,
placeholder,
type = 'text',
}) => {
return ( return (
<> <>
<div style={{ marginTop: 10 }}> <div style={{ marginTop: 10 }}>
...@@ -12,10 +19,10 @@ const TextInput = ({ label, name, value, onChange, placeholder, type = 'text' }) ...@@ -12,10 +19,10 @@ const TextInput = ({ label, name, value, onChange, placeholder, type = 'text' })
placeholder={placeholder} placeholder={placeholder}
onChange={(value) => onChange(value)} onChange={(value) => onChange(value)}
value={value} value={value}
autoComplete="new-password" autoComplete='new-password'
/> />
</> </>
); );
} };
export default TextInput; export default TextInput;
...@@ -12,10 +12,10 @@ const TextNumberInput = ({ label, name, value, onChange, placeholder }) => { ...@@ -12,10 +12,10 @@ const TextNumberInput = ({ label, name, value, onChange, placeholder }) => {
placeholder={placeholder} placeholder={placeholder}
onChange={(value) => onChange(value)} onChange={(value) => onChange(value)}
value={value} value={value}
autoComplete="new-password" autoComplete='new-password'
/> />
</> </>
); );
} };
export default TextNumberInput; export default TextNumberInput;
...@@ -13,7 +13,7 @@ async function fetchTokenKeys() { ...@@ -13,7 +13,7 @@ async function fetchTokenKeys() {
throw new Error('Failed to fetch token keys'); throw new Error('Failed to fetch token keys');
} }
} catch (error) { } catch (error) {
console.error("Error fetching token keys:", error); console.error('Error fetching token keys:', error);
return []; return [];
} }
} }
...@@ -27,7 +27,7 @@ function getServerAddress() { ...@@ -27,7 +27,7 @@ function getServerAddress() {
status = JSON.parse(status); status = JSON.parse(status);
serverAddress = status.server_address || ''; serverAddress = status.server_address || '';
} catch (error) { } catch (error) {
console.error("Failed to parse status from localStorage:", error); console.error('Failed to parse status from localStorage:', error);
} }
} }
......
...@@ -20,13 +20,12 @@ export async function onOIDCClicked(auth_url, client_id, openInNewTab = false) { ...@@ -20,13 +20,12 @@ export async function onOIDCClicked(auth_url, client_id, openInNewTab = false) {
const state = await getOAuthState(); const state = await getOAuthState();
if (!state) return; if (!state) return;
const redirect_uri = `${window.location.origin}/oauth/oidc`; const redirect_uri = `${window.location.origin}/oauth/oidc`;
const response_type = "code"; const response_type = 'code';
const scope = "openid profile email"; const scope = 'openid profile email';
const url = `${auth_url}?client_id=${client_id}&redirect_uri=${redirect_uri}&response_type=${response_type}&scope=${scope}&state=${state}`; const url = `${auth_url}?client_id=${client_id}&redirect_uri=${redirect_uri}&response_type=${response_type}&scope=${scope}&state=${state}`;
if (openInNewTab) { if (openInNewTab) {
window.open(url); window.open(url);
} else } else {
{
window.location.href = url; window.location.href = url;
} }
} }
......
...@@ -3,86 +3,86 @@ export const CHANNEL_OPTIONS = [ ...@@ -3,86 +3,86 @@ export const CHANNEL_OPTIONS = [
{ {
value: 2, value: 2,
color: 'light-blue', color: 'light-blue',
label: 'Midjourney Proxy' label: 'Midjourney Proxy',
}, },
{ {
value: 5, value: 5,
color: 'blue', color: 'blue',
label: 'Midjourney Proxy Plus' label: 'Midjourney Proxy Plus',
}, },
{ {
value: 36, value: 36,
color: 'purple', color: 'purple',
label: 'Suno API' label: 'Suno API',
}, },
{ value: 4, color: 'grey', label: 'Ollama' }, { value: 4, color: 'grey', label: 'Ollama' },
{ {
value: 14, value: 14,
color: 'indigo', color: 'indigo',
label: 'Anthropic Claude' label: 'Anthropic Claude',
}, },
{ {
value: 33, value: 33,
color: 'indigo', color: 'indigo',
label: 'AWS Claude' label: 'AWS Claude',
}, },
{ value: 41, color: 'blue', label: 'Vertex AI' }, { value: 41, color: 'blue', label: 'Vertex AI' },
{ {
value: 3, value: 3,
color: 'teal', color: 'teal',
label: 'Azure OpenAI' label: 'Azure OpenAI',
}, },
{ {
value: 34, value: 34,
color: 'purple', color: 'purple',
label: 'Cohere' label: 'Cohere',
}, },
{ value: 39, color: 'grey', label: 'Cloudflare' }, { value: 39, color: 'grey', label: 'Cloudflare' },
{ value: 43, color: 'blue', label: 'DeepSeek' }, { value: 43, color: 'blue', label: 'DeepSeek' },
{ {
value: 15, value: 15,
color: 'blue', color: 'blue',
label: '百度文心千帆' label: '百度文心千帆',
}, },
{ {
value: 46, value: 46,
color: 'blue', color: 'blue',
label: '百度文心千帆V2' label: '百度文心千帆V2',
}, },
{ {
value: 17, value: 17,
color: 'orange', color: 'orange',
label: '阿里通义千问' label: '阿里通义千问',
}, },
{ {
value: 18, value: 18,
color: 'blue', color: 'blue',
label: '讯飞星火认知' label: '讯飞星火认知',
}, },
{ {
value: 16, value: 16,
color: 'violet', color: 'violet',
label: '智谱 ChatGLM' label: '智谱 ChatGLM',
}, },
{ {
value: 26, value: 26,
color: 'purple', color: 'purple',
label: '智谱 GLM-4V' label: '智谱 GLM-4V',
}, },
{ {
value: 24, value: 24,
color: 'orange', color: 'orange',
label: 'Google Gemini' label: 'Google Gemini',
}, },
{ {
value: 11, value: 11,
color: 'orange', color: 'orange',
label: 'Google PaLM2' label: 'Google PaLM2',
}, },
{ {
value: 47, value: 47,
color: 'blue', color: 'blue',
label: 'Xinference' label: 'Xinference',
}, },
{ value: 25, color: 'green', label: 'Moonshot' }, { value: 25, color: 'green', label: 'Moonshot' },
{ value: 20, color: 'green', label: 'OpenRouter' }, { value: 20, color: 'green', label: 'OpenRouter' },
...@@ -98,21 +98,21 @@ export const CHANNEL_OPTIONS = [ ...@@ -98,21 +98,21 @@ export const CHANNEL_OPTIONS = [
{ {
value: 22, value: 22,
color: 'blue', color: 'blue',
label: '知识库:FastGPT' label: '知识库:FastGPT',
}, },
{ {
value: 21, value: 21,
color: 'purple', color: 'purple',
label: '知识库:AI Proxy' label: '知识库:AI Proxy',
}, },
{ {
value: 44, value: 44,
color: 'purple', color: 'purple',
label: '嵌入模型:MokaAI M3E' label: '嵌入模型:MokaAI M3E',
}, },
{ {
value: 45, value: 45,
color: 'blue', color: 'blue',
label: '字节火山方舟、豆包、DeepSeek通用' label: '字节火山方舟、豆包、DeepSeek通用',
}, },
]; ];
...@@ -19,25 +19,25 @@ export const StyleProvider = ({ children }) => { ...@@ -19,25 +19,25 @@ export const StyleProvider = ({ children }) => {
if ('type' in action) { if ('type' in action) {
switch (action.type) { switch (action.type) {
case 'TOGGLE_SIDER': case 'TOGGLE_SIDER':
setState(prev => ({ ...prev, showSider: !prev.showSider })); setState((prev) => ({ ...prev, showSider: !prev.showSider }));
break; break;
case 'SET_SIDER': case 'SET_SIDER':
setState(prev => ({ ...prev, showSider: action.payload })); setState((prev) => ({ ...prev, showSider: action.payload }));
break; break;
case 'SET_MOBILE': case 'SET_MOBILE':
setState(prev => ({ ...prev, isMobile: action.payload })); setState((prev) => ({ ...prev, isMobile: action.payload }));
break; break;
case 'SET_SIDER_COLLAPSED': case 'SET_SIDER_COLLAPSED':
setState(prev => ({ ...prev, siderCollapsed: action.payload })); setState((prev) => ({ ...prev, siderCollapsed: action.payload }));
break break;
case 'SET_INNER_PADDING': case 'SET_INNER_PADDING':
setState(prev => ({ ...prev, shouldInnerPadding: action.payload })); setState((prev) => ({ ...prev, shouldInnerPadding: action.payload }));
break; break;
default: default:
setState(prev => ({ ...prev, ...action })); setState((prev) => ({ ...prev, ...action }));
} }
} else { } else {
setState(prev => ({ ...prev, ...action })); setState((prev) => ({ ...prev, ...action }));
} }
}; };
...@@ -57,7 +57,12 @@ export const StyleProvider = ({ children }) => { ...@@ -57,7 +57,12 @@ export const StyleProvider = ({ children }) => {
const updateShowSider = () => { const updateShowSider = () => {
// check pathname // check pathname
const pathname = window.location.pathname; const pathname = window.location.pathname;
if (pathname === '' || pathname === '/' || pathname.includes('/home') || pathname.includes('/chat')) { if (
pathname === '' ||
pathname === '/' ||
pathname.includes('/home') ||
pathname.includes('/chat')
) {
dispatch({ type: 'SET_SIDER', payload: false }); dispatch({ type: 'SET_SIDER', payload: false });
dispatch({ type: 'SET_INNER_PADDING', payload: false }); dispatch({ type: 'SET_INNER_PADDING', payload: false });
} else if (pathname === '/setup') { } else if (pathname === '/setup') {
...@@ -73,7 +78,8 @@ export const StyleProvider = ({ children }) => { ...@@ -73,7 +78,8 @@ export const StyleProvider = ({ children }) => {
updateShowSider(); updateShowSider();
const updateSiderCollapsed = () => { const updateSiderCollapsed = () => {
const isCollapsed = localStorage.getItem('default_collapse_sidebar') === 'true'; const isCollapsed =
localStorage.getItem('default_collapse_sidebar') === 'true';
dispatch({ type: 'SET_SIDER_COLLAPSED', payload: isCollapsed }); dispatch({ type: 'SET_SIDER_COLLAPSED', payload: isCollapsed });
}; };
......
...@@ -7,8 +7,8 @@ export let API = axios.create({ ...@@ -7,8 +7,8 @@ export let API = axios.create({
: '', : '',
headers: { headers: {
'New-API-User': getUserIdFromLocalStorage(), 'New-API-User': getUserIdFromLocalStorage(),
'Cache-Control': 'no-store' 'Cache-Control': 'no-store',
} },
}); });
export function updateAPI() { export function updateAPI() {
...@@ -18,8 +18,8 @@ export function updateAPI() { ...@@ -18,8 +18,8 @@ export function updateAPI() {
: '', : '',
headers: { headers: {
'New-API-User': getUserIdFromLocalStorage(), 'New-API-User': getUserIdFromLocalStorage(),
'Cache-Control': 'no-store' 'Cache-Control': 'no-store',
} },
}); });
} }
......
export function getLogOther(otherStr) { export function getLogOther(otherStr) {
if (otherStr === undefined || otherStr === '') { if (otherStr === undefined || otherStr === '') {
otherStr = '{}' otherStr = '{}';
} }
let other = JSON.parse(otherStr) let other = JSON.parse(otherStr);
return other return other;
} }
...@@ -51,11 +51,11 @@ export async function copy(text) { ...@@ -51,11 +51,11 @@ export async function copy(text) {
} catch (e) { } catch (e) {
try { try {
// 构建input 执行 复制命令 // 构建input 执行 复制命令
var _input = window.document.createElement("input"); var _input = window.document.createElement('input');
_input.value = text; _input.value = text;
window.document.body.appendChild(_input); window.document.body.appendChild(_input);
_input.select(); _input.select();
window.document.execCommand("Copy"); window.document.execCommand('Copy');
window.document.body.removeChild(_input); window.document.body.removeChild(_input);
} catch (e) { } catch (e) {
okay = false; okay = false;
...@@ -191,7 +191,7 @@ export function timestamp2string1(timestamp, dataExportDefaultTime = 'hour') { ...@@ -191,7 +191,7 @@ export function timestamp2string1(timestamp, dataExportDefaultTime = 'hour') {
let day = date.getDate().toString(); let day = date.getDate().toString();
let hour = date.getHours().toString(); let hour = date.getHours().toString();
if (day === '24') { if (day === '24') {
console.log("timestamp", timestamp); console.log('timestamp', timestamp);
} }
if (month.length === 1) { if (month.length === 1) {
month = '0' + month; month = '0' + month;
...@@ -247,7 +247,6 @@ export function verifyJSONPromise(value) { ...@@ -247,7 +247,6 @@ export function verifyJSONPromise(value) {
} }
} }
export function shouldShowPrompt(id) { export function shouldShowPrompt(id) {
let prompt = localStorage.getItem(`prompt-${id}`); let prompt = localStorage.getItem(`prompt-${id}`);
return !prompt; return !prompt;
......
...@@ -11,16 +11,16 @@ i18n ...@@ -11,16 +11,16 @@ i18n
.init({ .init({
resources: { resources: {
en: { en: {
translation: enTranslation translation: enTranslation,
}, },
zh: { zh: {
translation: zhTranslation translation: zhTranslation,
} },
}, },
fallbackLng: 'zh', fallbackLng: 'zh',
interpolation: { interpolation: {
escapeValue: false escapeValue: false,
} },
}); });
export default i18n; export default i18n;
body { body {
margin: 0; margin: 0;
padding-top: 0; padding-top: 0;
font-family: Lato, 'Helvetica Neue', Arial, Helvetica, 'Microsoft YaHei', font-family:
sans-serif; Lato, 'Helvetica Neue', Arial, Helvetica, 'Microsoft YaHei', sans-serif;
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale; -moz-osx-font-smoothing: grayscale;
scrollbar-width: none; scrollbar-width: none;
...@@ -18,7 +18,20 @@ body { ...@@ -18,7 +18,20 @@ body {
overflow: hidden; overflow: hidden;
} }
#root > section > header > section > div > div > div > div.semi-navigation-header-list-outer > div.semi-navigation-list-wrapper > ul > div > a > li > span{ #root
> section
> header
> section
> div
> div
> div
> div.semi-navigation-header-list-outer
> div.semi-navigation-list-wrapper
> ul
> div
> a
> li
> span {
font-weight: 600 !important; font-weight: 600 !important;
} }
...@@ -44,13 +57,45 @@ body { ...@@ -44,13 +57,45 @@ body {
overflow-x: auto; overflow-x: auto;
scrollbar-width: none; scrollbar-width: none;
} }
#root > section > header > section > div > div > div > div.semi-navigation-footer > div > a > li { #root
> section
> header
> section
> div
> div
> div
> div.semi-navigation-footer
> div
> a
> li {
padding: 0 0; padding: 0 0;
} }
#root > section > header > section > div > div > div > div.semi-navigation-header-list-outer > div.semi-navigation-list-wrapper > ul > div > a > li { #root
> section
> header
> section
> div
> div
> div
> div.semi-navigation-header-list-outer
> div.semi-navigation-list-wrapper
> ul
> div
> a
> li {
padding: 0 5px; padding: 0 5px;
} }
#root > section > header > section > div > div > div > div.semi-navigation-footer > div:nth-child(1) > a > li { #root
> section
> header
> section
> div
> div
> div
> div.semi-navigation-footer
> div:nth-child(1)
> a
> li {
padding: 0 5px; padding: 0 5px;
} }
.semi-navigation-footer { .semi-navigation-footer {
...@@ -147,8 +192,8 @@ body::-webkit-scrollbar { ...@@ -147,8 +192,8 @@ body::-webkit-scrollbar {
} }
code { code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', font-family:
monospace; source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace;
} }
.semi-navigation-item { .semi-navigation-item {
......
...@@ -28,7 +28,7 @@ root.render( ...@@ -28,7 +28,7 @@ root.render(
<BrowserRouter> <BrowserRouter>
<ThemeProvider> <ThemeProvider>
<StyleProvider> <StyleProvider>
<PageLayout/> <PageLayout />
</StyleProvider> </StyleProvider>
</ThemeProvider> </ThemeProvider>
</BrowserRouter> </BrowserRouter>
......
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { API, showError, showInfo, showSuccess, showWarning, verifyJSON } from '../../helpers'; import {
import { SideSheet, Space, Button, Input, Typography, Spin, Modal, Select, Banner, TextArea } from '@douyinfe/semi-ui'; API,
showError,
showInfo,
showSuccess,
showWarning,
verifyJSON,
} from '../../helpers';
import {
SideSheet,
Space,
Button,
Input,
Typography,
Spin,
Modal,
Select,
Banner,
TextArea,
} from '@douyinfe/semi-ui';
import TextInput from '../../components/custom/TextInput.js'; import TextInput from '../../components/custom/TextInput.js';
import { getChannelModels } from '../../components/utils.js'; import { getChannelModels } from '../../components/utils.js';
const MODEL_MAPPING_EXAMPLE = { const MODEL_MAPPING_EXAMPLE = {
'gpt-3.5-turbo': 'gpt-3.5-turbo-0125' 'gpt-3.5-turbo': 'gpt-3.5-turbo-0125',
}; };
const EditTagModal = (props) => { const EditTagModal = (props) => {
...@@ -23,7 +41,7 @@ const EditTagModal = (props) => { ...@@ -23,7 +41,7 @@ const EditTagModal = (props) => {
model_mapping: null, model_mapping: null,
groups: [], groups: [],
models: [], models: [],
} };
const [inputs, setInputs] = useState(originInputs); const [inputs, setInputs] = useState(originInputs);
const handleInputChange = (name, value) => { const handleInputChange = (name, value) => {
...@@ -39,7 +57,7 @@ const EditTagModal = (props) => { ...@@ -39,7 +57,7 @@ const EditTagModal = (props) => {
'mj_blend', 'mj_blend',
'mj_upscale', 'mj_upscale',
'mj_describe', 'mj_describe',
'mj_uploads' 'mj_uploads',
]; ];
break; break;
case 5: case 5:
...@@ -59,14 +77,11 @@ const EditTagModal = (props) => { ...@@ -59,14 +77,11 @@ const EditTagModal = (props) => {
'mj_high_variation', 'mj_high_variation',
'mj_low_variation', 'mj_low_variation',
'mj_pan', 'mj_pan',
'mj_uploads' 'mj_uploads',
]; ];
break; break;
case 36: case 36:
localModels = [ localModels = ['suno_music', 'suno_lyrics'];
'suno_music',
'suno_lyrics'
];
break; break;
default: default:
localModels = getChannelModels(value); localModels = getChannelModels(value);
...@@ -84,7 +99,7 @@ const EditTagModal = (props) => { ...@@ -84,7 +99,7 @@ const EditTagModal = (props) => {
let res = await API.get(`/api/channel/models`); let res = await API.get(`/api/channel/models`);
let localModelOptions = res.data.data.map((model) => ({ let localModelOptions = res.data.data.map((model) => ({
label: model.id, label: model.id,
value: model.id value: model.id,
})); }));
setOriginModelOptions(localModelOptions); setOriginModelOptions(localModelOptions);
setFullModels(res.data.data.map((model) => model.id)); setFullModels(res.data.data.map((model) => model.id));
...@@ -93,7 +108,7 @@ const EditTagModal = (props) => { ...@@ -93,7 +108,7 @@ const EditTagModal = (props) => {
.filter((model) => { .filter((model) => {
return model.id.startsWith('gpt-') || model.id.startsWith('text-'); return model.id.startsWith('gpt-') || model.id.startsWith('text-');
}) })
.map((model) => model.id) .map((model) => model.id),
); );
} catch (error) { } catch (error) {
showError(error.message); showError(error.message);
...@@ -109,27 +124,26 @@ const EditTagModal = (props) => { ...@@ -109,27 +124,26 @@ const EditTagModal = (props) => {
setGroupOptions( setGroupOptions(
res.data.data.map((group) => ({ res.data.data.map((group) => ({
label: group, label: group,
value: group value: group,
})) })),
); );
} catch (error) { } catch (error) {
showError(error.message); showError(error.message);
} }
}; };
const handleSave = async () => { const handleSave = async () => {
setLoading(true); setLoading(true);
let data = { let data = {
tag: tag, tag: tag,
} };
if (inputs.model_mapping !== null && inputs.model_mapping !== '') { if (inputs.model_mapping !== null && inputs.model_mapping !== '') {
if (inputs.model_mapping !== '' && !verifyJSON(inputs.model_mapping)) { if (inputs.model_mapping !== '' && !verifyJSON(inputs.model_mapping)) {
showInfo('模型映射必须是合法的 JSON 格式!'); showInfo('模型映射必须是合法的 JSON 格式!');
setLoading(false); setLoading(false);
return; return;
} }
data.model_mapping = inputs.model_mapping data.model_mapping = inputs.model_mapping;
} }
if (inputs.groups.length > 0) { if (inputs.groups.length > 0) {
data.groups = inputs.groups.join(','); data.groups = inputs.groups.join(',');
...@@ -139,7 +153,12 @@ const EditTagModal = (props) => { ...@@ -139,7 +153,12 @@ const EditTagModal = (props) => {
} }
data.new_tag = inputs.new_tag; data.new_tag = inputs.new_tag;
// check have any change // check have any change
if (data.model_mapping === undefined && data.groups === undefined && data.models === undefined && data.new_tag === undefined) { if (
data.model_mapping === undefined &&
data.groups === undefined &&
data.models === undefined &&
data.new_tag === undefined
) {
showWarning('没有任何修改!'); showWarning('没有任何修改!');
setLoading(false); setLoading(false);
return; return;
...@@ -159,7 +178,7 @@ const EditTagModal = (props) => { ...@@ -159,7 +178,7 @@ const EditTagModal = (props) => {
} catch (error) { } catch (error) {
showError(error); showError(error);
} }
} };
useEffect(() => { useEffect(() => {
let localModelOptions = [...originModelOptions]; let localModelOptions = [...originModelOptions];
...@@ -167,7 +186,7 @@ const EditTagModal = (props) => { ...@@ -167,7 +186,7 @@ const EditTagModal = (props) => {
if (!localModelOptions.find((option) => option.label === model)) { if (!localModelOptions.find((option) => option.label === model)) {
localModelOptions.push({ localModelOptions.push({
label: model, label: model,
value: model value: model,
}); });
} }
}); });
...@@ -179,7 +198,7 @@ const EditTagModal = (props) => { ...@@ -179,7 +198,7 @@ const EditTagModal = (props) => {
...originInputs, ...originInputs,
tag: tag, tag: tag,
new_tag: tag, new_tag: tag,
}) });
fetchModels().then(); fetchModels().then();
fetchGroups().then(); fetchGroups().then();
}, [visible]); }, [visible]);
...@@ -201,7 +220,7 @@ const EditTagModal = (props) => { ...@@ -201,7 +220,7 @@ const EditTagModal = (props) => {
// 添加到下拉选项 // 添加到下拉选项
key: model, key: model,
text: model, text: model,
value: model value: model,
}); });
} else if (model) { } else if (model) {
showError('某些模型已存在!'); showError('某些模型已存在!');
...@@ -217,17 +236,18 @@ const EditTagModal = (props) => { ...@@ -217,17 +236,18 @@ const EditTagModal = (props) => {
handleInputChange('models', localModels); handleInputChange('models', localModels);
}; };
return ( return (
<SideSheet <SideSheet
title="编辑标签" title='编辑标签'
visible={visible} visible={visible}
onCancel={handleClose} onCancel={handleClose}
footer={ footer={
<div style={{ display: 'flex', justifyContent: 'flex-end' }}> <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
<Space> <Space>
<Button onClick={handleClose}>取消</Button> <Button onClick={handleClose}>取消</Button>
<Button type="primary" onClick={handleSave} loading={loading}>保存</Button> <Button type='primary' onClick={handleSave} loading={loading}>
保存
</Button>
</Space> </Space>
</div> </div>
} }
...@@ -235,27 +255,23 @@ const EditTagModal = (props) => { ...@@ -235,27 +255,23 @@ const EditTagModal = (props) => {
<div style={{ marginTop: 10 }}> <div style={{ marginTop: 10 }}>
<Banner <Banner
type={'warning'} type={'warning'}
description={ description={<>所有编辑均为覆盖操作,留空则不更改</>}
<>
所有编辑均为覆盖操作,留空则不更改
</>
}
></Banner> ></Banner>
</div> </div>
<Spin spinning={loading}> <Spin spinning={loading}>
<TextInput <TextInput
label="标签名,留空则解散标签" label='标签名,留空则解散标签'
name="newTag" name='newTag'
value={inputs.new_tag} value={inputs.new_tag}
onChange={(value) => setInputs({ ...inputs, new_tag: value })} onChange={(value) => setInputs({ ...inputs, new_tag: value })}
placeholder="请输入新标签" placeholder='请输入新标签'
/> />
<div style={{ marginTop: 10 }}> <div style={{ marginTop: 10 }}>
<Typography.Text strong>模型,留空则不更改:</Typography.Text> <Typography.Text strong>模型,留空则不更改:</Typography.Text>
</div> </div>
<Select <Select
placeholder={'请选择该渠道所支持的模型,留空则不更改'} placeholder={'请选择该渠道所支持的模型,留空则不更改'}
name="models" name='models'
required required
multiple multiple
selection selection
...@@ -265,16 +281,16 @@ const EditTagModal = (props) => { ...@@ -265,16 +281,16 @@ const EditTagModal = (props) => {
handleInputChange('models', value); handleInputChange('models', value);
}} }}
value={inputs.models} value={inputs.models}
autoComplete="new-password" autoComplete='new-password'
optionList={modelOptions} optionList={modelOptions}
/> />
<Input <Input
addonAfter={ addonAfter={
<Button type="primary" onClick={addCustomModels}> <Button type='primary' onClick={addCustomModels}>
填入 填入
</Button> </Button>
} }
placeholder="输入自定义模型名称" placeholder='输入自定义模型名称'
value={customModel} value={customModel}
onChange={(value) => { onChange={(value) => {
setCustomModel(value.trim()); setCustomModel(value.trim());
...@@ -285,7 +301,7 @@ const EditTagModal = (props) => { ...@@ -285,7 +301,7 @@ const EditTagModal = (props) => {
</div> </div>
<Select <Select
placeholder={'请选择可以使用该渠道的分组,留空则不更改'} placeholder={'请选择可以使用该渠道的分组,留空则不更改'}
name="groups" name='groups'
required required
multiple multiple
selection selection
...@@ -295,7 +311,7 @@ const EditTagModal = (props) => { ...@@ -295,7 +311,7 @@ const EditTagModal = (props) => {
handleInputChange('groups', value); handleInputChange('groups', value);
}} }}
value={inputs.groups} value={inputs.groups}
autoComplete="new-password" autoComplete='new-password'
optionList={groupOptions} optionList={groupOptions}
/> />
<div style={{ marginTop: 10 }}> <div style={{ marginTop: 10 }}>
...@@ -303,25 +319,25 @@ const EditTagModal = (props) => { ...@@ -303,25 +319,25 @@ const EditTagModal = (props) => {
</div> </div>
<TextArea <TextArea
placeholder={`此项可选,用于修改请求体中的模型名称,为一个 JSON 字符串,键为请求中模型名称,值为要替换的模型名称,留空则不更改`} placeholder={`此项可选,用于修改请求体中的模型名称,为一个 JSON 字符串,键为请求中模型名称,值为要替换的模型名称,留空则不更改`}
name="model_mapping" name='model_mapping'
onChange={(value) => { onChange={(value) => {
handleInputChange('model_mapping', value); handleInputChange('model_mapping', value);
}} }}
autosize autosize
value={inputs.model_mapping} value={inputs.model_mapping}
autoComplete="new-password" autoComplete='new-password'
/> />
<Space> <Space>
<Typography.Text <Typography.Text
style={{ style={{
color: 'rgba(var(--semi-blue-5), 1)', color: 'rgba(var(--semi-blue-5), 1)',
userSelect: 'none', userSelect: 'none',
cursor: 'pointer' cursor: 'pointer',
}} }}
onClick={() => { onClick={() => {
handleInputChange( handleInputChange(
'model_mapping', 'model_mapping',
JSON.stringify(MODEL_MAPPING_EXAMPLE, null, 2) JSON.stringify(MODEL_MAPPING_EXAMPLE, null, 2),
); );
}} }}
> >
...@@ -331,13 +347,10 @@ const EditTagModal = (props) => { ...@@ -331,13 +347,10 @@ const EditTagModal = (props) => {
style={{ style={{
color: 'rgba(var(--semi-blue-5), 1)', color: 'rgba(var(--semi-blue-5), 1)',
userSelect: 'none', userSelect: 'none',
cursor: 'pointer' cursor: 'pointer',
}} }}
onClick={() => { onClick={() => {
handleInputChange( handleInputChange('model_mapping', JSON.stringify({}, null, 2));
'model_mapping',
JSON.stringify({}, null, 2)
);
}} }}
> >
清空重定向 清空重定向
...@@ -346,13 +359,10 @@ const EditTagModal = (props) => { ...@@ -346,13 +359,10 @@ const EditTagModal = (props) => {
style={{ style={{
color: 'rgba(var(--semi-blue-5), 1)', color: 'rgba(var(--semi-blue-5), 1)',
userSelect: 'none', userSelect: 'none',
cursor: 'pointer' cursor: 'pointer',
}} }}
onClick={() => { onClick={() => {
handleInputChange( handleInputChange('model_mapping', '');
'model_mapping',
""
);
}} }}
> >
不更改 不更改
......
import React, {useEffect} from 'react'; import React, { useEffect } from 'react';
import { useTokenKeys } from '../../components/fetchTokenKeys'; import { useTokenKeys } from '../../components/fetchTokenKeys';
import {Banner, Layout} from '@douyinfe/semi-ui'; import { Banner, Layout } from '@douyinfe/semi-ui';
import { useParams } from 'react-router-dom'; import { useParams } from 'react-router-dom';
const ChatPage = () => { const ChatPage = () => {
...@@ -10,7 +10,7 @@ const ChatPage = () => { ...@@ -10,7 +10,7 @@ const ChatPage = () => {
const comLink = (key) => { const comLink = (key) => {
// console.log('chatLink:', chatLink); // console.log('chatLink:', chatLink);
if (!serverAddress || !key) return ''; if (!serverAddress || !key) return '';
let link = ""; let link = '';
if (id) { if (id) {
let chats = localStorage.getItem('chats'); let chats = localStorage.getItem('chats');
if (chats) { if (chats) {
...@@ -18,7 +18,10 @@ const ChatPage = () => { ...@@ -18,7 +18,10 @@ const ChatPage = () => {
if (Array.isArray(chats) && chats.length > 0) { if (Array.isArray(chats) && chats.length > 0) {
for (let k in chats[id]) { for (let k in chats[id]) {
link = chats[id][k]; link = chats[id][k];
link = link.replaceAll('{address}', encodeURIComponent(serverAddress)); link = link.replaceAll(
'{address}',
encodeURIComponent(serverAddress),
);
link = link.replaceAll('{key}', 'sk-' + key); link = link.replaceAll('{key}', 'sk-' + key);
} }
} }
...@@ -33,17 +36,14 @@ const ChatPage = () => { ...@@ -33,17 +36,14 @@ const ChatPage = () => {
<iframe <iframe
src={iframeSrc} src={iframeSrc}
style={{ width: '100%', height: '100%', border: 'none' }} style={{ width: '100%', height: '100%', border: 'none' }}
title="Token Frame" title='Token Frame'
allow="camera;microphone" allow='camera;microphone'
/> />
) : ( ) : (
<div> <div>
<Layout> <Layout>
<Layout.Header> <Layout.Header>
<Banner <Banner description={'正在跳转......'} type={'warning'} />
description={"正在跳转......"}
type={"warning"}
/>
</Layout.Header> </Layout.Header>
</Layout> </Layout>
</div> </div>
......
...@@ -99,7 +99,9 @@ const Home = () => { ...@@ -99,7 +99,9 @@ const Home = () => {
</span> </span>
} }
> >
<p>{t('名称')}{statusState?.status?.system_name}</p> <p>
{t('名称')}{statusState?.status?.system_name}
</p>
<p> <p>
{t('版本')} {t('版本')}
{statusState?.status?.version {statusState?.status?.version
...@@ -126,7 +128,9 @@ const Home = () => { ...@@ -126,7 +128,9 @@ const Home = () => {
Apache-2.0 License Apache-2.0 License
</a> </a>
</p> </p>
<p>{t('启动时间')}{getStartTimeString()}</p> <p>
{t('启动时间')}{getStartTimeString()}
</p>
</Card> </Card>
</Col> </Col>
<Col span={12}> <Col span={12}>
......
...@@ -8,7 +8,11 @@ import { ...@@ -8,7 +8,11 @@ import {
showError, showError,
showSuccess, showSuccess,
} from '../../helpers'; } from '../../helpers';
import { getQuotaPerUnit, renderQuota, renderQuotaWithPrompt } from '../../helpers/render'; import {
getQuotaPerUnit,
renderQuota,
renderQuotaWithPrompt,
} from '../../helpers/render';
import { import {
AutoComplete, AutoComplete,
Button, Button,
...@@ -171,7 +175,9 @@ const EditRedemption = (props) => { ...@@ -171,7 +175,9 @@ const EditRedemption = (props) => {
/> />
<Divider /> <Divider />
<div style={{ marginTop: 20 }}> <div style={{ marginTop: 20 }}>
<Typography.Text>{t('额度') + renderQuotaWithPrompt(quota)}</Typography.Text> <Typography.Text>
{t('额度') + renderQuotaWithPrompt(quota)}
</Typography.Text>
</div> </div>
<AutoComplete <AutoComplete
style={{ marginTop: 8 }} style={{ marginTop: 8 }}
......
...@@ -16,7 +16,7 @@ const Redemption = () => { ...@@ -16,7 +16,7 @@ const Redemption = () => {
</Layout.Content> </Layout.Content>
</Layout> </Layout>
</> </>
); );
} };
export default Redemption; export default Redemption;
...@@ -5,23 +5,27 @@ import { ...@@ -5,23 +5,27 @@ import {
API, API,
showError, showError,
showSuccess, showSuccess,
showWarning, verifyJSON showWarning,
verifyJSON,
} from '../../../helpers'; } from '../../../helpers';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import Text from '@douyinfe/semi-ui/lib/es/typography/text'; import Text from '@douyinfe/semi-ui/lib/es/typography/text';
const CLAUDE_HEADER = { const CLAUDE_HEADER = {
'claude-3-7-sonnet-20250219-thinking': { 'claude-3-7-sonnet-20250219-thinking': {
'anthropic-beta': ['output-128k-2025-02-19', 'token-efficient-tools-2025-02-19'], 'anthropic-beta': [
} 'output-128k-2025-02-19',
'token-efficient-tools-2025-02-19',
],
},
}; };
const CLAUDE_DEFAULT_MAX_TOKENS = { const CLAUDE_DEFAULT_MAX_TOKENS = {
'default': 8192, default: 8192,
"claude-3-haiku-20240307": 4096, 'claude-3-haiku-20240307': 4096,
"claude-3-opus-20240229": 4096, 'claude-3-opus-20240229': 4096,
'claude-3-7-sonnet-20250219-thinking': 8192, 'claude-3-7-sonnet-20250219-thinking': 8192,
} };
export default function SettingClaudeModel(props) { export default function SettingClaudeModel(props) {
const { t } = useTranslation(); const { t } = useTranslation();
...@@ -53,7 +57,8 @@ export default function SettingClaudeModel(props) { ...@@ -53,7 +57,8 @@ export default function SettingClaudeModel(props) {
if (requestQueue.length === 1) { if (requestQueue.length === 1) {
if (res.includes(undefined)) return; if (res.includes(undefined)) return;
} else if (requestQueue.length > 1) { } else if (requestQueue.length > 1) {
if (res.includes(undefined)) return showError(t('部分保存失败,请重试')); if (res.includes(undefined))
return showError(t('部分保存失败,请重试'));
} }
showSuccess(t('保存成功')); showSuccess(t('保存成功'));
props.refresh(); props.refresh();
...@@ -92,18 +97,29 @@ export default function SettingClaudeModel(props) { ...@@ -92,18 +97,29 @@ export default function SettingClaudeModel(props) {
<Form.TextArea <Form.TextArea
label={t('Claude请求头覆盖')} label={t('Claude请求头覆盖')}
field={'claude.model_headers_settings'} field={'claude.model_headers_settings'}
placeholder={t('为一个 JSON 文本,例如:') + '\n' + JSON.stringify(CLAUDE_HEADER, null, 2)} placeholder={
extraText={t('示例') + '\n' + JSON.stringify(CLAUDE_HEADER, null, 2)} t('为一个 JSON 文本,例如:') +
'\n' +
JSON.stringify(CLAUDE_HEADER, null, 2)
}
extraText={
t('示例') + '\n' + JSON.stringify(CLAUDE_HEADER, null, 2)
}
autosize={{ minRows: 6, maxRows: 12 }} autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur' trigger='blur'
stopValidateWithError stopValidateWithError
rules={[ rules={[
{ {
validator: (rule, value) => verifyJSON(value), validator: (rule, value) => verifyJSON(value),
message: t('不是合法的 JSON 字符串') message: t('不是合法的 JSON 字符串'),
} },
]} ]}
onChange={(value) => setInputs({ ...inputs, 'claude.model_headers_settings': value })} onChange={(value) =>
setInputs({
...inputs,
'claude.model_headers_settings': value,
})
}
/> />
</Col> </Col>
</Row> </Row>
...@@ -112,18 +128,28 @@ export default function SettingClaudeModel(props) { ...@@ -112,18 +128,28 @@ export default function SettingClaudeModel(props) {
<Form.TextArea <Form.TextArea
label={t('缺省 MaxTokens')} label={t('缺省 MaxTokens')}
field={'claude.default_max_tokens'} field={'claude.default_max_tokens'}
placeholder={t('为一个 JSON 文本,例如:') + '\n' + JSON.stringify(CLAUDE_DEFAULT_MAX_TOKENS, null, 2)} placeholder={
extraText={t('示例') + '\n' + JSON.stringify(CLAUDE_DEFAULT_MAX_TOKENS, null, 2)} t('为一个 JSON 文本,例如:') +
'\n' +
JSON.stringify(CLAUDE_DEFAULT_MAX_TOKENS, null, 2)
}
extraText={
t('示例') +
'\n' +
JSON.stringify(CLAUDE_DEFAULT_MAX_TOKENS, null, 2)
}
autosize={{ minRows: 6, maxRows: 12 }} autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur' trigger='blur'
stopValidateWithError stopValidateWithError
rules={[ rules={[
{ {
validator: (rule, value) => verifyJSON(value), validator: (rule, value) => verifyJSON(value),
message: t('不是合法的 JSON 字符串') message: t('不是合法的 JSON 字符串'),
} },
]} ]}
onChange={(value) => setInputs({ ...inputs, 'claude.default_max_tokens': value })} onChange={(value) =>
setInputs({ ...inputs, 'claude.default_max_tokens': value })
}
/> />
</Col> </Col>
</Row> </Row>
...@@ -132,7 +158,12 @@ export default function SettingClaudeModel(props) { ...@@ -132,7 +158,12 @@ export default function SettingClaudeModel(props) {
<Form.Switch <Form.Switch
label={t('启用Claude思考适配(-thinking后缀)')} label={t('启用Claude思考适配(-thinking后缀)')}
field={'claude.thinking_adapter_enabled'} field={'claude.thinking_adapter_enabled'}
onChange={(value) => setInputs({ ...inputs, 'claude.thinking_adapter_enabled': value })} onChange={(value) =>
setInputs({
...inputs,
'claude.thinking_adapter_enabled': value,
})
}
/> />
</Col> </Col>
</Row> </Row>
...@@ -140,7 +171,9 @@ export default function SettingClaudeModel(props) { ...@@ -140,7 +171,9 @@ export default function SettingClaudeModel(props) {
<Col span={16}> <Col span={16}>
{/*//展示MaxTokens和BudgetTokens的计算公式, 并展示实际数字*/} {/*//展示MaxTokens和BudgetTokens的计算公式, 并展示实际数字*/}
<Text> <Text>
{t('Claude思考适配 BudgetTokens = MaxTokens * BudgetTokens 百分比')} {t(
'Claude思考适配 BudgetTokens = MaxTokens * BudgetTokens 百分比',
)}
</Text> </Text>
</Col> </Col>
</Row> </Row>
...@@ -153,7 +186,12 @@ export default function SettingClaudeModel(props) { ...@@ -153,7 +186,12 @@ export default function SettingClaudeModel(props) {
extraText={t('0.1-1之间的小数')} extraText={t('0.1-1之间的小数')}
min={0.1} min={0.1}
max={1} max={1}
onChange={(value) => setInputs({ ...inputs, 'claude.thinking_adapter_budget_tokens_percentage': value })} onChange={(value) =>
setInputs({
...inputs,
'claude.thinking_adapter_budget_tokens_percentage': value,
})
}
/> />
</Col> </Col>
</Row> </Row>
......
...@@ -5,20 +5,20 @@ import { ...@@ -5,20 +5,20 @@ import {
API, API,
showError, showError,
showSuccess, showSuccess,
showWarning, verifyJSON showWarning,
verifyJSON,
} from '../../../helpers'; } from '../../../helpers';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
const GEMINI_SETTING_EXAMPLE = { const GEMINI_SETTING_EXAMPLE = {
'default': 'OFF', default: 'OFF',
'HARM_CATEGORY_CIVIC_INTEGRITY': 'BLOCK_NONE', HARM_CATEGORY_CIVIC_INTEGRITY: 'BLOCK_NONE',
}; };
const GEMINI_VERSION_EXAMPLE = { const GEMINI_VERSION_EXAMPLE = {
'default': 'v1beta', default: 'v1beta',
}; };
export default function SettingGeminiModel(props) { export default function SettingGeminiModel(props) {
const { t } = useTranslation(); const { t } = useTranslation();
...@@ -51,7 +51,8 @@ export default function SettingGeminiModel(props) { ...@@ -51,7 +51,8 @@ export default function SettingGeminiModel(props) {
if (requestQueue.length === 1) { if (requestQueue.length === 1) {
if (res.includes(undefined)) return; if (res.includes(undefined)) return;
} else if (requestQueue.length > 1) { } else if (requestQueue.length > 1) {
if (res.includes(undefined)) return showError(t('部分保存失败,请重试')); if (res.includes(undefined))
return showError(t('部分保存失败,请重试'));
} }
showSuccess(t('保存成功')); showSuccess(t('保存成功'));
props.refresh(); props.refresh();
...@@ -89,19 +90,27 @@ export default function SettingGeminiModel(props) { ...@@ -89,19 +90,27 @@ export default function SettingGeminiModel(props) {
<Col xs={24} sm={12} md={8} lg={8} xl={8}> <Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.TextArea <Form.TextArea
label={t('Gemini安全设置')} label={t('Gemini安全设置')}
placeholder={t('为一个 JSON 文本,例如:') + '\n' + JSON.stringify(GEMINI_SETTING_EXAMPLE, null, 2)} placeholder={
t('为一个 JSON 文本,例如:') +
'\n' +
JSON.stringify(GEMINI_SETTING_EXAMPLE, null, 2)
}
field={'gemini.safety_settings'} field={'gemini.safety_settings'}
extraText={t('default为默认设置,可单独设置每个分类的安全等级')} extraText={t(
'default为默认设置,可单独设置每个分类的安全等级',
)}
autosize={{ minRows: 6, maxRows: 12 }} autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur' trigger='blur'
stopValidateWithError stopValidateWithError
rules={[ rules={[
{ {
validator: (rule, value) => verifyJSON(value), validator: (rule, value) => verifyJSON(value),
message: t('不是合法的 JSON 字符串') message: t('不是合法的 JSON 字符串'),
} },
]} ]}
onChange={(value) => setInputs({ ...inputs, 'gemini.safety_settings': value })} onChange={(value) =>
setInputs({ ...inputs, 'gemini.safety_settings': value })
}
/> />
</Col> </Col>
</Row> </Row>
...@@ -109,7 +118,11 @@ export default function SettingGeminiModel(props) { ...@@ -109,7 +118,11 @@ export default function SettingGeminiModel(props) {
<Col xs={24} sm={12} md={8} lg={8} xl={8}> <Col xs={24} sm={12} md={8} lg={8} xl={8}>
<Form.TextArea <Form.TextArea
label={t('Gemini版本设置')} label={t('Gemini版本设置')}
placeholder={t('为一个 JSON 文本,例如:') + '\n' + JSON.stringify(GEMINI_VERSION_EXAMPLE, null, 2)} placeholder={
t('为一个 JSON 文本,例如:') +
'\n' +
JSON.stringify(GEMINI_VERSION_EXAMPLE, null, 2)
}
field={'gemini.version_settings'} field={'gemini.version_settings'}
extraText={t('default为默认设置,可单独设置每个模型的版本')} extraText={t('default为默认设置,可单独设置每个模型的版本')}
autosize={{ minRows: 6, maxRows: 12 }} autosize={{ minRows: 6, maxRows: 12 }}
...@@ -118,10 +131,12 @@ export default function SettingGeminiModel(props) { ...@@ -118,10 +131,12 @@ export default function SettingGeminiModel(props) {
rules={[ rules={[
{ {
validator: (rule, value) => verifyJSON(value), validator: (rule, value) => verifyJSON(value),
message: t('不是合法的 JSON 字符串') message: t('不是合法的 JSON 字符串'),
} },
]} ]}
onChange={(value) => setInputs({ ...inputs, 'gemini.version_settings': value })} onChange={(value) =>
setInputs({ ...inputs, 'gemini.version_settings': value })
}
/> />
</Col> </Col>
</Row> </Row>
......
...@@ -5,7 +5,8 @@ import { ...@@ -5,7 +5,8 @@ import {
API, API,
showError, showError,
showSuccess, showSuccess,
showWarning, verifyJSON showWarning,
verifyJSON,
} from '../../../helpers'; } from '../../../helpers';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
...@@ -40,7 +41,8 @@ export default function SettingGlobalModel(props) { ...@@ -40,7 +41,8 @@ export default function SettingGlobalModel(props) {
if (requestQueue.length === 1) { if (requestQueue.length === 1) {
if (res.includes(undefined)) return; if (res.includes(undefined)) return;
} else if (requestQueue.length > 1) { } else if (requestQueue.length > 1) {
if (res.includes(undefined)) return showError(t('部分保存失败,请重试')); if (res.includes(undefined))
return showError(t('部分保存失败,请重试'));
} }
showSuccess(t('保存成功')); showSuccess(t('保存成功'));
props.refresh(); props.refresh();
...@@ -79,8 +81,15 @@ export default function SettingGlobalModel(props) { ...@@ -79,8 +81,15 @@ export default function SettingGlobalModel(props) {
<Form.Switch <Form.Switch
label={t('启用请求透传')} label={t('启用请求透传')}
field={'global.pass_through_request_enabled'} field={'global.pass_through_request_enabled'}
onChange={(value) => setInputs({ ...inputs, 'global.pass_through_request_enabled': value })} onChange={(value) =>
extraText={'开启后,所有请求将直接透传给上游,不会进行任何处理(重定向和渠道适配也将失效),请谨慎开启'} setInputs({
...inputs,
'global.pass_through_request_enabled': value,
})
}
extraText={
'开启后,所有请求将直接透传给上游,不会进行任何处理(重定向和渠道适配也将失效),请谨慎开启'
}
/> />
</Col> </Col>
</Row> </Row>
......
...@@ -15,19 +15,23 @@ export default function GroupRatioSettings(props) { ...@@ -15,19 +15,23 @@ export default function GroupRatioSettings(props) {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState({ const [inputs, setInputs] = useState({
GroupRatio: '', GroupRatio: '',
UserUsableGroups: '' UserUsableGroups: '',
}); });
const refForm = useRef(); const refForm = useRef();
const [inputsRow, setInputsRow] = useState(inputs); const [inputsRow, setInputsRow] = useState(inputs);
async function onSubmit() { async function onSubmit() {
try { try {
await refForm.current.validate().then(() => { await refForm.current
.validate()
.then(() => {
const updateArray = compareObjects(inputs, inputsRow); const updateArray = compareObjects(inputs, inputsRow);
if (!updateArray.length) return showWarning(t('你似乎并没有修改什么')); if (!updateArray.length)
return showWarning(t('你似乎并没有修改什么'));
const requestQueue = updateArray.map((item) => { const requestQueue = updateArray.map((item) => {
const value = typeof inputs[item.key] === 'boolean' const value =
typeof inputs[item.key] === 'boolean'
? String(inputs[item.key]) ? String(inputs[item.key])
: inputs[item.key]; : inputs[item.key];
return API.put('/api/option/', { key: item.key, value }); return API.put('/api/option/', { key: item.key, value });
...@@ -37,7 +41,11 @@ export default function GroupRatioSettings(props) { ...@@ -37,7 +41,11 @@ export default function GroupRatioSettings(props) {
Promise.all(requestQueue) Promise.all(requestQueue)
.then((res) => { .then((res) => {
if (res.includes(undefined)) { if (res.includes(undefined)) {
return showError(requestQueue.length > 1 ? t('部分保存失败,请重试') : t('保存失败')); return showError(
requestQueue.length > 1
? t('部分保存失败,请重试')
: t('保存失败'),
);
} }
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
...@@ -49,14 +57,15 @@ export default function GroupRatioSettings(props) { ...@@ -49,14 +57,15 @@ export default function GroupRatioSettings(props) {
showSuccess(t('保存成功')); showSuccess(t('保存成功'));
props.refresh(); props.refresh();
}) })
.catch(error => { .catch((error) => {
console.error('Unexpected error:', error); console.error('Unexpected error:', error);
showError(t('保存失败,请重试')); showError(t('保存失败,请重试'));
}) })
.finally(() => { .finally(() => {
setLoading(false); setLoading(false);
}); });
}).catch(() => { })
.catch(() => {
showError(t('请检查输入')); showError(t('请检查输入'));
}); });
} catch (error) { } catch (error) {
...@@ -97,10 +106,12 @@ export default function GroupRatioSettings(props) { ...@@ -97,10 +106,12 @@ export default function GroupRatioSettings(props) {
rules={[ rules={[
{ {
validator: (rule, value) => verifyJSON(value), validator: (rule, value) => verifyJSON(value),
message: t('不是合法的 JSON 字符串') message: t('不是合法的 JSON 字符串'),
} },
]} ]}
onChange={(value) => setInputs({ ...inputs, GroupRatio: value })} onChange={(value) =>
setInputs({ ...inputs, GroupRatio: value })
}
/> />
</Col> </Col>
</Row> </Row>
...@@ -116,10 +127,12 @@ export default function GroupRatioSettings(props) { ...@@ -116,10 +127,12 @@ export default function GroupRatioSettings(props) {
rules={[ rules={[
{ {
validator: (rule, value) => verifyJSON(value), validator: (rule, value) => verifyJSON(value),
message: t('不是合法的 JSON 字符串') message: t('不是合法的 JSON 字符串'),
} },
]} ]}
onChange={(value) => setInputs({ ...inputs, UserUsableGroups: value })} onChange={(value) =>
setInputs({ ...inputs, UserUsableGroups: value })
}
/> />
</Col> </Col>
</Row> </Row>
......
import React, { useEffect, useState, useRef } from 'react'; import React, { useEffect, useState, useRef } from 'react';
import { Button, Col, Form, Popconfirm, Row, Space, Spin } from '@douyinfe/semi-ui'; import {
Button,
Col,
Form,
Popconfirm,
Row,
Space,
Spin,
} from '@douyinfe/semi-ui';
import { import {
compareObjects, compareObjects,
API, API,
...@@ -24,12 +32,16 @@ export default function ModelRatioSettings(props) { ...@@ -24,12 +32,16 @@ export default function ModelRatioSettings(props) {
async function onSubmit() { async function onSubmit() {
try { try {
await refForm.current.validate().then(() => { await refForm.current
.validate()
.then(() => {
const updateArray = compareObjects(inputs, inputsRow); const updateArray = compareObjects(inputs, inputsRow);
if (!updateArray.length) return showWarning(t('你似乎并没有修改什么')); if (!updateArray.length)
return showWarning(t('你似乎并没有修改什么'));
const requestQueue = updateArray.map((item) => { const requestQueue = updateArray.map((item) => {
const value = typeof inputs[item.key] === 'boolean' const value =
typeof inputs[item.key] === 'boolean'
? String(inputs[item.key]) ? String(inputs[item.key])
: inputs[item.key]; : inputs[item.key];
return API.put('/api/option/', { key: item.key, value }); return API.put('/api/option/', { key: item.key, value });
...@@ -39,7 +51,11 @@ export default function ModelRatioSettings(props) { ...@@ -39,7 +51,11 @@ export default function ModelRatioSettings(props) {
Promise.all(requestQueue) Promise.all(requestQueue)
.then((res) => { .then((res) => {
if (res.includes(undefined)) { if (res.includes(undefined)) {
return showError(requestQueue.length > 1 ? t('部分保存失败,请重试') : t('保存失败')); return showError(
requestQueue.length > 1
? t('部分保存失败,请重试')
: t('保存失败'),
);
} }
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
...@@ -51,14 +67,15 @@ export default function ModelRatioSettings(props) { ...@@ -51,14 +67,15 @@ export default function ModelRatioSettings(props) {
showSuccess(t('保存成功')); showSuccess(t('保存成功'));
props.refresh(); props.refresh();
}) })
.catch(error => { .catch((error) => {
console.error('Unexpected error:', error); console.error('Unexpected error:', error);
showError(t('保存失败,请重试')); showError(t('保存失败,请重试'));
}) })
.finally(() => { .finally(() => {
setLoading(false); setLoading(false);
}); });
}).catch(() => { })
.catch(() => {
showError(t('请检查输入')); showError(t('请检查输入'));
}); });
} catch (error) { } catch (error) {
...@@ -106,7 +123,9 @@ export default function ModelRatioSettings(props) { ...@@ -106,7 +123,9 @@ export default function ModelRatioSettings(props) {
<Form.TextArea <Form.TextArea
label={t('模型固定价格')} label={t('模型固定价格')}
extraText={t('一次调用消耗多少刀,优先级大于模型倍率')} extraText={t('一次调用消耗多少刀,优先级大于模型倍率')}
placeholder={t('为一个 JSON 文本,键为模型名称,值为一次调用消耗多少刀,比如 "gpt-4-gizmo-*": 0.1,一次消耗0.1刀')} placeholder={t(
'为一个 JSON 文本,键为模型名称,值为一次调用消耗多少刀,比如 "gpt-4-gizmo-*": 0.1,一次消耗0.1刀',
)}
field={'ModelPrice'} field={'ModelPrice'}
autosize={{ minRows: 6, maxRows: 12 }} autosize={{ minRows: 6, maxRows: 12 }}
trigger='blur' trigger='blur'
...@@ -114,10 +133,12 @@ export default function ModelRatioSettings(props) { ...@@ -114,10 +133,12 @@ export default function ModelRatioSettings(props) {
rules={[ rules={[
{ {
validator: (rule, value) => verifyJSON(value), validator: (rule, value) => verifyJSON(value),
message: '不是合法的 JSON 字符串' message: '不是合法的 JSON 字符串',
} },
]} ]}
onChange={(value) => setInputs({ ...inputs, ModelPrice: value })} onChange={(value) =>
setInputs({ ...inputs, ModelPrice: value })
}
/> />
</Col> </Col>
</Row> </Row>
...@@ -133,10 +154,12 @@ export default function ModelRatioSettings(props) { ...@@ -133,10 +154,12 @@ export default function ModelRatioSettings(props) {
rules={[ rules={[
{ {
validator: (rule, value) => verifyJSON(value), validator: (rule, value) => verifyJSON(value),
message: '不是合法的 JSON 字符串' message: '不是合法的 JSON 字符串',
} },
]} ]}
onChange={(value) => setInputs({ ...inputs, ModelRatio: value })} onChange={(value) =>
setInputs({ ...inputs, ModelRatio: value })
}
/> />
</Col> </Col>
</Row> </Row>
...@@ -152,10 +175,12 @@ export default function ModelRatioSettings(props) { ...@@ -152,10 +175,12 @@ export default function ModelRatioSettings(props) {
rules={[ rules={[
{ {
validator: (rule, value) => verifyJSON(value), validator: (rule, value) => verifyJSON(value),
message: '不是合法的 JSON 字符串' message: '不是合法的 JSON 字符串',
} },
]} ]}
onChange={(value) => setInputs({ ...inputs, CacheRatio: value })} onChange={(value) =>
setInputs({ ...inputs, CacheRatio: value })
}
/> />
</Col> </Col>
</Row> </Row>
...@@ -172,10 +197,12 @@ export default function ModelRatioSettings(props) { ...@@ -172,10 +197,12 @@ export default function ModelRatioSettings(props) {
rules={[ rules={[
{ {
validator: (rule, value) => verifyJSON(value), validator: (rule, value) => verifyJSON(value),
message: '不是合法的 JSON 字符串' message: '不是合法的 JSON 字符串',
} },
]} ]}
onChange={(value) => setInputs({ ...inputs, CompletionRatio: value })} onChange={(value) =>
setInputs({ ...inputs, CompletionRatio: value })
}
/> />
</Col> </Col>
</Row> </Row>
......
import React, { useEffect, useState, useRef } from 'react'; import React, { useEffect, useState, useRef } from 'react';
import { Banner, Button, Col, Form, Popconfirm, Row, Space, Spin } from '@douyinfe/semi-ui'; import {
Banner,
Button,
Col,
Form,
Popconfirm,
Row,
Space,
Spin,
} from '@douyinfe/semi-ui';
import { import {
compareObjects, compareObjects,
API, API,
...@@ -7,7 +16,7 @@ import { ...@@ -7,7 +16,7 @@ import {
showSuccess, showSuccess,
showWarning, showWarning,
verifyJSON, verifyJSON,
verifyJSONPromise verifyJSONPromise,
} from '../../../helpers'; } from '../../../helpers';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
...@@ -15,7 +24,7 @@ export default function SettingsChats(props) { ...@@ -15,7 +24,7 @@ export default function SettingsChats(props) {
const { t } = useTranslation(); const { t } = useTranslation();
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [inputs, setInputs] = useState({ const [inputs, setInputs] = useState({
Chats: "[]", Chats: '[]',
}); });
const refForm = useRef(); const refForm = useRef();
const [inputsRow, setInputsRow] = useState(inputs); const [inputsRow, setInputsRow] = useState(inputs);
...@@ -23,10 +32,13 @@ export default function SettingsChats(props) { ...@@ -23,10 +32,13 @@ export default function SettingsChats(props) {
async function onSubmit() { async function onSubmit() {
try { try {
console.log('Starting validation...'); console.log('Starting validation...');
await refForm.current.validate().then(() => { await refForm.current
.validate()
.then(() => {
console.log('Validation passed'); console.log('Validation passed');
const updateArray = compareObjects(inputs, inputsRow); const updateArray = compareObjects(inputs, inputsRow);
if (!updateArray.length) return showWarning(t('你似乎并没有修改什么')); if (!updateArray.length)
return showWarning(t('你似乎并没有修改什么'));
const requestQueue = updateArray.map((item) => { const requestQueue = updateArray.map((item) => {
let value = ''; let value = '';
if (typeof inputs[item.key] === 'boolean') { if (typeof inputs[item.key] === 'boolean') {
...@@ -36,7 +48,7 @@ export default function SettingsChats(props) { ...@@ -36,7 +48,7 @@ export default function SettingsChats(props) {
} }
return API.put('/api/option/', { return API.put('/api/option/', {
key: item.key, key: item.key,
value value,
}); });
}); });
setLoading(true); setLoading(true);
...@@ -57,7 +69,8 @@ export default function SettingsChats(props) { ...@@ -57,7 +69,8 @@ export default function SettingsChats(props) {
.finally(() => { .finally(() => {
setLoading(false); setLoading(false);
}); });
}).catch((error) => { })
.catch((error) => {
console.error('Validation failed:', error); console.error('Validation failed:', error);
showError(t('请检查输入')); showError(t('请检查输入'));
}); });
...@@ -109,11 +122,15 @@ export default function SettingsChats(props) { ...@@ -109,11 +122,15 @@ export default function SettingsChats(props) {
<Form.Section text={t('令牌聊天设置')}> <Form.Section text={t('令牌聊天设置')}>
<Banner <Banner
type='warning' type='warning'
description={t('必须将上方聊天链接全部设置为空,才能使用下方聊天设置功能')} description={t(
'必须将上方聊天链接全部设置为空,才能使用下方聊天设置功能',
)}
/> />
<Banner <Banner
type='info' type='info'
description={t('链接中的{key}将自动替换为sk-xxxx,{address}将自动替换为系统设置的服务器地址,末尾不带/和/v1')} description={t(
'链接中的{key}将自动替换为sk-xxxx,{address}将自动替换为系统设置的服务器地址,末尾不带/和/v1',
)}
/> />
<Form.TextArea <Form.TextArea
label={t('聊天配置')} label={t('聊天配置')}
...@@ -128,22 +145,20 @@ export default function SettingsChats(props) { ...@@ -128,22 +145,20 @@ export default function SettingsChats(props) {
validator: (rule, value) => { validator: (rule, value) => {
return verifyJSON(value); return verifyJSON(value);
}, },
message: t('不是合法的 JSON 字符串') message: t('不是合法的 JSON 字符串'),
} },
]} ]}
onChange={(value) => onChange={(value) =>
setInputs({ setInputs({
...inputs, ...inputs,
Chats: value Chats: value,
}) })
} }
/> />
</Form.Section> </Form.Section>
</Form> </Form>
<Space> <Space>
<Button onClick={onSubmit}> <Button onClick={onSubmit}>{t('保存聊天设置')}</Button>
{t('保存聊天设置')}
</Button>
</Space> </Space>
</Spin> </Spin>
); );
......
...@@ -42,7 +42,8 @@ export default function SettingsCreditLimit(props) { ...@@ -42,7 +42,8 @@ export default function SettingsCreditLimit(props) {
if (requestQueue.length === 1) { if (requestQueue.length === 1) {
if (res.includes(undefined)) return; if (res.includes(undefined)) return;
} else if (requestQueue.length > 1) { } else if (requestQueue.length > 1) {
if (res.includes(undefined)) return showError(t('部分保存失败,请重试')); if (res.includes(undefined))
return showError(t('部分保存失败,请重试'));
} }
showSuccess(t('保存成功')); showSuccess(t('保存成功'));
props.refresh(); props.refresh();
......
...@@ -47,7 +47,8 @@ export default function DataDashboard(props) { ...@@ -47,7 +47,8 @@ export default function DataDashboard(props) {
if (requestQueue.length === 1) { if (requestQueue.length === 1) {
if (res.includes(undefined)) return; if (res.includes(undefined)) return;
} else if (requestQueue.length > 1) { } else if (requestQueue.length > 1) {
if (res.includes(undefined)) return showError(t('部分保存失败,请重试')); if (res.includes(undefined))
return showError(t('部分保存失败,请重试'));
} }
showSuccess(t('保存成功')); showSuccess(t('保存成功'));
props.refresh(); props.refresh();
......
...@@ -44,7 +44,8 @@ export default function SettingsDrawing(props) { ...@@ -44,7 +44,8 @@ export default function SettingsDrawing(props) {
if (requestQueue.length === 1) { if (requestQueue.length === 1) {
if (res.includes(undefined)) return; if (res.includes(undefined)) return;
} else if (requestQueue.length > 1) { } else if (requestQueue.length > 1) {
if (res.includes(undefined)) return showError(t('部分保存失败,请重试')); if (res.includes(undefined))
return showError(t('部分保存失败,请重试'));
} }
showSuccess(t('保存成功')); showSuccess(t('保存成功'));
props.refresh(); props.refresh();
...@@ -146,7 +147,8 @@ export default function SettingsDrawing(props) { ...@@ -146,7 +147,8 @@ export default function SettingsDrawing(props) {
label={ label={
<> <>
{t('开启之后会清除用户提示词中的')} <Tag>--fast</Tag> {t('开启之后会清除用户提示词中的')} <Tag>--fast</Tag>
<Tag>--relax</Tag> {t('以及')} <Tag>--turbo</Tag> {t('参数')} <Tag>--relax</Tag> {t('以及')} <Tag>--turbo</Tag>{' '}
{t('参数')}
</> </>
} }
size='default' size='default'
......
import React, { useEffect, useState, useRef } from 'react'; import React, { useEffect, useState, useRef } from 'react';
import { Banner, Button, Col, Form, Row, Spin, Collapse, Modal } from '@douyinfe/semi-ui'; import {
Banner,
Button,
Col,
Form,
Row,
Spin,
Collapse,
Modal,
} from '@douyinfe/semi-ui';
import { import {
compareObjects, compareObjects,
API, API,
...@@ -54,7 +63,8 @@ export default function GeneralSettings(props) { ...@@ -54,7 +63,8 @@ export default function GeneralSettings(props) {
if (requestQueue.length === 1) { if (requestQueue.length === 1) {
if (res.includes(undefined)) return; if (res.includes(undefined)) return;
} else if (requestQueue.length > 1) { } else if (requestQueue.length > 1) {
if (res.includes(undefined)) return showError(t('部分保存失败,请重试')); if (res.includes(undefined))
return showError(t('部分保存失败,请重试'));
} }
showSuccess(t('保存成功')); showSuccess(t('保存成功'));
props.refresh(); props.refresh();
...@@ -209,7 +219,9 @@ export default function GeneralSettings(props) { ...@@ -209,7 +219,9 @@ export default function GeneralSettings(props) {
> >
<Banner <Banner
type='warning' type='warning'
description={t('此设置用于系统内部计算,默认值500000是为了精确到6位小数点设计,不推荐修改。')} description={t(
'此设置用于系统内部计算,默认值500000是为了精确到6位小数点设计,不推荐修改。',
)}
bordered bordered
fullMode={false} fullMode={false}
closeIcon={null} closeIcon={null}
......
...@@ -45,7 +45,8 @@ export default function SettingsLog(props) { ...@@ -45,7 +45,8 @@ export default function SettingsLog(props) {
if (requestQueue.length === 1) { if (requestQueue.length === 1) {
if (res.includes(undefined)) return; if (res.includes(undefined)) return;
} else if (requestQueue.length > 1) { } else if (requestQueue.length > 1) {
if (res.includes(undefined)) return showError(t('部分保存失败,请重试')); if (res.includes(undefined))
return showError(t('部分保存失败,请重试'));
} }
showSuccess(t('保存成功')); showSuccess(t('保存成功'));
props.refresh(); props.refresh();
......
...@@ -5,7 +5,8 @@ import { ...@@ -5,7 +5,8 @@ import {
API, API,
showError, showError,
showSuccess, showSuccess,
showWarning, verifyJSON showWarning,
verifyJSON,
} from '../../../helpers'; } from '../../../helpers';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
...@@ -43,7 +44,8 @@ export default function SettingsMonitoring(props) { ...@@ -43,7 +44,8 @@ export default function SettingsMonitoring(props) {
if (requestQueue.length === 1) { if (requestQueue.length === 1) {
if (res.includes(undefined)) return; if (res.includes(undefined)) return;
} else if (requestQueue.length > 1) { } else if (requestQueue.length > 1) {
if (res.includes(undefined)) return showError(t('部分保存失败,请重试')); if (res.includes(undefined))
return showError(t('部分保存失败,请重试'));
} }
showSuccess(t('保存成功')); showSuccess(t('保存成功'));
props.refresh(); props.refresh();
...@@ -84,7 +86,9 @@ export default function SettingsMonitoring(props) { ...@@ -84,7 +86,9 @@ export default function SettingsMonitoring(props) {
step={1} step={1}
min={0} min={0}
suffix={t('秒')} suffix={t('秒')}
extraText={t('当运行通道全部测试时,超过此时间将自动禁用通道')} extraText={t(
'当运行通道全部测试时,超过此时间将自动禁用通道',
)}
placeholder={''} placeholder={''}
field={'ChannelDisableThreshold'} field={'ChannelDisableThreshold'}
onChange={(value) => onChange={(value) =>
...@@ -150,10 +154,14 @@ export default function SettingsMonitoring(props) { ...@@ -150,10 +154,14 @@ export default function SettingsMonitoring(props) {
<Form.TextArea <Form.TextArea
label={t('自动禁用关键词')} label={t('自动禁用关键词')}
placeholder={t('一行一个,不区分大小写')} placeholder={t('一行一个,不区分大小写')}
extraText={t('当上游通道返回错误中包含这些关键词时(不区分大小写),自动禁用通道')} extraText={t(
'当上游通道返回错误中包含这些关键词时(不区分大小写),自动禁用通道',
)}
field={'AutomaticDisableKeywords'} field={'AutomaticDisableKeywords'}
autosize={{ minRows: 6, maxRows: 12 }} autosize={{ minRows: 6, maxRows: 12 }}
onChange={(value) => setInputs({ ...inputs, AutomaticDisableKeywords: value })} onChange={(value) =>
setInputs({ ...inputs, AutomaticDisableKeywords: value })
}
/> />
</Col> </Col>
</Row> </Row>
......
...@@ -41,7 +41,8 @@ export default function SettingsSensitiveWords(props) { ...@@ -41,7 +41,8 @@ export default function SettingsSensitiveWords(props) {
if (requestQueue.length === 1) { if (requestQueue.length === 1) {
if (res.includes(undefined)) return; if (res.includes(undefined)) return;
} else if (requestQueue.length > 1) { } else if (requestQueue.length > 1) {
if (res.includes(undefined)) return showError(t('部分保存失败,请重试')); if (res.includes(undefined))
return showError(t('部分保存失败,请重试'));
} }
showSuccess(t('保存成功')); showSuccess(t('保存成功'));
props.refresh(); props.refresh();
......
...@@ -17,7 +17,7 @@ export default function RequestRateLimit(props) { ...@@ -17,7 +17,7 @@ export default function RequestRateLimit(props) {
ModelRequestRateLimitEnabled: false, ModelRequestRateLimitEnabled: false,
ModelRequestRateLimitCount: -1, ModelRequestRateLimitCount: -1,
ModelRequestRateLimitSuccessCount: 1000, ModelRequestRateLimitSuccessCount: 1000,
ModelRequestRateLimitDurationMinutes: 1 ModelRequestRateLimitDurationMinutes: 1,
}); });
const refForm = useRef(); const refForm = useRef();
const [inputsRow, setInputsRow] = useState(inputs); const [inputsRow, setInputsRow] = useState(inputs);
...@@ -43,7 +43,8 @@ export default function RequestRateLimit(props) { ...@@ -43,7 +43,8 @@ export default function RequestRateLimit(props) {
if (requestQueue.length === 1) { if (requestQueue.length === 1) {
if (res.includes(undefined)) return; if (res.includes(undefined)) return;
} else if (requestQueue.length > 1) { } else if (requestQueue.length > 1) {
if (res.includes(undefined)) return showError(t('部分保存失败,请重试')); if (res.includes(undefined))
return showError(t('部分保存失败,请重试'));
} }
showSuccess(t('保存成功')); showSuccess(t('保存成功'));
props.refresh(); props.refresh();
......
import React from 'react'; import React from 'react';
import TaskLogsTable from "../../components/TaskLogsTable.js"; import TaskLogsTable from '../../components/TaskLogsTable.js';
const Task = () => ( const Task = () => (
<> <>
......
...@@ -18,8 +18,9 @@ import { ...@@ -18,8 +18,9 @@ import {
Select, Select,
SideSheet, SideSheet,
Space, Space,
Spin, TextArea, Spin,
Typography TextArea,
Typography,
} from '@douyinfe/semi-ui'; } from '@douyinfe/semi-ui';
import Title from '@douyinfe/semi-ui/lib/es/typography/title'; import Title from '@douyinfe/semi-ui/lib/es/typography/title';
import { Divider } from 'semantic-ui-react'; import { Divider } from 'semantic-ui-react';
...@@ -47,7 +48,7 @@ const EditToken = (props) => { ...@@ -47,7 +48,7 @@ const EditToken = (props) => {
model_limits_enabled, model_limits_enabled,
model_limits, model_limits,
allow_ips, allow_ips,
group group,
} = inputs; } = inputs;
// const [visible, setVisible] = useState(false); // const [visible, setVisible] = useState(false);
const [models, setModels] = useState([]); const [models, setModels] = useState([]);
...@@ -100,7 +101,7 @@ const EditToken = (props) => { ...@@ -100,7 +101,7 @@ const EditToken = (props) => {
let localGroupOptions = Object.entries(data).map(([group, info]) => ({ let localGroupOptions = Object.entries(data).map(([group, info]) => ({
label: info.desc, label: info.desc,
value: group, value: group,
ratio: info.ratio ratio: info.ratio,
})); }));
setGroups(localGroupOptions); setGroups(localGroupOptions);
} else { } else {
...@@ -229,9 +230,7 @@ const EditToken = (props) => { ...@@ -229,9 +230,7 @@ const EditToken = (props) => {
} }
if (successCount > 0) { if (successCount > 0) {
showSuccess( showSuccess(t('令牌创建成功,请在列表页面点击复制获取令牌!'));
t('令牌创建成功,请在列表页面点击复制获取令牌!')
);
props.refresh(); props.refresh();
props.handleClose(); props.handleClose();
} }
...@@ -246,7 +245,9 @@ const EditToken = (props) => { ...@@ -246,7 +245,9 @@ const EditToken = (props) => {
<SideSheet <SideSheet
placement={isEdit ? 'right' : 'left'} placement={isEdit ? 'right' : 'left'}
title={ title={
<Title level={3}>{isEdit ? t('更新令牌信息') : t('创建新的令牌')}</Title> <Title level={3}>
{isEdit ? t('更新令牌信息') : t('创建新的令牌')}
</Title>
} }
headerStyle={{ borderBottom: '1px solid var(--semi-color-border)' }} headerStyle={{ borderBottom: '1px solid var(--semi-color-border)' }}
bodyStyle={{ borderBottom: '1px solid var(--semi-color-border)' }} bodyStyle={{ borderBottom: '1px solid var(--semi-color-border)' }}
...@@ -333,7 +334,9 @@ const EditToken = (props) => { ...@@ -333,7 +334,9 @@ const EditToken = (props) => {
<Divider /> <Divider />
<Banner <Banner
type={'warning'} type={'warning'}
description={t('注意,令牌的额度仅用于限制令牌本身的最大额度使用量,实际的使用受到账户的剩余额度限制。')} description={t(
'注意,令牌的额度仅用于限制令牌本身的最大额度使用量,实际的使用受到账户的剩余额度限制。',
)}
></Banner> ></Banner>
<div style={{ marginTop: 20 }}> <div style={{ marginTop: 20 }}>
<Typography.Text>{`${t('额度')}${renderQuotaWithPrompt(remain_quota)}`}</Typography.Text> <Typography.Text>{`${t('额度')}${renderQuotaWithPrompt(remain_quota)}`}</Typography.Text>
...@@ -396,7 +399,9 @@ const EditToken = (props) => { ...@@ -396,7 +399,9 @@ const EditToken = (props) => {
</div> </div>
<Divider /> <Divider />
<div style={{ marginTop: 10 }}> <div style={{ marginTop: 10 }}>
<Typography.Text>{t('IP白名单(请勿过度信任此功能)')}</Typography.Text> <Typography.Text>
{t('IP白名单(请勿过度信任此功能)')}
</Typography.Text>
</div> </div>
<TextArea <TextArea
label={t('IP白名单')} label={t('IP白名单')}
...@@ -440,7 +445,7 @@ const EditToken = (props) => { ...@@ -440,7 +445,7 @@ const EditToken = (props) => {
<div style={{ marginTop: 10 }}> <div style={{ marginTop: 10 }}>
<Typography.Text>{t('令牌分组,默认为用户的分组')}</Typography.Text> <Typography.Text>{t('令牌分组,默认为用户的分组')}</Typography.Text>
</div> </div>
{groups.length > 0 ? {groups.length > 0 ? (
<Select <Select
style={{ marginTop: 8 }} style={{ marginTop: 8 }}
placeholder={t('令牌分组,默认为用户的分组')} placeholder={t('令牌分组,默认为用户的分组')}
...@@ -455,14 +460,15 @@ const EditToken = (props) => { ...@@ -455,14 +460,15 @@ const EditToken = (props) => {
value={inputs.group} value={inputs.group}
autoComplete='new-password' autoComplete='new-password'
optionList={groups} optionList={groups}
/>: />
) : (
<Select <Select
style={{ marginTop: 8 }} style={{ marginTop: 8 }}
placeholder={t('管理员未设置用户可选分组')} placeholder={t('管理员未设置用户可选分组')}
name='gruop' name='gruop'
disabled={true} disabled={true}
/> />
} )}
</Spin> </Spin>
</SideSheet> </SideSheet>
</> </>
......
...@@ -10,7 +10,9 @@ const Token = () => { ...@@ -10,7 +10,9 @@ const Token = () => {
<Layout.Header> <Layout.Header>
<Banner <Banner
type='warning' type='warning'
description={t('令牌无法精确控制使用额度,只允许自用,请勿直接将令牌分发给他人。')} description={t(
'令牌无法精确控制使用额度,只允许自用,请勿直接将令牌分发给他人。',
)}
/> />
</Layout.Header> </Layout.Header>
<Layout.Content> <Layout.Content>
......
...@@ -228,8 +228,12 @@ const TopUp = () => { ...@@ -228,8 +228,12 @@ const TopUp = () => {
size={'small'} size={'small'}
centered={true} centered={true}
> >
<p>{t('充值数量')}{topUpCount}</p> <p>
<p>{t('实付金额')}{renderAmount()}</p> {t('充值数量')}{topUpCount}
</p>
<p>
{t('实付金额')}{renderAmount()}
</p>
<p>{t('是否确认充值?')}</p> <p>{t('是否确认充值?')}</p>
</Modal> </Modal>
<div <div
...@@ -280,7 +284,9 @@ const TopUp = () => { ...@@ -280,7 +284,9 @@ const TopUp = () => {
disabled={!enableOnlineTopUp} disabled={!enableOnlineTopUp}
field={'redemptionCount'} field={'redemptionCount'}
label={t('实付金额:') + ' ' + renderAmount()} label={t('实付金额:') + ' ' + renderAmount()}
placeholder={t('充值数量,最低 ') + renderQuotaWithAmount(minTopUp)} placeholder={
t('充值数量,最低 ') + renderQuotaWithAmount(minTopUp)
}
name='redemptionCount' name='redemptionCount'
type={'number'} type={'number'}
value={topUpCount} value={topUpCount}
......
...@@ -201,7 +201,9 @@ const EditUser = (props) => { ...@@ -201,7 +201,9 @@ const EditUser = (props) => {
search search
selection selection
allowAdditions allowAdditions
additionLabel={t('请在系统设置页面编辑分组倍率以添加新的分组:')} additionLabel={t(
'请在系统设置页面编辑分组倍率以添加新的分组:',
)}
onChange={(value) => handleInputChange('group', value)} onChange={(value) => handleInputChange('group', value)}
value={inputs.group} value={inputs.group}
autoComplete='new-password' autoComplete='new-password'
...@@ -231,7 +233,9 @@ const EditUser = (props) => { ...@@ -231,7 +233,9 @@ const EditUser = (props) => {
name='github_id' name='github_id'
value={github_id} value={github_id}
autoComplete='new-password' autoComplete='new-password'
placeholder={t('此项只读,需要用户通过个人设置页面的相关绑定按钮进行绑定,不可直接修改')} placeholder={t(
'此项只读,需要用户通过个人设置页面的相关绑定按钮进行绑定,不可直接修改',
)}
readonly readonly
/> />
<div style={{ marginTop: 20 }}> <div style={{ marginTop: 20 }}>
...@@ -240,7 +244,9 @@ const EditUser = (props) => { ...@@ -240,7 +244,9 @@ const EditUser = (props) => {
<Input <Input
name='oidc_id' name='oidc_id'
value={oidc_id} value={oidc_id}
placeholder={t('此项只读,需要用户通过个人设置页面的相关绑定按钮进行绑定,不可直接修改')} placeholder={t(
'此项只读,需要用户通过个人设置页面的相关绑定按钮进行绑定,不可直接修改',
)}
readonly readonly
/> />
<div style={{ marginTop: 20 }}> <div style={{ marginTop: 20 }}>
...@@ -250,7 +256,9 @@ const EditUser = (props) => { ...@@ -250,7 +256,9 @@ const EditUser = (props) => {
name='wechat_id' name='wechat_id'
value={wechat_id} value={wechat_id}
autoComplete='new-password' autoComplete='new-password'
placeholder={t('此项只读,需要用户通过个人设置页面的相关绑定按钮进行绑定,不可直接修改')} placeholder={t(
'此项只读,需要用户通过个人设置页面的相关绑定按钮进行绑定,不可直接修改',
)}
readonly readonly
/> />
<div style={{ marginTop: 20 }}> <div style={{ marginTop: 20 }}>
...@@ -260,7 +268,9 @@ const EditUser = (props) => { ...@@ -260,7 +268,9 @@ const EditUser = (props) => {
name='email' name='email'
value={email} value={email}
autoComplete='new-password' autoComplete='new-password'
placeholder={t('此项只读,需要用户通过个人设置页面的相关绑定按钮进行绑定,不可直接修改')} placeholder={t(
'此项只读,需要用户通过个人设置页面的相关绑定按钮进行绑定,不可直接修改',
)}
readonly readonly
/> />
<div style={{ marginTop: 20 }}> <div style={{ marginTop: 20 }}>
...@@ -270,7 +280,9 @@ const EditUser = (props) => { ...@@ -270,7 +280,9 @@ const EditUser = (props) => {
name='telegram_id' name='telegram_id'
value={telegram_id} value={telegram_id}
autoComplete='new-password' autoComplete='new-password'
placeholder={t('此项只读,需要用户通过个人设置页面的相关绑定按钮进行绑定,不可直接修改')} placeholder={t(
'此项只读,需要用户通过个人设置页面的相关绑定按钮进行绑定,不可直接修改',
)}
readonly readonly
/> />
</Spin> </Spin>
......
...@@ -46,7 +46,11 @@ export default defineConfig({ ...@@ -46,7 +46,11 @@ export default defineConfig({
'react-toastify', 'react-toastify',
'react-turnstile', 'react-turnstile',
], ],
'i18n': ['i18next', 'react-i18next', 'i18next-browser-languagedetector'], i18n: [
'i18next',
'react-i18next',
'i18next-browser-languagedetector',
],
}, },
}, },
}, },
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment