From 7241b48df9c2b62bb882745eb2fd7c04b59c7dc5 Mon Sep 17 00:00:00 2001 From: Todos Date: Sun, 8 Nov 2026 18:17:14 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(public):=20=E9=A6=96=E9=A1=B5=E7=BC=96?= =?UTF-8?q?=E8=BE=91=E6=A8=A1=E5=BC=8F=E6=94=AF=E6=8C=81=E6=8B=96=E6=8B=BD?= =?UTF-8?q?=E6=8E=92=E5=BA=8F=E5=88=86=E7=BB=84=E3=80=81=E8=A7=92=E6=A0=87?= =?UTF-8?q?=E5=88=A0=E9=99=A4=E4=B8=8E=E7=82=B9=E5=87=BB=E7=BC=96=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - dnd-kit 多容器拖拽:分类内换位、跨分类落点/标题行末尾/空分类,乐观写入 + 失败整体回滚 - 编辑模式坞入口(铅笔 ⇄ 对勾)、Esc/场景/搜索自动退出;✕ 延迟 5 秒落库并带撤销 - 链接编辑弹窗抽成共享组件,首页与后台复用;privateData 由 adminData 同步投影,不整表重拉 - 补充 store/纯函数/组件测试与 390px 底部留白 Checkpoint: 5AD6rIaHM66eWgl0E4t4C --- web/src/components/admin/crud-panels.tsx | 184 +------ web/src/components/admin/link-edit-dialog.tsx | 239 +++++++++ web/src/components/home-edit-board.tsx | 420 ++++++++++++++++ web/src/components/link-grid.tsx | 166 +++++-- web/src/components/public-dock.tsx | 30 +- web/src/components/public-page.tsx | 140 +++++- web/src/components/search-bar.tsx | 8 +- web/src/lib/api.ts | 19 + web/src/lib/link-order.ts | 53 ++ web/src/lib/mockDb.ts | 27 ++ web/src/lib/nav-store.ts | 373 +++++++++++++- web/test/api-link-move.test.ts | 67 +++ web/test/link-order.test.ts | 92 ++++ web/test/nav-store-link-edits.test.ts | 459 ++++++++++++++++++ web/test/public-dock.test.tsx | 39 ++ web/test/public-edit-mode.test.tsx | 394 +++++++++++++++ web/test/public-page.test.tsx | 4 +- 17 files changed, 2471 insertions(+), 243 deletions(-) create mode 100644 web/src/components/admin/link-edit-dialog.tsx create mode 100644 web/src/components/home-edit-board.tsx create mode 100644 web/src/lib/link-order.ts create mode 100644 web/test/api-link-move.test.ts create mode 100644 web/test/link-order.test.ts create mode 100644 web/test/nav-store-link-edits.test.ts create mode 100644 web/test/public-edit-mode.test.tsx diff --git a/web/src/components/admin/crud-panels.tsx b/web/src/components/admin/crud-panels.tsx index 74cfd72..8730d79 100644 --- a/web/src/components/admin/crud-panels.tsx +++ b/web/src/components/admin/crud-panels.tsx @@ -30,15 +30,13 @@ import { deleteReplacedAsset, useAssetDraftCleanup, } from "@/components/admin/asset-upload"; -import { IconPickerField } from "@/components/admin/icon-picker"; +import { LinkEditDialog } from "@/components/admin/link-edit-dialog"; import { SiteIcon } from "@/components/site-icon"; import { adminCreateCategory, - adminCreateLink, adminDeleteCategory, adminDeleteLink, adminUpdateCategory, - adminUpdateLink, } from "@/lib/api"; import { useNavStore } from "@/lib/nav-store"; import type { AdminCategory, AdminLink, Visibility } from "@/lib/types"; @@ -268,107 +266,31 @@ export function LinkPanel({ ).sort((a, b) => a.sortOrder - b.sortOrder); const [editingId, setEditingId] = React.useState(null); const [creating, setCreating] = React.useState(false); - const [form, setForm] = React.useState({ - categoryId: "", - title: "", - url: "", - iconUrl: "", - description: "", - visibility: "public" as Visibility, - }); - const draft = useAssetDraftCleanup(); const openCreate = () => { if (!category) { toast.error("请先选择一个分类"); return; } - setForm({ - categoryId: category.id, - title: "", - url: "", - iconUrl: "", - description: "", - visibility: "public", - }); setEditingId(null); setCreating(true); }; 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 ?? "", - description: l.description ?? "", - visibility: l.visibility, - }); + // 预选值由弹窗自己按链接实际所属分类填写。 setEditingId(id); setCreating(false); }; - const close = () => { - void draft.discard(); + const closeDialog = () => { setCreating(false); setEditingId(null); }; - 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, - description: form.description || null, - visibility: form.visibility, - }; - try { - if (editingId) { - if (moved) { - // 换分类要把「最后一次写」留给这次 PUT:先等在飞的 /links/reorder 落库, - // 同时作废本地顺序簿记(旧顺序若在 PUT 之后落库,会把这个链接改回旧槽位, - // 成功后还会把旧顺序写回本地、让界面继续按旧槽位排)。 - await useNavStore.getState().settleLinkOrder(); - } - await adminUpdateLink(editingId, payload); - toast.success( - moved && targetCategory - ? `链接已移到「${targetCategory.name}」末尾` - : "链接已更新", - ); - } else { - await adminCreateLink(payload); - toast.success("链接已创建"); - } - } catch (error) { - // 与分类/场景面板同口径:保存失败弹错误原文,弹窗保持打开 - toast.error(`保存失败:${(error as Error).message}`); - return; - } - draft.commit(); - // 图标清旧由前端负责(后端只对 settings 的 background/logo 自动清旧) - await deleteReplacedAsset(previousIcon, payload.iconUrl); - setCreating(false); - setEditingId(null); - onChanged(); - }; + const dialogLink = editingId + ? (links.find((l) => l.id === editingId) ?? null) + : null; const remove = async (id: string) => { await adminDeleteLink(id); @@ -456,91 +378,17 @@ export function LinkPanel({

)} - { - if (!open) close(); + { + closeDialog(); + onChanged(); }} - > - - - {editingId ? "编辑链接" : "新建链接"} - -
-
- - {/* 只列当前场景的分类(跨场景搬分类不做);编辑时预选链接实际分类 */} - -
-
- - setForm({ ...form, title: e.target.value })} - /> -
-
- - setForm({ ...form, url: e.target.value })} - /> -
- setForm({ ...form, iconUrl })} - onUploaded={draft.track} - title={form.title} - url={form.url} - /> -
- - - setForm({ ...form, description: e.target.value }) - } - /> -
-
- - - setForm({ ...form, visibility: v ? "private" : "public" }) - } - /> -
-
- - - -
-
+ /> ); } diff --git a/web/src/components/admin/link-edit-dialog.tsx b/web/src/components/admin/link-edit-dialog.tsx new file mode 100644 index 0000000..eb03b0d --- /dev/null +++ b/web/src/components/admin/link-edit-dialog.tsx @@ -0,0 +1,239 @@ +import * as React from "react"; +import { toast } from "sonner"; +import { + deleteReplacedAsset, + useAssetDraftCleanup, +} from "@/components/admin/asset-upload"; +import { IconPickerField } from "@/components/admin/icon-picker"; +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { Switch } from "@/components/ui/switch"; +import { adminCreateLink, adminUpdateLink } from "@/lib/api"; +import { useNavStore } from "@/lib/nav-store"; +import type { AdminCategory, AdminLink, Visibility } from "@/lib/types"; + +/** + * 链接编辑弹窗(后台「链接」面板与首页编辑模式共用同一份实现,不另写平行表单)。 + * + * 口径沿用 nav #21: + * - 「所属分类」只列**当前场景**的分类,编辑时预选链接的实际分类; + * - 改分类 = 把链接搬到目标分类末尾(服务端在 categoryId 变更且未给 sortOrder 时 + * 置全局 MAX+1);所以换分类前先 `settleLinkOrder()`,保证这次 PUT 是最后一次写; + * - 保存失败弹错误原文、弹窗保持打开;成功清理被替换的 R2 图标。 + * + * `link === null` 表示新建(后台用);首页编辑模式只用编辑态。 + */ +export function LinkEditDialog({ + open, + link, + categories, + defaultCategoryId, + onClose, + onSaved, +}: { + open: boolean; + /** 编辑的链接;null = 新建 */ + link: AdminLink | null; + /** 当前场景的分类(分类下拉只列这些) */ + categories: AdminCategory[]; + /** 新建时预选的分类(后台必须先在筛选器里选一个) */ + defaultCategoryId?: string; + onClose: () => void; + /** 保存成功:回传服务端返回的最新 DTO,由调用方决定就地替换还是整表刷新 */ + onSaved: (link: AdminLink) => void; +}) { + const [form, setForm] = React.useState({ + categoryId: "", + title: "", + url: "", + iconUrl: "", + description: "", + visibility: "public" as Visibility, + }); + const draft = useAssetDraftCleanup(); + + // 只在「打开」或「换了一条链接」时初始化表单:父组件重渲染(store 别的写入) + // 换了对象引用也不能把用户正在输入的内容冲掉。 + const initializedKey = React.useRef(null); + React.useEffect(() => { + if (!open) { + initializedKey.current = null; + return; + } + const key = link?.id ?? "new"; + if (initializedKey.current === key) return; + initializedKey.current = key; + setForm( + link + ? { + categoryId: link.categoryId, + title: link.title, + url: link.url, + iconUrl: link.iconUrl ?? "", + description: link.description ?? "", + visibility: link.visibility, + } + : { + categoryId: defaultCategoryId ?? "", + title: "", + url: "", + iconUrl: "", + description: "", + visibility: "public", + }, + ); + }, [open, link, defaultCategoryId]); + + const close = () => { + void draft.discard(); + onClose(); + }; + + const save = async () => { + if (!form.categoryId) { + toast.error("请先选择一个分类"); + return; + } + const previousIcon = link?.iconUrl ?? null; + const moved = !!link && link.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, + description: form.description || null, + visibility: form.visibility, + }; + try { + let saved: AdminLink; + if (link) { + if (moved) { + // 换分类要把「最后一次写」留给这次 PUT:先等在飞的 /links/reorder 落库, + // 同时作废本地顺序簿记(旧顺序若在 PUT 之后落库,会把这个链接改回旧槽位, + // 成功后还会把旧顺序写回本地、让界面继续按旧槽位排)。 + await useNavStore.getState().settleLinkOrder(); + } + saved = await adminUpdateLink(link.id, payload); + toast.success( + moved && targetCategory + ? `链接已移到「${targetCategory.name}」末尾` + : "链接已更新", + ); + } else { + saved = await adminCreateLink(payload); + toast.success("链接已创建"); + } + draft.commit(); + // 图标清旧由前端负责(后端只对 settings 的 background/logo 自动清旧) + await deleteReplacedAsset(previousIcon, payload.iconUrl); + onSaved(saved); + } catch (error) { + // 与分类/场景面板同口径:保存失败弹错误原文,弹窗保持打开 + toast.error(`保存失败:${(error as Error).message}`); + } + }; + + return ( + { + if (!next) close(); + }} + > + + + {link ? "编辑链接" : "新建链接"} + +
+
+ + {/* 只列当前场景的分类(跨场景搬分类不做);编辑时预选链接实际分类 */} + +
+
+ + setForm({ ...form, title: e.target.value })} + /> +
+
+ + setForm({ ...form, url: e.target.value })} + /> +
+ setForm({ ...form, iconUrl })} + onUploaded={draft.track} + title={form.title} + url={form.url} + /> +
+ + + setForm({ ...form, description: e.target.value }) + } + /> +
+
+ + + setForm({ ...form, visibility: v ? "private" : "public" }) + } + /> +
+
+ + + +
+
+ ); +} diff --git a/web/src/components/home-edit-board.tsx b/web/src/components/home-edit-board.tsx new file mode 100644 index 0000000..712dfa5 --- /dev/null +++ b/web/src/components/home-edit-board.tsx @@ -0,0 +1,420 @@ +import * as React from "react"; +import { + DndContext, + DragOverlay, + MouseSensor, + TouchSensor, + closestCorners, + pointerWithin, + useDroppable, + useSensor, + useSensors, + type CollisionDetection, + type DragEndEvent, + type DragOverEvent, + type DragStartEvent, +} from "@dnd-kit/core"; +import { + SortableContext, + arrayMove, + rectSortingStrategy, + useSortable, +} from "@dnd-kit/sortable"; +import { CSS } from "@dnd-kit/utilities"; +import { X } from "lucide-react"; +import { FadeIn } from "@/components/glass"; +import { + CategoryHeading, + LINK_GRID_CLASS, + LinkTileContent, + linkTileClassName, +} from "@/components/link-grid"; +import { cn } from "@/lib/utils"; +import type { LinkStyle, SiteCategory, SiteLink } from "@/lib/types"; + +/** + * 首页编辑模式的拖动看板(dnd-kit 原生多容器 Sortable)。 + * + * 结构:一个 `DndContext` 罩住所有分类,每个分类一个 `SortableContext` + * (`rectSortingStrategy`,砖是自动换行的网格)。投放目标三种: + * - 某块砖:落到它的下标位置(同分类换位、跨分类插入都走这条); + * - 分类标题行(`end:`):落到该分类**末尾**; + * - 空分类占位(`cat:`):虚线框、无文字、与同档砖同高,落到唯一位置。 + * + * 拖动中的预览顺序放在组件本地草稿里(只是拖拽期间的临时 UI 状态),松手才写 store: + * `onDragOver` 做跨容器搬运,`onDragEnd` 再补同容器换位,然后把「目标分类 + 前驱 id」 + * 交给调用方 → `moveLinkOnHome` 乐观写 + 串行保存。store 数据一变(乐观写入 / 回滚 / + * 删除)就按 props 重建草稿,所以保存失败会自然回到原样、不回弹。 + * + * 触屏:`TouchSensor` 长按 250ms 才激活(普通滑动照常滚动页面),`MouseSensor` + * 位移 6px 激活(单击不被吃掉)。拖拽覆盖层用 dnd-kit 原生 `DragOverlay`。 + */ + +/** 分类标题行投放目标(落到该分类末尾)的 id 前缀 */ +const END_PREFIX = "end:"; +/** 空分类占位投放目标的 id 前缀 */ +const CAT_PREFIX = "cat:"; + +/** + * 命中判定:指针落在分类标题行上时优先判为「该分类末尾」。 + * + * 标题行只有 ~30px 高,`closestCorners` 比的是整块拖拽矩形的角距,会被紧挨着 + * 下方的第一排砖抢走(表现为「拖到标题行却插到了最前面」)。这里用 dnd-kit 自带的 + * `pointerWithin` 先做一次指针命中,只认标题行投放目标,其余情况仍走 `closestCorners`。 + */ +const collisionDetection: CollisionDetection = (args) => { + const endTarget = pointerWithin(args).find(({ id }) => + String(id).startsWith(END_PREFIX), + ); + return endTarget ? [endTarget] : closestCorners(args); +}; + +/** 空分类占位的高度:与同档一块砖一致(虚线框内不写字) */ +const PLACEHOLDER_CLASS: Record = { + classic: "min-h-[132px]", + compact: "min-h-11", + wide: "min-h-[60px]", +}; + +type Order = Record; + +function containerOf(order: Order, id: string): string | null { + if (id.startsWith(END_PREFIX)) return id.slice(END_PREFIX.length); + if (id.startsWith(CAT_PREFIX)) return id.slice(CAT_PREFIX.length); + for (const [categoryId, ids] of Object.entries(order)) { + if (ids.includes(id)) return categoryId; + } + return null; +} + +/** + * 把 `activeId` 挪到 `overId` 表示的位置,返回新草稿(无变化时返回原对象)。 + * 同容器:普通换位;标题行 → 末尾;跨容器:插入 over 下标(末尾目标则追加)。 + */ +function relocate(prev: Order, activeId: string, overId: string): Order { + const from = containerOf(prev, activeId); + const to = containerOf(prev, overId); + if (!from || !to) return prev; + + if (from === to) { + const items = prev[from]; + if (overId.startsWith(END_PREFIX)) { + if (items[items.length - 1] === activeId) return prev; + return { + ...prev, + [from]: [...items.filter((id) => id !== activeId), activeId], + }; + } + if (overId.startsWith(CAT_PREFIX)) return prev; + const oldIndex = items.indexOf(activeId); + const newIndex = items.indexOf(overId); + if (oldIndex < 0 || newIndex < 0 || oldIndex === newIndex) return prev; + return { ...prev, [from]: arrayMove(items, oldIndex, newIndex) }; + } + + const fromItems = prev[from]; + const toItems = prev[to]; + const activeIndex = fromItems.indexOf(activeId); + if (activeIndex < 0) return prev; + let insertAt = toItems.length; + if (!overId.startsWith(END_PREFIX) && !overId.startsWith(CAT_PREFIX)) { + const overIndex = toItems.indexOf(overId); + if (overIndex >= 0) insertAt = overIndex; + } + return { + ...prev, + [from]: fromItems.filter((id) => id !== activeId), + [to]: [...toItems.slice(0, insertAt), activeId, ...toItems.slice(insertAt)], + }; +} + +/** 一条链接砖(编辑模式):单击编辑、右上角删除;整块可拖。 */ +function EditableTile({ + link, + linkStyle, + onEdit, + onRemove, +}: { + link: SiteLink; + linkStyle: LinkStyle; + onEdit: (linkId: string) => void; + onRemove: (linkId: string) => void; +}) { + const { + attributes, + listeners, + setNodeRef, + transform, + transition, + isDragging, + } = useSortable({ id: link.id }); + + return ( +
+ + +
+ ); +} + +/** 分类标题行:拖到这一行 = 落到该分类末尾。 */ +function EndDropTarget({ + categoryId, + children, +}: { + categoryId: string; + children: React.ReactNode; +}) { + const { setNodeRef, isOver } = useDroppable({ + id: `${END_PREFIX}${categoryId}`, + }); + return ( +
+ {children} +
+ ); +} + +/** 空分类的空投放位:与砖同尺寸的虚线框,不写字。 */ +function EmptyDropZone({ + categoryId, + linkStyle, +}: { + categoryId: string; + linkStyle: LinkStyle; +}) { + const { setNodeRef, isOver } = useDroppable({ + id: `${CAT_PREFIX}${categoryId}`, + }); + return ( +