feat(announcement): 支持 Markdown 预览后再发布 (#342)
This commit is contained in:
@@ -1,4 +1,5 @@
|
|||||||
import { Fragment, createElement, type ReactNode } from "react";
|
import ReactMarkdown from "react-markdown";
|
||||||
|
import remarkGfm from "remark-gfm";
|
||||||
|
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
@@ -7,72 +8,32 @@ type AnnouncementContentProps = {
|
|||||||
className?: string;
|
className?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const elementMap = {
|
|
||||||
a: "a",
|
|
||||||
b: "strong",
|
|
||||||
blockquote: "blockquote",
|
|
||||||
br: "br",
|
|
||||||
code: "code",
|
|
||||||
del: "del",
|
|
||||||
div: "div",
|
|
||||||
em: "em",
|
|
||||||
i: "em",
|
|
||||||
li: "li",
|
|
||||||
mark: "mark",
|
|
||||||
ol: "ol",
|
|
||||||
p: "p",
|
|
||||||
s: "s",
|
|
||||||
strong: "strong",
|
|
||||||
u: "u",
|
|
||||||
ul: "ul",
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
const ignoredTags = new Set(["iframe", "object", "script", "style", "svg", "template"]);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 公告由管理员输入但会在所有用户页面展示,因此只将受控标签转换成 React 节点,避免直接注入 HTML。
|
* 公告由管理员输入但会在所有用户页面展示,因此不启用原始 HTML,避免直接注入 HTML。
|
||||||
* 链接强制新窗口打开,并且只允许 http/https 协议。
|
* 链接强制新窗口打开,并且只允许 http/https 协议。
|
||||||
*/
|
*/
|
||||||
export function AnnouncementContent({ content, className }: AnnouncementContentProps) {
|
export function AnnouncementContent({ content, className }: AnnouncementContentProps) {
|
||||||
return <div className={cn("whitespace-pre-wrap break-words", className)}>{parseAnnouncementContent(content)}</div>;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseAnnouncementContent(content: string): ReactNode {
|
|
||||||
if (typeof DOMParser === "undefined") return content;
|
|
||||||
|
|
||||||
const document = new DOMParser().parseFromString(content, "text/html");
|
|
||||||
return Array.from(document.body.childNodes).map((node, index) => renderNode(node, `announcement-${index}`));
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderNode(node: ChildNode, key: string): ReactNode {
|
|
||||||
if (node.nodeType === Node.TEXT_NODE) {
|
|
||||||
return <Fragment key={key}>{node.textContent}</Fragment>;
|
|
||||||
}
|
|
||||||
if (node.nodeType !== Node.ELEMENT_NODE) return null;
|
|
||||||
|
|
||||||
const element = node as HTMLElement;
|
|
||||||
const tag = element.tagName.toLowerCase();
|
|
||||||
if (ignoredTags.has(tag)) return null;
|
|
||||||
|
|
||||||
const children = Array.from(element.childNodes).map((child, index) => renderNode(child, `${key}-${index}`));
|
|
||||||
if (!(tag in elementMap)) return <Fragment key={key}>{children}</Fragment>;
|
|
||||||
|
|
||||||
if (tag === "a") {
|
|
||||||
const href = safeHref(element.getAttribute("href"));
|
|
||||||
if (!href) return <Fragment key={key}>{children}</Fragment>;
|
|
||||||
return (
|
return (
|
||||||
<a key={key} href={href} target="_blank" rel="noopener noreferrer" className="text-blue-600 underline decoration-blue-600/40 underline-offset-2 transition hover:text-blue-700 dark:text-blue-400 dark:decoration-blue-400/50 dark:hover:text-blue-300">
|
<div className={cn("break-words [&_a]:text-blue-600 [&_a]:underline [&_a]:decoration-blue-600/40 [&_a]:underline-offset-2 [&_a]:transition [&_a]:hover:text-blue-700 dark:[&_a]:text-blue-400 dark:[&_a]:decoration-blue-400/50 dark:[&_a]:hover:text-blue-300 [&_blockquote]:my-2 [&_blockquote]:border-l-2 [&_blockquote]:border-border [&_blockquote]:pl-3 [&_code]:rounded [&_code]:bg-muted [&_code]:px-1 [&_code]:py-0.5 [&_code]:font-mono [&_code]:text-[0.9em] [&_h1]:mb-2 [&_h1]:mt-3 [&_h1]:text-lg [&_h1]:font-semibold [&_h2]:mb-2 [&_h2]:mt-3 [&_h2]:text-base [&_h2]:font-semibold [&_h3]:mb-1 [&_h3]:mt-2 [&_h3]:font-semibold [&_li]:ml-5 [&_li]:list-disc [&_ol_li]:list-decimal [&_ol]:my-2 [&_p]:my-2 [&_pre]:my-2 [&_pre]:overflow-x-auto [&_pre]:rounded-md [&_pre]:bg-muted [&_pre]:p-3 [&_pre_code]:bg-transparent [&_pre_code]:p-0 [&_table]:my-2 [&_table]:border-collapse [&_td]:border [&_td]:border-border [&_td]:px-2 [&_td]:py-1 [&_th]:border [&_th]:border-border [&_th]:bg-muted [&_th]:px-2 [&_th]:py-1 [&_ul]:my-2", className)}>
|
||||||
{children}
|
<ReactMarkdown
|
||||||
</a>
|
remarkPlugins={[remarkGfm]}
|
||||||
|
skipHtml
|
||||||
|
components={{
|
||||||
|
a: ({ children, href }) => {
|
||||||
|
const safeURL = safeHref(href);
|
||||||
|
return safeURL ? <a href={safeURL} target="_blank" rel="noopener noreferrer">{children}</a> : <>{children}</>;
|
||||||
|
},
|
||||||
|
table: ({ children }) => <div className="overflow-x-auto"><table>{children}</table></div>,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{content}
|
||||||
|
</ReactMarkdown>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
|
||||||
|
|
||||||
const component = elementMap[tag as keyof typeof elementMap];
|
|
||||||
return createElement(component, { key }, children);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function safeHref(value: string | null) {
|
function safeHref(value?: string) {
|
||||||
if (!value) return null;
|
if (!value || typeof window === "undefined") return null;
|
||||||
try {
|
try {
|
||||||
const url = new URL(value, window.location.href);
|
const url = new URL(value, window.location.href);
|
||||||
return url.protocol === "http:" || url.protocol === "https:" ? url.href : null;
|
return url.protocol === "http:" || url.protocol === "https:" ? url.href : null;
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
import { App, Button, Form, Input, Modal, Select, Switch, Tag } from "antd";
|
import { App, Button, Form, Input, Modal, Select, Segmented, Switch, Tag } from "antd";
|
||||||
|
import type { FormInstance } from "antd";
|
||||||
import type { ColumnsType } from "antd/es/table";
|
import type { ColumnsType } from "antd/es/table";
|
||||||
import { Pin, Plus, Search, Upload, X } from "lucide-react";
|
import { Eye, Pencil, Pin, Plus, Search, Upload, X } from "lucide-react";
|
||||||
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from "react";
|
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from "react";
|
||||||
|
|
||||||
import { PaginationBar } from "@/components/layout/workspace-page";
|
import { PaginationBar } from "@/components/layout/workspace-page";
|
||||||
|
import { AnnouncementContent } from "@/components/ui/announcement-content";
|
||||||
import { useDebouncedValue } from "@/hooks/use-debounced-value";
|
import { useDebouncedValue } from "@/hooks/use-debounced-value";
|
||||||
import {
|
import {
|
||||||
announcementImageUrl,
|
announcementImageUrl,
|
||||||
@@ -60,6 +62,7 @@ export default function AdminAnnouncementsPanel() {
|
|||||||
const [imagePreviewUrl, setImagePreviewUrl] = useState("");
|
const [imagePreviewUrl, setImagePreviewUrl] = useState("");
|
||||||
const [draftImageResourceId, setDraftImageResourceId] = useState("");
|
const [draftImageResourceId, setDraftImageResourceId] = useState("");
|
||||||
const [imageUploading, setImageUploading] = useState(false);
|
const [imageUploading, setImageUploading] = useState(false);
|
||||||
|
const [editorMode, setEditorMode] = useState<"edit" | "preview">("edit");
|
||||||
const imageInputRef = useRef<HTMLInputElement | null>(null);
|
const imageInputRef = useRef<HTMLInputElement | null>(null);
|
||||||
|
|
||||||
const reload = useCallback(async () => {
|
const reload = useCallback(async () => {
|
||||||
@@ -84,6 +87,7 @@ export default function AdminAnnouncementsPanel() {
|
|||||||
form.setFieldsValue({ title: "", content: "", imageResourceId: "", level: "info", pinned: false });
|
form.setFieldsValue({ title: "", content: "", imageResourceId: "", level: "info", pinned: false });
|
||||||
setImagePreviewUrl("");
|
setImagePreviewUrl("");
|
||||||
setDraftImageResourceId("");
|
setDraftImageResourceId("");
|
||||||
|
setEditorMode("edit");
|
||||||
setModalOpen(true);
|
setModalOpen(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -92,6 +96,7 @@ export default function AdminAnnouncementsPanel() {
|
|||||||
form.setFieldsValue({ title: announcement.title, content: announcement.content, imageResourceId: announcement.imageResourceId || "", level: announcement.level, pinned: announcement.pinned });
|
form.setFieldsValue({ title: announcement.title, content: announcement.content, imageResourceId: announcement.imageResourceId || "", level: announcement.level, pinned: announcement.pinned });
|
||||||
setImagePreviewUrl(announcementImageUrl(announcement));
|
setImagePreviewUrl(announcementImageUrl(announcement));
|
||||||
setDraftImageResourceId("");
|
setDraftImageResourceId("");
|
||||||
|
setEditorMode("edit");
|
||||||
setModalOpen(true);
|
setModalOpen(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -259,8 +264,19 @@ export default function AdminAnnouncementsPanel() {
|
|||||||
footer={<PaginationBar alwaysShow current={page} pageSize={pageSize} total={total} onChange={(nextPage, nextPageSize) => { setPage(nextPageSize !== pageSize ? 1 : nextPage); setPageSize(nextPageSize); }} />}
|
footer={<PaginationBar alwaysShow current={page} pageSize={pageSize} total={total} onChange={(nextPage, nextPageSize) => { setPage(nextPageSize !== pageSize ? 1 : nextPage); setPageSize(nextPageSize); }} />}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Modal title={editingAnnouncement ? "编辑并重新发布公告" : "发布系统公告"} open={modalOpen} width={760} centered okText={editingAnnouncement ? "保存并重新发布" : "立即发布"} cancelText="取消" confirmLoading={publishing} okButtonProps={{ disabled: imageUploading }} cancelButtonProps={{ disabled: imageUploading }} onOk={() => void publish()} onCancel={() => void closeEditor()} destroyOnHidden>
|
<Modal title={editingAnnouncement ? "编辑并重新发布公告" : "发布系统公告"} open={modalOpen} width={760} centered okText={editorMode === "preview" ? (editingAnnouncement ? "确认并重新发布" : "确认并发布") : "请先预览"} cancelText="取消" confirmLoading={publishing} okButtonProps={{ disabled: imageUploading || editorMode !== "preview" }} cancelButtonProps={{ disabled: imageUploading }} onOk={() => void publish()} onCancel={() => void closeEditor()} destroyOnHidden>
|
||||||
<Form form={form} layout="vertical" className="pt-3" requiredMark={false}>
|
<div className="flex justify-end border-b border-border/70 pb-3 pt-3">
|
||||||
|
<Segmented
|
||||||
|
value={editorMode}
|
||||||
|
onChange={(value) => setEditorMode(value as "edit" | "preview")}
|
||||||
|
options={[
|
||||||
|
{ value: "edit", label: <span className="inline-flex items-center gap-1.5"><Pencil className="size-3.5" />编辑</span> },
|
||||||
|
{ value: "preview", label: <span className="inline-flex items-center gap-1.5"><Eye className="size-3.5" />预览</span> },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{editorMode === "preview" ? <AnnouncementDraftPreview form={form} imagePreviewUrl={imagePreviewUrl} /> : null}
|
||||||
|
<Form form={form} layout="vertical" className={editorMode === "preview" ? "hidden" : "pt-4"} requiredMark={false}>
|
||||||
<Form.Item name="title" label="公告标题" rules={[{ required: true, whitespace: true, message: "请填写公告标题" }, { max: 120, message: "标题不能超过 120 个字符" }]}>
|
<Form.Item name="title" label="公告标题" rules={[{ required: true, whitespace: true, message: "请填写公告标题" }, { max: 120, message: "标题不能超过 120 个字符" }]}>
|
||||||
<Input maxLength={120} showCount placeholder="例如:视频模型已恢复正常使用" />
|
<Input maxLength={120} showCount placeholder="例如:视频模型已恢复正常使用" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
@@ -285,8 +301,13 @@ export default function AdminAnnouncementsPanel() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item name="content" label="公告正文" rules={[{ required: true, whitespace: true, message: "请填写公告正文" }, { max: 4000, message: "正文不能超过 4000 个字符" }]}>
|
<Form.Item
|
||||||
<Input.TextArea maxLength={4000} showCount autoSize={{ minRows: 6, maxRows: 12 }} placeholder="填写服务状态、影响范围和用户需要采取的操作" />
|
name="content"
|
||||||
|
label="公告正文(支持 Markdown)"
|
||||||
|
extra="支持标题、加粗、列表、链接、引用和表格;不支持原始 HTML。"
|
||||||
|
rules={[{ required: true, whitespace: true, message: "请填写公告正文" }, { max: 4000, message: "正文不能超过 4000 个字符" }]}
|
||||||
|
>
|
||||||
|
<Input.TextArea maxLength={4000} showCount autoSize={{ minRows: 6, maxRows: 12 }} placeholder="填写服务状态、影响范围和用户需要采取的操作,可使用 Markdown 语法" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
</Form>
|
</Form>
|
||||||
</Modal>
|
</Modal>
|
||||||
@@ -294,6 +315,33 @@ export default function AdminAnnouncementsPanel() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function AnnouncementDraftPreview({ form, imagePreviewUrl }: { form: FormInstance<AnnouncementFormValues>; imagePreviewUrl: string }) {
|
||||||
|
const title = Form.useWatch("title", form) || "未填写标题";
|
||||||
|
const content = Form.useWatch("content", form) || "暂未填写公告正文";
|
||||||
|
const level = Form.useWatch("level", form) || "info";
|
||||||
|
const pinned = Form.useWatch("pinned", form);
|
||||||
|
const meta = levelMeta[level as AnnouncementLevel] || levelMeta.info;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-80 py-5">
|
||||||
|
<div className="mx-auto max-w-2xl overflow-hidden rounded-xl border border-border/70 bg-background shadow-sm">
|
||||||
|
<div className="flex items-center justify-between border-b border-border/60 px-5 py-3">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<AdminStatusBadge label={meta.label} tone={meta.tone} />
|
||||||
|
{pinned ? <span className="inline-flex items-center gap-1 text-xs font-medium text-amber-500"><Pin className="size-3" />置顶</span> : null}
|
||||||
|
</div>
|
||||||
|
<span className="text-xs text-foreground/40">预览效果</span>
|
||||||
|
</div>
|
||||||
|
<div className="p-5">
|
||||||
|
<h2 className="text-lg font-semibold leading-7 text-foreground">{title}</h2>
|
||||||
|
{imagePreviewUrl ? <img src={imagePreviewUrl} alt="公告配图预览" className="mt-4 max-h-56 w-full rounded-lg border border-border/70 bg-muted/20 object-contain p-1" /> : null}
|
||||||
|
<AnnouncementContent content={content} className="mt-3 text-sm leading-6 text-foreground/75" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function formatDateTime(value: string) {
|
function formatDateTime(value: string) {
|
||||||
const date = new Date(value);
|
const date = new Date(value);
|
||||||
if (Number.isNaN(date.getTime())) return "--";
|
if (Number.isNaN(date.getTime())) return "--";
|
||||||
|
|||||||
Reference in New Issue
Block a user