onAdd(category.id)}
className={cn(
- "rounded-2xl border border-dashed border-white/40 transition-colors",
+ linkTileClassName(linkStyle),
PLACEHOLDER_CLASS[linkStyle],
+ "w-full min-w-0 items-center justify-center border border-dashed border-white/40 bg-transparent text-white/80 hover:bg-white/10 hover:text-white",
isOver && "bg-white/10",
)}
- />
+ >
+
+
);
}
@@ -287,6 +311,7 @@ export function HomeEditBoard({
onEditLink,
onRemoveLink,
onMoveLink,
+ onAddLink,
}: {
/** 当前场景的分类(组内链接已按 sortOrder 排好,与正常模式同源) */
categories: readonly SiteCategory[];
@@ -295,6 +320,8 @@ export function HomeEditBoard({
privateCategories: ReadonlySet
;
onEditLink: (linkId: string) => void;
onRemoveLink: (linkId: string) => void;
+ /** 末尾「+」砖:在该分类新建链接 */
+ onAddLink: (categoryId: string) => void;
/** 松手后保存:目标分类 + 落点前一块的 id(null = 该分类第一个位置) */
onMoveLink: (
linkId: string,
@@ -429,26 +456,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 bfc960f..4362f54 100644
--- a/web/src/components/public-page.tsx
+++ b/web/src/components/public-page.tsx
@@ -31,7 +31,7 @@ import {
* 分类区块,公共页与访客都无法在这里改。
*
* 首页编辑模式(登录态专属,纯前端本地状态):坞里的铅笔把页面切成
- * `HomeEditBoard`(拖动排序/分组、✕ 延迟删除、单击复用后台编辑弹窗),
+ * `HomeEditBoard`(拖动排序/分组、✕ 延迟删除、单击砖编辑、分类末尾「+」砖新建),
* 退出/刷新/Esc/切场景/输入搜索都回到正常模式;编辑模式里砖不再跳转。
*
* 安全口径:未登录时私有区完全不渲染 —— privateData 未加载时组件树里没有私有区块,
@@ -55,7 +55,8 @@ export function PublicPage({ onOpenAdmin }: { onOpenAdmin: () => void }) {
exitEditMode,
moveLinkOnHome,
removeLinkOnHome,
- applyEditedLink,
+ applySavedLink,
+ createLinkOnHome,
} = useNavStore();
const authenticated = useAuthenticated();
// 本机场景偏好(前后台共用):只影响显示过滤,不写服务端
@@ -64,6 +65,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();
@@ -81,16 +86,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。
@@ -202,6 +213,7 @@ export function PublicPage({ onOpenAdmin }: { onOpenAdmin: () => void }) {
onEditLink={setEditingLinkId}
onRemoveLink={removeLinkOnHome}
onMoveLink={handleMoveLink}
+ onAddLink={setCreatingCategoryId}
/>
) : (
@@ -232,15 +244,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 9aeac2b..fd49509 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();