feat: 完善官网配置、预约管理与文章编辑

This commit is contained in:
zhanjunhao
2026-10-31 19:02:58 +08:00
parent b8659d0a9a
commit 2e6fe73939
54 changed files with 4898 additions and 203 deletions
+1 -1
View File
@@ -51,7 +51,7 @@ const CardPro = ({
searchArea,
paginationArea, // 新增分页区域
// 卡片属性
shadows = '',
shadows,
bordered = true,
// 自定义样式
style,
+2 -3
View File
@@ -134,7 +134,7 @@ const CardTable = ({
if (!col.title) {
return (
<div key={idx} className='mt-2 flex justify-end'>
<Skeleton.Title active style={{ width: 100, height: 24 }} />
<Skeleton.Title style={{ width: 100, height: 24 }} />
</div>
);
}
@@ -145,9 +145,8 @@ const CardTable = ({
className='flex justify-between items-center py-1 border-b last:border-b-0 border-dashed'
style={{ borderColor: 'var(--semi-color-border)' }}
>
<Skeleton.Title active style={{ width: 80, height: 14 }} />
<Skeleton.Title style={{ width: 80, height: 14 }} />
<Skeleton.Title
active
style={{
width: `${50 + (idx % 3) * 10}%`,
maxWidth: 180,
+125
View File
@@ -0,0 +1,125 @@
.rich-text-editor {
border: 1px solid var(--semi-color-border);
border-radius: 4px;
overflow: hidden;
background: var(--semi-color-bg-2);
}
.rich-text-editor.is-invalid {
border-color: var(--semi-color-danger);
}
.rich-text-editor:focus-within {
border-color: var(--semi-color-primary);
}
.rich-text-toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px;
padding: 8px;
border-bottom: 1px solid var(--semi-color-border);
background: var(--semi-color-fill-0);
}
.rich-text-toolbar button,
.rich-text-toolbar select {
display: inline-flex;
align-items: center;
justify-content: center;
height: 30px;
min-width: 30px;
padding: 4px 6px;
border: 0;
border-radius: 4px;
background: transparent;
color: var(--semi-color-text-1);
cursor: pointer;
}
.rich-text-toolbar select {
width: 112px;
margin-right: 4px;
}
.rich-text-toolbar button:hover,
.rich-text-toolbar button[aria-pressed='true'] {
background: var(--semi-color-primary-light-default);
color: var(--semi-color-primary);
}
.rich-text-toolbar button:focus-visible,
.rich-text-toolbar select:focus-visible {
outline: 2px solid var(--semi-color-primary);
outline-offset: 1px;
}
.rich-text-toolbar button:disabled {
opacity: 0.35;
cursor: not-allowed;
}
.rich-text-content .ql-editor {
min-height: 300px;
padding: 16px;
outline: none;
line-height: 1.9;
color: var(--semi-color-text-0);
overflow-wrap: anywhere;
}
.rich-text-content .ql-editor > * + * {
margin-top: 12px;
}
.rich-text-content .ql-editor.ql-blank::before {
color: var(--semi-color-text-2);
font-style: normal;
pointer-events: none;
white-space: pre-wrap;
}
.rich-text-content h2 {
font-size: 22px;
font-weight: 600;
}
.rich-text-content h3 {
font-size: 18px;
font-weight: 600;
}
.rich-text-content ul {
list-style: disc;
padding-left: 24px;
}
.rich-text-content .ql-editor ol {
padding-left: 0;
}
.rich-text-content blockquote {
border-left: 3px solid var(--semi-color-border);
padding-left: 16px;
color: var(--semi-color-text-2);
}
.rich-text-content img {
max-width: 100%;
height: auto;
}
.rich-text-count {
border-top: 1px solid var(--semi-color-border);
padding: 4px 12px;
text-align: right;
font-size: 12px;
color: var(--semi-color-text-2);
}
.rich-text-content.ql-container,
.rich-text-content .ql-container {
font-family: inherit;
font-size: 14px;
}
.rich-text-editor.is-invalid:focus-within {
border-color: var(--semi-color-danger);
}
.rich-text-toolbar select option {
background: var(--semi-color-bg-2);
color: var(--semi-color-text-0);
}
.rich-text-content .ql-editor img {
display: inline-block;
vertical-align: middle;
}
.rich-text-image-error {
padding: 8px 12px;
font-size: 12px;
color: var(--semi-color-danger);
border-top: 1px solid var(--semi-color-border);
line-height: 1.6;
}
+509
View File
@@ -0,0 +1,509 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useRef, useState } from 'react';
import Quill, { Delta } from 'quill/core';
import BoldFormat from 'quill/formats/bold';
import ItalicFormat from 'quill/formats/italic';
import UnderlineFormat from 'quill/formats/underline';
import HeaderFormat from 'quill/formats/header';
import ListFormat from 'quill/formats/list';
import QuoteFormat from 'quill/formats/blockquote';
import ImageFormat from 'quill/formats/image';
import {
Bold,
Italic,
Underline,
List,
ListOrdered,
Quote,
Undo2,
Redo2,
Eraser,
ImagePlus,
} from 'lucide-react';
import {
articleImageSource,
ARTICLE_IMAGE_TYPES,
readArticleImage,
} from './richTextImages';
import { sanitizeArticleHtml } from './richTextContent';
import { countRichText, limitRichTextChange } from './richTextLength';
import 'quill/dist/quill.core.css';
import './RichTextEditor.css';
Quill.register(
{
'formats/bold': BoldFormat,
'formats/italic': ItalicFormat,
'formats/underline': UnderlineFormat,
'formats/header': HeaderFormat,
'formats/list': ListFormat,
'formats/blockquote': QuoteFormat,
'formats/image': ImageFormat,
},
true,
);
export default function RichTextEditor({
value = '',
onChange,
disabled = false,
invalid = false,
onBusyChange,
label = '富文本正文',
placeholder = '',
maxLength,
}) {
const host = useRef(null);
const picker = useRef(null);
const instance = useRef(null);
const selection = useRef({ index: 0, length: 0 });
const callbacks = useRef({
value,
onChange,
onBusyChange,
disabled,
label,
placeholder,
maxLength,
});
const insertFiles = useRef(null);
const lastHtml = useRef('');
const [format, setFormat] = useState({});
const [count, setCount] = useState(0);
const [busy, setBusy] = useState(false);
const [imageError, setImageError] = useState('');
useEffect(() => {
callbacks.current = {
value,
onChange,
onBusyChange,
disabled,
label,
placeholder,
maxLength,
};
}, [value, onChange, onBusyChange, disabled, label, placeholder, maxLength]);
useEffect(() => {
// A separate mount node keeps Quill DOM mutations outside React's tree.
const mount = document.createElement('div');
const container = host.current;
container.append(mount);
let active = true;
let processing = false;
let compositionStart = null;
const quill = new Quill(mount, {
readOnly: callbacks.current.disabled,
placeholder: callbacks.current.placeholder,
formats: [
'bold',
'italic',
'underline',
'header',
'list',
'blockquote',
'image',
],
modules: { history: { userOnly: false }, toolbar: false },
});
instance.current = quill;
const root = quill.root;
root.setAttribute('role', 'textbox');
root.setAttribute('aria-multiline', 'true');
root.setAttribute('aria-required', 'true');
root.setAttribute('aria-label', callbacks.current.label);
const update = (change, old) => {
if (compositionStart) return;
const limit = callbacks.current.maxLength;
if (Number.isFinite(limit) && old && change) {
const bounded = old.compose(
new Delta(limitRichTextChange(old, change, limit)),
);
const correction = quill.getContents().diff(bounded);
if (correction.length()) quill.updateContents(correction, 'silent');
}
const html = sanitizeArticleHtml(quill.getSemanticHTML());
const next =
!quill.getText().trim() && !root.querySelector('img') ? '' : html;
lastHtml.current = next;
setCount(countRichText(quill.getText()));
callbacks.current.onChange?.(next);
};
const updateSelection = (range) => {
if (range)
selection.current = { index: range.index, length: range.length };
setFormat(quill.getFormat(range || selection.current));
};
quill.setContents(
quill.clipboard.convert({
html: sanitizeArticleHtml(callbacks.current.value),
}),
'silent',
);
lastHtml.current = callbacks.current.value;
setCount(countRichText(quill.getText()));
quill.history.clear();
quill.on('text-change', update);
quill.on('editor-change', updateSelectionFromEditor);
function updateSelectionFromEditor(name, range) {
updateSelection(
name === 'selection-change' ? range : quill.getSelection(),
);
}
const begin = () => {
if (!active || processing || callbacks.current.disabled) return false;
processing = true;
setBusy(true);
setImageError('');
callbacks.current.onBusyChange?.(true);
quill.enable(false);
return true;
};
const finish = () => {
processing = false;
if (!active) return;
setBusy(false);
callbacks.current.onBusyChange?.(false);
quill.enable(!callbacks.current.disabled);
if (!callbacks.current.disabled) {
const range = { ...selection.current };
quill.focus();
quill.setSelection(range, 'silent');
}
};
const insert = (delta, range) => {
if (!active) return;
let change = new Delta()
.retain(range.index)
.delete(range.length)
.concat(delta);
if (Number.isFinite(callbacks.current.maxLength)) {
change = new Delta(
limitRichTextChange(
quill.getContents(),
change,
callbacks.current.maxLength,
),
);
}
quill.history.cutoff();
quill.updateContents(change, 'api');
quill.history.cutoff();
selection.current = {
index: change.transformPosition(range.index, false),
length: 0,
};
};
const readFiles = async (files) => {
const sources = [];
for (const file of files) {
try {
sources.push(await readArticleImage(file));
} catch (error) {
if (active) setImageError(error.message);
sources.push('');
}
}
return sources;
};
insertFiles.current = async (files) => {
if (!begin()) return;
const range = { ...selection.current };
try {
const sources = await readFiles(files);
const delta = sources
.filter(Boolean)
.reduce(
(result, source) => result.insert({ image: source }),
new Delta(),
);
if (delta.length()) insert(delta, range);
} finally {
finish();
}
};
const paste = async (event) => {
event.preventDefault();
event.stopImmediatePropagation();
if (!begin()) return;
const range = quill.getSelection() || selection.current;
const html = event.clipboardData?.getData('text/html') || '';
const text = event.clipboardData?.getData('text/plain') || '';
const files = Array.from(event.clipboardData?.files || []);
try {
let delta;
if (html) {
const template = document.createElement('template');
template.innerHTML = html;
let fileIndex = 0;
let sources;
for (const img of template.content.querySelectorAll('img')) {
const original = img.getAttribute('src') || '';
let source =
articleImageSource(original) ||
articleImageSource(img.getAttribute('data-src'));
if (
!source &&
/^(?:file:|blob:|cid:|$)/i.test(original) &&
files.length
) {
sources ??= await readFiles(files);
source = sources[fileIndex++];
}
if (source) img.setAttribute('src', source);
else {
img.remove();
if (active)
setImageError(
'部分图片无法粘贴,请使用可公开访问的图片地址,或粘贴不超过 2 MB 的 JPG、PNG、WebP、GIF 图片。',
);
}
}
delta = quill.clipboard.convert({
html: sanitizeArticleHtml(template.innerHTML),
text,
});
} else if (files.length) {
const sources = await readFiles(files);
delta = sources
.filter(Boolean)
.reduce(
(result, source) => result.insert({ image: source }),
new Delta(),
);
} else
delta = quill.clipboard.convert(
{ text },
quill.getFormat(range.index),
);
if (delta.length()) insert(delta, range);
} catch {
if (active) setImageError('粘贴失败,请重试或使用纯文本粘贴');
} finally {
finish();
}
};
const imageFailed = (event) => {
if (event.target.tagName === 'IMG')
setImageError(
'部分图片加载失败,请确认原图地址可公开访问,或下载图片后重新插入。',
);
};
// Capture before Quill's default clipboard/uploader to validate every image path.
root.addEventListener('paste', paste, true);
root.addEventListener('error', imageFailed, true);
const drop = (event) => {
event.preventDefault();
event.stopImmediatePropagation();
insertFiles.current?.(Array.from(event.dataTransfer?.files || []));
};
root.addEventListener('drop', drop, true);
const startComposition = () => {
compositionStart = quill.getContents();
};
const endComposition = () => {
queueMicrotask(() => {
if (!active || !compositionStart) return;
const old = compositionStart;
compositionStart = null;
quill.update();
update(old.diff(quill.getContents()), old);
});
};
root.addEventListener('compositionstart', startComposition);
root.addEventListener('compositionend', endComposition);
return () => {
active = false;
callbacks.current.onBusyChange?.(false);
quill.off('text-change', update);
quill.off('editor-change', updateSelectionFromEditor);
root.removeEventListener('paste', paste, true);
root.removeEventListener('error', imageFailed, true);
root.removeEventListener('drop', drop, true);
root.removeEventListener('compositionstart', startComposition);
root.removeEventListener('compositionend', endComposition);
quill.enable(false);
instance.current = null;
insertFiles.current = null;
mount.remove();
container.classList.remove('ql-container');
};
}, []);
useEffect(() => {
const quill = instance.current;
if (!quill) return;
quill.enable(!disabled && !busy);
quill.root.setAttribute('aria-invalid', String(invalid));
quill.root.setAttribute('aria-label', label);
// Quill renders placeholder text via CSS, keeping it outside saved HTML.
quill.root.setAttribute('data-placeholder', placeholder);
quill.root.setAttribute('aria-placeholder', placeholder);
}, [disabled, busy, invalid, label, placeholder]);
useEffect(() => {
const quill = instance.current;
if (!quill || value === lastHtml.current) return;
quill.setContents(
quill.clipboard.convert({ html: sanitizeArticleHtml(value) }),
'silent',
);
quill.history.clear();
lastHtml.current = value;
selection.current = { index: 0, length: 0 };
setCount(countRichText(quill.getText()));
setFormat({});
}, [value]);
const run = (command) => {
const quill = instance.current;
if (!quill || disabled || busy) return;
const range = { ...selection.current };
quill.focus();
quill.setSelection(range, 'silent');
command(quill);
setFormat(quill.getFormat());
};
const tools = [
['加粗', Bold, (q) => q.format('bold', !format.bold, 'user'), format.bold],
[
'斜体',
Italic,
(q) => q.format('italic', !format.italic, 'user'),
format.italic,
],
[
'下划线',
Underline,
(q) => q.format('underline', !format.underline, 'user'),
format.underline,
],
[
'项目列表',
List,
(q) =>
q.format('list', format.list === 'bullet' ? false : 'bullet', 'user'),
format.list === 'bullet',
],
[
'有序列表',
ListOrdered,
(q) =>
q.format('list', format.list === 'ordered' ? false : 'ordered', 'user'),
format.list === 'ordered',
],
[
'引用',
Quote,
(q) => q.format('blockquote', !format.blockquote, 'user'),
format.blockquote,
],
['撤销', Undo2, (q) => q.history.undo()],
['重做', Redo2, (q) => q.history.redo()],
[
'清除格式',
Eraser,
(q) =>
q.removeFormat(
selection.current.index,
selection.current.length || 1,
'user',
),
],
];
return (
<div
className={`rich-text-editor ${invalid ? 'is-invalid' : ''}`}
aria-busy={busy}
>
<div
className='rich-text-toolbar'
role='toolbar'
aria-label='富文本工具栏'
>
<select
aria-label='段落格式'
disabled={disabled || busy}
value={format.header || ''}
onChange={(event) =>
run((q) =>
q.format('header', Number(event.target.value) || false, 'user'),
)
}
>
<option value=''>正文段落</option>
<option value='2'>二级标题</option>
<option value='3'>三级标题</option>
</select>
{tools.map(([name, Icon, command, selected = false]) => (
<button
key={name}
type='button'
title={name}
aria-label={name}
aria-pressed={Boolean(selected)}
disabled={disabled || busy}
onMouseDown={(event) => event.preventDefault()}
onClick={() => run(command)}
>
<Icon size={16} />
</button>
))}
<button
type='button'
title='插入正文图片(单张不超过 2 MB)'
aria-label='插入正文图片'
disabled={disabled || busy}
onMouseDown={(event) => event.preventDefault()}
onClick={() => {
picker.current.value = '';
picker.current.click();
}}
>
<ImagePlus size={16} />
</button>
<input
ref={picker}
type='file'
accept={ARTICLE_IMAGE_TYPES.join(',')}
hidden
multiple
onChange={(event) =>
insertFiles.current?.(Array.from(event.target.files || []))
}
/>
</div>
<div ref={host} className='rich-text-content' />
{imageError && (
<div className='rich-text-image-error' role='alert'>
{imageError}
</div>
)}
<div className='rich-text-count'>
{busy
? '图片处理中…'
: `${count}${maxLength ? ` / ${maxLength}` : ''} 字`}
</div>
</div>
);
}
@@ -153,10 +153,9 @@ const SelectableButtonGroup = ({
}}
>
{withCheckbox && (
<Skeleton.Title active style={{ width: 14, height: 14 }} />
<Skeleton.Title style={{ width: 14, height: 14 }} />
)}
<Skeleton.Title
active
style={{
width: `${60 + (index % 3) * 20}px`,
height: 14,
@@ -264,7 +263,7 @@ const SelectableButtonGroup = ({
{title && (
<Divider margin='12px' align='left'>
{showSkeleton ? (
<Skeleton.Title active style={{ width: 80, height: 14 }} />
<Skeleton.Title style={{ width: 80, height: 14 }} />
) : (
title
)}
@@ -0,0 +1,86 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { articleImageSource } from './richTextImages.js';
const TAGS = new Set([
'P',
'DIV',
'H2',
'H3',
'BR',
'B',
'STRONG',
'I',
'EM',
'U',
'UL',
'OL',
'LI',
'IMG',
'SPAN',
'BLOCKQUOTE',
]);
export function sanitizeArticleHtml(html) {
const template = document.createElement('template');
template.innerHTML = String(html || '');
const clean = (node) => {
for (const child of [...node.children]) {
if (
[
'SCRIPT',
'STYLE',
'IFRAME',
'OBJECT',
'SVG',
'MATH',
'LINK',
'META',
].includes(child.tagName)
) {
child.remove();
continue;
}
clean(child);
if (!TAGS.has(child.tagName)) {
child.replaceWith(...child.childNodes);
continue;
}
const src = child.getAttribute('src');
for (const attribute of [...child.attributes])
child.removeAttribute(attribute.name);
if (child.tagName === 'IMG') {
const source = articleImageSource(src);
if (source) {
child.setAttribute('src', source);
child.setAttribute('alt', '文章配图');
} else child.remove();
}
}
};
clean(template.content);
// Quill images are inline embeds; standalone images need their own paragraph.
for (const child of [...template.content.children]) {
if (child.tagName !== 'IMG') continue;
const paragraph = document.createElement('p');
child.replaceWith(paragraph);
paragraph.append(child);
}
return template.innerHTML;
}
@@ -0,0 +1,68 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
export const ARTICLE_IMAGE_LIMIT = 2 * 1024 * 1024;
export const ARTICLE_IMAGE_TYPES = [
'image/jpeg',
'image/png',
'image/webp',
'image/gif',
];
export function articleImageSource(value) {
const source = String(value || '').trim();
if (source.startsWith('data:')) {
const match =
/^data:(image\/(?:png|jpeg|webp|gif));base64,([A-Za-z0-9+/]+={0,2})$/i.exec(
source,
);
if (!match || match[2].length % 4) return '';
const bytes =
(match[2].length * 3) / 4 - (match[2].match(/=+$/)?.[0].length || 0);
return bytes > 0 && bytes <= ARTICLE_IMAGE_LIMIT ? source : '';
}
try {
const url = new URL(source);
return ['http:', 'https:'].includes(url.protocol) &&
!url.username &&
!url.password
? url.href
: '';
} catch {
return '';
}
}
export async function readArticleImage(file) {
if (!ARTICLE_IMAGE_TYPES.includes(file.type))
throw new Error('正文图片仅支持 JPG、PNG、WebP、GIF 格式');
if (!file.size || file.size > ARTICLE_IMAGE_LIMIT)
throw new Error('单张正文图片大小不能超过 2 MB,且不能为空');
try {
const bitmap = await createImageBitmap(file);
bitmap.close();
} catch {
throw new Error('无法读取图片,请选择有效的图片文件');
}
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result));
reader.onerror = () => reject(new Error('图片读取失败,请重新选择或粘贴'));
reader.readAsDataURL(file);
});
}
@@ -0,0 +1,59 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { decodeHTML } from 'entities';
export const ARTICLE_BODY_LIMIT = 20000;
export const countRichText = (text) =>
Array.from(text.replace(/\s/g, '')).length;
export const countArticleHtml = (html) =>
countRichText(decodeHTML(String(html || '').replace(/<[^>]*>/g, '')));
const countDelta = (delta) =>
delta.ops.reduce(
(total, op) =>
total + (typeof op.insert === 'string' ? countRichText(op.insert) : 0),
0,
);
// Budget only newly inserted text, keeping the original text after the caret intact.
export function limitRichTextChange(old, change, limit) {
let oldIndex = 0;
let remaining = limit - countDelta(old);
for (const op of change.ops) {
if (op.delete)
remaining += countDelta(old.slice(oldIndex, oldIndex + op.delete));
oldIndex += op.retain || op.delete || 0;
}
remaining = Math.max(0, remaining);
const ops = change.ops.flatMap((op) => {
if (typeof op.insert !== 'string') return [op];
const text = Array.from(op.insert)
.filter((char) => {
if (/\s/.test(char)) return true;
if (!remaining) return false;
remaining--;
return true;
})
.join('');
return text ? [{ ...op, insert: text }] : [];
});
return ops;
}
+2 -5
View File
@@ -77,7 +77,6 @@ const printConsoleWelcome = (status) => {
};
const PageLayout = () => {
console.log('[PageLayout] Component rendering...');
const [userState, userDispatch] = useContext(UserContext);
const [statusState, statusDispatch] = useContext(StatusContext);
const isMobile = useIsMobile();
@@ -96,7 +95,8 @@ const PageLayout = () => {
const shouldInnerPadding =
location.pathname.includes('/console') &&
!location.pathname.startsWith('/console/chat') &&
location.pathname !== '/console/playground';
location.pathname !== '/console/playground' &&
location.pathname !== '/console/website-setting';
const isConsoleRoute = location.pathname.startsWith('/console');
const showSider = isConsoleRoute && (!isMobile || drawerOpen);
@@ -226,10 +226,8 @@ const PageLayout = () => {
};
const loadStatus = async () => {
console.log('[PageLayout] Loading status from API...');
try {
const res = await API.get('/api/status');
console.log('[PageLayout] API response received:', res.data);
const { success, data } = res.data;
if (success) {
statusDispatch({ type: 'set', payload: data });
@@ -243,7 +241,6 @@ const PageLayout = () => {
if (data.theme_config !== undefined) {
applyTheme(data.theme_config);
}
console.log('[PageLayout] Status loaded successfully');
} else {
console.error('[PageLayout] API returned success=false');
showError('Unable to connect to server');
+47 -13
View File
@@ -27,6 +27,11 @@ import { useSidebar } from '../../hooks/common/useSidebar';
import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime';
import { isAdmin, isRoot, showError } from '../../helpers';
import { StatusContext } from '../../context/Status';
import { UserContext } from '../../context/User';
import {
canAccessDelegatedAdminPage,
getDelegatedSettingTabs,
} from '../../helpers/adminDelegation';
import SkeletonWrapper from './components/SkeletonWrapper';
import { CLOUD_BRAIN_UI_ENABLED } from '../../config/cloudBrainUi';
@@ -42,6 +47,8 @@ const routerMap = {
log: '/console/log',
midjourney: '/console/midjourney',
setting: '/console/setting',
'website-setting': '/console/website-setting',
'demo-reservations': '/console/demo-reservations',
about: '/about',
detail: '/console',
pricing: '/market',
@@ -75,16 +82,13 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
} = useSidebar();
const [statusState] = useContext(StatusContext);
const [userState] = useContext(UserContext);
const delegatedPermissions = statusState?.status?.AdminDelegatedSettingTabs;
// 系统设置 tab 权限下放:普通管理员在被下放了至少一个 tab 时,才显示「系统设置」入口
const delegatedSettingTabs = useMemo(() => {
try {
const raw = statusState?.status?.AdminDelegatedSettingTabs;
const parsed = raw ? JSON.parse(raw) : [];
return Array.isArray(parsed) ? parsed : [];
} catch (e) {
return [];
}
}, [statusState?.status?.AdminDelegatedSettingTabs]);
const delegatedSettingTabs = useMemo(
() => getDelegatedSettingTabs(delegatedPermissions),
[delegatedPermissions],
);
const canAccessSetting =
isRoot() || (isAdmin() && delegatedSettingTabs.length > 0);
@@ -284,10 +288,31 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
to: '/setting',
className: canAccessSetting ? '' : 'tableHiddle',
},
{
text: t('官网设置'),
itemKey: 'website-setting',
className: isAdmin() ? '' : 'tableHiddle',
},
{
text: t('预约演示'),
itemKey: 'demo-reservations',
className: isAdmin() ? '' : 'tableHiddle',
},
];
// 根据配置过滤项目
const filteredItems = items.filter((item) => {
if (
(item.itemKey === 'website-setting' ||
item.itemKey === 'demo-reservations') &&
!canAccessDelegatedAdminPage(
userState?.user?.role,
delegatedPermissions,
item.itemKey,
)
) {
return false;
}
if (
!CLOUD_BRAIN_UI_ENABLED &&
(item.itemKey === 'skill-platform' ||
@@ -315,7 +340,16 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
});
return filteredItems;
}, [isAdmin(), isRoot(), t, isModuleVisible, canAccessSetting]);
}, [
isAdmin(),
isRoot(),
t,
isModuleVisible,
canAccessSetting,
delegatedSettingTabs,
delegatedPermissions,
userState?.user?.role,
]);
const chatMenuItems = useMemo(() => {
const items = [
@@ -597,8 +631,8 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
</>
)}
{/* 管理员区域 - 只在管理员时显示且配置允许时显示 */}
{isAdmin() && hasSectionVisibleModules('admin') && (
{/* 管理员区域:按角色、权限下放及菜单配置过滤。 */}
{isAdmin() && (
<>
<Divider className='sidebar-divider' />
<div>
@@ -637,7 +671,7 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
/>
}
onClick={toggleCollapsed}
icononly={collapsed}
aria-label={collapsed ? t('展开侧边栏') : t('收起侧边栏')}
style={
collapsed
? { width: 36, height: 24, padding: 0 }
@@ -52,7 +52,6 @@ const SkeletonWrapper = ({
active
placeholder={
<Skeleton.Title
active
style={{ width: isMobile ? 40 : width, height }}
/>
}
@@ -71,7 +70,7 @@ const SkeletonWrapper = ({
loading={true}
active
placeholder={
<Skeleton.Avatar active size='extra-small' className='shadow-sm' />
<Skeleton.Avatar size='extra-small' className='shadow-sm' />
}
/>
<div className='ml-1.5 mr-1'>
@@ -80,7 +79,6 @@ const SkeletonWrapper = ({
active
placeholder={
<Skeleton.Title
active
style={{ width: isMobile ? 15 : width, height: 12 }}
/>
}
@@ -98,7 +96,6 @@ const SkeletonWrapper = ({
active
placeholder={
<Skeleton.Image
active
className={`absolute inset-0 !rounded-full ${className}`}
style={{ width: '100%', height: '100%' }}
/>
@@ -113,7 +110,7 @@ const SkeletonWrapper = ({
<Skeleton
loading={true}
active
placeholder={<Skeleton.Title active style={{ width, height: 24 }} />}
placeholder={<Skeleton.Title style={{ width, height: 24 }} />}
/>
);
};
@@ -125,7 +122,7 @@ const SkeletonWrapper = ({
<Skeleton
loading={true}
active
placeholder={<Skeleton.Title active style={{ width, height }} />}
placeholder={<Skeleton.Title style={{ width, height }} />}
/>
</div>
);
@@ -139,10 +136,7 @@ const SkeletonWrapper = ({
loading={true}
active
placeholder={
<Skeleton.Title
active
style={{ width, height, borderRadius: 9999 }}
/>
<Skeleton.Title style={{ width, height, borderRadius: 9999 }} />
}
/>
</div>
@@ -164,7 +158,7 @@ const SkeletonWrapper = ({
loading={true}
active
placeholder={
<Skeleton.Avatar active size='extra-small' shape='square' />
<Skeleton.Avatar size='extra-small' shape='square' />
}
/>
</div>
@@ -174,7 +168,6 @@ const SkeletonWrapper = ({
active
placeholder={
<Skeleton.Title
active
style={{ width: width || 80, height: height || 14 }}
/>
}
@@ -192,7 +185,6 @@ const SkeletonWrapper = ({
active
placeholder={
<Skeleton.Title
active
style={{ width: width || 60, height: height || 12 }}
/>
}
@@ -217,7 +209,6 @@ const SkeletonWrapper = ({
active
placeholder={
<Skeleton.Avatar
active
shape='square'
style={{ width: ICON_SIZE, height: ICON_SIZE }}
/>
@@ -230,10 +221,7 @@ const SkeletonWrapper = ({
loading={true}
active
placeholder={
<Skeleton.Title
active
style={{ width: labelWidth, height: TEXT_HEIGHT }}
/>
<Skeleton.Title style={{ width: labelWidth, height: TEXT_HEIGHT }} />
}
/>
);
@@ -269,7 +257,6 @@ const SkeletonWrapper = ({
active
placeholder={
<Skeleton.Avatar
active
shape='square'
style={{ width: ICON_SIZE, height: ICON_SIZE }}
/>
@@ -284,22 +271,22 @@ const SkeletonWrapper = ({
{Array(2)
.fill(null)
.map((_, i) => (
<CollapsedRow keyPrefix='c-chat' index={i} />
<CollapsedRow key={i} keyPrefix='c-chat' index={i} />
))}
{Array(5)
.fill(null)
.map((_, i) => (
<CollapsedRow keyPrefix='c-console' index={i} />
<CollapsedRow key={i} keyPrefix='c-console' index={i} />
))}
{Array(2)
.fill(null)
.map((_, i) => (
<CollapsedRow keyPrefix='c-personal' index={i} />
<CollapsedRow key={i} keyPrefix='c-personal' index={i} />
))}
{Array(5)
.fill(null)
.map((_, i) => (
<CollapsedRow keyPrefix='c-admin' index={i} />
<CollapsedRow key={i} keyPrefix='c-admin' index={i} />
))}
</div>
);
@@ -329,7 +316,6 @@ const SkeletonWrapper = ({
active
placeholder={
<Skeleton.Title
active
style={{ width: sec.titleWidth, height: TITLE_HEIGHT }}
/>
}
@@ -350,7 +336,6 @@ const SkeletonWrapper = ({
active
placeholder={
<Skeleton.Title
active
style={{ width: sec.titleWidth, height: TITLE_HEIGHT }}
/>
}
@@ -82,19 +82,21 @@ const LanguageSelector = ({ currentLang, onLanguageChange, t }) => {
</Dropdown.Menu>
}
>
<Button
icon={<Globe size={20} />}
aria-label={t('common.changeLanguage')}
theme='borderless'
type='tertiary'
className='!w-8 !h-8 sm:!w-9 sm:!h-9 !flex !items-center !justify-center hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !rounded-full !transition-all !duration-200 hover:!scale-[1.08] active:!scale-95'
style={{
color:
actualTheme === 'dark'
? 'rgba(243,244,246,0.9)'
: 'rgba(75,85,99,1)',
}}
/>
<span className='inline-flex'>
<Button
icon={<Globe size={20} />}
aria-label={t('common.changeLanguage')}
theme='borderless'
type='tertiary'
className='!w-8 !h-8 sm:!w-9 sm:!h-9 !flex !items-center !justify-center hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !rounded-full !transition-all !duration-200 hover:!scale-[1.08] active:!scale-95'
style={{
color:
actualTheme === 'dark'
? 'rgba(243,244,246,0.9)'
: 'rgba(75,85,99,1)',
}}
/>
</span>
</Dropdown>
);
};
@@ -133,19 +133,21 @@ const MobileNavMenu = ({ mainNavLinks, userState, t }) => {
</Dropdown.Menu>
}
>
<Button
theme='borderless'
type='tertiary'
aria-label={t('主导航')}
aria-haspopup='menu'
aria-expanded={visible}
icon={<Compass size={16} />}
className='!ml-1 !px-2 !h-8 max-w-[9rem] !rounded-xl !text-current hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !transition-all !duration-200 active:!scale-95 [&_.semi-button-content]:min-w-0'
>
<span className='ml-1 text-[13px] font-semibold truncate'>
{activeItem ? activeItem.text : t('导航')}
</span>
</Button>
<span className='inline-flex'>
<Button
theme='borderless'
type='tertiary'
aria-label={t('主导航')}
aria-haspopup='menu'
aria-expanded={visible}
icon={<Compass size={16} />}
className='!ml-1 !px-2 !h-8 max-w-[9rem] !rounded-xl !text-current hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !transition-all !duration-200 active:!scale-95 [&_.semi-button-content]:min-w-0'
>
<span className='ml-1 text-[13px] font-semibold truncate'>
{activeItem ? activeItem.text : t('导航')}
</span>
</Button>
</span>
</Dropdown>
);
};
+16 -13
View File
@@ -251,19 +251,22 @@ const ThemeToggle = ({ theme, onThemeToggle, t }) => {
</Dropdown.Menu>
}
>
<Button
icon={currentButtonIcon}
aria-label={t('切换主题')}
theme='borderless'
type='tertiary'
className='!w-8 !h-8 sm:!w-9 sm:!h-9 !flex !items-center !justify-center hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !rounded-full !transition-all !duration-200 hover:!scale-[1.08] active:!scale-95'
style={{
color:
actualTheme === 'dark'
? 'rgba(243,244,246,0.9)'
: 'rgba(75,85,99,1)',
}}
/>
{/* Semi can resolve a DOM trigger directly without findDOMNode. */}
<span className='inline-flex'>
<Button
icon={currentButtonIcon}
aria-label={t('切换主题')}
theme='borderless'
type='tertiary'
className='!w-8 !h-8 sm:!w-9 sm:!h-9 !flex !items-center !justify-center hover:!bg-brand/10 dark:hover:!bg-brand/15 hover:!text-brand-deep dark:hover:!text-brand-from !rounded-full !transition-all !duration-200 hover:!scale-[1.08] active:!scale-95'
style={{
color:
actualTheme === 'dark'
? 'rgba(243,244,246,0.9)'
: 'rgba(75,85,99,1)',
}}
/>
</span>
</Dropdown>
);
};
+35 -33
View File
@@ -300,41 +300,43 @@ const UserArea = ({
</Dropdown.Menu>
}
>
<Button
theme='borderless'
type='tertiary'
className='flex items-center gap-2 !pl-1.5 !pr-2.5 !py-1.5 !h-10 !rounded-full hover:!bg-brand/10 dark:hover:!bg-brand/15 !bg-transparent !transition-all !duration-200 hover:!-translate-y-0.5 group'
>
<div className='relative'>
<Avatar
size='small'
src={avatarUrl}
color={stringToColor(displayName)}
className='!w-7 !h-7 !text-xs ring-2 ring-white dark:ring-gray-800 group-hover:!ring-brand/40 dark:group-hover:!ring-brand/50 transition-all'
>
{displayName[0].toUpperCase()}
</Avatar>
{/* 在线状态点 */}
<span className='absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 bg-emerald-500 border-2 border-white dark:border-gray-800 rounded-full' />
</div>
<span className='hidden md:flex flex-col items-start'>
<Typography.Text
className='!text-sm !font-medium !leading-none'
<span className='inline-flex'>
<Button
theme='borderless'
type='tertiary'
className='flex items-center gap-2 !pl-1.5 !pr-2.5 !py-1.5 !h-10 !rounded-full hover:!bg-brand/10 dark:hover:!bg-brand/15 !bg-transparent !transition-all !duration-200 hover:!-translate-y-0.5 group'
>
<div className='relative'>
<Avatar
size='small'
src={avatarUrl}
color={stringToColor(displayName)}
className='!w-7 !h-7 !text-xs ring-2 ring-white dark:ring-gray-800 group-hover:!ring-brand/40 dark:group-hover:!ring-brand/50 transition-all'
>
{displayName[0].toUpperCase()}
</Avatar>
{/* 在线状态点 */}
<span className='absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 bg-emerald-500 border-2 border-white dark:border-gray-800 rounded-full' />
</div>
<span className='hidden md:flex flex-col items-start'>
<Typography.Text
className='!text-sm !font-medium !leading-none'
style={{
color: isDark ? 'rgba(243,244,246,0.9)' : 'rgba(55,65,81,1)',
}}
>
{displayName}
</Typography.Text>
</span>
<ChevronDown
size={14}
style={{
color: isDark ? 'rgba(243,244,246,0.9)' : 'rgba(55,65,81,1)',
color: isDark ? 'rgba(209,213,219,1)' : 'rgba(156,163,175,1)',
}}
>
{displayName}
</Typography.Text>
</span>
<ChevronDown
size={14}
style={{
color: isDark ? 'rgba(209,213,219,1)' : 'rgba(156,163,175,1)',
}}
className='group-hover:!opacity-80 transition-colors'
/>
</Button>
className='group-hover:!opacity-80 transition-colors'
/>
</Button>
</span>
</Dropdown>
);
} else {
+63 -9
View File
@@ -18,7 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Card, Spin } from '@douyinfe/semi-ui';
import { Banner, Button, Card, Spin } from '@douyinfe/semi-ui';
import SettingsGeneral from '../../pages/Setting/Operation/SettingsGeneral';
import SettingsLanguage from '../../pages/Setting/Operation/SettingsLanguage';
import SettingsHeaderNavModules from '../../pages/Setting/Operation/SettingsHeaderNavModules';
@@ -35,7 +35,34 @@ import SettingsFallback from '../../pages/Setting/Operation/SettingsFallback';
import SettingsTheme from '../../pages/Setting/Operation/SettingsTheme';
import SettingsAdminDelegation from '../../pages/Setting/Operation/SettingsAdminDelegation';
import SettingsSkillInject from '../../pages/Setting/Operation/SettingsSkillInject';
import { API, showError, toBoolean } from '../../helpers';
import { API, toBoolean } from '../../helpers';
const ProgressiveSettingsSections = ({ children, loading }) => {
const sections = React.Children.toArray(children);
const [visibleCount, setVisibleCount] = useState(1);
useEffect(() => {
if (visibleCount >= sections.length) return;
// Yield between sections so mounting all forms cannot block one task.
const timer = setTimeout(() => setVisibleCount((count) => count + 1), 0);
return () => clearTimeout(timer);
}, [visibleCount, sections.length]);
return (
<Spin spinning={loading} size='large'>
{sections.slice(0, visibleCount)}
{visibleCount < sections.length && (
<div
role='status'
aria-busy='true'
className='flex justify-center py-6'
>
<Spin spinning />
</div>
)}
</Spin>
);
};
const OperationSetting = () => {
let [inputs, setInputs] = useState({
@@ -98,6 +125,13 @@ const OperationSetting = () => {
/* 提示词采集(实验性,方案 §35 一期) */
GlobalPromptArchiveEnabled: false,
/* Skill switches arrive as strings from the options API. */
SkillMarketRequireAuth: false,
SkillInjectEnabled: false,
SkillInjectMaxSkills: '5',
SkillInjectMaxRunes: '3000',
SkillInjectCacheTTLSeconds: '60',
/* 监控设置 */
ChannelDisableThreshold: 0,
QuotaRemindThreshold: 0,
@@ -135,13 +169,15 @@ const OperationSetting = () => {
'fallback_setting.max_attempts_per_request': 10,
});
let [loading, setLoading] = useState(false);
const [loading, setLoading] = useState(true);
const [optionsLoaded, setOptionsLoaded] = useState(false);
const [loadError, setLoadError] = useState('');
const inputTypes = useRef(inputs);
const getOptions = useCallback(async () => {
const res = await API.get('/api/option/');
const { success, message, data } = res.data;
if (success) {
if (success && Array.isArray(data)) {
let newInputs = {};
data.forEach((item) => {
if (typeof inputTypes.current[item.key] === 'boolean') {
@@ -153,16 +189,17 @@ const OperationSetting = () => {
setInputs(newInputs);
} else {
showError(message);
throw new Error(message || '运营设置读取失败,请重试');
}
}, []);
const onRefresh = useCallback(async () => {
try {
setLoading(true);
setLoadError('');
await getOptions();
// showSuccess('刷新成功');
setOptionsLoaded(true);
} catch (error) {
showError('刷新失败');
setLoadError(error.message || '运营设置读取失败,请重试');
} finally {
setLoading(false);
}
@@ -172,9 +209,26 @@ const OperationSetting = () => {
onRefresh();
}, [onRefresh]);
const errorBanner = loadError && (
<Banner type='danger' closeIcon={null} description={loadError}>
<Button onClick={onRefresh} disabled={loading}>
重新加载运营设置
</Button>
</Banner>
);
// Never mount editable defaults when the initial request fails.
if (!optionsLoaded) {
if (loadError) return errorBanner;
return (
<Spin spinning size='large' style={{ minHeight: 200, width: '100%' }} />
);
}
return (
<>
<Spin spinning={loading} size='large'>
{errorBanner}
<ProgressiveSettingsSections loading={loading}>
{/* 通用设置 */}
<Card style={{ marginTop: '10px' }}>
<SettingsGeneral options={inputs} refresh={onRefresh} />
@@ -235,7 +289,7 @@ const OperationSetting = () => {
<SettingsExperienceCenter options={inputs} refresh={onRefresh} />
{/* 普通管理员可见的系统设置页(权限下放) */}
<SettingsAdminDelegation options={inputs} refresh={onRefresh} />
</Spin>
</ProgressiveSettingsSections>
</>
);
};