From ac97048df6ae85360f9259bb8a93e258b259ab6c Mon Sep 17 00:00:00 2001 From: Todos Date: Sun, 8 Nov 2026 20:00:48 +0800 Subject: [PATCH] =?UTF-8?q?feat(public):=20=E5=88=86=E7=B1=BB=E6=9C=AB?= =?UTF-8?q?=E5=B0=BE=E3=80=8C+=E3=80=8D=E7=A0=96=E6=96=B0=E5=BB=BA?= =?UTF-8?q?=E9=93=BE=E6=8E=A5=E5=B9=B6=E7=A7=BB=E9=99=A4=E5=90=8E=E5=8F=B0?= =?UTF-8?q?=E9=93=BE=E6=8E=A5=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 删除后台「链接」分区与 LinkPanel,LinkEditDialog 保留给首页编辑模式复用 - 新建按全局 MAX+1 提交、POST 后读回完整 DTO 并入 store;空分类的「+」砖兼作拖拽落点 - 顺带修编辑模式砖宽不足、以及弹窗开着按 Esc 连编辑模式一起退出的问题 Checkpoint: xYV_sayjVh-x1OYDUsidJ --- web/src/components/admin/admin-page.tsx | 24 +- web/src/components/admin/crud-panels.tsx | 167 +----- web/src/components/admin/link-edit-dialog.tsx | 15 +- web/src/components/home-edit-board.tsx | 103 ++-- web/src/components/public-page.tsx | 40 +- web/src/lib/api.ts | 22 +- web/src/lib/nav-store.ts | 54 +- web/test/admin-page.test.tsx | 7 +- web/test/admin-scenes.test.tsx | 40 +- web/test/crud-panels.test.tsx | 517 +----------------- web/test/link-edit-dialog.test.tsx | 356 ++++++++++++ web/test/nav-store-link-edits.test.ts | 90 ++- web/test/public-edit-mode.test.tsx | 108 +++- 13 files changed, 737 insertions(+), 806 deletions(-) create mode 100644 web/test/link-edit-dialog.test.tsx diff --git a/web/src/components/admin/admin-page.tsx b/web/src/components/admin/admin-page.tsx index a55371d..895917a 100644 --- a/web/src/components/admin/admin-page.tsx +++ b/web/src/components/admin/admin-page.tsx @@ -4,7 +4,6 @@ import { FolderTree, Info, Layers, - Link as LinkIcon, LogOut, Search, Settings as SettingsIcon, @@ -13,7 +12,7 @@ import { } from "lucide-react"; import * as React from "react"; import { AboutPanel } from "@/components/admin/about-panel"; -import { CategoryPanel, LinkPanel } from "@/components/admin/crud-panels"; +import { CategoryPanel } from "@/components/admin/crud-panels"; import { ScenePanel } from "@/components/admin/scene-panel"; import { SecurityPanel } from "@/components/admin/security-panel"; import { @@ -41,8 +40,9 @@ import type { AdminScene } from "@/lib/types"; * + 玻璃内容卡。分区菜单用 Radix Tabs 单一根:宽屏是左栏竖排,窄屏变内容区顶部的 * 横向滚动菜单条(同一个 TabsList,只换 orientation 与响应式类,不做抽屉)。 * - * 分区内容(分类 / 链接 / 场景管理 / 搜索引擎 / 站点设置 / 导入导出 / + * 分区内容(分类 / 场景管理 / 搜索引擎 / 站点设置 / 导入导出 / * 安全·两步验证 / 系统管理 / 关于)的容器换成了玻璃卡,面板组件本身的表单与业务逻辑不动。 + * 链接不在这里管:首页编辑模式(`home-edit-board.tsx`)已能增删改与拖动排序。 * * 后台数据由 store(useNavStore.adminData)承载,本页只负责加载与分发; * 安全区的数据(2FA 状态、Passkey 凭据)属会话期敏感数据,由 SecurityPanel 自行拉取, @@ -52,7 +52,6 @@ import type { AdminScene } from "@/lib/types"; /** 左栏菜单项(图标用 Lucide,与前台同一视觉家族)。 */ const ADMIN_TABS = [ { value: "categories", label: "分类", icon: FolderTree }, - { value: "links", label: "链接", icon: LinkIcon }, { value: "scenes", label: "场景管理", icon: Layers }, { value: "engines", label: "搜索引擎", icon: Search }, { value: "settings", label: "站点设置", icon: SettingsIcon }, @@ -94,8 +93,8 @@ function PanelCard({ children }: { children: React.ReactNode }) { } /** - * 后台场景胶囊:「分类」「链接」两分区内容卡顶部,只有场景、没有「全部」 - * (后台永远停在具体场景:新建分类/链接要带 sceneId)。与前台共用 `nav.scene`。 + * 后台场景胶囊:「分类」分区内容卡顶部,只有场景、没有「全部」 + * (后台永远停在具体场景:新建分类要带 sceneId)。与前台共用 `nav.scene`。 * 没有场景(旧后端 / 无场景概念)时不渲染。 */ function AdminSceneBar({ @@ -248,19 +247,6 @@ export function AdminPage({ onBack }: { onBack: () => void }) { - - -
- - void loadAdmin()} - /> -
-
-
- ); } - -/** 「所有」筛选项的哨兵值:Radix Select 不允许 SelectItem 用空串(空串代表未选) */ -const ALL_CATEGORIES = "__all__"; - -/** 链接 CRUD + 分类内排序(后台 links 为扁平列表;按当前场景的分类 id 过滤) */ -export function LinkPanel({ - categories, - links, - onChanged, -}: { - /** 当前场景的分类(已过滤):分类选择器只列这些,新建链接只归当前场景 */ - categories: AdminCategory[]; - /** 全量链接:展示按当前场景过滤,排序重建仍用全局 ids(链接 sort_order 语义不变) */ - links: AdminLink[]; - onChanged: () => void; -}) { - const [categoryId, setCategoryId] = React.useState(ALL_CATEGORIES); - const category = categories.find((c) => c.id === categoryId); - // 链接没有场景字段:其场景由所属分类唯一决定,这里经分类 id 过滤(保持全局 sortOrder) - const sceneCategoryIds = new Set(categories.map((c) => c.id)); - const sceneLinks = links.filter((l) => sceneCategoryIds.has(l.categoryId)); - // 「所有」:不过滤分类,直接按全局 sortOrder 展示当前场景全部链接 - const categoryLinks = ( - category - ? sceneLinks.filter((l) => l.categoryId === category.id) - : sceneLinks - ).sort((a, b) => a.sortOrder - b.sortOrder); - const [editingId, setEditingId] = React.useState(null); - const [creating, setCreating] = React.useState(false); - - const openCreate = () => { - if (!category) { - toast.error("请先选择一个分类"); - return; - } - setEditingId(null); - setCreating(true); - }; - - const openEdit = (id: string) => { - // 「所有」视图下 categoryLinks 就是当前场景的全部链接,因此编辑照样可用, - // 预选值由弹窗自己按链接实际所属分类填写。 - setEditingId(id); - setCreating(false); - }; - - const closeDialog = () => { - setCreating(false); - setEditingId(null); - }; - - const dialogLink = editingId - ? (links.find((l) => l.id === editingId) ?? null) - : null; - - const remove = async (id: string) => { - await adminDeleteLink(id); - toast.success("链接已删除"); - onChanged(); - }; - - const reorder = async (orderedIds: string[]) => { - // 契约 reorder 为全局 ids 列表(sort_order 全局);此处重建全量顺序, - // 仅替换当前分类链接的相对位置,其余分类链接保持原有相对顺序。 - const selectedSet = new Set(orderedIds); - const sorted = [...links].sort((a, b) => a.sortOrder - b.sortOrder); - const firstIdx = sorted.findIndex((l) => selectedSet.has(l.id)); - const before: string[] = []; - const after: string[] = []; - sorted.forEach((l, i) => { - if (selectedSet.has(l.id)) return; - if (i < firstIdx) before.push(l.id); - else after.push(l.id); - }); - try { - await useNavStore - .getState() - .reorderLinks([...before, ...orderedIds, ...after]); - } catch { - toast.error("排序失败,已恢复原顺序"); - } - }; - - return ( -
-
-

链接

-
- - -
-
- - {categories.length > 0 ? ( - ({ - id: l.id, - label: l.title, - meta: ( - - - - {l.visibility === "private" ? "私有" : "公开"} - - - ), - }))} - onReorder={reorder} - onEdit={openEdit} - onRemove={remove} - confirmRemove - removeDescription="删除链接后无法恢复,请确认。" - /> - ) : ( -

- 暂无分类,请先创建分类。 -

- )} - - { - closeDialog(); - onChanged(); - }} - /> -
- ); -} diff --git a/web/src/components/admin/link-edit-dialog.tsx b/web/src/components/admin/link-edit-dialog.tsx index eb03b0d..b67f255 100644 --- a/web/src/components/admin/link-edit-dialog.tsx +++ b/web/src/components/admin/link-edit-dialog.tsx @@ -23,7 +23,7 @@ import { SelectValue, } from "@/components/ui/select"; import { Switch } from "@/components/ui/switch"; -import { adminCreateLink, adminUpdateLink } from "@/lib/api"; +import { adminUpdateLink, type CreateLinkInput } from "@/lib/api"; import { useNavStore } from "@/lib/nav-store"; import type { AdminCategory, AdminLink, Visibility } from "@/lib/types"; @@ -36,13 +36,16 @@ import type { AdminCategory, AdminLink, Visibility } from "@/lib/types"; * 置全局 MAX+1);所以换分类前先 `settleLinkOrder()`,保证这次 PUT 是最后一次写; * - 保存失败弹错误原文、弹窗保持打开;成功清理被替换的 R2 图标。 * - * `link === null` 表示新建(后台用);首页编辑模式只用编辑态。 + * `link === null` 是新建(首页编辑模式分类末尾的「+」砖)。新建交给调用方的 + * `onCreateLink`:置位/排序与读回完整 DTO 是调用方的事(契约 POST 只回 `{id}`); + * 两条路径成功后都走 `onSaved`,并入 store 只有一条路径。 */ export function LinkEditDialog({ open, link, categories, defaultCategoryId, + onCreateLink, onClose, onSaved, }: { @@ -51,10 +54,12 @@ export function LinkEditDialog({ link: AdminLink | null; /** 当前场景的分类(分类下拉只列这些) */ categories: AdminCategory[]; - /** 新建时预选的分类(后台必须先在筛选器里选一个) */ + /** 新建时预选的分类(首页编辑模式选中那块「+」砖所属的分类) */ defaultCategoryId?: string; + /** 新建提交:落库后回传完整 DTO(排序号由调用方定,POST 只回 {id}) */ + onCreateLink: (input: CreateLinkInput) => Promise; onClose: () => void; - /** 保存成功:回传服务端返回的最新 DTO,由调用方决定就地替换还是整表刷新 */ + /** 保存成功:回传服务端的最新 DTO,由调用方就地并入 store */ onSaved: (link: AdminLink) => void; }) { const [form, setForm] = React.useState({ @@ -136,7 +141,7 @@ export function LinkEditDialog({ : "链接已更新", ); } else { - saved = await adminCreateLink(payload); + saved = await onCreateLink(payload); toast.success("链接已创建"); } draft.commit(); diff --git a/web/src/components/home-edit-board.tsx b/web/src/components/home-edit-board.tsx index 1baa433..712820a 100644 --- a/web/src/components/home-edit-board.tsx +++ b/web/src/components/home-edit-board.tsx @@ -21,7 +21,7 @@ import { useSortable, } from "@dnd-kit/sortable"; import { CSS } from "@dnd-kit/utilities"; -import { X } from "lucide-react"; +import { Plus, X } from "lucide-react"; import { FadeIn } from "@/components/glass"; import { CategoryHeading, @@ -39,7 +39,11 @@ import type { LinkStyle, SiteCategory, SiteLink } from "@/lib/types"; * (`rectSortingStrategy`,砖是自动换行的网格)。投放目标三种: * - 某块砖:落到它的下标位置(同分类换位、跨分类插入都走这条); * - 分类标题行(`end:`):落到该分类**末尾**; - * - 空分类占位(`cat:`):虚线框、无文字、与同档砖同高,落到唯一位置。 + * - 空分类末尾的「+」砖(`cat:`):与同档砖同高,落到唯一位置。 + * + * 每个分类网格末尾恒有一块「+」砖(`AddLinkTile`):点它在该分类新建链接。 + * 分类为空时这块砖就是上面那个落点(把最后一块拖走后还能拖回来);分类非空时 + * 它不注册 droppable,不抢命中。 * * 拖动中的预览顺序放在组件本地草稿里(只是拖拽期间的临时 UI 状态),松手才写 store: * `onDragOver` 做跨容器搬运,`onDragEnd` 再补同容器换位,然后把「目标分类 + 前驱 id」 @@ -52,7 +56,7 @@ import type { LinkStyle, SiteCategory, SiteLink } from "@/lib/types"; /** 分类标题行投放目标(落到该分类末尾)的 id 前缀 */ const END_PREFIX = "end:"; -/** 空分类占位投放目标的 id 前缀 */ +/** 空分类落点(也就是那块「+」砖)投放目标的 id 前缀 */ const CAT_PREFIX = "cat:"; /** @@ -69,11 +73,11 @@ const collisionDetection: CollisionDetection = (args) => { return endTarget ? [endTarget] : closestCorners(args); }; -/** 空分类占位的高度:与同档一块砖一致(虚线框内不写字) */ +/** 同档一块砖的高度(三档实测值):编辑模式末尾的「+」砖与空分类落点共用 */ const PLACEHOLDER_CLASS: Record = { - classic: "min-h-[132px]", - compact: "min-h-11", - wide: "min-h-[60px]", + classic: "min-h-[130px]", + compact: "min-h-9", + wide: "min-h-[62px]", }; type Order = Record; @@ -196,7 +200,9 @@ function EditableTile({ aria-label={link.title} className={cn( linkTileClassName(linkStyle), - "cursor-grab select-none active:cursor-grabbing", + // ` ); } @@ -274,6 +300,7 @@ export function HomeEditBoard({ onEditLink, onRemoveLink, onMoveLink, + onAddLink, }: { /** 当前场景的分类(组内链接已按 sortOrder 排好,与正常模式同源) */ categories: readonly SiteCategory[]; @@ -282,6 +309,8 @@ export function HomeEditBoard({ privateCategories: ReadonlySet; onEditLink: (linkId: string) => void; onRemoveLink: (linkId: string) => void; + /** 末尾「+」砖:在该分类新建链接 */ + onAddLink: (categoryId: string) => void; /** 松手后保存:目标分类 + 落点前一块的 id(null = 该分类第一个位置) */ onMoveLink: ( linkId: string, @@ -416,26 +445,26 @@ export function HomeEditBoard({
- {ids.length === 0 ? ( - - ) : ( - ids.map((id) => { - const link = linkById.get(id); - if (!link) return null; - return ( - - ); - }) - )} + {ids.map((id) => { + const link = linkById.get(id); + if (!link) return null; + return ( + + ); + })} + {/* 末尾恒有一个「+」砖:空分类时它就是该分类唯一的投放目标 */} +
diff --git a/web/src/components/public-page.tsx b/web/src/components/public-page.tsx index da76acf..015c3c6 100644 --- a/web/src/components/public-page.tsx +++ b/web/src/components/public-page.tsx @@ -30,7 +30,7 @@ import { * 分类区块,公共页与访客都无法在这里改。 * * 首页编辑模式(登录态专属,纯前端本地状态):坞里的铅笔把页面切成 - * `HomeEditBoard`(拖动排序/分组、✕ 延迟删除、单击复用后台编辑弹窗), + * `HomeEditBoard`(拖动排序/分组、✕ 延迟删除、单击砖编辑、分类末尾「+」砖新建), * 退出/刷新/Esc/切场景/输入搜索都回到正常模式;编辑模式里砖不再跳转。 * * 安全口径:未登录时私有区完全不渲染 —— privateData 未加载时组件树里没有私有区块, @@ -54,7 +54,8 @@ export function PublicPage({ onOpenAdmin }: { onOpenAdmin: () => void }) { exitEditMode, moveLinkOnHome, removeLinkOnHome, - applyEditedLink, + applySavedLink, + createLinkOnHome, } = useNavStore(); const authenticated = useAuthenticated(); // 本机场景偏好(前后台共用):只影响显示过滤,不写服务端 @@ -63,6 +64,10 @@ export function PublicPage({ onOpenAdmin }: { onOpenAdmin: () => void }) { // 搜索框内容只用于「编辑模式的进出门槛」,搜索本身仍由 SearchBar 自己持有 const [searchQuery, setSearchQuery] = React.useState(""); const [editingLinkId, setEditingLinkId] = React.useState(null); + // 分类末尾「+」砖新建:非 null 时弹窗处于新建态,所属分类预选它 + const [creatingCategoryId, setCreatingCategoryId] = React.useState< + string | null + >(null); React.useEffect(() => { void loadPublic(); @@ -80,16 +85,22 @@ export function PublicPage({ onOpenAdmin }: { onOpenAdmin: () => void }) { }; }, []); - // Esc 退出编辑模式;编辑弹窗打开时 Esc 归弹窗(关弹窗,不退出编辑模式) + // Esc 退出编辑模式。链接弹窗(编辑态 / 新建态)打开时 Esc 归弹窗:Radix 在同一次 + // keydown 里先把弹窗关掉,React 的 state 可能已经清空、而窗口级的这个监听器最后才跑, + // 所以光看 state 不够 —— 事件目标仍在弹窗里就不再当成「退出编辑」。 React.useEffect(() => { if (!editMode) return; const onKey = (event: KeyboardEvent) => { - if (event.key !== "Escape" || editingLinkId) return; + if (event.key !== "Escape") return; + if (editingLinkId || creatingCategoryId) return; + const target = event.target; + if (target instanceof Element && target.closest('[role="dialog"]')) + return; exitEditMode(); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); - }, [editMode, editingLinkId, exitEditMode]); + }, [editMode, editingLinkId, creatingCategoryId, exitEditMode]); // 契约:/api/private 返回与 /api/public 同结构的全量数据(公开+私有)。 // 登录后直接以 privateData.categories 作为全量列表,不再拼接 public/private。 @@ -199,6 +210,7 @@ export function PublicPage({ onOpenAdmin }: { onOpenAdmin: () => void }) { onEditLink={setEditingLinkId} onRemoveLink={removeLinkOnHome} onMoveLink={handleMoveLink} + onAddLink={setCreatingCategoryId} /> ) : (
@@ -228,15 +240,25 @@ export function PublicPage({ onOpenAdmin }: { onOpenAdmin: () => void }) { onLogout={() => void logout()} /> - {/* 首页编辑模式的单击编辑:复用后台同一个链接弹窗,保存后就地生效 */} + {/* + 首页编辑模式的链接弹窗:点砖是编辑(复用后台同一份实现)、分类末尾「+」砖是新建 + (所属分类预选该分类,排序号由 store 定为分类末尾)。两态共用一个弹窗与一条 + 「保存后并入 store」的路径。 + */} setEditingLinkId(null)} + defaultCategoryId={creatingCategoryId ?? undefined} + onCreateLink={createLinkOnHome} + onClose={() => { + setEditingLinkId(null); + setCreatingCategoryId(null); + }} onSaved={(link) => { - applyEditedLink(link); + applySavedLink(link); setEditingLinkId(null); + setCreatingCategoryId(null); }} /> diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index f38761a..27fb469 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -534,7 +534,7 @@ export async function adminReorderScenes(ids: string[]): Promise { } // 链接 -export async function adminCreateLink(input: { +export interface CreateLinkInput { title: string; url: string; categoryId: string; @@ -542,14 +542,30 @@ export async function adminCreateLink(input: { description?: string | null; sortOrder?: number; visibility?: "public" | "private"; -}): Promise { +} + +/** + * 新建链接。契约(docs/api-contract.md §链接)只回 **201 `{id}`**,不回整条 DTO: + * 需要完整对象的调用方(首页编辑模式要就地渲染新砖)自己用 `adminListLinks()` 读回。 + * dev mock 返回整条 DTO,结构上是本类型的一个超集,兼容。 + */ +export async function adminCreateLink( + input: CreateLinkInput, +): Promise<{ id: string }> { if (USE_MOCK) return (await devMock()).createLink(input); - return request(`${API.admin}/links`, { + return request<{ id: string }>(`${API.admin}/links`, { method: "POST", body: JSON.stringify(input), }); } +/** 后台链接全量(扁平,按服务端顺序):新建后读回完整 DTO 用。 */ +export async function adminListLinks(): Promise { + if (USE_MOCK) return (await devMock()).adminListAll().then((d) => d.links); + const data = await request<{ links: AdminLink[] }>(`${API.admin}/links`); + return data.links; +} + export async function adminUpdateLink( id: string, input: Partial, diff --git a/web/src/lib/nav-store.ts b/web/src/lib/nav-store.ts index b50369f..1700cd3 100644 --- a/web/src/lib/nav-store.ts +++ b/web/src/lib/nav-store.ts @@ -9,7 +9,9 @@ import { logout as apiLogout, verifyTotp as apiVerifyTotp, adminDeleteLink, + adminCreateLink, adminListAll, + adminListLinks, adminMoveLink, adminReorderCategories, adminReorderEngines, @@ -18,6 +20,7 @@ import { UnauthorizedError, ApiError, type AdminData, + type CreateLinkInput, type LoginResult, } from "@/lib/api"; import { buildMoveIds } from "@/lib/link-order"; @@ -139,8 +142,13 @@ interface NavState { undoRemoveLink: (linkId: string) => void; /** 退出编辑模式 / 页面卸载:待落库的删除立即落库 */ flushPendingLinkDeletes: () => void; - /** 后台链接弹窗保存后:就地替换 store 里的链接并投影(不重拉) */ - applyEditedLink: (link: AdminLink) => void; + /** 后台链接弹窗保存后:就地替换 store 里的链接并投影(不重拉);不存在则追加 */ + applySavedLink: (link: AdminLink) => void; + /** + * 首页编辑模式新建链接:定好「分类末尾」的 sortOrder 提交,再读回完整 DTO 交给调用方。 + * 不直接改 store(并入走 `applySavedLink`,与编辑保存同一条路径)。 + */ + createLinkOnHome: (input: CreateLinkInput) => Promise; /** 设置保存成功后就地刷新 store 里所有存活的 settings 切片(三片原子更新) */ patchAdminSettings: (settings: SiteSettings) => void; @@ -422,12 +430,15 @@ export const useNavStore = create((set, get) => ({ } }, - applyEditedLink: (link) => { + applySavedLink: (link) => { const data = get().adminData; - if (!data || !data.links.some((item) => item.id === link.id)) return; + if (!data) return; + const exists = data.links.some((item) => item.id === link.id); const next: AdminData = { ...data, - links: data.links.map((item) => (item.id === link.id ? link : item)), + links: exists + ? data.links.map((item) => (item.id === link.id ? link : item)) + : [...data.links, link], }; set((state) => ({ adminData: next, @@ -435,6 +446,26 @@ export const useNavStore = create((set, get) => ({ })); }, + createLinkOnHome: async (input) => { + if (!get().adminData) throw new Error("编辑数据未加载"); + // 排在在飞的排序 / 拖动之后落库:这次新建才是顺序相关的最后一次写(也顺带 + // 等在飞的拖动回滚落定,下面取的最大序号才是稳定的) + await get().settleLinkOrder(); + const data = get().adminData; + if (!data) throw new Error("编辑数据未加载"); + // 契约允许显式给 sortOrder;省略时后端兜底 0(新链接会插到分类最前), + // 这里取全局 MAX+1,让它落到分类末尾。基数含待删链接,避免与待删行撞号。 + const { id } = await adminCreateLink({ + ...input, + sortOrder: nextLinkSortOrder(data.links), + }); + // POST 只回 {id}:完整 DTO 从列表端点读回(不本地拼 createdAt/updatedAt)。 + // 只取命中那一条、不整表替换:待删链接与在飞状态因此不受影响。 + const created = (await adminListLinks()).find((link) => link.id === id); + if (!created) throw new Error("链接已创建,但读回失败,请刷新页面后确认"); + return created; + }, + defaultEngine: () => { const engines = get().publicData?.searchEngines ?? []; return engines.find((e) => e.isDefault) ?? engines[0] ?? null; @@ -839,6 +870,19 @@ interface PendingLinkDelete { const pendingLinkDeletes = new Map(); +/** + * 新建链接的全局 sortOrder:全表 MAX+1(链接 sort_order 是跨分类、跨场景的一条全局序列)。 + * 待删链接还没落库、行还在服务端,它们占的槽位也算进基数,否则新建行可能与待删行同号。 + */ +function nextLinkSortOrder(links: readonly AdminLink[]): number { + let max = -1; + for (const link of links) max = Math.max(max, link.sortOrder); + for (const record of pendingLinkDeletes.values()) { + max = Math.max(max, record.link.sortOrder); + } + return max + 1; +} + function toSiteLink(link: AdminLink): SiteLink { return { id: link.id, diff --git a/web/test/admin-page.test.tsx b/web/test/admin-page.test.tsx index 094cf5d..c965424 100644 --- a/web/test/admin-page.test.tsx +++ b/web/test/admin-page.test.tsx @@ -140,7 +140,7 @@ describe("AdminPage 外壳:玻璃顶栏 + 左栏菜单 + 壁纸背景 + 玻璃 ); }); - it("分区菜单是单一 TabsList,九项齐全(含「关于」与图标)", () => { + it("分区菜单是单一 TabsList,八项齐全(含「关于」与图标,链接不在后台管)", () => { seedAdmin(); renderAdmin(); @@ -149,7 +149,6 @@ describe("AdminPage 外壳:玻璃顶栏 + 左栏菜单 + 壁纸背景 + 玻璃 const tabs = within(tablist[0]).getAllByRole("tab"); expect(tabs.map((t) => t.textContent)).toEqual([ "分类", - "链接", "场景管理", "搜索引擎", "站点设置", @@ -158,6 +157,8 @@ describe("AdminPage 外壳:玻璃顶栏 + 左栏菜单 + 壁纸背景 + 玻璃 "系统管理", "关于", ]); + // 首页编辑模式接管链接的增删改与拖动,后台不再有「链接」入口 + expect(screen.queryByRole("tab", { name: "链接" })).toBeNull(); for (const tab of tabs) { expect(tab.querySelector("svg")).not.toBeNull(); } @@ -252,7 +253,7 @@ describe("AdminPage 外壳:玻璃顶栏 + 左栏菜单 + 壁纸背景 + 玻璃 first.focus(); await user.keyboard("{ArrowDown}"); - expect(screen.getByRole("tab", { name: "链接" })).toHaveAttribute( + expect(screen.getByRole("tab", { name: "场景管理" })).toHaveAttribute( "aria-selected", "true", ); diff --git a/web/test/admin-scenes.test.tsx b/web/test/admin-scenes.test.tsx index ecc6f46..55b92be 100644 --- a/web/test/admin-scenes.test.tsx +++ b/web/test/admin-scenes.test.tsx @@ -585,39 +585,6 @@ describe("AdminPage:后台场景胶囊(只有场景、无「全部」)", ( ); }); - it("链接分区:只显示当前场景的分类与链接;分类选择器只列当前场景", async () => { - const user = userEvent.setup(); - renderAdmin(); - - await user.click(screen.getByRole("tab", { name: "链接" })); - await user.click(screen.getByRole("radio", { name: "工作" })); - - expect(screen.getByText("服务器面板")).toBeInTheDocument(); - expect(screen.queryByText("GitHub")).toBeNull(); - - await user.click(screen.getByRole("combobox", { name: "选择分类" })); - const options = screen.getAllByRole("option").map((el) => el.textContent); - expect(options).toEqual(["所有", "运维"]); - expect(options).not.toContain("开发"); - }); - - it("链接分区:当前场景没有分类时不能新建链接(先提示选分类)", async () => { - const user = userEvent.setup(); - seedAdmin({ - ...adminData, - categories: [workCategory], - links: [makeLink("l_work", "c_work", "服务器面板", 0)], - }); - renderAdmin(); - - await user.click(screen.getByRole("tab", { name: "链接" })); - await user.click(screen.getByRole("radio", { name: "通用" })); - - expect(screen.getByText("暂无分类,请先创建分类。")).toBeInTheDocument(); - await user.click(screen.getByRole("button", { name: "新建链接" })); - expect(toastErrorMock).toHaveBeenCalledWith("请先选择一个分类"); - }); - it("「场景管理」分区可达,渲染场景面板", async () => { const user = userEvent.setup(); renderAdmin(); @@ -635,8 +602,7 @@ describe("AdminPage:后台场景胶囊(只有场景、无「全部」)", ( ).toBeNull(); }); - it("没有场景(旧后端 / 无场景概念):不渲染胶囊,分类与链接保持现状平铺", async () => { - const user = userEvent.setup(); + it("没有场景(旧后端 / 无场景概念):不渲染胶囊,分类保持现状平铺", () => { seedAdmin({ ...adminData, scenes: [], @@ -650,9 +616,5 @@ describe("AdminPage:后台场景胶囊(只有场景、无「全部」)", ( expect(screen.queryByRole("radiogroup")).toBeNull(); expect(screen.getByText("开发")).toBeInTheDocument(); expect(screen.getByText("运维")).toBeInTheDocument(); - - await user.click(screen.getByRole("tab", { name: "链接" })); - expect(screen.getByText("GitHub")).toBeInTheDocument(); - expect(screen.getByText("服务器面板")).toBeInTheDocument(); }); }); diff --git a/web/test/crud-panels.test.tsx b/web/test/crud-panels.test.tsx index 4d2666f..2fa3390 100644 --- a/web/test/crud-panels.test.tsx +++ b/web/test/crud-panels.test.tsx @@ -8,22 +8,18 @@ import { import userEvent from "@testing-library/user-event"; import { toast } from "sonner"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import { CategoryPanel, LinkPanel } from "@/components/admin/crud-panels"; +import { CategoryPanel } from "@/components/admin/crud-panels"; import { SearchEnginePanel } from "@/components/admin/settings-panels"; import { adminCreateCategory, - adminCreateLink, adminDeleteAsset, adminDeleteCategory, adminDeleteEngine, - adminDeleteLink, adminListAll, adminReorderCategories, adminReorderEngines, - adminReorderLinks, adminUpdateCategory, adminUpdateEngine, - adminUpdateLink, adminUploadAsset, type AdminData, } from "@/lib/api"; @@ -42,16 +38,12 @@ vi.mock("@/lib/api", async (importOriginal) => { adminUploadAsset: vi.fn(), adminDeleteAsset: vi.fn(), adminCreateCategory: vi.fn(), - adminCreateLink: vi.fn(), adminUpdateCategory: vi.fn(), adminDeleteCategory: vi.fn(), - adminDeleteLink: vi.fn(), adminDeleteEngine: vi.fn(), - adminUpdateLink: vi.fn(), adminUpdateEngine: vi.fn(), adminListAll: vi.fn(), adminReorderCategories: vi.fn(), - adminReorderLinks: vi.fn(), adminReorderEngines: vi.fn(), }; }); @@ -59,16 +51,12 @@ vi.mock("@/lib/api", async (importOriginal) => { const uploadMock = vi.mocked(adminUploadAsset); const deleteMock = vi.mocked(adminDeleteAsset); const createCategoryMock = vi.mocked(adminCreateCategory); -const createLinkMock = vi.mocked(adminCreateLink); const updateCategoryMock = vi.mocked(adminUpdateCategory); const deleteCategoryMock = vi.mocked(adminDeleteCategory); -const deleteLinkMock = vi.mocked(adminDeleteLink); const deleteEngineMock = vi.mocked(adminDeleteEngine); -const updateLinkMock = vi.mocked(adminUpdateLink); const updateEngineMock = vi.mocked(adminUpdateEngine); const listAllMock = vi.mocked(adminListAll); const reorderCategoriesMock = vi.mocked(adminReorderCategories); -const reorderLinksMock = vi.mocked(adminReorderLinks); const reorderEnginesMock = vi.mocked(adminReorderEngines); const toastErrorMock = vi.mocked(toast.error); const toastSuccessMock = vi.mocked(toast.success); @@ -131,14 +119,6 @@ function CategoryHarness({ onChanged }: { onChanged: () => void }) { return ; } -function LinkHarness({ onChanged }: { onChanged: () => void }) { - const categories = useNavStore((s) => s.adminData?.categories ?? []); - const links = useNavStore((s) => s.adminData?.links ?? []); - return ( - - ); -} - function EngineHarness({ onChanged }: { onChanged: () => void }) { const engines = useNavStore((s) => s.adminData?.searchEngines ?? []); return ; @@ -200,23 +180,18 @@ beforeEach(() => { createCategoryMock.mockReset(); updateCategoryMock.mockReset(); deleteCategoryMock.mockReset(); - deleteLinkMock.mockReset(); deleteEngineMock.mockReset(); - updateLinkMock.mockReset(); updateEngineMock.mockReset(); toastErrorMock.mockReset(); toastSuccessMock.mockReset(); deleteCategoryMock.mockResolvedValue(undefined); - deleteLinkMock.mockResolvedValue(undefined); deleteEngineMock.mockResolvedValue(undefined); resetAdminOrderState(); listAllMock.mockReset(); reorderCategoriesMock.mockReset(); - reorderLinksMock.mockReset(); reorderEnginesMock.mockReset(); listAllMock.mockResolvedValue(adminBase); reorderCategoriesMock.mockResolvedValue(undefined); - reorderLinksMock.mockResolvedValue(undefined); reorderEnginesMock.mockResolvedValue(undefined); useNavStore.setState({ adminData: adminBase, authStatus: "authenticated" }); createCategoryMock.mockImplementation(async (input) => ({ @@ -230,11 +205,6 @@ beforeEach(() => { id, ...input, })); - updateLinkMock.mockImplementation(async (id, input) => ({ - ...link, - id, - ...input, - })); updateEngineMock.mockImplementation(async (id, input) => ({ ...engine, id, @@ -313,77 +283,6 @@ describe("CategoryPanel:分类图标上传 / 回填 / 清旧 / 列表预览", }); }); -describe("LinkPanel:链接图标上传 / 回填 / 清旧", () => { - it("上传图标后回填 iconUrl 并随更新提交,同时清掉旧图标", async () => { - const user = userEvent.setup(); - uploadMock.mockResolvedValue({ path: "/assets/assets/icon/link-new.png" }); - - render( - , - ); - - await openRow(user, "GitHub"); - pickFile(screen.getByLabelText("上传链接图标")); - await waitFor(() => - expect(screen.getByLabelText("链接图标")).toHaveValue( - "/assets/assets/icon/link-new.png", - ), - ); - - await user.click(screen.getByRole("button", { name: "保存" })); - - await waitFor(() => - expect(updateLinkMock).toHaveBeenCalledWith("l1", { - categoryId: "c1", - title: "GitHub", - url: "https://github.com", - iconUrl: "/assets/assets/icon/link-new.png", - description: null, - visibility: "public", - }), - ); - await waitFor(() => - expect(deleteMock).toHaveBeenCalledWith( - "/assets/assets/icon/link-old.png", - ), - ); - }); - - it("移除图标:保存后 iconUrl 为 null,旧图标被删", async () => { - const user = userEvent.setup(); - - render( - , - ); - - await openRow(user, "GitHub"); - await user.click(screen.getByRole("button", { name: /移除/ })); - expect(screen.getByLabelText("链接图标")).toHaveValue(""); - - await user.click(screen.getByRole("button", { name: "保存" })); - - await waitFor(() => - expect(updateLinkMock).toHaveBeenCalledWith( - "l1", - expect.objectContaining({ iconUrl: null }), - ), - ); - await waitFor(() => - expect(deleteMock).toHaveBeenCalledWith( - "/assets/assets/icon/link-old.png", - ), - ); - }); -}); - describe("SearchEnginePanel:搜索引擎图标上传 / 回填 / 列表预览", () => { it("上传图标后回填并随更新提交", async () => { const user = userEvent.setup(); @@ -440,17 +339,9 @@ describe("列表行交互:编辑图标 / 点行不再进入编辑", () => { ).toBeInTheDocument(); }); - it("链接与搜索引擎列表都带行尾编辑图标", () => { - render( - <> - - - , - ); + it("搜索引擎列表带行尾编辑图标", () => { + render(); - expect( - screen.getByRole("button", { name: "编辑 GitHub" }), - ).toBeInTheDocument(); expect( screen.getByRole("button", { name: "编辑 Google" }), ).toBeInTheDocument(); @@ -550,352 +441,7 @@ describe("CategoryPanel:同名分类前端拦截", () => { }); }); -describe("LinkPanel:分类筛选「所有」", () => { - const reading: AdminCategory = { - ...category, - id: "c2", - name: "阅读", - sortOrder: 1, - }; - const sspai: AdminLink = { - ...link, - id: "l2", - categoryId: "c2", - title: "少数派", - url: "https://sspai.com", - sortOrder: 1, - }; - - it("默认选中「所有」,显示全部分类的链接(按 sortOrder)", () => { - render( - , - ); - - expect( - screen.getByRole("combobox", { name: "选择分类" }), - ).toHaveTextContent("所有"); - expect(screen.getByText("GitHub")).toBeInTheDocument(); - expect(screen.getByText("少数派")).toBeInTheDocument(); - expect( - screen - .getAllByRole("button", { name: /^编辑 / }) - .map((el) => el.getAttribute("aria-label")), - ).toEqual(["编辑 GitHub", "编辑 少数派"]); - }); - - it("选中具体分类只显示该分类链接,选回「所有」恢复全量", async () => { - const user = userEvent.setup(); - render( - , - ); - - await user.click(screen.getByRole("combobox", { name: "选择分类" })); - await user.click(screen.getByRole("option", { name: "阅读" })); - - await waitFor(() => expect(screen.queryByText("GitHub")).toBeNull()); - expect(screen.getByText("少数派")).toBeInTheDocument(); - - await user.click(screen.getByRole("combobox", { name: "选择分类" })); - await user.click(screen.getByRole("option", { name: "所有" })); - - await waitFor(() => expect(screen.getByText("GitHub")).toBeInTheDocument()); - expect(screen.getByText("少数派")).toBeInTheDocument(); - }); - - it("「所有」下新建链接先要求选分类:只提示、不弹新建框", async () => { - const user = userEvent.setup(); - render( - , - ); - - await user.click(screen.getByRole("button", { name: "新建链接" })); - expect(toastErrorMock).toHaveBeenCalledWith("请先选择一个分类"); - expect(screen.queryByRole("dialog")).toBeNull(); - }); -}); - -describe("LinkPanel:编辑链接可改所属分类", () => { - const reading: AdminCategory = { - ...category, - id: "c2", - name: "阅读", - sortOrder: 1, - }; - const sspai: AdminLink = { - ...link, - id: "l2", - categoryId: "c2", - title: "少数派", - url: "https://sspai.com", - sortOrder: 1, - }; - - it("编辑弹窗只列当前场景的分类,并预选链接实际所属分类", async () => { - const user = userEvent.setup(); - render( - , - ); - - await openRow(user, "GitHub"); - expect( - screen.getByRole("combobox", { name: "选择所属分类" }), - ).toHaveTextContent("开发"); - - await user.click(screen.getByRole("combobox", { name: "选择所属分类" })); - expect(screen.getAllByRole("option").map((el) => el.textContent)).toEqual([ - "开发", - "阅读", - ]); - }); - - it("「所有」筛选下编辑同样可用,预选值是链接实际所属分类", async () => { - const user = userEvent.setup(); - render( - , - ); - - // 筛选器停在「所有」,但预选跟链接走:少数派属于阅读 - expect( - screen.getByRole("combobox", { name: "选择分类" }), - ).toHaveTextContent("所有"); - await openRow(user, "少数派"); - expect( - screen.getByRole("combobox", { name: "选择所属分类" }), - ).toHaveTextContent("阅读"); - }); - - it("改分类保存:payload 带新 categoryId,并提示已移到目标分类末尾", async () => { - const user = userEvent.setup(); - render( - , - ); - - await openRow(user, "GitHub"); - await user.click(screen.getByRole("combobox", { name: "选择所属分类" })); - await user.click(screen.getByRole("option", { name: "阅读" })); - await user.click(screen.getByRole("button", { name: "保存" })); - - await waitFor(() => - expect(updateLinkMock).toHaveBeenCalledWith("l1", { - categoryId: "c2", - title: "GitHub", - url: "https://github.com", - iconUrl: null, - description: null, - visibility: "public", - }), - ); - expect(toastSuccessMock).toHaveBeenCalledWith("链接已移到「阅读」末尾"); - }); - - it("分类未改:照旧带上当前 categoryId,不提示搬家", async () => { - const user = userEvent.setup(); - render( - , - ); - - await openRow(user, "GitHub"); - await user.click(screen.getByRole("button", { name: "保存" })); - - await waitFor(() => - expect(updateLinkMock).toHaveBeenCalledWith( - "l1", - expect.objectContaining({ categoryId: "c1" }), - ), - ); - expect(toastSuccessMock).toHaveBeenCalledWith("链接已更新"); - }); - - it("新建链接弹窗也有所属分类下拉:默认当前分类,可改后再创建", async () => { - const user = userEvent.setup(); - createLinkMock.mockResolvedValue({ ...link, id: "l9" }); - render( - , - ); - - await user.click(screen.getByRole("combobox", { name: "选择分类" })); - await user.click(screen.getByRole("option", { name: "开发" })); - await user.click(screen.getByRole("button", { name: "新建链接" })); - expect( - screen.getByRole("combobox", { name: "选择所属分类" }), - ).toHaveTextContent("开发"); - - await user.click(screen.getByRole("combobox", { name: "选择所属分类" })); - await user.click(screen.getByRole("option", { name: "阅读" })); - await user.type(screen.getByLabelText("标题"), "新链接"); - await user.type(screen.getByLabelText("URL"), "https://example.com/new"); - await user.click(screen.getByRole("button", { name: "保存" })); - - await waitFor(() => - expect(createLinkMock).toHaveBeenCalledWith( - expect.objectContaining({ categoryId: "c2", title: "新链接" }), - ), - ); - }); - - it("排序请求还在飞时改分类保存:先等排序落库再发 PUT(保证 move 是最后一次写)", async () => { - const user = userEvent.setup(); - const reorderPending = deferred(); - reorderLinksMock.mockReturnValue(reorderPending.promise); - - render( - void useNavStore.getState().loadAdmin()} />, - ); - - // 拖一次排序:请求在飞(复现「排序未落库就改分类」的交错) - await user.click(screen.getByRole("button", { name: "下移 GitHub" })); - expect(reorderLinksMock).toHaveBeenCalledTimes(1); - - await openRow(user, "MDN"); - await user.click(screen.getByRole("combobox", { name: "选择所属分类" })); - await user.click(screen.getByRole("option", { name: "阅读" })); - await user.click(screen.getByRole("button", { name: "保存" })); - - await new Promise((r) => setTimeout(r, 0)); - // 排序未落库前不得发 PUT:否则 /links/reorder 可能在 PUT 之后落库, - // 把这个链接改回旧槽位(目标分类末尾就不成立了) - expect(updateLinkMock).not.toHaveBeenCalled(); - - reorderPending.resolve(); - await waitFor(() => expect(updateLinkMock).toHaveBeenCalledTimes(1)); - expect(updateLinkMock).toHaveBeenCalledWith( - "l3", - expect.objectContaining({ categoryId: "c2" }), - ); - }); - - it("改分类保存后:链接落到目标分类末尾,原分类里消失(不被本地旧槽位改写)", async () => { - const user = userEvent.setup(); - // 四个链接:开发 = GitHub/MDN,阅读 = 少数派/V2EX - const four: AdminLink[] = [ - link, - sspai, - { ...link, id: "l3", categoryId: "c1", title: "MDN", sortOrder: 2 }, - { - ...link, - id: "l4", - categoryId: "c2", - title: "V2EX", - url: "https://v2ex.com", - sortOrder: 3, - }, - ]; - useNavStore.setState({ - adminData: { ...adminBase, links: four }, - authStatus: "authenticated", - }); - - render( - void useNavStore.getState().loadAdmin()} />, - ); - - // 先拖一次排序,让本地链接顺序簿记(localIds)占位: - // 排序后全局序号变成 l2=0 / l1=1 / l3=2 / l4=3 - await user.click(screen.getByRole("button", { name: "下移 GitHub" })); - await waitFor(() => - expect(editLabels()).toEqual([ - "编辑 少数派", - "编辑 GitHub", - "编辑 MDN", - "编辑 V2EX", - ]), - ); - - // 服务端视角:MDN(l3) 搬到「阅读」,落全局 MAX+1 = 4(不是旧槽位的 2) - const serverLinks = [ - { ...four[1], sortOrder: 0 }, - { ...four[0], sortOrder: 1 }, - { ...four[3], sortOrder: 3 }, - { ...four[2], categoryId: "c2", sortOrder: 4 }, - ]; - updateLinkMock.mockImplementation(async (id, input) => ({ - ...(four.find((l) => l.id === id) as AdminLink), - ...input, - })); - listAllMock.mockResolvedValue({ ...adminBase, links: serverLinks }); - - // 「所有」视图下直接编辑 - await openRow(user, "MDN"); - await user.click(screen.getByRole("combobox", { name: "选择所属分类" })); - await user.click(screen.getByRole("option", { name: "阅读" })); - await user.click(screen.getByRole("button", { name: "保存" })); - await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); - - // 目标分类:搬到末尾(V2EX 之后,而不是旧槽位对应的 MDN 前) - await user.click(screen.getByRole("combobox", { name: "选择分类" })); - await user.click(screen.getByRole("option", { name: "阅读" })); - await waitFor(() => - expect(editLabels()).toEqual(["编辑 少数派", "编辑 V2EX", "编辑 MDN"]), - ); - - // 原分类:已消失 - await user.click(screen.getByRole("combobox", { name: "选择分类" })); - await user.click(screen.getByRole("option", { name: "开发" })); - await waitFor(() => expect(editLabels()).toEqual(["编辑 GitHub"])); - }); -}); - -describe("链接 / 搜索引擎:删除同样二次确认", () => { - it("链接:点删除先弹确认框;取消不删,确认后才调删除接口", async () => { - const user = userEvent.setup(); - const onChanged = vi.fn(); - render( - , - ); - - await user.click(screen.getByRole("button", { name: "删除 GitHub" })); - expect(deleteLinkMock).not.toHaveBeenCalled(); - expect(screen.getByRole("alertdialog")).toBeInTheDocument(); - expect( - screen.getByText("删除链接后无法恢复,请确认。"), - ).toBeInTheDocument(); - - await user.click(screen.getByRole("button", { name: "取消" })); - expect(deleteLinkMock).not.toHaveBeenCalled(); - - await user.click(screen.getByRole("button", { name: "删除 GitHub" })); - await user.click(screen.getByRole("button", { name: "删除" })); - await waitFor(() => expect(deleteLinkMock).toHaveBeenCalledWith("l1")); - expect(onChanged).toHaveBeenCalled(); - expect(toastSuccessMock).toHaveBeenCalledWith("链接已删除"); - }); - +describe("搜索引擎:删除二次确认", () => { it("搜索引擎:点删除先弹确认框;取消不删,确认后才调删除接口", async () => { const user = userEvent.setup(); const onChanged = vi.fn(); @@ -959,32 +505,6 @@ describe("排序:乐观即时生效,成功后不再整表重拉", () => { expect(listAllMock).not.toHaveBeenCalled(); }); - it("链接(按分类过滤):提交重建后的全局 ids,跨分类相对顺序不变", async () => { - const pending = deferred(); - reorderLinksMock.mockReturnValue(pending.promise); - const onChanged = vi.fn(); - const user = userEvent.setup(); - render(); - - await user.click(screen.getByRole("combobox", { name: "选择分类" })); - await user.click(screen.getByRole("option", { name: "开发" })); - await waitFor(() => expect(screen.queryByText("少数派")).toBeNull()); - - await user.click(screen.getByRole("button", { name: "下移 GitHub" })); - - expect(editLabels()).toEqual(["编辑 MDN", "编辑 GitHub"]); - // 全局 ids:本分类内换位,其他分类的「少数派」仍排在后面 - expect(reorderLinksMock).toHaveBeenCalledWith(["l3", "l1", "l2"]); - expect(onChanged).not.toHaveBeenCalled(); - expect( - useNavStore.getState().adminData?.links.map((item) => item.id), - ).toEqual(["l3", "l1", "l2"]); - - await act(async () => { - pending.resolve(); - }); - }); - it("排序失败:回滚到操作前顺序并 toast,按服务端再刷一次", async () => { const pending = deferred(); reorderCategoriesMock.mockReturnValue(pending.promise); @@ -1069,35 +589,6 @@ describe("新建分类:场景内末尾排序 + 保存失败可见", () => { }); }); -describe("链接保存失败可见(同一错误口径)", () => { - it("新建链接失败:错误 toast、弹窗不关、不刷新", async () => { - createLinkMock.mockRejectedValueOnce(new Error("boom")); - const onChanged = vi.fn(); - const user = userEvent.setup(); - render( - , - ); - - await user.click(screen.getByRole("combobox", { name: "选择分类" })); - await user.click(screen.getByRole("option", { name: "开发" })); - await user.click(screen.getByRole("button", { name: "新建链接" })); - await user.type(screen.getByLabelText("标题"), "新链接"); - await user.type(screen.getByLabelText("URL"), "https://example.com/new"); - await user.click(screen.getByRole("button", { name: "保存" })); - - await waitFor(() => - expect(toastErrorMock).toHaveBeenCalledWith("保存失败:boom"), - ); - expect(createLinkMock).toHaveBeenCalledTimes(1); - expect(screen.getByRole("dialog")).toBeInTheDocument(); - expect(onChanged).not.toHaveBeenCalled(); - }); -}); - describe("CategoryPanel:分类所在场景私有时的有效状态提示", () => { it("场景私有时每行给「场景私有,对外不可见」提示", () => { render( diff --git a/web/test/link-edit-dialog.test.tsx b/web/test/link-edit-dialog.test.tsx new file mode 100644 index 0000000..eda7d86 --- /dev/null +++ b/web/test/link-edit-dialog.test.tsx @@ -0,0 +1,356 @@ +import type * as React from "react"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { toast } from "sonner"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { LinkEditDialog } from "@/components/admin/link-edit-dialog"; +import { + adminDeleteAsset, + adminListAll, + adminReorderLinks, + adminUpdateLink, + adminUploadAsset, + type AdminData, + type CreateLinkInput, +} from "@/lib/api"; +import { resetAdminOrderState, useNavStore } from "@/lib/nav-store"; +import type { AdminCategory, AdminLink } from "@/lib/types"; +import { deferred } from "./deferred"; + +/** + * 链接编辑弹窗(后台「链接」面板删除后由首页编辑模式复用):编辑态的图标上传与清旧、 + * 分类搬家(含「排序在飞时先 settle」的交错)、新建态走 `onCreateLink` 并把完整 DTO + * 回传给 `onSaved`、以及两条路径共用的失败口径(错误 toast、弹窗不关)。 + */ + +vi.mock("sonner", () => ({ + toast: { success: vi.fn(), error: vi.fn() }, +})); + +vi.mock("@/lib/api", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + adminUploadAsset: vi.fn(), + adminDeleteAsset: vi.fn(), + adminUpdateLink: vi.fn(), + adminReorderLinks: vi.fn(), + adminListAll: vi.fn(), + }; +}); + +const uploadMock = vi.mocked(adminUploadAsset); +const deleteMock = vi.mocked(adminDeleteAsset); +const updateLinkMock = vi.mocked(adminUpdateLink); +const reorderLinksMock = vi.mocked(adminReorderLinks); +const listAllMock = vi.mocked(adminListAll); +const toastErrorMock = vi.mocked(toast.error); +const toastSuccessMock = vi.mocked(toast.success); + +const file = new File([new Uint8Array([1, 2, 3])], "icon.png", { + type: "image/png", +}); + +const stamp = "2026-11-08T00:00:00.000Z"; + +const category: AdminCategory = { + id: "c1", + name: "开发", + icon: null, + sceneId: "scene_default", + sortOrder: 0, + visibility: "public", + createdAt: stamp, + updatedAt: stamp, +}; + +const reading: AdminCategory = { + ...category, + id: "c2", + name: "阅读", + sortOrder: 1, +}; + +const link: AdminLink = { + id: "l1", + categoryId: "c1", + title: "GitHub", + url: "https://github.com", + iconUrl: null, + description: null, + sortOrder: 0, + visibility: "public", + createdAt: stamp, + updatedAt: stamp, +}; + +const adminBase: AdminData = { + scenes: [], + categories: [category, reading], + links: [link], + searchEngines: [], + settings: { + siteTitle: "我的导航", + backgroundUrl: "", + wallpaperSource: "bing", + logoUrl: "", + columns: 6, + searchNewTab: true, + }, +}; + +function pickFile(input: HTMLElement) { + fireEvent.change(input, { target: { files: [file] } }); +} + +function renderDialog( + props: Partial> = {}, +) { + const onClose = vi.fn(); + const onSaved = vi.fn(); + const onCreateLink = vi.fn(async (input: CreateLinkInput) => ({ + ...link, + id: "l9", + ...input, + })); + render( + , + ); + return { onClose, onSaved, onCreateLink }; +} + +beforeEach(() => { + uploadMock.mockReset(); + deleteMock.mockReset(); + updateLinkMock.mockReset(); + reorderLinksMock.mockReset(); + listAllMock.mockReset(); + toastErrorMock.mockReset(); + toastSuccessMock.mockReset(); + deleteMock.mockResolvedValue(undefined); + reorderLinksMock.mockResolvedValue(undefined); + listAllMock.mockResolvedValue(adminBase); + resetAdminOrderState(); + useNavStore.setState({ adminData: adminBase, authStatus: "authenticated" }); + updateLinkMock.mockImplementation(async (id, input) => ({ + ...link, + id, + ...input, + })); +}); + +describe("LinkEditDialog:链接图标上传 / 回填 / 清旧", () => { + it("上传图标后回填 iconUrl 并随更新提交,同时清掉旧图标", async () => { + const user = userEvent.setup(); + uploadMock.mockResolvedValue({ path: "/assets/assets/icon/link-new.png" }); + renderDialog({ + link: { ...link, iconUrl: "/assets/assets/icon/link-old.png" }, + }); + + pickFile(screen.getByLabelText("上传链接图标")); + await waitFor(() => + expect(screen.getByLabelText("链接图标")).toHaveValue( + "/assets/assets/icon/link-new.png", + ), + ); + + await user.click(screen.getByRole("button", { name: "保存" })); + + await waitFor(() => + expect(updateLinkMock).toHaveBeenCalledWith("l1", { + categoryId: "c1", + title: "GitHub", + url: "https://github.com", + iconUrl: "/assets/assets/icon/link-new.png", + description: null, + visibility: "public", + }), + ); + await waitFor(() => + expect(deleteMock).toHaveBeenCalledWith( + "/assets/assets/icon/link-old.png", + ), + ); + }); + + it("移除图标:保存后 iconUrl 为 null,旧图标被删", async () => { + const user = userEvent.setup(); + renderDialog({ + link: { ...link, iconUrl: "/assets/assets/icon/link-old.png" }, + }); + + await user.click(screen.getByRole("button", { name: /移除/ })); + expect(screen.getByLabelText("链接图标")).toHaveValue(""); + + await user.click(screen.getByRole("button", { name: "保存" })); + + await waitFor(() => + expect(updateLinkMock).toHaveBeenCalledWith( + "l1", + expect.objectContaining({ iconUrl: null }), + ), + ); + await waitFor(() => + expect(deleteMock).toHaveBeenCalledWith( + "/assets/assets/icon/link-old.png", + ), + ); + }); +}); + +describe("LinkEditDialog:分类下拉与搬家", () => { + it("只列传入的分类,并预选链接实际所属分类", async () => { + const user = userEvent.setup(); + renderDialog({ link: { ...link, categoryId: "c2" } }); + + const trigger = screen.getByRole("combobox", { name: "选择所属分类" }); + expect(trigger).toHaveTextContent("阅读"); + + await user.click(trigger); + expect(screen.getAllByRole("option").map((el) => el.textContent)).toEqual([ + "开发", + "阅读", + ]); + }); + + it("改分类保存:payload 带新 categoryId,并提示已移到目标分类末尾", async () => { + const user = userEvent.setup(); + renderDialog(); + + await user.click(screen.getByRole("combobox", { name: "选择所属分类" })); + await user.click(screen.getByRole("option", { name: "阅读" })); + await user.click(screen.getByRole("button", { name: "保存" })); + + await waitFor(() => + expect(updateLinkMock).toHaveBeenCalledWith("l1", { + categoryId: "c2", + title: "GitHub", + url: "https://github.com", + iconUrl: null, + description: null, + visibility: "public", + }), + ); + expect(toastSuccessMock).toHaveBeenCalledWith("链接已移到「阅读」末尾"); + }); + + it("分类未改:照旧带上当前 categoryId,不提示搬家", async () => { + const user = userEvent.setup(); + renderDialog(); + + await user.click(screen.getByRole("button", { name: "保存" })); + + await waitFor(() => + expect(updateLinkMock).toHaveBeenCalledWith( + "l1", + expect.objectContaining({ categoryId: "c1" }), + ), + ); + expect(toastSuccessMock).toHaveBeenCalledWith("链接已更新"); + }); + + it("排序请求还在飞时改分类保存:先等排序落库再发 PUT(保证 PUT 是最后一次写)", async () => { + const user = userEvent.setup(); + const pending = deferred(); + reorderLinksMock.mockReturnValue(pending.promise); + // 后台链接面板(或上一次拖动)留下的排序请求在飞:settleLinkOrder 必须等它落库 + void useNavStore.getState().reorderLinks(["l1"]); + renderDialog(); + + await user.click(screen.getByRole("combobox", { name: "选择所属分类" })); + await user.click(screen.getByRole("option", { name: "阅读" })); + await user.click(screen.getByRole("button", { name: "保存" })); + + await new Promise((r) => setTimeout(r, 0)); + // 排序未落库前不得发 PUT:否则 /links/reorder 可能晚于 PUT 落库,把链接改回旧槽位 + expect(updateLinkMock).not.toHaveBeenCalled(); + + pending.resolve(); + await waitFor(() => expect(updateLinkMock).toHaveBeenCalledTimes(1)); + expect(updateLinkMock).toHaveBeenCalledWith( + "l1", + expect.objectContaining({ categoryId: "c2" }), + ); + }); +}); + +describe("LinkEditDialog:新建走 onCreateLink", () => { + it("预选默认分类、可改分类后创建,成功后把完整 DTO 回传给 onSaved", async () => { + const user = userEvent.setup(); + const { onCreateLink, onSaved } = renderDialog({ + link: null, + defaultCategoryId: "c1", + }); + + expect( + screen.getByRole("heading", { name: "新建链接" }), + ).toBeInTheDocument(); + expect( + screen.getByRole("combobox", { name: "选择所属分类" }), + ).toHaveTextContent("开发"); + + await user.click(screen.getByRole("combobox", { name: "选择所属分类" })); + await user.click(screen.getByRole("option", { name: "阅读" })); + await user.type(screen.getByLabelText("标题"), "新链接"); + await user.type(screen.getByLabelText("URL"), "https://example.com/new"); + await user.click(screen.getByRole("button", { name: "保存" })); + + await waitFor(() => expect(onCreateLink).toHaveBeenCalledTimes(1)); + expect(onCreateLink.mock.calls[0][0]).toEqual({ + categoryId: "c2", + title: "新链接", + url: "https://example.com/new", + iconUrl: null, + description: null, + visibility: "public", + }); + await waitFor(() => + expect(onSaved).toHaveBeenCalledWith( + expect.objectContaining({ id: "l9", categoryId: "c2" }), + ), + ); + expect(toastSuccessMock).toHaveBeenCalledWith("链接已创建"); + }); + + it("新建失败:错误 toast、弹窗不关、不回调 onSaved", async () => { + const user = userEvent.setup(); + const { onCreateLink, onSaved } = renderDialog({ + link: null, + defaultCategoryId: "c1", + }); + onCreateLink.mockRejectedValueOnce(new Error("boom")); + + await user.type(screen.getByLabelText("标题"), "新链接"); + await user.type(screen.getByLabelText("URL"), "https://example.com/new"); + await user.click(screen.getByRole("button", { name: "保存" })); + + await waitFor(() => + expect(toastErrorMock).toHaveBeenCalledWith("保存失败:boom"), + ); + expect(onCreateLink).toHaveBeenCalledTimes(1); + expect(onSaved).not.toHaveBeenCalled(); + expect(screen.getByRole("dialog")).toBeInTheDocument(); + }); + + it("编辑失败同样有错误 toast、弹窗不关", async () => { + const user = userEvent.setup(); + const { onSaved } = renderDialog(); + updateLinkMock.mockRejectedValueOnce(new Error("boom")); + + await user.click(screen.getByRole("button", { name: "保存" })); + + await waitFor(() => + expect(toastErrorMock).toHaveBeenCalledWith("保存失败:boom"), + ); + expect(onSaved).not.toHaveBeenCalled(); + expect(screen.getByRole("dialog")).toBeInTheDocument(); + }); +}); diff --git a/web/test/nav-store-link-edits.test.ts b/web/test/nav-store-link-edits.test.ts index a5eedc3..44ceb4f 100644 --- a/web/test/nav-store-link-edits.test.ts +++ b/web/test/nav-store-link-edits.test.ts @@ -1,8 +1,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { toast } from "sonner"; import { + adminCreateLink, adminDeleteLink, adminListAll, + adminListLinks, adminMoveLink, type AdminData, } from "@/lib/api"; @@ -41,12 +43,16 @@ vi.mock("@/lib/api", async (importOriginal) => { return { ...actual, adminListAll: vi.fn(), + adminListLinks: vi.fn(), + adminCreateLink: vi.fn(), adminMoveLink: vi.fn(), adminDeleteLink: vi.fn(), }; }); const listAllMock = vi.mocked(adminListAll); +const listLinksMock = vi.mocked(adminListLinks); +const createMock = vi.mocked(adminCreateLink); const moveMock = vi.mocked(adminMoveLink); const deleteMock = vi.mocked(adminDeleteLink); const toastMock = vi.mocked(toast); @@ -202,6 +208,8 @@ beforeEach(() => { resetAdminOrderState(); resetHomeEditState(); listAllMock.mockReset(); + listLinksMock.mockReset(); + createMock.mockReset(); moveMock.mockReset(); deleteMock.mockReset(); toastMock.mockClear(); @@ -466,10 +474,10 @@ describe("removeLinkOnHome:延迟删除 + 撤销", () => { }); }); -describe("applyEditedLink:弹窗保存后就地生效", () => { +describe("applySavedLink:弹窗保存后就地生效", () => { it("替换链接字段并同步公开页投影,改分类后落到目标分类末尾", () => { const original = adminData().links.find((l) => l.id === "l1")!; - useNavStore.getState().applyEditedLink({ + useNavStore.getState().applySavedLink({ ...original, title: "GitHub 新版", categoryId: "c2", @@ -483,6 +491,84 @@ describe("applyEditedLink:弹窗保存后就地生效", () => { expect(privateLinks("c2")).toEqual(["l2", "l4", "l1"]); expect(listAllMock).not.toHaveBeenCalled(); }); + + it("store 里还没有的链接(新建)直接追加并同步投影", () => { + useNavStore.getState().applySavedLink(link("l5", "c1", "新链接", 4)); + + expect(ids(adminData().links)).toEqual(["l1", "l2", "l3", "l4", "l5"]); + expect(privateLinks("c1")).toEqual(["l1", "l3", "l5"]); + }); +}); + +describe("createLinkOnHome:新建按「分类末尾」提交并读回完整 DTO", () => { + it("显式送全局 MAX+1 的 sortOrder,返回读回的 DTO(并入 store 由调用方做)", async () => { + const created = link("l5", "c1", "新链接", 4); + createMock.mockResolvedValue({ id: "l5" }); + listLinksMock.mockResolvedValue([...adminData().links, created]); + + const saved = await useNavStore.getState().createLinkOnHome({ + categoryId: "c1", + title: "新链接", + url: "https://example.com/l5", + }); + + // 契约省略 sortOrder 会兜底 0(插到分类最前),这里必须显式给全局 MAX+1 + expect(createMock).toHaveBeenCalledWith({ + categoryId: "c1", + title: "新链接", + url: "https://example.com/l5", + sortOrder: 4, + }); + expect(saved).toEqual(created); + // 只读回、不整表替换:store 由 applySavedLink 并入 + expect(ids(adminData().links)).toEqual(["l1", "l2", "l3", "l4"]); + }); + + it("待删链接占的槽位也算进基数(避免与待删行同号)", async () => { + useNavStore.getState().removeLinkOnHome("l4"); + createMock.mockResolvedValue({ id: "l5" }); + listLinksMock.mockResolvedValue([ + ...adminData().links, + link("l5", "c1", "新链接", 4), + ]); + + await useNavStore.getState().createLinkOnHome({ + categoryId: "c1", + title: "新链接", + url: "https://example.com/l5", + }); + + expect(createMock).toHaveBeenCalledWith( + expect.objectContaining({ sortOrder: 4 }), + ); + }); + + it("读回不到这条链接:报「已创建但读回失败」,不重试创建", async () => { + createMock.mockResolvedValue({ id: "l5" }); + listLinksMock.mockResolvedValue([...adminData().links]); + + await expect( + useNavStore.getState().createLinkOnHome({ + categoryId: "c1", + title: "新链接", + url: "https://example.com/l5", + }), + ).rejects.toThrow("链接已创建,但读回失败,请刷新页面后确认"); + expect(createMock).toHaveBeenCalledTimes(1); + }); + + it("创建失败:错误原样透传,不读列表", async () => { + createMock.mockRejectedValue(new Error("离线")); + + await expect( + useNavStore.getState().createLinkOnHome({ + categoryId: "c1", + title: "新链接", + url: "https://example.com/l5", + }), + ).rejects.toThrow("离线"); + expect(listLinksMock).not.toHaveBeenCalled(); + }); }); describe("enterEditMode:进入前拉一份最新的后台数据", () => { diff --git a/web/test/public-edit-mode.test.tsx b/web/test/public-edit-mode.test.tsx index b7a03e0..3717ae1 100644 --- a/web/test/public-edit-mode.test.tsx +++ b/web/test/public-edit-mode.test.tsx @@ -11,7 +11,12 @@ import type { UserEvent } from "@testing-library/user-event"; import { toast } from "sonner"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { PublicPage } from "@/components/public-page"; -import { adminListAll, type AdminData } from "@/lib/api"; +import { + adminCreateLink, + adminListAll, + adminListLinks, + type AdminData, +} from "@/lib/api"; import { resetAdminOrderState, resetHomeEditState, @@ -51,10 +56,14 @@ vi.mock("@/lib/api", async (importOriginal) => { return { ...actual, adminListAll: vi.fn(), + adminCreateLink: vi.fn(), + adminListLinks: vi.fn(), }; }); const listAllMock = vi.mocked(adminListAll); +const createLinkMock = vi.mocked(adminCreateLink); +const listLinksMock = vi.mocked(adminListLinks); const toastMock = vi.mocked(toast); const toastErrorMock = vi.mocked(toast.error); @@ -206,6 +215,8 @@ beforeEach(() => { resetAdminOrderState(); resetHomeEditState(); listAllMock.mockReset(); + createLinkMock.mockReset(); + listLinksMock.mockReset(); toastMock.mockClear(); toastErrorMock.mockClear(); useScenePreferenceStore.setState({ raw: "s_default" }); @@ -286,14 +297,20 @@ describe("进入 / 退出编辑模式", () => { expect(useNavStore.getState().editMode).toBe(false); }); - it("空分类在编辑模式渲染无文字的空投放位(虚线框)", async () => { + it("每个分类网格末尾都有「+」砖,空分类那块兼作落点(不再是空白虚线框)", async () => { const user = userEvent.setup(); const { container } = renderPage(); await enterEdit(user); - const placeholders = container.querySelectorAll(".border-dashed"); - expect(placeholders).toHaveLength(1); - expect(placeholders[0].textContent).toBe(""); + // 默认场景只有「开发」「空」两个分类 + expect( + screen.getByRole("button", { name: "向「开发」新增链接" }), + ).toBeInTheDocument(); + expect( + screen.getByRole("button", { name: "向「空」新增链接" }), + ).toBeInTheDocument(); + // 虚线砖就是这两块「+」砖:没有额外的无文字占位 + expect(container.querySelectorAll(".border-dashed")).toHaveLength(2); }); }); @@ -317,6 +334,87 @@ describe("编辑模式:单击砖复用后台编辑弹窗", () => { }); }); +describe("编辑模式:分类末尾「+」砖新建链接", () => { + it("新建弹窗打开时 Esc 只关弹窗,不退出编辑模式", async () => { + const user = userEvent.setup(); + renderPage(); + await enterEdit(user); + + await user.click( + screen.getByRole("button", { name: "向「开发」新增链接" }), + ); + const dialog = await screen.findByRole("dialog"); + + // 真实浏览器里 Esc 发在弹窗内的焦点元素上(冒泡到 window 时弹窗已被 Radix 关掉) + fireEvent.keyDown(within(dialog).getByLabelText("选择所属分类"), { + key: "Escape", + }); + + expect(useNavStore.getState().editMode).toBe(true); + }); + + it("没有弹窗时 Esc 仍正常退出编辑模式", async () => { + const user = userEvent.setup(); + renderPage(); + await enterEdit(user); + + fireEvent.keyDown(window, { key: "Escape" }); + + expect(useNavStore.getState().editMode).toBe(false); + }); + + it("点「+」打开「新建链接」且分类已预选;保存后新砖出现在该分类末尾", async () => { + const user = userEvent.setup(); + createLinkMock.mockResolvedValue({ id: "l9" }); + listLinksMock.mockResolvedValue([ + ...makeAdminData().links, + { + ...adminLink({ + id: "l9", + categoryId: "c-empty", + title: "新链接", + url: "https://example.com/new", + iconUrl: null, + description: null, + sortOrder: 3, + }), + }, + ]); + renderPage(); + await enterEdit(user); + + await user.click(screen.getByRole("button", { name: "向「空」新增链接" })); + const dialog = await screen.findByRole("dialog"); + expect(within(dialog).getByText("新建链接")).toBeInTheDocument(); + expect(within(dialog).getByLabelText("选择所属分类")).toHaveTextContent( + "空", + ); + + await user.type(within(dialog).getByLabelText("标题"), "新链接"); + await user.type( + within(dialog).getByLabelText("URL"), + "https://example.com/new", + ); + await user.click(within(dialog).getByRole("button", { name: "保存" })); + + await waitFor(() => expect(createLinkMock).toHaveBeenCalledTimes(1)); + // 契约省略 sortOrder 会兜底 0(插到分类最前):新建一律显式送全局 MAX+1 + expect(createLinkMock.mock.calls[0][0]).toMatchObject({ + categoryId: "c-empty", + title: "新链接", + url: "https://example.com/new", + sortOrder: 3, + }); + + await waitFor(() => + expect( + screen.getByRole("button", { name: "新链接" }), + ).toBeInTheDocument(), + ); + expect(screen.queryByRole("dialog")).toBeNull(); + }); +}); + describe("编辑模式:✕ 延迟删除 + 撤销", () => { it("点 ✕ 立即移除并弹带撤销的 toast;撤销恢复原位,且不误开编辑弹窗", async () => { const user = userEvent.setup();