feat(banner): 首页常驻滚动通知 - 合并 PR #531 到本地

将常驻通知迁移顺延为 v20-v22,避免与已发布的 v19 支付插件版本冲突。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
ddCatandCursor committed 2026-09-18 09:43:40 +08:00
commit 521629c2a8
36 files changed
+3379 -12

No files matched your search

@@ -1,6 +1,7 @@
import { lazy, Suspense, useEffect, useState, type ReactNode } from "react";
import { useLocation, useNavigate } from "react-router";
import { BannerAnnouncementsSlider } from "@/components/layout/banner-announcements-slider";
import { ModelSetupGuide } from "@/components/layout/model-setup-guide";
import { WorkspaceSidebarNav } from "@/components/layout/workspace-sidebar-nav";
import { readWorkspaceSidebarCollapsed, writeWorkspaceSidebarCollapsed } from "@/components/layout/workspace-sidebar-state";
@@ -81,6 +82,8 @@ export function AppWorkspaceShell({ children }: { children: ReactNode }) {
<div className={cn("app-workspace-shell flex h-dvh min-h-0 w-full flex-col overflow-hidden", spatialWorkbench && "is-spatial", creationWorkspace && "is-creation-workspace")}>
{!hideChrome && mobileSidebarExpanded ? <button type="button" className="app-workspace-sidebar-scrim lg:hidden" aria-label="收起侧栏" onClick={() => setMobileSidebarExpanded(false)} /> : null}
{showGlobalTopBar ? <BannerAnnouncementsSlider /> : null}
<div className="app-workspace-main-row flex min-h-0 min-w-0 flex-1 overflow-hidden">
{!hideChrome ? (
<aside
@@ -0,0 +1,53 @@
import { ChevronRight } from "lucide-react";
import { bannerNoticeSurfaceCSS } from "@/lib/announcements/banner-notice";
import { bannerTitleRunStyle, type BannerTitleRun } from "@/lib/announcements/banner-title";
/**
* 通知条的展示单元:底色、富文本标题、详情入口。
*
* 首页通知条与后台「前台效果预览」共用这里的每一个部件——后台 DIY 出来的结果之所以能原样回显,
* 靠的就是两处不各写一份渲染,而不是靠两边样式对齐。
* 图标素材(emoji)是标题文本的一部分,随 BannerAnnouncementTitle 一起渲染,这里不单独处理。
*/
/** 通知条底色:由通知类型决定,明暗两档交给 token 在各自主题下解析,组件不感知主题。 */
export function bannerAnnouncementBarStyle(noticeType?: string | null) {
return { backgroundColor: bannerNoticeSurfaceCSS(noticeType) };
}
/** 「详情 ›」入口;仅在通知可点击时由调用方渲染。 */
export function BannerAnnouncementLinkHint({ chevronClassName }: { chevronClassName?: string }) {
return (
<span className="flex shrink-0 items-center gap-1 text-[var(--fs-label)] font-semibold text-white">
<span>详情</span>
<ChevronRight className={chevronClassName || "size-3.5"} aria-hidden="true" />
</span>
);
}
/**
* 通知标题:按样式分段输出行内 span,未设置样式的维度沿用外层类名(通知条为白色 12px 半粗)。
* 分段为空时回落到纯文本标题,避免旧数据不显示。
*/
export function BannerAnnouncementTitle({ runs, fallbackText }: { runs?: BannerTitleRun[] | null; fallbackText?: string }) {
if (!runs || !runs.length) {
return <>{fallbackText || ""}</>;
}
return (
<>
{runs.map((run, index) => {
const style = bannerTitleRunStyle(run);
return (
<span
key={`${index}:${run.text}`}
style={style}
className={!run.color ? "text-white" : undefined}
>
{run.text}
</span>
);
})}
</>
);
}
@@ -0,0 +1,144 @@
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { X } from "lucide-react";
import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router";
import { getActiveBanners, type BannerAnnouncement } from "@/services/api/announcements";
import {
BannerAnnouncementLinkHint,
BannerAnnouncementTitle,
bannerAnnouncementBarStyle,
} from "@/components/layout/banner-announcement-content";
import { useUserStore } from "@/stores/use-user-store";
const BANNER_AUTO_SLIDE_MS = 4000;
const BANNER_DISMISS_STORAGE_PREFIX = "yingce.banner-announcements.dismissed";
export function BannerAnnouncementsSlider() {
const navigate = useNavigate();
const reducedMotion = useReducedMotion();
const userId = useUserStore((state) => state.user?.id);
const [currentIndex, setCurrentIndex] = useState(0);
const [dismissed, setDismissed] = useState(false);
const { data } = useQuery({
queryKey: ["active-banner-announcements"],
queryFn: getActiveBanners,
staleTime: 60_000,
refetchInterval: 3 * 60_000,
});
const banners = data?.banners || [];
const fingerprint = bannerFeedFingerprint(banners);
const hasLink = Boolean(banners[currentIndex % Math.max(banners.length, 1)]?.link);
useEffect(() => {
if (banners.length <= 1) return;
const timer = window.setInterval(() => {
setCurrentIndex((prev) => (prev + 1) % banners.length);
}, BANNER_AUTO_SLIDE_MS);
return () => window.clearInterval(timer);
}, [banners.length]);
const handleClick = () => {
const current = banners[currentIndex % Math.max(banners.length, 1)];
if (!current?.link) return;
if (/^https?:\/\//i.test(current.link)) {
window.open(current.link, "_blank", "noopener,noreferrer");
return;
}
navigate(current.link);
};
// banners 数量变化时把下标收拢到有效范围,避免残留越界值。
useEffect(() => {
if (banners.length > 0 && currentIndex >= banners.length) {
setCurrentIndex(0);
}
}, [banners.length, currentIndex]);
// 关闭状态按「用户 + 通知快照」记录:后台新增或重新编辑通知后快照变化,通知条会再次出现。
useEffect(() => {
setDismissed(fingerprint ? hasBannerDismissal(userId, fingerprint) : false);
}, [fingerprint, userId]);
const handleDismiss = () => {
rememberBannerDismissal(userId, fingerprint);
setDismissed(true);
};
if (!banners.length || dismissed) return null;
const currentBanner = banners[currentIndex % banners.length];
// 底色随每条通知的类型切换:加过渡让不同风格的条目轮播时平滑换色,与标题动画节奏一致。
return (
<div
className="relative flex min-h-10 w-full shrink-0 items-center justify-center px-4 py-2 text-white transition-colors duration-300 ease-out"
style={bannerAnnouncementBarStyle(currentBanner.noticeType)}
>
<button
type="button"
onClick={handleClick}
disabled={!hasLink}
className="group flex h-full w-full min-w-0 items-center justify-center px-8 transition-opacity enabled:hover:opacity-90 disabled:cursor-default"
title={hasLink ? "点击查看详情" : undefined}
>
<span className="flex min-w-0 items-center justify-center gap-2.5">
{/* 标题内容区:通过外层弹性居中对齐,不用固定高度控制 */}
<span className="relative flex min-w-0 items-center justify-center">
<AnimatePresence mode="wait">
<motion.span
key={currentBanner.id}
initial={reducedMotion ? { opacity: 0, y: 0 } : { opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
exit={reducedMotion ? { opacity: 0, y: 0 } : { opacity: 0, y: -10 }}
transition={{ duration: 0.3, ease: "easeOut" }}
className="inline-flex items-center justify-center truncate font-semibold tracking-wide drop-shadow-sm"
>
<BannerAnnouncementTitle runs={currentBanner.titleRuns} fallbackText={currentBanner.title} />
</motion.span>
</AnimatePresence>
</span>
{hasLink ? <BannerAnnouncementLinkHint chevronClassName="size-3.5 transition-transform group-hover:translate-x-0.5" /> : null}
</span>
</button>
<button
type="button"
onClick={handleDismiss}
aria-label="关闭通知"
title="关闭"
className="absolute right-3 top-1/2 grid size-6 -translate-y-1/2 place-items-center rounded-full text-white transition-colors hover:bg-white/20"
>
<X className="size-3.5" aria-hidden="true" />
</button>
</div>
);
}
function bannerFeedFingerprint(banners: BannerAnnouncement[]) {
return banners
.map((banner) => `${banner.id}:${banner.updatedAt}`)
.sort()
.join("|");
}
function bannerDismissalKey(userId?: string) {
return `${BANNER_DISMISS_STORAGE_PREFIX}.${userId || "anonymous"}`;
}
function hasBannerDismissal(userId: string | undefined, fingerprint: string) {
try {
return localStorage.getItem(bannerDismissalKey(userId)) === fingerprint;
} catch {
return false;
}
}
function rememberBannerDismissal(userId: string | undefined, fingerprint: string) {
try {
localStorage.setItem(bannerDismissalKey(userId), fingerprint);
} catch {
// 浏览器禁用存储时仍允许关闭,本次组件生命周期内不会重复出现。
}
}
+181
View File
@@ -0,0 +1,181 @@
/**
* 首页常驻通知条的「通知类型」与「标题图标素材」模型。
*
* 通知类型决定通知条底色(后台与前台共用同一套 token)。
* 图标素材是 emoji 字符:它就是普通文本,随 TitleRuns 的文本分段一起存储与渲染,
* 因此可以插到标题任意位置、跟随分段样式、参与关键字检索,后端不需要单独字段或白名单。
*
* 本模块只放纯数据与纯函数,不 import 任何组件。
*/
export type BannerNoticeType = "notice" | "activity" | "update" | "warning";
/** 未指定类型时的兜底:平台公告。 */
export const BANNER_NOTICE_DEFAULT_TYPE: BannerNoticeType = "notice";
export const BANNER_NOTICE_TYPES: {
key: BannerNoticeType;
label: string;
hint: string;
/** 该类型的语义底色 token;由 globals.css 按明暗主题分别取值。 */
surfaceVar: string;
}[] = [
{ key: "notice", label: "公告", hint: "平台公告、规则与流程变更", surfaceVar: "--notice-banner-surface-notice" },
{ key: "activity", label: "活动", hint: "运营活动、限时促销与福利", surfaceVar: "--notice-banner-surface-activity" },
{ key: "update", label: "更新", hint: "版本发布、功能上新与改版", surfaceVar: "--notice-banner-surface-update" },
{ key: "warning", label: "警告", hint: "维护窗口、风险与服务异常", surfaceVar: "--notice-banner-surface-warning" },
];
const BANNER_NOTICE_TYPE_KEYS = new Set<string>(BANNER_NOTICE_TYPES.map((item) => item.key));
/** 未知 / 空类型一律回落到默认类型,通知条不会因为脏数据失去底色。 */
export function normalizeBannerNoticeType(value?: string | null): BannerNoticeType {
const raw = (value || "").trim().toLowerCase();
return BANNER_NOTICE_TYPE_KEYS.has(raw) ? (raw as BannerNoticeType) : BANNER_NOTICE_DEFAULT_TYPE;
}
export function bannerNoticeTypeMeta(value?: string | null) {
const key = normalizeBannerNoticeType(value);
return BANNER_NOTICE_TYPES.find((item) => item.key === key) as (typeof BANNER_NOTICE_TYPES)[number];
}
export function bannerNoticeTypeLabel(value?: string | null) {
return bannerNoticeTypeMeta(value).label;
}
export function bannerNoticeTypeHint(value?: string | null) {
return bannerNoticeTypeMeta(value).hint;
}
/** 该类型底色的 CSS 引用(含 var());scope 内可被预览容器覆盖成明暗指定档。 */
export function bannerNoticeSurfaceCSS(value?: string | null) {
return `var(${bannerNoticeTypeMeta(value).surfaceVar})`;
}
/** 合法类型键,供后端白名单与前端一致性测试使用。 */
export const BANNER_NOTICE_TYPE_VALUES = BANNER_NOTICE_TYPES.map((item) => item.key);
/**
* 标题可插入的 emoji 图标素材,按用途分组。
* 每项的 char 会作为普通文本插进标题(跟随光标处的字号 / 颜色样式),label 供搜索与 aria 标注。
*/
export const BANNER_NOTICE_EMOJI_GROUPS: { key: string; label: string; emoji: { char: string; label: string }[] }[] = [
{
key: "notice",
label: "通知",
emoji: [
{ char: "📢", label: "喇叭" },
{ char: "📣", label: "扩音" },
{ char: "🔔", label: "铃铛" },
{ char: "📮", label: "邮筒" },
{ char: "📌", label: "图钉" },
{ char: "📄", label: "文件" },
{ char: "📝", label: "备注" },
{ char: "📰", label: "快讯" },
{ char: "🗓️", label: "日历" },
{ char: "⏰", label: "闹钟" },
{ char: "🕐", label: "时钟" },
{ char: "🎯", label: "目标" },
],
},
{
key: "celebrate",
label: "庆祝",
emoji: [
{ char: "🎉", label: "撒花" },
{ char: "🎊", label: "礼花" },
{ char: "🎈", label: "气球" },
{ char: "🎁", label: "礼物" },
{ char: "🎂", label: "蛋糕" },
{ char: "🥳", label: "狂欢" },
{ char: "🏆", label: "奖杯" },
{ char: "🥇", label: "金牌" },
{ char: "👑", label: "皇冠" },
{ char: "💎", label: "宝石" },
{ char: "✨", label: "闪光" },
{ char: "⭐", label: "星星" },
],
},
{
key: "hot",
label: "热门",
emoji: [
{ char: "🔥", label: "热门" },
{ char: "🚀", label: "火箭" },
{ char: "⚡", label: "闪电" },
{ char: "💥", label: "爆炸" },
{ char: "🌟", label: "亮星" },
{ char: "💫", label: "星晕" },
{ char: "🌈", label: "彩虹" },
{ char: "☀️", label: "太阳" },
{ char: "🌙", label: "月亮" },
{ char: "❤️", label: "红心" },
{ char: "💯", label: "满分" },
{ char: "👍", label: "点赞" },
],
},
{
key: "commerce",
label: "商业",
emoji: [
{ char: "💰", label: "钱袋" },
{ char: "💸", label: "飞钱" },
{ char: "💳", label: "银行卡" },
{ char: "🏦", label: "银行" },
{ char: "🛒", label: "购物车" },
{ char: "🛍️", label: "购物袋" },
{ char: "🏷️", label: "价签" },
{ char: "💼", label: "公文包" },
{ char: "📈", label: "上涨" },
{ char: "📉", label: "下跌" },
{ char: "🎫", label: "票券" },
{ char: "🎟️", label: "门票" },
],
},
{
key: "status",
label: "状态",
emoji: [
{ char: "✅", label: "完成" },
{ char: "❌", label: "取消" },
{ char: "⚠️", label: "警告" },
{ char: "⛔", label: "禁止" },
{ char: "🚫", label: "禁用" },
{ char: "❓", label: "疑问" },
{ char: "❗", label: "感叹" },
{ char: "⏳", label: "等待" },
{ char: "🔄", label: "刷新" },
{ char: "🔧", label: "扳手" },
{ char: "🔒", label: "上锁" },
{ char: "🐞", label: "缺陷" },
],
},
];
/** 扁平化的 emoji 清单,顺序与分组一致。 */
export const BANNER_NOTICE_EMOJIS = BANNER_NOTICE_EMOJI_GROUPS.flatMap((group) =>
group.emoji.map((item) => ({ ...item, group: group.key, groupLabel: group.label })),
);
/** 按关键字过滤(匹配中文名、分组名或字符本身),空关键字返回全量。 */
export function searchBannerNoticeEmojis(keyword: string) {
const query = keyword.trim().toLowerCase();
if (!query) return BANNER_NOTICE_EMOJIS;
return BANNER_NOTICE_EMOJIS.filter((item) => item.char.includes(query) || item.label.includes(query) || item.groupLabel.includes(query));
}
/**
* 读取指定类型在当前主题下的通知条实底色,避免把设计 token 的色值复制到 TS 里。
* scope 传后台预览容器可在该容器强制指定的明 / 暗档里取值。
*/
export function readBannerNoticeSurface(noticeType?: string | null, scope?: HTMLElement | null) {
if (typeof window === "undefined") return "";
const host = scope || window.document.body || window.document.documentElement;
if (!host) return "";
const probe = window.document.createElement("span");
probe.style.cssText = `position:absolute;left:-9999px;top:-9999px;background-color:${bannerNoticeSurfaceCSS(noticeType)}`;
host.appendChild(probe);
const resolved = window.getComputedStyle(probe).backgroundColor;
probe.remove();
return resolved;
}
@@ -0,0 +1,217 @@
/**
* 通知标题富文本编辑与通知条渲染之间的桥接层。
*
* 编辑器用 Tiptap 提供选区能力,但存储与渲染都只认 `BannerTitleRun[]`:
* - 只保留一个 paragraph 与行内 `textStyle` 标记,标题永远是单段、单行语义。
* - 字号 / 字体只接受白名单档位(其余值在转换时丢弃),因此不会把任意 CSS 写进通知条。
*/
import { Extension, type Editor, type JSONContent } from "@tiptap/core";
import CharacterCount from "@tiptap/extension-character-count";
import { Color } from "@tiptap/extension-color";
import Placeholder from "@tiptap/extension-placeholder";
import { FontFamily, FontSize, TextStyle } from "@tiptap/extension-text-style";
import { StarterKit } from "@tiptap/starter-kit";
import {
BANNER_TITLE_FONT_FAMILIES,
BANNER_TITLE_FONT_SIZES,
BANNER_TITLE_FONT_WEIGHTS,
bannerTitleFontFamilyCSS,
bannerTitleFontFamilyKey,
normalizeBannerTitleHex,
normalizeBannerTitleRuns,
type BannerTitleFontFamilyKey,
type BannerTitleRun,
} from "./banner-title";
export const BANNER_TITLE_TEXT_STYLE = "textStyle";
/**
* 字重没有官方扩展,按 FontSize 的写法把 fontWeight 挂到 textStyle 标记上。
* 只声明属性,不下发命令:样式统一走 applyBannerTitleStyle,保证每个文本节点只留一个标记。
*/
export const BannerTitleFontWeight = Extension.create<{ types: string[] }>({
name: "bannerTitleFontWeight",
addOptions() {
return { types: [BANNER_TITLE_TEXT_STYLE] };
},
addGlobalAttributes() {
return [
{
types: this.options.types,
attributes: {
fontWeight: {
default: null,
parseHTML: (element) => element.style.fontWeight || null,
renderHTML: (attributes) => (attributes.fontWeight ? { style: `font-weight: ${attributes.fontWeight}` } : {}),
},
},
},
];
},
});
export function createBannerTitleExtensions(placeholder?: string) {
return [
StarterKit.configure({
bold: false,
blockquote: false,
bulletList: false,
code: false,
codeBlock: false,
dropcursor: false,
gapcursor: false,
hardBreak: false,
heading: false,
horizontalRule: false,
italic: false,
link: false,
listItem: false,
listKeymap: false,
orderedList: false,
strike: false,
trailingNode: false,
underline: false,
}),
TextStyle,
FontSize,
FontFamily,
Color,
BannerTitleFontWeight,
CharacterCount,
...(placeholder ? [Placeholder.configure({ placeholder })] : []),
];
}
export type BannerTitleStylePatch = {
fontSize?: number | null;
fontWeight?: number | null;
fontFamily?: BannerTitleFontFamilyKey | null;
color?: string | null;
};
export type BannerTitleSelectionStyle = {
fontSize?: number;
fontWeight?: number;
fontFamily?: BannerTitleFontFamilyKey;
color?: string;
};
export function bannerTitleRunsToDoc(runs: BannerTitleRun[]): JSONContent {
const content = [];
for (const run of normalizeBannerTitleRuns(runs)) {
const attrs = bannerTitleMarkAttrs(run);
const node: JSONContent = { type: "text", text: run.text };
if (Object.values(attrs).some((value) => value)) {
node.marks = [{ type: BANNER_TITLE_TEXT_STYLE, attrs }];
}
content.push(node);
}
return { type: "doc", content: [{ type: "paragraph", content }] };
}
export function bannerDocToRuns(doc?: JSONContent | null): BannerTitleRun[] {
const paragraph = (doc?.content || []).find((node) => node.type === "paragraph");
const runs: BannerTitleRun[] = [];
for (const node of paragraph?.content || []) {
if (node.type !== "text" || !node.text) continue;
const attrs = textStyleAttributes(node);
const run: BannerTitleRun = { text: node.text };
const size = Number(attrs.fontSize ? String(attrs.fontSize).replace(/[^\d]/g, "") : "");
if (BANNER_TITLE_FONT_SIZES.includes(size)) run.fontSize = size;
const weight = Number(String(attrs.fontWeight || "").replace(/[^\d]/g, ""));
if (BANNER_TITLE_FONT_WEIGHTS.some((item) => item.value === weight)) run.fontWeight = weight;
const family = bannerTitleFontFamilyKey(typeof attrs.fontFamily === "string" ? attrs.fontFamily : "");
if (family && family !== "sans") run.fontFamily = family;
const color = normalizeBannerTitleHex(typeof attrs.color === "string" ? attrs.color : "");
if (color) run.color = color;
runs.push(run);
}
return normalizeBannerTitleRuns(runs);
}
export function bannerTitleSelectionStyle(editor: Editor): BannerTitleSelectionStyle {
const attrs = editor.getAttributes(BANNER_TITLE_TEXT_STYLE) as Record<string, unknown>;
const selection: BannerTitleSelectionStyle = {};
const size = Number(attrs.fontSize ? String(attrs.fontSize).replace(/[^\d]/g, "") : "");
if (BANNER_TITLE_FONT_SIZES.includes(size)) selection.fontSize = size;
const weight = Number(String(attrs.fontWeight || "").replace(/[^\d]/g, ""));
if (BANNER_TITLE_FONT_WEIGHTS.some((item) => item.value === weight)) selection.fontWeight = weight;
const family = bannerTitleFontFamilyKey(typeof attrs.fontFamily === "string" ? attrs.fontFamily : "");
if (family && family !== "sans") selection.fontFamily = family;
const color = normalizeBannerTitleHex(typeof attrs.color === "string" ? attrs.color : "");
if (color) selection.color = color;
return selection;
}
/**
* 把样式片段应用到当前选区。
*
* 没有用 Tiptap 的 `setMark`:同一文本节点上它会叠加多个 textStyle 标记(属性不合并),
* 反复调整会留下旧值。这里按节点先移除旧标记再写入合并后的属性,保证每个节点只有一个标记。
*/
export function applyBannerTitleStyle(editor: Editor, patch: BannerTitleStylePatch) {
const textStyle = editor.state.schema.marks[BANNER_TITLE_TEXT_STYLE];
if (!textStyle) return;
const markPatch: Record<string, string | null> = {};
if (patch.fontSize !== undefined) markPatch.fontSize = patch.fontSize ? `${patch.fontSize}px` : null;
if (patch.fontWeight !== undefined) markPatch.fontWeight = patch.fontWeight ? String(patch.fontWeight) : null;
if (patch.fontFamily !== undefined) markPatch.fontFamily = patch.fontFamily ? bannerTitleFontFamilyCSS(patch.fontFamily) || null : null;
if (patch.color !== undefined) markPatch.color = patch.color ? normalizeBannerTitleHex(patch.color) || null : null;
const { from, to, empty } = editor.state.selection;
const transaction = editor.state.tr;
if (empty) {
transaction.addStoredMark(textStyle.create({ ...(editor.getAttributes(BANNER_TITLE_TEXT_STYLE) as Record<string, unknown>), ...markPatch }));
} else {
editor.state.doc.nodesBetween(from, to, (node, pos) => {
if (!node.isText) return;
const start = Math.max(pos, from);
const end = Math.min(pos + node.nodeSize, to);
if (start >= end) return;
const attrs = textStyleAttributes(node);
transaction.removeMark(start, end, textStyle);
transaction.addMark(start, end, textStyle.create({ ...attrs, ...markPatch }));
});
}
editor.view.dispatch(transaction);
}
export function clearBannerTitleStyle(editor: Editor) {
const textStyle = editor.state.schema.marks[BANNER_TITLE_TEXT_STYLE];
if (!textStyle) return;
const { from, to, empty } = editor.state.selection;
const transaction = editor.state.tr;
if (empty) {
transaction.removeStoredMark(textStyle);
} else {
transaction.removeMark(from, to, textStyle);
}
editor.view.dispatch(transaction);
}
function bannerTitleMarkAttrs(run: BannerTitleRun) {
return {
fontSize: run.fontSize ? `${run.fontSize}px` : null,
fontWeight: run.fontWeight ? String(run.fontWeight) : null,
fontFamily: bannerTitleFontFamilyCSS(run.fontFamily) || null,
color: run.color || null,
};
}
/**
* 同一文本节点可能带有多个 textStyle 标记,按出现顺序合并,后写入的取最终值。
* 标记来自两处:编辑器里的 ProseMirror 节点(`mark.type` 是 MarkType 对象)与 JSON 文档(`mark.type` 是字符串)。
*/
function textStyleAttributes(node: { marks?: readonly { type?: string | { name?: string }; attrs?: Record<string, unknown> }[] }) {
const attrs: Record<string, unknown> = {};
for (const mark of node.marks || []) {
const name = typeof mark.type === "string" ? mark.type : mark.type?.name;
if (name !== BANNER_TITLE_TEXT_STYLE) continue;
Object.assign(attrs, mark.attrs || {});
}
return attrs;
}
export { BANNER_TITLE_FONT_FAMILIES };
+167
View File
@@ -0,0 +1,167 @@
/**
* 首页常驻通知条的标题样式模型。
*
* 标题按「样式分段」存储:每段是一串连续文本加可选的字号 / 字重 / 字体 / 颜色覆盖。
* 后端只接受这里的白名单取值(字号 10-20、字重 400/500/600/700、字体 sans|serif|mono、颜色 #RRGGBB),
* 所以通知条渲染时不会出现任意 CSS 值。
*/
export type BannerTitleFontFamilyKey = "sans" | "serif" | "mono";
export type BannerTitleRun = {
text: string;
fontSize?: number;
fontWeight?: number;
fontFamily?: BannerTitleFontFamilyKey;
color?: string;
};
export const BANNER_TITLE_MAX_CHARS = 120;
export const BANNER_TITLE_MIN_FONT_SIZE = 10;
export const BANNER_TITLE_MAX_FONT_SIZE = 20;
/** 通知条标题默认字号,与前台 `text-xs` 一致。 */
export const BANNER_TITLE_DEFAULT_FONT_SIZE = 12;
/** 通知条标题默认字重,与前台 `font-semibold` 一致。 */
export const BANNER_TITLE_DEFAULT_FONT_WEIGHT = 600;
export const BANNER_TITLE_FONT_SIZES = [10, 11, 12, 13, 14, 15, 16, 18, 20];
export const BANNER_TITLE_FONT_WEIGHTS = [
{ value: 400, label: "常规" },
{ value: 500, label: "中等" },
{ value: 600, label: "半粗" },
{ value: 700, label: "粗体" },
];
export const BANNER_TITLE_FONT_FAMILIES: { key: BannerTitleFontFamilyKey; label: string; css: string }[] = [
{ key: "sans", label: "默认", css: "" },
{ key: "serif", label: "衬线", css: 'Georgia, "Songti SC", "SimSun", serif' },
{ key: "mono", label: "等宽", css: "var(--font-mono)" },
];
export function bannerTitleFontFamilyCSS(key?: BannerTitleFontFamilyKey) {
if (!key) return "";
return BANNER_TITLE_FONT_FAMILIES.find((item) => item.key === key)?.css || "";
}
/** 由 CSS 值反查字体档位;未知字体返回空,调用方按未设置处理。 */
export function bannerTitleFontFamilyKey(css?: string) {
const value = (css || "").trim();
if (!value) return "" as const;
return BANNER_TITLE_FONT_FAMILIES.find((item) => item.css === value)?.key || ("" as const);
}
/** 清洗单个分段:非法取值一律丢弃,不调用方兜底。 */
export function normalizeBannerTitleRun(run: BannerTitleRun): BannerTitleRun | null {
const text = typeof run.text === "string" ? run.text : "";
if (!text) return null;
const normalized: BannerTitleRun = { text };
const size = Number.isInteger(run.fontSize) ? (run.fontSize as number) : undefined;
if (size && size >= BANNER_TITLE_MIN_FONT_SIZE && size <= BANNER_TITLE_MAX_FONT_SIZE) normalized.fontSize = size;
const weight = BANNER_TITLE_FONT_WEIGHTS.find((item) => item.value === run.fontWeight)?.value;
if (weight) normalized.fontWeight = weight;
const family = BANNER_TITLE_FONT_FAMILIES.find((item) => item.key === run.fontFamily)?.key;
if (family && family !== "sans") normalized.fontFamily = family;
const color = normalizeBannerTitleHex(run.color);
if (color) normalized.color = color;
return normalized;
}
/** 清洗整段标题并合并相邻同样式分段,与后端 normalizeBannerTitleRuns 保持同一套规则。 */
export function normalizeBannerTitleRuns(runs?: BannerTitleRun[] | null): BannerTitleRun[] {
const normalized: BannerTitleRun[] = [];
for (const run of runs || []) {
const next = normalizeBannerTitleRun(run);
if (!next) continue;
const previous = normalized[normalized.length - 1];
if (previous && sameBannerTitleRunStyle(previous, next)) {
previous.text += next.text;
continue;
}
normalized.push(next);
}
return normalized;
}
export function sameBannerTitleRunStyle(left: BannerTitleRun, right: BannerTitleRun) {
return left.fontSize === right.fontSize && left.fontWeight === right.fontWeight && left.fontFamily === right.fontFamily && left.color === right.color;
}
export function bannerTitlePlainText(runs?: BannerTitleRun[] | null) {
return (runs || []).map((run) => run.text).join("");
}
/** 按码点计数,与后端 utf8.RuneCountInString 一致(emoji 等代理对按 1 个字符算)。 */
export function bannerTitleCharCount(runs?: BannerTitleRun[] | null) {
return Array.from(bannerTitlePlainText(runs)).length;
}
export function normalizeBannerTitleHex(value?: string) {
const raw = (value || "").trim().toUpperCase();
if (!raw) return "";
const hex = raw.startsWith("#") ? raw.slice(1) : raw;
if (/^[0-9A-F]{3}$/.test(hex)) {
return `#${hex[0]}${hex[0]}${hex[1]}${hex[1]}${hex[2]}${hex[2]}`;
}
return /^[0-9A-F]{6}$/.test(hex) ? `#${hex}` : "";
}
/** 分段对应的内联样式;未设置的维度交给外层类名(通知条默认白色文字、12px)。 */
export function bannerTitleRunStyle(run: BannerTitleRun) {
const style: Record<string, string | number> = {};
if (run.fontSize) {
style.fontSize = `${run.fontSize}px`;
}
if (run.fontWeight) style.fontWeight = run.fontWeight;
const family = bannerTitleFontFamilyCSS(run.fontFamily);
if (family) style.fontFamily = family;
if (run.color) style.color = run.color;
return style;
}
/** 解析 #RGB / #RRGGBB / rgb() 为 0-255 三元组;无法解析时返回 null。 */
export function parseBannerTitleColor(value?: string): [number, number, number] | null {
const raw = (value || "").trim();
if (!raw) return null;
const hex = normalizeBannerTitleHex(raw);
if (hex) {
return [Number.parseInt(hex.slice(1, 3), 16), Number.parseInt(hex.slice(3, 5), 16), Number.parseInt(hex.slice(5, 7), 16)];
}
const rgb = raw.match(/^rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)/i);
if (!rgb) return null;
return [Number(rgb[1]), Number(rgb[2]), Number(rgb[3])];
}
/** WCAG 对比度;任一颜色无法解析时返回 null。 */
export function bannerTitleContrastRatio(foreground?: string, background?: string) {
const front = parseBannerTitleColor(foreground);
const back = parseBannerTitleColor(background);
if (!front || !back) return null;
const frontLuminance = relativeLuminance(front);
const backLuminance = relativeLuminance(back);
const lighter = Math.max(frontLuminance, backLuminance);
const darker = Math.min(frontLuminance, backLuminance);
return (lighter + 0.05) / (darker + 0.05);
}
function relativeLuminance([red, green, blue]: [number, number, number]) {
const channels = [red, green, blue].map((channel) => {
const value = channel / 255;
return value <= 0.03928 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
});
return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2];
}
/** 返回该主题下对比度不足 4.5:1 的文字颜色(去重),用于编辑时的可读性提示。 */
export function lowContrastBannerTitleColors(runs: BannerTitleRun[] | null | undefined, background: string) {
if (!background) return [];
const failing = new Set<string>();
for (const run of runs || []) {
if (!run.color) continue;
const ratio = bannerTitleContrastRatio(run.color, background);
if (ratio !== null && ratio < 4.5) failing.add(run.color);
}
return Array.from(failing);
}
+22
View File
@@ -8,6 +8,7 @@ import { readAnnouncementPendingReview } from "./components/admin-announcement-s
const AnalyticsPanel = lazy(() => import("./components/analytics-panel"));
const AdminAnnouncementsPanel = lazy(() => import("./components/admin-announcements-panel"));
const AdminBannerAnnouncementsPanel = lazy(() => import("./components/admin-banner-announcements-panel"));
const CreditOperationsPanel = lazy(() => import("./components/credit-operations-panel"));
const AccessSettingsPanel = lazy(() => import("./components/access-settings-panel"));
const EmailSettingsPanel = lazy(() => import("./components/email-settings-panel"));
@@ -53,6 +54,27 @@ export function AnnouncementsPage() {
);
}
export function BannerAnnouncementsPage() {
const [createOpen, setCreateOpen] = useState(false);
return (
<AdminPageFrame
title="常驻通知"
description="配置首页顶部常驻展示的通知,支持标题、状态与有效期"
actions={
<Button
type="primary"
icon={<Plus className="size-4" />}
onClick={() => setCreateOpen(true)}
>
新增常驻通知
</Button>
}
>
<AdminBannerAnnouncementsPanel createOpen={createOpen} onCreateOpenChange={setCreateOpen} />
</AdminPageFrame>
);
}
export function CreditOperationsPage() {
const { references } = useAdminContext();
const [activeOperation, setActiveOperation] = useState<"policy" | "adjustment" | null>(null);
@@ -0,0 +1,438 @@
import { App, Button, DatePicker, Form, Input, Modal, Popconfirm, Select, Switch } from "antd";
import type { ColumnsType } from "antd/es/table";
import { Trash2, Edit3, Search } from "lucide-react";
import dayjs, { type Dayjs } from "dayjs";
import { useCallback, useEffect, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import {
createAdminBanner,
deleteAdminBanner,
listAdminBanners,
updateAdminBanner,
type BannerAnnouncement,
} from "@/services/api/announcements";
import {
BANNER_NOTICE_DEFAULT_TYPE,
bannerNoticeTypeLabel,
normalizeBannerNoticeType,
type BannerNoticeType,
} from "@/lib/announcements/banner-notice";
import { bannerAnnouncementBarStyle } from "@/components/layout/banner-announcement-content";
import { BANNER_TITLE_MAX_CHARS, bannerTitleCharCount, bannerTitlePlainText, normalizeBannerTitleRuns, type BannerTitleRun } from "@/lib/announcements/banner-title";
import { AdminDataTable } from "./admin-ui";
import { BannerNoticeTypeSelector } from "./banner-notice-type-selector";
import { BannerNoticePreview, BannerTitleEditor } from "./banner-title-editor";
type FormValues = {
noticeType: BannerNoticeType;
link?: string;
status: boolean;
dateRange?: [Dayjs | null, Dayjs | null] | null;
};
type BannerDialog = { mode: "create" } | { mode: "edit"; banner: BannerAnnouncement };
export default function AdminBannerAnnouncementsPanel({
createOpen,
onCreateOpenChange,
}: {
createOpen: boolean;
onCreateOpenChange: (open: boolean) => void;
}) {
const { message, modal } = App.useApp();
const queryClient = useQueryClient();
const [form] = Form.useForm<FormValues>();
const linkValue = Form.useWatch("link", form);
const [banners, setBanners] = useState<BannerAnnouncement[]>([]);
const [keyword, setKeyword] = useState("");
const [status, setStatus] = useState<string>("all");
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(true);
const [dialog, setDialog] = useState<BannerDialog | null>(null);
const [titleRuns, setTitleRuns] = useState<BannerTitleRun[]>([]);
const [noticeType, setNoticeType] = useState<BannerNoticeType>(BANNER_NOTICE_DEFAULT_TYPE);
const [titleTouched, setTitleTouched] = useState(false);
const [dirty, setDirty] = useState(false);
const [submitting, setSubmitting] = useState(false);
const reload = async (targetPage = page, targetPageSize = pageSize) => {
setLoading(true);
try {
const data = await listAdminBanners({
keyword: keyword.trim() || undefined,
status: status === "all" ? undefined : status,
page: targetPage,
pageSize: targetPageSize,
});
setBanners(data.banners || []);
setTotal(data.total || 0);
} catch (error) {
message.error(error instanceof Error ? error.message : "读取常驻通知列表失败");
} finally {
setLoading(false);
}
};
useEffect(() => {
void reload(1, pageSize);
}, [keyword, status]);
const openCreate = useCallback(() => {
setTitleRuns([]);
setNoticeType(BANNER_NOTICE_DEFAULT_TYPE);
setTitleTouched(false);
setDirty(false);
form.resetFields();
form.setFieldsValue({
noticeType: BANNER_NOTICE_DEFAULT_TYPE,
status: true,
});
setDialog({ mode: "create" });
}, [form]);
// 父级的 createOpen 只是「请求新建」信号:消费后立即复位,避免它再次触发时把编辑中的内容重置掉。
useEffect(() => {
if (!createOpen) return;
onCreateOpenChange(false);
openCreate();
}, [createOpen, onCreateOpenChange, openCreate]);
const openEdit = (banner: BannerAnnouncement) => {
const initialRuns = banner.titleRuns?.length ? banner.titleRuns : banner.title ? [{ text: banner.title }] : [];
const type = normalizeBannerNoticeType(banner.noticeType);
setTitleRuns(initialRuns);
setNoticeType(type);
setTitleTouched(false);
setDirty(false);
form.setFieldsValue({
noticeType: type,
link: banner.link || undefined,
status: banner.status === "active",
dateRange: banner.startsAt || banner.endsAt ? [banner.startsAt ? dayjs(banner.startsAt) : null, banner.endsAt ? dayjs(banner.endsAt) : null] : null,
});
setDialog({ mode: "edit", banner });
};
const requestClose = () => {
if (submitting) return;
if (!dirty) {
setDialog(null);
return;
}
modal.confirm({
title: "放弃未保存的修改?",
content: "关闭后本次编辑的内容不会保留。",
okText: "放弃修改",
cancelText: "继续编辑",
okButtonProps: { danger: true },
onOk: () => setDialog(null),
});
};
const handleDelete = async (id: string) => {
try {
await deleteAdminBanner(id);
message.success("常驻通知已删除");
void queryClient.invalidateQueries({ queryKey: ["active-banner-announcements"] });
void reload(page, pageSize);
} catch (error) {
message.error(error instanceof Error ? error.message : "删除失败");
}
};
const handleToggleStatus = async (banner: BannerAnnouncement, nextStatus: boolean) => {
try {
await updateAdminBanner(banner.id, {
title: banner.title,
// 必须带上样式分段与通知类型:后端更新走显式字段表,漏传会把它们清空。
titleRuns: banner.titleRuns,
noticeType: normalizeBannerNoticeType(banner.noticeType),
link: banner.link,
status: nextStatus ? "active" : "disabled",
startsAt: banner.startsAt,
endsAt: banner.endsAt,
});
message.success(nextStatus ? "常驻通知已启用" : "常驻通知已禁用");
void queryClient.invalidateQueries({ queryKey: ["active-banner-announcements"] });
void reload(page, pageSize);
} catch (error) {
message.error(error instanceof Error ? error.message : "更新状态失败");
}
};
const handleSubmit = async (values: FormValues) => {
setTitleTouched(true);
const runs = normalizeBannerTitleRuns(titleRuns);
const plain = bannerTitlePlainText(runs).trim();
if (!plain || !runs.length) {
message.error("请填写通知标题");
return;
}
if (bannerTitleCharCount(runs) > BANNER_TITLE_MAX_CHARS) {
message.error(`通知标题不能超过 ${BANNER_TITLE_MAX_CHARS} 个字符`);
return;
}
setSubmitting(true);
try {
const startsAt = values.dateRange?.[0] ? values.dateRange[0].toISOString() : undefined;
const endsAt = values.dateRange?.[1] ? values.dateRange[1].toISOString() : undefined;
const selectedNoticeType = values.noticeType || noticeType;
const payload = {
title: plain,
titleRuns: runs,
noticeType: selectedNoticeType,
link: values.link?.trim() || undefined,
status: (values.status ? "active" : "disabled") as "active" | "disabled",
startsAt,
endsAt,
};
if (dialog?.mode === "edit") {
await updateAdminBanner(dialog.banner.id, payload);
message.success("常驻通知已更新");
} else {
await createAdminBanner(payload);
message.success("常驻通知已新建");
}
setDialog(null);
form.resetFields();
void queryClient.invalidateQueries({ queryKey: ["active-banner-announcements"] });
void reload(1, pageSize);
} catch (error) {
message.error(error instanceof Error ? error.message : "保存常驻通知失败");
} finally {
setSubmitting(false);
}
};
const columns: ColumnsType<BannerAnnouncement> = [
{
title: "通知标题",
dataIndex: "title",
key: "title",
render: (text: string, record) => (
<div className="flex flex-col gap-0.5">
<span className="font-medium text-foreground">{text}</span>
{record.link ? (
<span className="font-mono text-[var(--fs-label)] text-foreground/45" title={record.link}>
{record.link.length > 44 ? `${record.link.slice(0, 44)}…` : record.link}
</span>
) : null}
</div>
),
},
{
title: "类型",
key: "noticeType",
width: 92,
// 用真实底色渲染类型,和前台/预览看到的是同一个 token。
render: (_, record) => (
<span
className="inline-flex items-center rounded-full px-2 py-0.5 text-[var(--fs-micro)] font-semibold text-white"
style={bannerAnnouncementBarStyle(record.noticeType)}
>
{bannerNoticeTypeLabel(record.noticeType)}
</span>
),
},
{
title: "状态",
dataIndex: "status",
key: "status",
width: 110,
render: (value: string, record) => (
<Switch
size="small"
checked={value === "active"}
onChange={(checked) => void handleToggleStatus(record, checked)}
/>
),
},
{
title: "有效期",
key: "validity",
width: 280,
render: (_, record) => {
if (!record.startsAt && !record.endsAt) {
return <span className="text-foreground/45">长期有效</span>;
}
const startStr = record.startsAt ? dayjs(record.startsAt).format("YYYY-MM-DD HH:mm") : "不限";
const endStr = record.endsAt ? dayjs(record.endsAt).format("YYYY-MM-DD HH:mm") : "不限";
return (
<span className="text-xs text-foreground/75 font-mono">
{startStr} 至 {endStr}
</span>
);
},
},
{
title: "创建时间",
dataIndex: "createdAt",
key: "createdAt",
width: 160,
render: (date: string) => <span className="text-xs text-foreground/60 font-mono">{dayjs(date).format("YYYY-MM-DD HH:mm")}</span>,
},
{
title: "操作",
key: "action",
width: 120,
align: "right",
render: (_, record) => (
<div className="flex justify-end gap-1">
<Button type="text" size="small" icon={<Edit3 className="size-3.5" />} onClick={() => openEdit(record)}>
编辑
</Button>
<Popconfirm title="确认删除此常驻通知?" onConfirm={() => void handleDelete(record.id)}>
<Button type="text" size="small" danger icon={<Trash2 className="size-3.5" />}>
删除
</Button>
</Popconfirm>
</div>
),
},
];
const hasFilters = Boolean(keyword.trim() || status !== "all");
const titleMissing = titleTouched && (!titleRuns.length || !bannerTitlePlainText(titleRuns).trim());
const titleTooLong = bannerTitleCharCount(titleRuns) > BANNER_TITLE_MAX_CHARS;
return (
<div className="flex min-h-0 flex-1 flex-col pb-4">
<AdminDataTable
toolbar={
<Input
allowClear
aria-label="搜索常驻通知标题"
className="app-list-search"
prefix={<Search className="size-4 text-foreground/40" />}
value={keyword}
placeholder="搜索常驻通知标题"
onChange={(event) => {
setKeyword(event.target.value);
setPage(1);
}}
/>
}
toolbarActive={hasFilters}
toolbarFilters={
<Select
aria-label="按状态筛选常驻通知"
className="w-32"
value={status}
onChange={(value) => {
setStatus(value);
setPage(1);
}}
options={[
{ label: "全部状态", value: "all" },
{ label: "已启用", value: "active" },
{ label: "已禁用", value: "disabled" },
]}
/>
}
onReset={() => {
setKeyword("");
setStatus("all");
setPage(1);
}}
table={{
rowKey: "id",
size: "small",
loading,
columns,
dataSource: banners,
pagination: {
current: page,
pageSize,
total,
onChange: (p, ps) => {
setPage(p);
setPageSize(ps);
void reload(p, ps);
},
},
}}
/>
<Modal
title={dialog?.mode === "edit" ? "编辑常驻通知" : "新建常驻通知"}
open={Boolean(dialog)}
onCancel={requestClose}
onOk={() => form.submit()}
confirmLoading={submitting}
centered
destroyOnHidden
width="min(880px, calc(100vw - 32px))"
rootClassName="admin-modal-root"
>
<Form
form={form}
layout="vertical"
// 表单比弹窗高时在表单内部滚动,底部按钮始终可见;下拉层由 AntD 挂到 body,不会被裁剪。
style={{ maxHeight: "68vh", overflowY: "auto", paddingRight: 4 }}
onFinish={(values) => void handleSubmit(values)}
onValuesChange={() => setDirty(true)}
>
<Form.Item name="noticeType" label="通知类型" extra="决定通知条底色;浅色 / 深色主题各有一档取值">
<BannerNoticeTypeSelector
value={noticeType}
onChange={(next) => {
setNoticeType(next);
form.setFieldValue("noticeType", next);
setDirty(true);
}}
/>
</Form.Item>
<Form.Item
label="通知标题"
required
validateStatus={titleMissing || titleTooLong ? "error" : undefined}
help={
titleMissing
? "请输入常驻通知标题"
: titleTooLong
? `已超出 ${BANNER_TITLE_MAX_CHARS} 个字符上限`
: "支持按选区设置字号、字重、字体与颜色,用「图标」插入 emoji 素材;标题在通知条内固定单行展示"
}
>
<BannerTitleEditor
key={dialog?.mode === "edit" ? dialog.banner.id : "create"}
value={titleRuns}
onChange={(runs) => {
setTitleRuns(runs);
setDirty(true);
}}
/>
</Form.Item>
{/* 预览放在 Form 内但不用 Form.Item:避免 AntD 向非表单控件注入 value/onChange/ref。 */}
<div className="mb-6">
<div className="mb-2 text-sm text-foreground/85">前台效果预览</div>
<BannerNoticePreview runs={titleRuns} hasLink={Boolean(linkValue?.trim())} noticeType={noticeType} />
</div>
<Form.Item
name="link"
label="跳转链接(可选)"
extra="支持 https:// 外链或以 / 开头的站内路径(如 /projects);留空表示不可点击"
rules={[{ max: 500, message: "链接最多 500 字符" }]}
>
<Input maxLength={500} placeholder="https://… 或 /projects" />
</Form.Item>
<Form.Item name="status" label="发布状态" valuePropName="checked">
<Switch checkedChildren="启用" unCheckedChildren="禁用" />
</Form.Item>
<Form.Item name="dateRange" label="有效期(可选)" extra="留空表示长期有效;设置时间段后仅在有效期内于前台展示">
<DatePicker.RangePicker showTime format="YYYY-MM-DD HH:mm" className="w-full" />
</Form.Item>
</Form>
</Modal>
</div>
);
}
@@ -19,6 +19,7 @@ import {
KeyRound,
Layers3,
Mail,
Megaphone,
MessageSquareText,
Moon,
Palette,
@@ -79,6 +80,7 @@ const adminNavigation: Array<{ label: string; items: AdminNavigationItem[] }> =
label: "运营",
items: [
{ path: "/admin/announcements", label: "系统公告", description: "发布、关闭与历史公告", icon: <BellRing className="size-4" /> },
{ path: "/admin/banner-announcements", label: "常驻通知", description: "首页顶部常驻滚动通知", icon: <Megaphone className="size-4" /> },
{ path: "/admin/agent-lessons", label: "Agent 记忆", description: "按用户查看个人记忆", icon: <Sparkles className="size-4" /> },
{ path: "/admin/payments", label: "支付充值", description: "支付渠道、订单与对账", icon: <CreditCard className="size-4" /> },
{ path: "/admin/credit-operations", label: "积分运营", description: "人工调账与异常计费", icon: <Coins className="size-4" /> },
@@ -0,0 +1,90 @@
import { Input, Popover, Button } from "antd";
import { SmilePlus, Search } from "lucide-react";
import { useMemo, useState } from "react";
import { BANNER_NOTICE_EMOJI_GROUPS, searchBannerNoticeEmojis } from "@/lib/announcements/banner-notice";
/**
* emoji 图标素材面板:按分组铺开,支持按中文名搜索。
* 选中即作为普通文本插进标题光标处,可插任意多个、任意位置,并跟随光标处的字号 / 颜色样式。
* 面板不自动关闭,方便连续插入;点击面板外任意位置收起。
*/
export function BannerNoticeEmojiPanel({ onPick }: { onPick: (emoji: string) => void }) {
const [keyword, setKeyword] = useState("");
const matched = useMemo(() => new Set(searchBannerNoticeEmojis(keyword).map((item) => item.char)), [keyword]);
const groups = useMemo(
() =>
BANNER_NOTICE_EMOJI_GROUPS.map((group) => ({
...group,
emoji: group.emoji.filter((item) => matched.has(item.char)),
})).filter((group) => group.emoji.length > 0),
[matched],
);
return (
<div className="admin-banner-icon-picker">
<div className="admin-banner-icon-picker-search">
<Input
size="small"
allowClear
aria-label="搜索图标素材"
placeholder="搜索素材(如 礼物、火箭)"
prefix={<Search className="size-3.5 text-foreground/40" aria-hidden="true" />}
value={keyword}
onChange={(event) => setKeyword(event.target.value)}
/>
</div>
<div className="admin-banner-icon-picker-body">
{groups.length ? (
groups.map((group) => (
<div key={group.key} className="admin-banner-icon-picker-group">
<span className="admin-banner-icon-picker-group-label">{group.label}</span>
<div className="admin-banner-icon-picker-grid" role="listbox" aria-label={`${group.label}素材`}>
{group.emoji.map((item) => (
<button
key={item.char}
type="button"
role="option"
aria-selected="false"
aria-label={item.label}
title={item.label}
className="admin-banner-icon-picker-option admin-banner-icon-picker-option-emoji"
onClick={() => onPick(item.char)}
>
{item.char}
</button>
))}
</div>
</div>
))
) : (
<p className="admin-banner-icon-picker-empty">没有匹配「{keyword.trim()}」的素材</p>
)}
</div>
</div>
);
}
/**
* 标题编辑工具栏的「插入图标」入口:默认不占任何视觉位,点了才弹出素材面板。
* onPick 由调用方提供(编辑器要把内容插到光标处)。
*/
export function BannerNoticeEmojiPopover({ onPick }: { onPick: (emoji: string) => void }) {
return (
<Popover
trigger="click"
placement="bottomLeft"
arrow={false}
content={<BannerNoticeEmojiPanel onPick={onPick} />}
// AntD 6 Popover 的语义样式键是 content / container / root / arrow,没有 body;
// container 对应 .ant-popover-inner(内边距所在元素)。
styles={{ container: { padding: 0 } }}
>
<Button size="small" type="text" title="在光标处插入 emoji 图标素材" icon={<SmilePlus className="size-3.5" />} aria-label="插入图标素材">
图标
</Button>
</Popover>
);
}
@@ -0,0 +1,40 @@
import { Check } from "lucide-react";
import { BANNER_NOTICE_TYPES, normalizeBannerNoticeType, type BannerNoticeType } from "@/lib/announcements/banner-notice";
/**
* 通知类型选择:每种类型决定通知条底色,卡片上直接铺真实底色条,
* 免得用「蓝色 / 橙色」这种文字去描述一个已经看得见的颜色。
*/
export function BannerNoticeTypeSelector({ value, onChange }: { value: string; onChange: (type: BannerNoticeType) => void }) {
const active = normalizeBannerNoticeType(value);
return (
<div className="admin-banner-type-grid" role="radiogroup" aria-label="通知类型">
{BANNER_NOTICE_TYPES.map((type) => {
const selected = active === type.key;
return (
<button
key={type.key}
type="button"
role="radio"
aria-checked={selected}
data-banner-type={type.key}
className={`admin-banner-type-card${selected ? " is-active" : ""}`}
onClick={() => onChange(type.key)}
>
<span className="admin-banner-type-card-name">
{type.label}
{selected ? <Check className="admin-banner-type-card-check size-3.5" aria-hidden="true" /> : null}
</span>
<span className="admin-banner-type-card-hint">{type.hint}</span>
{/* 真实底色条:颜色来自该类型 token,随当前主题解析 */}
<span className="admin-banner-type-card-preview" aria-hidden="true">
<span className="truncate">{type.label}通知效果预览</span>
</span>
</button>
);
})}
</div>
);
}
@@ -0,0 +1,213 @@
import type { Editor } from "@tiptap/core";
import { EditorContent, useEditor } from "@tiptap/react";
import { Button, ColorPicker, Select, Tooltip } from "antd";
import { Eraser, X } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import {
BannerAnnouncementLinkHint,
BannerAnnouncementTitle,
bannerAnnouncementBarStyle,
} from "@/components/layout/banner-announcement-content";
import { readBannerNoticeSurface, bannerNoticeTypeLabel } from "@/lib/announcements/banner-notice";
import { BannerNoticeEmojiPopover } from "./banner-notice-emoji-picker";
import {
BANNER_TITLE_DEFAULT_FONT_SIZE,
BANNER_TITLE_DEFAULT_FONT_WEIGHT,
BANNER_TITLE_FONT_FAMILIES,
BANNER_TITLE_FONT_SIZES,
BANNER_TITLE_FONT_WEIGHTS,
BANNER_TITLE_MAX_CHARS,
bannerTitleCharCount,
lowContrastBannerTitleColors,
type BannerTitleRun,
} from "@/lib/announcements/banner-title";
import {
applyBannerTitleStyle,
bannerDocToRuns,
bannerTitleRunsToDoc,
bannerTitleSelectionStyle,
clearBannerTitleStyle,
createBannerTitleExtensions,
type BannerTitleSelectionStyle,
type BannerTitleStylePatch,
} from "@/lib/announcements/banner-title-rich-text";
const DEFAULT_OPTION = "default";
/** 一次性读出编辑器当前的分段与光标处样式,供受控渲染和回调共用。 */
function readEditorTitle(instance: Editor) {
const runs = bannerDocToRuns(instance.getJSON());
return { runs, selection: bannerTitleSelectionStyle(instance) };
}
/**
* 通知标题编辑区:文字按选区设置字号 / 字重 / 字体 / 颜色。
* 组件只把 title 分段当初始值,切换编辑对象时由调用方通过 key 重建实例。
*/
export function BannerTitleEditor({ value, onChange }: { value: BannerTitleRun[]; onChange: (runs: BannerTitleRun[]) => void }) {
const [selectionStyle, setSelectionStyle] = useState<BannerTitleSelectionStyle>({});
const [charCount, setCharCount] = useState(() => bannerTitleCharCount(value));
const editor = useEditor({
immediatelyRender: false,
extensions: createBannerTitleExtensions("输入首页顶部展示的通知标题"),
content: bannerTitleRunsToDoc(value),
editorProps: {
attributes: { class: "outline-none", "aria-label": "通知标题编辑区" },
handleKeyDown: (_view, event) => {
// 通知条标题是单行语义,Enter 不产生新段落。
return event.key === "Enter";
},
},
onUpdate: ({ editor: instance }) => {
const { runs, selection } = readEditorTitle(instance);
setSelectionStyle(selection);
setCharCount(bannerTitleCharCount(runs));
onChange(runs);
},
});
const applyStyle = (patch: BannerTitleStylePatch) => {
if (!editor) return;
editor.view.focus();
applyBannerTitleStyle(editor, patch);
const { runs, selection } = readEditorTitle(editor);
setSelectionStyle(selection);
setCharCount(bannerTitleCharCount(runs));
onChange(runs);
};
const tooLong = charCount > BANNER_TITLE_MAX_CHARS;
return (
<div className="space-y-2">
<div className="flex flex-wrap items-center gap-2">
<Select
size="small"
className="w-[104px]"
aria-label="标题字号"
value={selectionStyle.fontSize ?? DEFAULT_OPTION}
onChange={(next) => applyStyle({ fontSize: next === DEFAULT_OPTION ? null : Number(next) })}
options={[
{ value: DEFAULT_OPTION, label: `默认(${BANNER_TITLE_DEFAULT_FONT_SIZE}px)` },
...BANNER_TITLE_FONT_SIZES.map((size) => ({ value: size, label: `${size}px` })),
]}
/>
<Select
size="small"
className="w-[92px]"
aria-label="标题字重"
value={selectionStyle.fontWeight ?? DEFAULT_OPTION}
onChange={(next) => applyStyle({ fontWeight: next === DEFAULT_OPTION ? null : Number(next) })}
options={[
{ value: DEFAULT_OPTION, label: "默认字重" },
...BANNER_TITLE_FONT_WEIGHTS.map((item) => ({ value: item.value, label: `${item.label} ${item.value}` })),
]}
/>
<Select
size="small"
className="w-[92px]"
aria-label="标题字体"
value={selectionStyle.fontFamily ?? DEFAULT_OPTION}
onChange={(next) => applyStyle({ fontFamily: next === DEFAULT_OPTION ? null : (next as BannerTitleRun["fontFamily"]) })}
options={[{ value: DEFAULT_OPTION, label: "默认字体" }, ...BANNER_TITLE_FONT_FAMILIES.map((item) => ({ value: item.key, label: item.label }))]}
/>
<ColorPicker
size="small"
aria-label="标题颜色"
value={selectionStyle.color || "#FFFFFF"}
onChange={(color) => applyStyle({ color: color.toHexString().toUpperCase() })}
presets={[{ label: "通知条常用", colors: ["#FFFFFF", "#FFE58F", "#FFB37B", "#FF9AA2", "#B7EB8F", "#8FD3FF", "#D3ADF7", "#1F1F1F"] }]}
/>
{/* 不能用 Tooltip 包住 EmojiPopover:Tooltip 会向 Popover 要 ref,嵌套弹层行为不可靠。 */}
<BannerNoticeEmojiPopover
onPick={(emoji) => {
if (!editor) return;
// emoji 是普通文本:插进光标处,跟随当前选区的字号 / 颜色样式,可连续插入。
editor.chain().focus().insertContent(emoji).run();
}}
/>
<Tooltip title="清除所选文字的样式">
<Button
size="small"
type="text"
icon={<Eraser className="size-3.5" />}
aria-label="清除样式"
onClick={() => {
if (!editor) return;
clearBannerTitleStyle(editor);
const { runs, selection } = readEditorTitle(editor);
setSelectionStyle(selection);
setCharCount(bannerTitleCharCount(runs));
onChange(runs);
}}
/>
</Tooltip>
<span className={`ml-auto font-mono text-[var(--fs-label)] ${tooLong ? "text-[var(--admin-status-error)]" : "text-foreground/45"}`}>
{charCount}/{BANNER_TITLE_MAX_CHARS}
</span>
</div>
<div className="admin-banner-title-editor" onClick={() => editor?.view.focus()}>
<EditorContent editor={editor} />
</div>
<p className="text-[var(--fs-label)] text-foreground/45">
选中文字后调整样式;未选中时设置后续输入的文字样式。「图标」可在光标处插入 emoji 素材,位置与个数不限。默认字号 {BANNER_TITLE_DEFAULT_FONT_SIZE}px、字重 {BANNER_TITLE_DEFAULT_FONT_WEIGHT},与通知条一致。
</p>
</div>
);
}
/**
* 前台效果预览:明暗两态各一条,按当前通知类型取各自主题下的真实底色。
* 标题分段全部走前台同一份展示单元,因此预览即前台结果。
*/
export function BannerNoticePreview({ runs, hasLink, noticeType }: { runs: BannerTitleRun[]; hasLink: boolean; noticeType: string }) {
const lightRef = useRef<HTMLDivElement | null>(null);
const darkRef = useRef<HTMLDivElement | null>(null);
const [backgrounds, setBackgrounds] = useState({ light: "", dark: "" });
useEffect(() => {
// 底色由类型决定,切换类型后需要重新解析两个预览容器里的实际取值。
setBackgrounds({
light: readBannerNoticeSurface(noticeType, lightRef.current),
dark: readBannerNoticeSurface(noticeType, darkRef.current),
});
}, [noticeType]);
const themes = [
{ key: "light", label: "浅色主题", background: backgrounds.light, ref: lightRef, className: "admin-banner-title-preview-light" },
{ key: "dark", label: "深色主题", background: backgrounds.dark, ref: darkRef, className: "admin-banner-title-preview-dark" },
] as const;
return (
<div className="space-y-2">
{themes.map((theme) => {
const lowContrast = lowContrastBannerTitleColors(runs, theme.background);
return (
<div key={theme.key} className="space-y-1">
<div
ref={theme.ref}
className={`relative flex min-h-10 w-full items-center justify-center px-4 py-2 text-white ${theme.className}`}
style={bannerAnnouncementBarStyle(noticeType)}
>
<span className="flex w-full min-w-0 items-center justify-center gap-2.5 px-8">
<span className="min-w-0 truncate font-semibold">
<BannerAnnouncementTitle runs={runs} fallbackText="通知标题预览" />
</span>
{hasLink ? <BannerAnnouncementLinkHint /> : null}
</span>
<X className="absolute right-4 size-3.5 shrink-0 text-white" aria-hidden="true" />
</div>
<p className="text-[var(--fs-label)] text-foreground/45">
{theme.label} · {bannerNoticeTypeLabel(noticeType)}
{lowContrast.length ? ` · ${lowContrast.join("、")} 在该底色上对比度不足 4.5:1,建议调亮或调暗` : " · 对比度达标"}
</p>
</div>
);
})}
</div>
);
}
+2
View File
@@ -11,6 +11,7 @@ import RouteErrorPage from "@/pages/route-error";
const AdminPage = lazy(() => import("@/pages/admin"));
const AnalyticsPage = lazy(() => import("@/pages/admin/admin-route-pages").then((module) => ({ default: module.AnalyticsPage })));
const AnnouncementsPage = lazy(() => import("@/pages/admin/admin-route-pages").then((module) => ({ default: module.AnnouncementsPage })));
const BannerAnnouncementsPage = lazy(() => import("@/pages/admin/admin-route-pages").then((module) => ({ default: module.BannerAnnouncementsPage })));
const StorageResourcesPage = lazy(() => import("@/pages/admin/admin-route-pages").then((module) => ({ default: module.StorageResourcesPage })));
const CreditOperationsPage = lazy(() => import("@/pages/admin/admin-route-pages").then((module) => ({ default: module.CreditOperationsPage })));
const AccessSettingsPage = lazy(() => import("@/pages/admin/admin-route-pages").then((module) => ({ default: module.AccessSettingsPage })));
@@ -191,6 +192,7 @@ export const router = createBrowserRouter([
{ path: "prompt-templates", element: <StoryboardPromptsPage /> },
{ path: "storyboard-prompts", element: <Navigate to="/admin/prompt-templates" replace /> },
{ path: "announcements", element: <AnnouncementsPage /> },
{ path: "banner-announcements", element: <BannerAnnouncementsPage /> },
{ path: "agent-lessons", element: <AgentLessonsPage /> },
{ path: "resources", element: <StorageResourcesPage /> },
{ path: "credit-operations", element: <CreditOperationsPage /> },
+57
View File
@@ -1,5 +1,9 @@
import { http, apiBaseURL } from "@/services/api/request";
import type { RemoteResource } from "@/services/api/resources";
import type { BannerNoticeType } from "@/lib/announcements/banner-notice";
import type { BannerTitleRun } from "@/lib/announcements/banner-title";
export type { BannerTitleRun };
export type AnnouncementLevel = "info" | "success" | "warning" | "critical";
export type AnnouncementStatus = "active" | "closed";
@@ -73,3 +77,56 @@ export function updateAdminAnnouncement(id: string, input: { title: string; cont
export function closeAdminAnnouncement(id: string) {
return http.post<{ announcement: SystemAnnouncement }>(`/admin/announcements/${encodeURIComponent(id)}/close`);
}
export type BannerAnnouncement = {
id: string;
title: string;
/** 标题样式分段;为空表示纯文本标题(取值白名单见 lib/announcements/banner-title)。 */
titleRuns?: BannerTitleRun[];
/** 通知类型,决定通知条底色;未知值按「公告」处理。 */
noticeType?: BannerNoticeType;
link?: string;
status: "active" | "disabled";
startsAt?: string;
endsAt?: string;
createdBy: string;
createdAt: string;
updatedAt: string;
};
export type AdminBannerListParams = {
keyword?: string;
status?: string;
page?: number;
pageSize?: number;
};
export type AdminBannerPayload = {
title: string;
titleRuns?: BannerTitleRun[];
noticeType?: BannerNoticeType;
link?: string;
status: "active" | "disabled";
startsAt?: string;
endsAt?: string;
};
export function getActiveBanners() {
return http.get<{ banners: BannerAnnouncement[] }>("/banner-announcements");
}
export function listAdminBanners(params: AdminBannerListParams = {}) {
return http.get<{ banners: BannerAnnouncement[]; total: number; page: number; pageSize: number }>("/admin/banner-announcements", { params });
}
export function createAdminBanner(input: AdminBannerPayload) {
return http.post<{ banner: BannerAnnouncement }>("/admin/banner-announcements", input);
}
export function updateAdminBanner(id: string, input: AdminBannerPayload) {
return http.put<{ banner: BannerAnnouncement }>(`/admin/banner-announcements/${encodeURIComponent(id)}`, input);
}
export function deleteAdminBanner(id: string) {
return http.delete<{ ok: boolean }>(`/admin/banner-announcements/${encodeURIComponent(id)}`);
}
+215
View File
@@ -10639,3 +10639,218 @@ html[data-magicui-theme-vt="active"] .admin-shell * {
grid-template-columns: 100px minmax(0, 1fr);
}
}
/* 常驻通知标题:富文本编辑区与明暗两态预览。
* 预览固定明暗两套底色,编辑时不受当前主题影响,便于同时校验两种主题下的可读性。 */
.admin-banner-title-editor {
border: 1px solid var(--admin-card-border);
border-radius: 8px;
background: var(--admin-layer-1);
padding: 8px 12px;
transition: border-color 160ms ease;
}
.admin-banner-title-editor:focus-within {
border-color: color-mix(in srgb, var(--foreground) 30%, var(--admin-card-border));
}
.admin-banner-title-editor .ProseMirror {
min-height: 26px;
outline: none;
line-height: 1.6;
white-space: pre-wrap;
word-break: break-word;
}
.admin-banner-title-editor .ProseMirror p {
margin: 0;
}
.admin-banner-title-editor .ProseMirror p.is-editor-empty:first-child::before {
float: left;
height: 0;
color: color-mix(in srgb, var(--foreground) 34%, transparent);
content: attr(data-placeholder);
pointer-events: none;
}
/* 预览容器强制指定四种通知类型的明 / 暗底色,不依赖页面当前主题。 */
.admin-banner-title-preview-light {
--notice-banner-surface-notice: var(--palette-banner-notice-500);
--notice-banner-surface-activity: var(--palette-banner-activity-500);
--notice-banner-surface-update: var(--palette-banner-update-500);
--notice-banner-surface-warning: var(--palette-banner-warning-500);
}
.admin-banner-title-preview-dark {
--notice-banner-surface-notice: var(--palette-banner-notice-700);
--notice-banner-surface-activity: var(--palette-banner-activity-700);
--notice-banner-surface-update: var(--palette-banner-update-700);
--notice-banner-surface-warning: var(--palette-banner-warning-700);
}
/* 常驻通知标题图标选择器 */
.admin-banner-icon-picker {
border: 1px solid var(--admin-card-border);
border-radius: 8px;
background: var(--admin-layer-1);
}
.admin-banner-icon-picker-search {
position: sticky;
top: 0;
z-index: 1;
padding: 8px;
border-bottom: 1px solid var(--admin-divider);
background: var(--admin-layer-1);
}
.admin-banner-icon-picker-body {
max-height: 208px;
overflow-y: auto;
padding: 2px 8px 8px;
}
.admin-banner-icon-picker-group-label {
display: block;
padding: 8px 2px 4px;
color: color-mix(in srgb, var(--foreground) 45%, transparent);
font-size: var(--fs-micro);
}
.admin-banner-icon-picker-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(34px, 1fr));
gap: 4px;
}
.admin-banner-icon-picker-option {
display: grid;
height: 34px;
place-items: center;
border: 1px solid transparent;
border-radius: 6px;
background: transparent;
color: color-mix(in srgb, var(--foreground) 62%, transparent);
cursor: pointer;
transition:
background-color 160ms ease,
border-color 160ms ease,
color 160ms ease;
}
.admin-banner-icon-picker-option:hover {
background: color-mix(in srgb, var(--foreground) 7%, transparent);
color: var(--foreground);
}
/* emoji 素材项:emoji 是文本字符,用原生字号渲染(彩色字形不受 color 影响) */
.admin-banner-icon-picker-option-emoji {
font-size: 16px;
line-height: 1;
}
.admin-banner-icon-picker-option.is-active {
border-color: color-mix(in srgb, var(--foreground) 22%, transparent);
background: var(--control-selected-bg);
color: var(--foreground);
}
.admin-banner-icon-picker-option:focus-visible {
outline: 1px solid color-mix(in srgb, var(--ring) 62%, transparent);
outline-offset: 1px;
}
.admin-banner-icon-picker-empty {
padding: 14px 2px;
color: color-mix(in srgb, var(--foreground) 45%, transparent);
font-size: var(--fs-label);
text-align: center;
}
/* 通知类型选择:卡片直接铺出该类型的真实底色,比文字描述颜色更直观。 */
.admin-banner-type-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 8px;
}
.admin-banner-type-card {
display: flex;
flex-direction: column;
gap: 2px;
border: 1px solid var(--admin-card-border);
border-radius: 8px;
background: var(--admin-layer-1);
padding: 8px 10px 10px;
text-align: left;
cursor: pointer;
transition:
border-color 160ms ease,
background-color 160ms ease;
}
.admin-banner-type-card:hover {
background: color-mix(in srgb, var(--foreground) 4%, var(--admin-layer-1));
}
.admin-banner-type-card.is-active {
border-color: color-mix(in srgb, var(--foreground) 26%, transparent);
background: var(--control-selected-bg);
}
.admin-banner-type-card:focus-visible {
outline: 1px solid color-mix(in srgb, var(--ring) 62%, transparent);
outline-offset: 1px;
}
.admin-banner-type-card-name {
display: flex;
align-items: center;
gap: 6px;
color: var(--foreground);
font-size: var(--fs-label);
font-weight: 600;
}
.admin-banner-type-card-check {
margin-left: auto;
color: var(--foreground);
}
.admin-banner-type-card-hint {
color: color-mix(in srgb, var(--foreground) 45%, transparent);
font-size: var(--fs-micro);
line-height: 1.5;
}
/* 类型卡片上的真实底色条;颜色由卡片的 data-banner-type 选中对应 token。 */
.admin-banner-type-card-preview {
display: flex;
align-items: center;
gap: 6px;
margin-top: 8px;
border-radius: 4px;
padding: 4px 8px;
color: #ffffff;
font-size: var(--fs-micro);
line-height: 1.4;
}
.admin-banner-type-card[data-banner-type="notice"] .admin-banner-type-card-preview {
background: var(--notice-banner-surface-notice);
}
.admin-banner-type-card[data-banner-type="activity"] .admin-banner-type-card-preview {
background: var(--notice-banner-surface-activity);
}
.admin-banner-type-card[data-banner-type="update"] .admin-banner-type-card-preview {
background: var(--notice-banner-surface-update);
}
.admin-banner-type-card[data-banner-type="warning"] .admin-banner-type-card-preview {
background: var(--notice-banner-surface-warning);
}
+42 -3
View File
@@ -53,6 +53,17 @@
--palette-status-loading: #2563eb;
--palette-status-warning: #d97706;
/* 顶部常驻通知条主题色:按「通知类型」区分底色(类型定义见 lib/announcements/banner-notice)
两档取值都由白字对比度反推——light 档 ≥ 4.5:1(WCAG AA 正文),dark 档约 8.5:1(压暗避免刺眼)*/
--palette-banner-notice-500: #5c67e2; /* 公告 · 白字 4.67:1 */
--palette-banner-notice-700: #3f4590; /* 白字 8.52:1 */
--palette-banner-activity-500: #da2470; /* 活动 · 白字 4.70:1 */
--palette-banner-activity-700: #7b3552; /* 白字 8.49:1 */
--palette-banner-update-500: #138279; /* 更新 · 白字 4.67:1 */
--palette-banner-update-700: #235450; /* 白字 8.55:1 */
--palette-banner-warning-500: #b55b0c; /* 警告 · 白字 4.70:1 */
--palette-banner-warning-700: #6a4424; /* 白字 8.52:1 */
/* --- 2. 间距(4px 栅格 + 半距)--- */
--space-0: 0px;
--space-half: 2px;
@@ -529,7 +540,10 @@
--color-cn-stroke: var(--cn-stroke);
--color-cn-fill: var(--cn-fill);
/* 字号(可用 text-fs-body / text-fs-caption 等)*/
/* 字号
注意:Tailwind v4 的字号命名空间是 --text-*,--font-size-* 不被识别,
因此下面这组声明不会生成 text-micro / text-caption 之类的工具类。
组件请沿用既有惯例直接引用 Primitive:text-[var(--fs-label)]、text-[var(--fs-caption)] 等。 */
--font-size-micro: var(--fs-micro);
--font-size-tiny: var(--fs-tiny);
--font-size-label: var(--fs-label);
@@ -595,6 +609,15 @@
--accent-soft: var(--workspace-accent-soft);
--muted: var(--color-neutral-100);
/* 顶部常驻通知条(Layer 3 组件引用;文字恒为白)
四个 --notice-banner-surface-<type> 与通知类型一一对应,dark 覆盖见 .dark 语义覆盖区;
--notice-banner-surface 是「公告」的别名,供不区分类型的引用使用。*/
--notice-banner-surface-notice: var(--palette-banner-notice-500);
--notice-banner-surface-activity: var(--palette-banner-activity-500);
--notice-banner-surface-update: var(--palette-banner-update-500);
--notice-banner-surface-warning: var(--palette-banner-warning-500);
--notice-banner-surface: var(--notice-banner-surface-notice);
/* Canvas Theme 语义(从 CSS 变量反序列化到 TS 主题对象,对应 #96 决策3)*/
--cn-text: var(--color-neutral-950);
--cn-muted: var(--color-neutral-500);
@@ -754,6 +777,13 @@
--surface-active: rgba(255, 255, 255, 0.12);
--muted: var(--color-neutral-900);
/* 顶部常驻通知条:暗色下四种类型统一压暗,白字对比度约 8.5:1 */
--notice-banner-surface-notice: var(--palette-banner-notice-700);
--notice-banner-surface-activity: var(--palette-banner-activity-700);
--notice-banner-surface-update: var(--palette-banner-update-700);
--notice-banner-surface-warning: var(--palette-banner-warning-700);
--notice-banner-surface: var(--notice-banner-surface-notice);
/* composio 文字层级(dark 直取)*/
--workspace-text-body: #a8a8a8; /* body(tokens.json text/body)*/
--workspace-text-muted: #888888; /* muted(tokens.json text/muted)*/
@@ -1306,7 +1336,8 @@
}
/* 全局轻量通知与消息提示框 */
.ant-message-notice .ant-message-notice-content {
.ant-message-notice .ant-message-notice-content,
:where(.dark, [data-theme="dark"]) .ant-message-notice .ant-message-notice-content {
color: var(--foreground) !important;
background: var(--color-surface, var(--workspace-overlay-bg-strong, #ffffff)) !important;
border: 1px solid var(--color-border, var(--workspace-overlay-border, rgba(0, 0, 0, 0.12))) !important;
@@ -1314,13 +1345,21 @@
}
.dark .ant-message-notice .ant-message-notice-content,
.dark body .ant-message-notice-content {
.dark body .ant-message-notice-content,
[data-theme="dark"] .ant-message-notice .ant-message-notice-content,
.dark .ant-message-custom-content,
.dark .ant-message-notice {
color: #f4f4f5 !important;
background: #1e1e20 !important;
border-color: rgba(255, 255, 255, 0.16) !important;
box-shadow: 0 12px 36px rgba(0, 0, 0, 0.55) !important;
}
.dark .ant-message-notice-content span,
.dark .ant-message-custom-content span {
color: #f4f4f5 !important;
}
.ant-notification-notice {
color: var(--foreground) !important;
background: var(--color-surface, var(--workspace-overlay-bg-strong, #ffffff)) !important;
+6 -6
View File
@@ -456,15 +456,15 @@
transform: translateX(2px);
}
.app-user-workspace .app-workspace-sidebar-nav.is-collapsed .app-workspace-nav-link { min-height: 62px; flex-direction: column; justify-content: center; gap: 4px; padding: 8px 2px; border-radius: 14px; }
.app-user-workspace .app-workspace-sidebar-nav.is-collapsed .app-workspace-nav-main { flex-direction: column; gap: 4px; }
.app-user-workspace .app-workspace-sidebar-nav.is-collapsed .app-workspace-nav-link.is-collapsed .app-workspace-nav-title { display: block !important; max-width: 100%; color: var(--user-ink-muted); font-size: 10px; line-height: 1.1; }
.app-user-workspace .app-workspace-sidebar-nav.is-collapsed .app-workspace-nav-link { min-height: 52px; flex-direction: column; justify-content: center; gap: 2px; padding: 6px 2px; border-radius: 12px; }
.app-user-workspace .app-workspace-sidebar-nav.is-collapsed .app-workspace-nav-main { flex-direction: column; gap: 2px; }
.app-user-workspace .app-workspace-sidebar-nav.is-collapsed .app-workspace-nav-link.is-collapsed .app-workspace-nav-title { display: block !important; max-width: 100%; color: var(--user-ink-muted); font-size: 10px; line-height: 1.1; margin-top: -1px; }
.app-user-workspace .app-workspace-sidebar-nav.is-collapsed .app-workspace-nav-link.is-active .app-workspace-nav-title { color: var(--user-ink); }
.app-user-workspace .app-workspace-sidebar-nav.is-collapsed .app-workspace-nav-link.is-collapsed .app-workspace-nav-meta { display: none !important; }
.app-user-workspace .app-workspace-sidebar-nav.is-collapsed .app-workspace-nav-group { gap: 10px; }
.app-user-workspace .app-workspace-sidebar-nav.is-collapsed .app-workspace-nav-link { width: 54px !important; padding: 6px 0 !important; }
.app-user-workspace .app-workspace-sidebar-nav.is-collapsed .app-workspace-nav-group { gap: 6px; }
.app-user-workspace .app-workspace-sidebar-nav.is-collapsed .app-workspace-nav-link { width: 54px !important; padding: 4px 0 !important; }
.app-user-workspace .app-workspace-sidebar-nav.is-collapsed .app-workspace-nav-main { width: 100%; align-items: center; justify-content: center; }
.app-user-workspace .app-workspace-sidebar-nav.is-collapsed .app-workspace-nav-icon { width: 30px; height: 30px; flex-basis: 30px; }
.app-user-workspace .app-workspace-sidebar-nav.is-collapsed .app-workspace-nav-icon { width: 24px; height: 24px; flex-basis: 24px; }
.app-user-workspace .app-workspace-sidebar-nav.is-collapsed .app-workspace-nav-link .app-workspace-nav-icon svg,
.app-user-workspace .app-workspace-sidebar-nav.is-collapsed .app-workspace-nav-link .app-workspace-nav-main > svg { width: 18px !important; height: 18px !important; flex: 0 0 18px; }
.app-user-workspace .app-workspace-sidebar-nav.is-collapsed .app-workspace-sidebar-account { width: 100%; align-items: center; }
+73
View File
@@ -293,6 +293,79 @@ test("request logs display user credit billing independently from upstream cost"
expect(apiSource).toContain("billingAvailable: boolean");
});
test("banner announcement editor keeps title styles through edit, save and status toggle", async () => {
const [panelSource, editorSource, sliderSource, apiSource, contentSource, emojiPickerSource, noticeSource] = await Promise.all([
Bun.file(new URL("../src/pages/admin/components/admin-banner-announcements-panel.tsx", import.meta.url)).text(),
Bun.file(new URL("../src/pages/admin/components/banner-title-editor.tsx", import.meta.url)).text(),
Bun.file(new URL("../src/components/layout/banner-announcements-slider.tsx", import.meta.url)).text(),
Bun.file(new URL("../src/services/api/announcements.ts", import.meta.url)).text(),
Bun.file(new URL("../src/components/layout/banner-announcement-content.tsx", import.meta.url)).text(),
Bun.file(new URL("../src/pages/admin/components/banner-notice-emoji-picker.tsx", import.meta.url)).text(),
Bun.file(new URL("../src/lib/announcements/banner-notice.ts", import.meta.url)).text(),
]);
const panel = compactSource(panelSource);
const slider = compactSource(sliderSource);
// 状态开关与保存都必须带上样式分段与通知类型:后端更新走显式字段表,漏传会清空它们。
expect(panel).toContain("titleRuns: banner.titleRuns");
expect(panel).toContain("titleRuns: runs");
expect(panel).toContain("noticeType: selectedNoticeType");
expect(panel).toContain("noticeType: normalizeBannerNoticeType(banner.noticeType)");
// 编辑入口不能被新建信号重置:父级 createOpen 消费后立即复位,编辑路径不再写回该标志。
expect(panel).toContain("onCreateOpenChange(false)");
expect(panel).toContain('setDialog({ mode: "edit", banner })');
expect(panel).toContain("banner.titleRuns?.length");
// AntD 6 用 destroyOnHidden,destroyOnClose 已废弃。
expect(panel).toContain("destroyOnHidden");
expect(panel).not.toContain("destroyOnClose");
// Modal 渲染在 body portal 里,必须挂 admin-modal-root 才能拿到弹窗作用域的强边框 / 分层 token,
// 否则编辑器等自绘控件的边框回落到 :root 的 8% 透明度,肉眼不可见。
expect(panel).toContain('rootClassName="admin-modal-root"');
// 非表单控件不能放进 Form.Item(会被注入 value/onChange/ref)。
expect(panel).toContain("<BannerNoticePreview runs={titleRuns} hasLink={Boolean(linkValue?.trim())} noticeType={noticeType} />");
// 通知类型在后台要有独立入口;emoji 图标不设独立字段,经编辑器「图标」按钮插入。
expect(panel).toContain("<BannerNoticeTypeSelector");
expect(panel).not.toContain("BannerNoticeIconPicker");
expect(panel).not.toContain("normalizeBannerNoticeIcon");
expect(editorSource).toContain("applyBannerTitleStyle");
expect(editorSource).toContain("clearBannerTitleStyle");
expect(editorSource).toContain("lowContrastBannerTitleColors");
// 标题是单行语义,Enter 不产生新段落。
expect(editorSource).toContain('event.key === "Enter"');
// emoji 素材插到光标处、作为普通文本保存(无独立字段、无默认图标)。
expect(editorSource).toContain("<BannerNoticeEmojiPopover");
expect(editorSource).toContain("insertContent(emoji)");
expect(editorSource).not.toContain("BannerAnnouncementIcon");
// 预览必须走前台同一份展示单元,否则「预览即前台」不成立。
expect(editorSource).toContain("bannerAnnouncementBarStyle(noticeType)");
// 前台通知条必须按分段渲染,不能退回纯文本;底色来自当前通知的类型,标题前不再有固定图标。
expect(sliderSource).toContain("BannerAnnouncementTitle");
expect(sliderSource).toContain("currentBanner.titleRuns");
expect(slider).toContain("bannerAnnouncementBarStyle(currentBanner.noticeType)");
expect(slider).not.toContain("BannerAnnouncementIcon");
expect(slider).not.toContain("notice-banner-surface");
// 展示单元是唯一来源:底色、富文本标题、详情入口都在这里定义,前台与预览共用;
// 图标素材是标题文本的一部分,展示单元不再单独处理图标。
expect(contentSource).toContain("export function bannerAnnouncementBarStyle");
expect(contentSource).toContain("export function BannerAnnouncementLinkHint");
expect(contentSource).toContain("export function BannerAnnouncementTitle");
expect(contentSource).not.toContain("BannerAnnouncementIcon");
// emoji 面板:默认收起(Popover 点击触发),插入后不自动关闭,方便连续插入。
expect(emojiPickerSource).toContain('trigger="click"');
expect(emojiPickerSource).toContain('onPick(item.char)');
expect(noticeSource).toContain("BANNER_NOTICE_EMOJI_GROUPS");
expect(noticeSource).not.toContain("DEFAULT_ICON");
expect(apiSource).toContain("titleRuns?: BannerTitleRun[]");
expect(apiSource).toContain("noticeType?: BannerNoticeType");
expect(apiSource).not.toContain("icon?:");
expect(apiSource).toContain("export type { BannerTitleRun }");
});
test("admin console tokens and shell stay isolated from the user workspace", async () => {
const [tokens, shell, chrome, globals] = await Promise.all([
Bun.file(new URL("../src/pages/admin/theme/admin-tokens.css", import.meta.url)).text(),
+147
View File
@@ -0,0 +1,147 @@
import { describe, expect, test } from "bun:test";
import {
BANNER_NOTICE_DEFAULT_TYPE,
BANNER_NOTICE_EMOJI_GROUPS,
BANNER_NOTICE_EMOJIS,
BANNER_NOTICE_TYPE_VALUES,
BANNER_NOTICE_TYPES,
bannerNoticeSurfaceCSS,
bannerNoticeTypeLabel,
normalizeBannerNoticeType,
searchBannerNoticeEmojis,
} from "@/lib/announcements/banner-notice";
import { bannerTitleContrastRatio } from "@/lib/announcements/banner-title";
async function readSource(relativePath: string) {
return Bun.file(new URL(relativePath, import.meta.url)).text();
}
/** 从 Go 的 `var X = map[string]struct{}{...}` 字面量里取出键集合。 */
function goMapKeys(source: string, variable: string) {
const start = source.indexOf(`var ${variable} = map[string]struct{}{`);
if (start < 0) throw new Error(`未找到 ${variable}`);
const end = source.indexOf("\n}", start);
if (end < 0) throw new Error(`${variable} 字面量未闭合`);
const body = source.slice(start, end);
return Array.from(body.matchAll(/"([a-z0-9-]+)"/g)).map((match) => match[1]);
}
describe("通知类型", () => {
test("未知或空值回落到默认类型", () => {
expect(normalizeBannerNoticeType(undefined)).toBe(BANNER_NOTICE_DEFAULT_TYPE);
expect(normalizeBannerNoticeType("")).toBe(BANNER_NOTICE_DEFAULT_TYPE);
expect(normalizeBannerNoticeType("rainbow")).toBe(BANNER_NOTICE_DEFAULT_TYPE);
expect(normalizeBannerNoticeType(" ACTIVITY ")).toBe("activity");
});
test("每种类型都有中文名与独立的底色 token", () => {
const vars = BANNER_NOTICE_TYPES.map((item) => item.surfaceVar);
expect(new Set(vars).size).toBe(vars.length);
for (const type of BANNER_NOTICE_TYPES) {
expect(bannerNoticeTypeLabel(type.key)).toBe(type.label);
expect(bannerNoticeSurfaceCSS(type.key)).toBe(`var(${type.surfaceVar})`);
}
// 未知类型也必须拿到可用底色,不能渲染成透明条。
expect(bannerNoticeSurfaceCSS("rainbow")).toBe(bannerNoticeSurfaceCSS(BANNER_NOTICE_DEFAULT_TYPE));
});
});
describe("emoji 图标素材库", () => {
test("字符唯一、非空,每个素材都有中文名", () => {
const chars = BANNER_NOTICE_EMOJIS.map((item) => item.char);
expect(new Set(chars).size).toBe(chars.length);
expect(chars.length).toBeGreaterThanOrEqual(50);
for (const item of BANNER_NOTICE_EMOJIS) {
expect(item.char.trim().length).toBeGreaterThan(0);
expect(item.label.trim().length).toBeGreaterThan(0);
expect(item.groupLabel.trim().length).toBeGreaterThan(0);
}
});
test("用户点名的素材必须在库内", () => {
for (const char of ["💰", "🚀", "🔥", "📢"]) {
expect(BANNER_NOTICE_EMOJIS.some((item) => item.char === char)).toBe(true);
}
});
test("搜索同时匹配中文名、分组名与字符本身", () => {
expect(searchBannerNoticeEmojis("火箭").map((item) => item.char)).toContain("🚀");
expect(searchBannerNoticeEmojis("钱袋").map((item) => item.char)).toContain("💰");
// 分组名搜索命中整组。
const statusHits = searchBannerNoticeEmojis("状态");
expect(statusHits.length).toBeGreaterThanOrEqual(BANNER_NOTICE_EMOJI_GROUPS.find((g) => g.key === "status")!.emoji.length);
// 字符本身也能搜到(支持从别处粘贴检索)。
expect(searchBannerNoticeEmojis("🔥").map((item) => item.char)).toContain("🔥");
expect(searchBannerNoticeEmojis(" ").length).toBe(BANNER_NOTICE_EMOJIS.length);
expect(searchBannerNoticeEmojis("不存在的素材")).toEqual([]);
});
test("emoji 是普通文本:标题纯文本拼接函数必须原样保留它", async () => {
// 防止未来有人给 run.text 做字符过滤,把 emoji 丢掉。
const { bannerTitlePlainText } = await import("@/lib/announcements/banner-title");
const runs = [
{ text: "🔥", fontSize: 20 },
{ text: "限时", color: "#FFE58F" },
{ text: "大促" },
];
expect(bannerTitlePlainText(runs as never)).toBe("🔥限时大促");
});
});
describe("与后端白名单保持一致", () => {
test("通知类型的后端白名单逐项等于前端注册表", async () => {
const goSource = await readSource("../../backend/internal/app/announcement.go");
expect(new Set(goMapKeys(goSource, "bannerNoticeTypes"))).toEqual(new Set(BANNER_NOTICE_TYPE_VALUES));
});
test("后端默认值常量与前端一致", async () => {
const goSource = await readSource("../../backend/internal/app/announcement.go");
expect(goSource).toContain(`bannerNoticeDefaultType = "${BANNER_NOTICE_DEFAULT_TYPE}"`);
});
test("后端不保存独立图标字段:emoji 必须内嵌在标题分段里", async () => {
const [goModel, goApp, goRepo] = await Promise.all([
readSource("../../backend/internal/model/models_project.go"),
readSource("../../backend/internal/app/announcement.go"),
readSource("../../backend/internal/repository/announcement.go"),
]);
// 防止 icon 字段被加回来却没人维护白名单:图标的存储形态就是 TitleRuns 的文本。
expect(goModel).not.toMatch(/\bIcon\s+string/);
expect(goApp).not.toContain("normalizeBannerIcon");
expect(goRepo).not.toContain('"icon"');
});
});
describe("通知条主题色", () => {
test("四种类型在明暗两档都满足白字对比度要求", async () => {
const css = await readSource("../src/styles/globals.css");
const value = (token: string) => {
const match = css.match(new RegExp(`--${token}:\\s*(#[0-9a-fA-F]{6})`));
if (!match) throw new Error(`globals.css 缺少 --${token}`);
return match[1];
};
for (const type of BANNER_NOTICE_TYPES) {
// 浅色档是正文级底色,必须达到 WCAG AA 的 4.5:1;
// 深色档统一压到 7:1 以上,避免暗色主题里底色过亮。
const light = value(`palette-banner-${type.key}-500`);
const dark = value(`palette-banner-${type.key}-700`);
expect(bannerTitleContrastRatio("#FFFFFF", light)).toBeGreaterThanOrEqual(4.5);
expect(bannerTitleContrastRatio("#FFFFFF", dark)).toBeGreaterThanOrEqual(7);
}
});
test("前台与预览都引用按类型取值的语义 token", async () => {
const [globals, adminUi] = await Promise.all([readSource("../src/styles/globals.css"), readSource("../src/styles/admin-ui.css")]);
for (const type of BANNER_NOTICE_TYPES) {
// surfaceVar 自带 `--` 前缀,拼接时不要再加一次。
const name = type.surfaceVar.replace(/^--/, "");
// 语义层明暗各定义一次::root 一次、.dark 一次。
const semantic = new RegExp(`--${name}: var\\(--palette-banner-${type.key}-\\d00\\)`, "g");
expect(globals.match(semantic)?.length).toBe(2);
// 后台预览强制两套底色,不受页面当前主题影响。
expect(adminUi).toContain(`--${name}: var(--palette-banner-${type.key}-500)`);
expect(adminUi).toContain(`--${name}: var(--palette-banner-${type.key}-700)`);
}
});
});
+72
View File
@@ -0,0 +1,72 @@
import { expect, test } from "bun:test";
import { bannerDocToRuns, bannerTitleRunsToDoc } from "@/lib/announcements/banner-title-rich-text";
test("样式分段与编辑文档互转保持幂等", () => {
const runs = [
{ text: "限时活动", fontSize: 16, fontWeight: 700, color: "#FF0000" },
{ text: "已上线", fontFamily: "mono" as const },
{ text: ",欢迎体验" },
];
const doc = bannerTitleRunsToDoc(runs);
expect(doc.content?.[0]?.type).toBe("paragraph");
expect(bannerDocToRuns(doc)).toEqual(runs);
});
test("编辑器文档里的白名单外样式在转回分段时被丢弃", () => {
const doc = {
type: "doc",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "标题",
marks: [{ type: "textStyle", attrs: { fontSize: "40px", fontWeight: "900", color: "red", fontFamily: "Comic Sans" } }],
},
],
},
],
};
expect(bannerDocToRuns(doc)).toEqual([{ text: "标题" }]);
});
test("同一节点上的多个 textStyle 标记按出现顺序合并取值", () => {
const doc = {
type: "doc",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "标题",
marks: [
{ type: "textStyle", attrs: { fontSize: "12px" } },
{ type: "textStyle", attrs: { fontSize: "18px", color: "#00ff00" } },
],
},
],
},
],
};
expect(bannerDocToRuns(doc)).toEqual([{ text: "标题", fontSize: 18, color: "#00FF00" }]);
});
test("多段文档只取首个段落,粘贴内容不会变成多行标题", () => {
const doc = {
type: "doc",
content: [
{ type: "paragraph", content: [{ type: "text", text: "第一行" }] },
{ type: "paragraph", content: [{ type: "text", text: "第二行" }] },
],
};
expect(bannerDocToRuns(doc)).toEqual([{ text: "第一行" }]);
});
test("空文档与空分段互转不报错", () => {
expect(bannerDocToRuns(undefined)).toEqual([]);
expect(bannerDocToRuns(null)).toEqual([]);
expect(bannerTitleRunsToDoc([])).toEqual({ type: "doc", content: [{ type: "paragraph", content: [] }] });
});
+101
View File
@@ -0,0 +1,101 @@
import { describe, expect, test } from "bun:test";
import {
BANNER_TITLE_FONT_FAMILIES,
bannerTitleCharCount,
bannerTitleContrastRatio,
bannerTitlePlainText,
bannerTitleRunStyle,
lowContrastBannerTitleColors,
normalizeBannerTitleHex,
normalizeBannerTitleRuns,
parseBannerTitleColor,
} from "@/lib/announcements/banner-title";
describe("通知标题样式分段清洗", () => {
test("合并相邻同样式分段,跳过空文本", () => {
const runs = normalizeBannerTitleRuns([
{ text: "限时", fontSize: 16, color: "#FF0000" },
{ text: "活动", fontSize: 16, color: "#ff0000" },
{ text: "", fontSize: 16 },
{ text: "上线", fontSize: 20 },
]);
expect(runs).toEqual([
{ text: "限时活动", fontSize: 16, color: "#FF0000" },
{ text: "上线", fontSize: 20 },
]);
});
test("丢弃白名单外的字号、字重、字体与颜色", () => {
expect(normalizeBannerTitleRuns([{ text: "标题", fontSize: 9 }])).toEqual([{ text: "标题" }]);
expect(normalizeBannerTitleRuns([{ text: "标题", fontSize: 21 }])).toEqual([{ text: "标题" }]);
expect(normalizeBannerTitleRuns([{ text: "标题", fontWeight: 6000 }])).toEqual([{ text: "标题" }]);
expect(normalizeBannerTitleRuns([{ text: "标题", fontFamily: "comic" as never }])).toEqual([{ text: "标题" }]);
expect(normalizeBannerTitleRuns([{ text: "标题", color: "red" }])).toEqual([{ text: "标题" }]);
expect(normalizeBannerTitleRuns([{ text: "标题", color: "#fff;background:url(x)" }])).toEqual([{ text: "标题" }]);
});
test("sans 视为默认字体,不写入分段", () => {
expect(normalizeBannerTitleRuns([{ text: "标题", fontFamily: "sans" }])).toEqual([{ text: "标题" }]);
expect(normalizeBannerTitleRuns([{ text: "标题", fontFamily: "mono" }])).toEqual([{ text: "标题", fontFamily: "mono" }]);
});
test("纯文本与字符数按码点统计", () => {
const runs = [{ text: "限时" }, { text: "活动🎉" }];
expect(bannerTitlePlainText(runs)).toBe("限时活动🎉");
expect(bannerTitleCharCount(runs)).toBe(5);
});
});
describe("通知标题样式输出", () => {
test("只输出已设置的维度", () => {
expect(bannerTitleRunStyle({ text: "标题" })).toEqual({});
expect(bannerTitleRunStyle({ text: "标题", fontSize: 20, fontWeight: 700, color: "#FF0000" })).toEqual({
fontSize: "20px",
fontWeight: 700,
color: "#FF0000",
});
});
test("字体档位输出对应字体栈", () => {
const serif = BANNER_TITLE_FONT_FAMILIES.find((item) => item.key === "serif");
expect(bannerTitleRunStyle({ text: "标题", fontFamily: "serif" }).fontFamily).toBe(serif?.css);
});
test("十六进制颜色归一化", () => {
expect(normalizeBannerTitleHex("#abc")).toBe("#AABBCC");
expect(normalizeBannerTitleHex("5f6ae4")).toBe("#5F6AE4");
expect(normalizeBannerTitleHex("#12345")).toBe("");
expect(parseBannerTitleColor("rgb(95, 106, 228)")).toEqual([95, 106, 228]);
expect(parseBannerTitleColor("not-a-color")).toBeNull();
});
});
describe("通知标题对比度检查", () => {
test("白字在通知条两种底色上的对比度", () => {
expect(bannerTitleContrastRatio("#FFFFFF", "#5C67E2")).toBeCloseTo(4.67, 2);
expect(bannerTitleContrastRatio("#FFFFFF", "#3F4590")).toBeCloseTo(8.52, 2);
expect(bannerTitleContrastRatio("not-a-color", "#3F4590")).toBeNull();
expect(bannerTitleContrastRatio("#FFFFFF", "")).toBeNull();
});
test("通知条底色 token 的白字对比度必须达到 AA(改 token 时同步更新此处)", () => {
// globals.css 的 --palette-banner-notice-500 / -700(「公告」类型);默认标题为白色 12px 正文,需 >= 4.5:1。
// 四种类型的完整覆盖见 test/banner-notice.test.ts。
expect(bannerTitleContrastRatio("#FFFFFF", "#5C67E2")).toBeGreaterThanOrEqual(4.5);
expect(bannerTitleContrastRatio("#FFFFFF", "#3F4590")).toBeGreaterThanOrEqual(4.5);
});
test("挑出对比度不足的颜色并去重,默认无色不参与检查", () => {
const runs = [
{ text: "低", color: "#808BF5" },
{ text: "也低", color: "#808BF5" },
{ text: "足够", color: "#FFFFFF" },
{ text: "没设颜色" },
];
expect(lowContrastBannerTitleColors(runs, "#5C67E2")).toEqual(["#808BF5"]);
expect(lowContrastBannerTitleColors(runs, "#3F4590")).toEqual(["#808BF5"]);
expect(lowContrastBannerTitleColors([{ text: "足够", color: "#FFFFFF" }], "#5C67E2")).toEqual([]);
expect(lowContrastBannerTitleColors(runs, "")).toEqual([]);
});
});