diff --git a/docs/api-contract.md b/docs/api-contract.md index 1c1dd0f..2983147 100644 --- a/docs/api-contract.md +++ b/docs/api-contract.md @@ -193,6 +193,8 @@ Passkey(WebAuthn,/api/auth/passkey/*,@simplewebauthn/server v14): - `GET /api/admin/links` → `{links:[{id,categoryId,title,url,iconUrl,description,sortOrder,visibility,createdAt,updatedAt}]}` - `POST /api/admin/links` body `{title, url, categoryId, iconUrl?, description?, sortOrder?, visibility?}` → 201 `{id}` - `PUT /api/admin/links/:id`(部分更新)→ 更新后对象 + - `categoryId` 不存在 → 400 `{"error":"categoryId does not exist"}`;改 `categoryId` 即把链接搬到目标分类(不另开端点,链接的 `sortOrder` 仍是**全局**序号,不是分类内序号)。 + - 搬分类时若同时给了 `sortOrder` 则以它为准;未给 `sortOrder` 时落到目标分类末尾(全表 `MAX(sort_order)+1`,与分类跨场景搬家同一口径),不会与现有排序撞号;`categoryId` 传的是原分类(未变)时不动顺序。 - `DELETE /api/admin/links/:id` → `{success:true}` - `POST /api/admin/links/reorder` body `{ids:[…]}` → `{success:true}` diff --git a/web/src/components/admin/crud-panels.tsx b/web/src/components/admin/crud-panels.tsx index 111de4c..74cfd72 100644 --- a/web/src/components/admin/crud-panels.tsx +++ b/web/src/components/admin/crud-panels.tsx @@ -269,6 +269,7 @@ export function LinkPanel({ const [editingId, setEditingId] = React.useState(null); const [creating, setCreating] = React.useState(false); const [form, setForm] = React.useState({ + categoryId: "", title: "", url: "", iconUrl: "", @@ -283,6 +284,7 @@ export function LinkPanel({ return; } setForm({ + categoryId: category.id, title: "", url: "", iconUrl: "", @@ -294,9 +296,12 @@ export function LinkPanel({ }; const openEdit = (id: string) => { + // 「所有」视图下 categoryLinks 就是当前场景的全部链接,因此编辑照样可用, + // 且预选值取链接实际所属的分类(不是筛选器当前选中的分类)。 const l = categoryLinks.find((x) => x.id === id); if (!l) return; setForm({ + categoryId: l.categoryId, title: l.title, url: l.url, iconUrl: l.iconUrl ?? "", @@ -314,8 +319,20 @@ export function LinkPanel({ }; const save = async () => { + // 所属分类是必填项(「所有」视图下 openCreate 已拦一次,这里再兜一道) + if (!form.categoryId) { + toast.error("请先选择一个分类"); + return; + } const previousIcon = links.find((l) => l.id === editingId)?.iconUrl ?? null; + // 分类变了 = 把链接搬到目标分类末尾(服务端在 categoryId 变更且未给 sortOrder + // 时置全局 MAX+1,沿 #17 分类搬家口径);未变时服务端不扰动顺序。 + const moved = + !!editingId && + links.find((l) => l.id === editingId)?.categoryId !== form.categoryId; + const targetCategory = categories.find((c) => c.id === form.categoryId); const payload = { + categoryId: form.categoryId, title: form.title, url: form.url, iconUrl: form.iconUrl || null, @@ -324,11 +341,20 @@ export function LinkPanel({ }; try { if (editingId) { + if (moved) { + // 换分类要把「最后一次写」留给这次 PUT:先等在飞的 /links/reorder 落库, + // 同时作废本地顺序簿记(旧顺序若在 PUT 之后落库,会把这个链接改回旧槽位, + // 成功后还会把旧顺序写回本地、让界面继续按旧槽位排)。 + await useNavStore.getState().settleLinkOrder(); + } await adminUpdateLink(editingId, payload); - toast.success("链接已更新"); + toast.success( + moved && targetCategory + ? `链接已移到「${targetCategory.name}」末尾` + : "链接已更新", + ); } else { - if (!category) return; - await adminCreateLink({ ...payload, categoryId: category.id }); + await adminCreateLink(payload); toast.success("链接已创建"); } } catch (error) { @@ -441,6 +467,29 @@ export function LinkPanel({ {editingId ? "编辑链接" : "新建链接"}
+
+ + {/* 只列当前场景的分类(跨场景搬分类不做);编辑时预选链接实际分类 */} + +
l.id === id); if (!item) throw new Error("link not found"); - Object.assign(item, input, { updatedAt: now() }); + // 与后端 PUT /api/admin/links/:id 同口径:换分类且未给 sortOrder 时落全局 MAX+1 + // (链接未变分类则不扰动顺序),供 dev 联调对照真实行为。 + const moved = + input.categoryId !== undefined && input.categoryId !== item.categoryId; + const appendAt = + state.links.reduce((max, l) => Math.max(max, l.sortOrder), -1) + 1; + Object.assign(item, input, { + sortOrder: + moved && input.sortOrder === undefined + ? appendAt + : (input.sortOrder ?? item.sortOrder), + updatedAt: now(), + }); persist(state); return item; }, diff --git a/web/src/lib/nav-store.ts b/web/src/lib/nav-store.ts index 085acbb..98604b2 100644 --- a/web/src/lib/nav-store.ts +++ b/web/src/lib/nav-store.ts @@ -89,6 +89,19 @@ interface NavState { reorderLinks: (ids: string[]) => Promise; reorderEngines: (ids: string[]) => Promise; reorderScenes: (ids: string[]) => Promise; + /** + * 链接换分类前调用:先等在飞的链接排序(/links/reorder)全部落库,再作废本地 + * 顺序簿记(localIds/pendingIds/beforeIds)。 + * + * 「全部落库」包括在飞期间又拖出的顺序:发送循环会先把 pendingIds 里最新的一轮发完 + * 才结束,所以 await 返回时旧顺序既不会再有请求待发,也不会在事后写回本地。 + * + * 为什么必须「等」而不是就地清掉:排序请求无法取消,若它在这次 PUT 之后才落库, + * 会把这个链接的 sort_order 改回旧槽位;而它的成功回调还会把旧顺序写回 localIds, + * 让随后的 loadAdmin 投影继续按旧槽位覆盖新位置——等到它落地再作废,才保证这次 + * PUT(全局 MAX+1)是链接顺序相关写入的最后一次。 + */ + settleLinkOrder: () => Promise; /** 设置保存成功后就地刷新 store 里所有存活的 settings 切片(三片原子更新) */ patchAdminSettings: (settings: SiteSettings) => void; loadPrivate: () => Promise; @@ -247,6 +260,16 @@ export const useNavStore = create((set, get) => ({ reorderList("searchEngines", ids, adminReorderEngines), reorderScenes: (ids) => reorderList("scenes", ids, adminReorderScenes), + settleLinkOrder: async () => { + const track = reorderTracks.links; + // 在飞的排序失败时 flushReorder 已自行回滚 + 回拉,并由原调用者 toast; + // 这里不能让它的失败挡住换分类的保存。 + if (track.inFlight) await track.inFlight.catch(() => {}); + track.localIds = null; + track.pendingIds = null; + track.beforeIds = null; + }, + defaultEngine: () => { const engines = get().publicData?.searchEngines ?? []; return engines.find((e) => e.isDefault) ?? engines[0] ?? null; @@ -280,10 +303,11 @@ export function useAuthenticated(): boolean { // 与乐观写入本质竞态——排序前发出的 GET 若晚到,会把更晚的乐观顺序盖回旧值。 // 全量刷新只在初始加载与增删改/导入/设置保存后发生,那几次由 projectLocalOrder // 把本地顺序投影到服务端数据上,所以旧响应同样盖不掉顺序。 -// 因此这里不需要版本号/序号/时间戳对账,只需要三件事: +// 因此这里不需要版本号/序号/时间戳对账,只需要四件事: // localIds 本地权威顺序(投影 + 本轮之后仍以它为准) // pendingIds 在飞期间又拖出的最新顺序(串行发送,只补发最新一次) // beforeIds 本轮排序开始前的显示顺序(终止失败时的即时回滚目标) +// inFlight 在飞循环的 Promise(给「必须排在排序写入之后」的操作 await) type AdminListKey = "scenes" | "categories" | "links" | "searchEngines"; @@ -297,22 +321,41 @@ interface ReorderTrack { beforeIds: string[] | null; /** 是否已有发送循环在跑(保证同一实体同一时刻只有一个请求在飞)。 */ running: boolean; + /** + * 在飞发送循环的 Promise(没有则为 null):给需要「排在排序写入之后」的操作 + * (如链接换分类)提供一个可 await 的落地点。 + */ + inFlight: Promise | null; } const reorderTracks: Record = { - scenes: { localIds: null, pendingIds: null, beforeIds: null, running: false }, + scenes: { + localIds: null, + pendingIds: null, + beforeIds: null, + running: false, + inFlight: null, + }, categories: { localIds: null, pendingIds: null, beforeIds: null, running: false, + inFlight: null, + }, + links: { + localIds: null, + pendingIds: null, + beforeIds: null, + running: false, + inFlight: null, }, - links: { localIds: null, pendingIds: null, beforeIds: null, running: false }, searchEngines: { localIds: null, pendingIds: null, beforeIds: null, running: false, + inFlight: null, }, }; @@ -334,6 +377,8 @@ export function resetAdminOrderState(): void { reorderTracks[key].pendingIds = null; reorderTracks[key].beforeIds = null; reorderTracks[key].running = false; + // 旧会话的循环不会清它(stale 后直接退出),这里一并置空 + reorderTracks[key].inFlight = null; } } @@ -494,7 +539,11 @@ function reorderList( ), }); if (track.running) return Promise.resolve(); - return flushReorder(key, send); + const run = flushReorder(key, send); + // flushReorder 同步设 running;若它没开循环就收尾了(无可发顺序),running + // 已是 false,这里不登记(否则会留一个已结束的 inFlight 永远不清)。 + if (track.running) track.inFlight = run; + return run; } /** @@ -557,7 +606,10 @@ async function flushReorder( } } finally { // 旧循环不得清掉新会话正在跑的循环的 running(否则会并发开出第二条循环) - if (!stale()) track.running = false; + if (!stale()) { + track.running = false; + track.inFlight = null; + } } if (!error) { track.beforeIds = null; // 本轮全部落库,下次排序重新取快照 diff --git a/web/test/crud-panels.test.tsx b/web/test/crud-panels.test.tsx index 684c460..4d2666f 100644 --- a/web/test/crud-panels.test.tsx +++ b/web/test/crud-panels.test.tsx @@ -338,6 +338,7 @@ describe("LinkPanel:链接图标上传 / 回填 / 清旧", () => { await waitFor(() => expect(updateLinkMock).toHaveBeenCalledWith("l1", { + categoryId: "c1", title: "GitHub", url: "https://github.com", iconUrl: "/assets/assets/icon/link-new.png", @@ -625,6 +626,247 @@ describe("LinkPanel:分类筛选「所有」", () => { }); }); +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(); diff --git a/web/test/nav-store-reorder.test.ts b/web/test/nav-store-reorder.test.ts index db415b2..629665b 100644 --- a/web/test/nav-store-reorder.test.ts +++ b/web/test/nav-store-reorder.test.ts @@ -550,3 +550,92 @@ describe("场景内排序不污染其他场景的 sortOrder", () => { ).toEqual(["a1", "a2"]); }); }); + +describe("链接换分类后作废本地顺序(服务端按目标分类末尾重排)", () => { + /** 服务端视角:l1 已从 c1 搬到 c2,落到全局 MAX+1 = 3。 */ + function serverAfterMove(): AdminData { + return { + ...makeAdminData(), + links: [ + link("l3", "c1", "MDN", 0), + link("l2", "c2", "少数派", 1), + link("l4", "c2", "V2EX", 2), + link("l1", "c2", "GitHub", 3), + ], + }; + } + + it("settleLinkOrder 之后 loadAdmin 用服务端序号:搬走的链接排到新分类末尾", async () => { + // 先拖一次排序,让本地权威顺序(localIds)占位 + await useNavStore.getState().reorderLinks(["l3", "l1", "l2", "l4"]); + listAllMock.mockResolvedValue(serverAfterMove()); + + await useNavStore.getState().settleLinkOrder(); + await useNavStore.getState().loadAdmin(); + + expect(adminData().links.find((l) => l.id === "l1")).toMatchObject({ + categoryId: "c2", + sortOrder: 3, + }); + expect(orders(adminData().links)).toEqual([0, 1, 2, 3]); + }); + + it("settleLinkOrder 会等在飞的排序落库,且不让它在落地后写回旧顺序", async () => { + const pending = deferred(); + reorderLinksMock.mockReturnValue(pending.promise); + + // 拖一次排序:请求在飞,本地已是新顺序 + const inFlight = useNavStore + .getState() + .reorderLinks(["l3", "l1", "l2", "l4"]); + let settled = false; + const settling = useNavStore + .getState() + .settleLinkOrder() + .then(() => { + settled = true; + }); + + await flushAsync(); + // 排序还没落库:换分类必须继续等,不能先去写 PUT + expect(settled).toBe(false); + + pending.resolve(); + await inFlight; + await settling; + + // 排序落地+作废之后,服务端的搬迁结果(l1 → c2 末尾)不被旧槽位改写 + listAllMock.mockResolvedValue(serverAfterMove()); + await useNavStore.getState().loadAdmin(); + expect(adminData().links.find((l) => l.id === "l1")).toMatchObject({ + categoryId: "c2", + sortOrder: 3, + }); + }); + + it("排序失败时 settleLinkOrder 不把错误抛给换分类的保存", async () => { + const pending = deferred(); + reorderLinksMock.mockReturnValue(pending.promise); + listAllMock.mockResolvedValue(makeAdminData()); + + const inFlight = useNavStore + .getState() + .reorderLinks(["l3", "l1", "l2", "l4"]); + const settling = useNavStore.getState().settleLinkOrder(); + pending.reject(new Error("boom")); + + await expect(settling).resolves.toBeUndefined(); + // 排序本身的失败仍由原调用者(面板 toast)承担 + await expect(inFlight).rejects.toThrow("boom"); + }); + + it("对照:不作废时本地旧槽位会把新 sortOrder 改写回去", async () => { + await useNavStore.getState().reorderLinks(["l3", "l1", "l2", "l4"]); + listAllMock.mockResolvedValue(serverAfterMove()); + + await useNavStore.getState().loadAdmin(); + + // 旧槽位(localIds 里 l1 排第 2)把服务端的 3 改成了 1 → 会插到新分类中间 + expect(adminData().links.find((l) => l.id === "l1")?.sortOrder).toBe(1); + }); +}); diff --git a/worker/src/db/queries/content.ts b/worker/src/db/queries/content.ts index 9f8b97f..315a7dc 100644 --- a/worker/src/db/queries/content.ts +++ b/worker/src/db/queries/content.ts @@ -154,6 +154,25 @@ export async function listLinks( return result.results; } +/** + * Next append-at-the-end sort order for links: MAX(sort_order) + 1 over the + * **whole** table (0 when empty). Link `sort_order` is a global sequence, not a + * per-category one, so a link that changes category lands after every existing + * link — i.e. at the end of its new category. Mirrors the category move rule + * (nav #17), which bases the append on the target scene. + */ +export async function nextLinkSortOrder( + db: D1Database, + prefix: string, +): Promise { + const row = await db + .prepare( + `SELECT COALESCE(MAX(sort_order), -1) + 1 AS next FROM ${prefix}links`, + ) + .first<{ next: number }>(); + return row?.next ?? 0; +} + export async function findLink( db: D1Database, prefix: string, diff --git a/worker/src/routes/admin.ts b/worker/src/routes/admin.ts index 5eaf681..c5016f5 100644 --- a/worker/src/routes/admin.ts +++ b/worker/src/routes/admin.ts @@ -27,6 +27,7 @@ import { listScenes, listSearchEngines, nextCategorySortOrder, + nextLinkSortOrder, nextSceneSortOrder, updateCategory, updateLink, @@ -436,13 +437,18 @@ adminRoutes.put("/links/:id", async (c) => { data.url = url; } if (body.categoryId !== undefined) { - const category = await findCategory( - c.env.DB, - prefix, - String(body.categoryId), - ); + const categoryId = String(body.categoryId); + const category = await findCategory(c.env.DB, prefix, categoryId); if (!category) return badRequest("categoryId does not exist"); - data.category_id = body.categoryId; + data.category_id = categoryId; + // Moving a link to another category appends it to the end of the target + // category (same rule as a category changing scene, nav #17). Link + // sort_order is a **global** sequence, so the base is the whole table's + // MAX+1 rather than a per-category one. An explicit sortOrder wins and is + // kept verbatim; leaving categoryId unchanged never touches the position. + if (categoryId !== existing.category_id && body.sortOrder === undefined) { + data.sort_order = await nextLinkSortOrder(c.env.DB, prefix); + } } if (body.iconUrl !== undefined) data.icon_url = diff --git a/worker/test/api-contract.test.ts b/worker/test/api-contract.test.ts index d612a51..cdce2cd 100644 --- a/worker/test/api-contract.test.ts +++ b/worker/test/api-contract.test.ts @@ -368,3 +368,170 @@ describe("setup flow", () => { expect(res.status).toBe(404); }); }); + +describe("link edit: moving a link to another category (nav #17 move rule)", () => { + let env: Env; + let app: Hono; + let cookie: string; + let devCat: string; + let readCat: string; + + const adminFetch = (path: string, init: RequestInit = {}) => + app.request( + path, + { + ...init, + headers: { "content-type": "application/json", cookie }, + }, + env, + ); + + async function createCategory(name: string): Promise { + const res = await adminFetch("/api/admin/categories", { + method: "POST", + body: JSON.stringify({ name }), + }); + return (await readJson(res)).id; + } + + async function createLink(body: Record): Promise { + const res = await adminFetch("/api/admin/links", { + method: "POST", + body: JSON.stringify({ + url: `https://example.com/${String(body.title)}`, + ...body, + }), + }); + return (await readJson(res)).id; + } + + /** 全量链接(后端按 sort_order, created_at 排序)。 */ + async function listLinks(): Promise< + { id: string; categoryId: string; title: string; sortOrder: number }[] + > { + return (await readJson(await adminFetch("/api/admin/links"))).links; + } + + beforeEach(async () => { + env = makeEnv(); + app = makeApp(); + await runMigrations(env); + cookie = (await setupRequest(app, env)).headers.get("set-cookie") ?? ""; + devCat = await createCategory("开发"); + readCat = await createCategory("阅读"); + }); + + it("appends the moved link to the end of the target category (global MAX+1)", async () => { + const github = await createLink({ + title: "GitHub", + categoryId: devCat, + sortOrder: 0, + }); + const mdn = await createLink({ + title: "MDN", + categoryId: devCat, + sortOrder: 1, + }); + await createLink({ title: "少数派", categoryId: readCat, sortOrder: 2 }); + + const res = await adminFetch(`/api/admin/links/${mdn}`, { + method: "PUT", + body: JSON.stringify({ categoryId: readCat }), + }); + expect(res.status).toBe(200); + expect(await readJson(res)).toMatchObject({ + id: mdn, + categoryId: readCat, + sortOrder: 3, + }); + + const links = await listLinks(); + // 原分类里只剩没搬走的那个 + expect( + links.filter((l) => l.categoryId === devCat).map((l) => l.title), + ).toEqual(["GitHub"]); + expect(links.find((l) => l.id === github)?.sortOrder).toBe(0); + // 目标分类:搬到末尾,原有顺序不变 + expect( + links.filter((l) => l.categoryId === readCat).map((l) => l.title), + ).toEqual(["少数派", "MDN"]); + }); + + it("keeps the position untouched when categoryId is unchanged", async () => { + const first = await createLink({ + title: "GitHub", + categoryId: devCat, + sortOrder: 0, + }); + const second = await createLink({ + title: "MDN", + categoryId: devCat, + sortOrder: 1, + }); + const third = await createLink({ + title: "少数派", + categoryId: readCat, + sortOrder: 2, + }); + + // 每次保存都原样带上当前 categoryId(前端如此),顺序不得被打乱 + const res = await adminFetch(`/api/admin/links/${first}`, { + method: "PUT", + body: JSON.stringify({ categoryId: devCat, title: "GitHub 改名" }), + }); + expect(res.status).toBe(200); + expect(await readJson(res)).toMatchObject({ + id: first, + categoryId: devCat, + sortOrder: 0, + title: "GitHub 改名", + }); + + const links = await listLinks(); + expect(links.map((l) => l.id)).toEqual([first, second, third]); + expect(links.map((l) => l.sortOrder)).toEqual([0, 1, 2]); + }); + + it("keeps an explicit sortOrder verbatim instead of appending", async () => { + await createLink({ title: "GitHub", categoryId: devCat, sortOrder: 0 }); + const mdn = await createLink({ + title: "MDN", + categoryId: devCat, + sortOrder: 4, + }); + + const res = await adminFetch(`/api/admin/links/${mdn}`, { + method: "PUT", + body: JSON.stringify({ categoryId: readCat, sortOrder: 1 }), + }); + expect(res.status).toBe(200); + expect(await readJson(res)).toMatchObject({ + categoryId: readCat, + sortOrder: 1, + }); + }); + + it("rejects an unknown categoryId with 400 and writes nothing", async () => { + const github = await createLink({ + title: "GitHub", + categoryId: devCat, + sortOrder: 0, + }); + + const res = await adminFetch(`/api/admin/links/${github}`, { + method: "PUT", + body: JSON.stringify({ categoryId: "ghost", title: "改不动的标题" }), + }); + expect(res.status).toBe(400); + expect(await readJson(res)).toEqual({ + error: "categoryId does not exist", + }); + + const links = await listLinks(); + expect(links.find((l) => l.id === github)).toMatchObject({ + title: "GitHub", + categoryId: devCat, + sortOrder: 0, + }); + }); +});