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

This commit is contained in:
zhanjunhao
2026-10-31 19:02:58 +08:00
parent a2e5f6ef0e
commit 90b710215a
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;
}