Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/api-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -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}`

Expand Down
55 changes: 52 additions & 3 deletions web/src/components/admin/crud-panels.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,7 @@ export function LinkPanel({
const [editingId, setEditingId] = React.useState<string | null>(null);
const [creating, setCreating] = React.useState(false);
const [form, setForm] = React.useState({
categoryId: "",
title: "",
url: "",
iconUrl: "",
Expand All @@ -283,6 +284,7 @@ export function LinkPanel({
return;
}
setForm({
categoryId: category.id,
title: "",
url: "",
iconUrl: "",
Expand All @@ -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 ?? "",
Expand All @@ -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,
Expand All @@ -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) {
Expand Down Expand Up @@ -441,6 +467,29 @@ export function LinkPanel({
<DialogTitle>{editingId ? "编辑链接" : "新建链接"}</DialogTitle>
</DialogHeader>
<div className="grid gap-4">
<div className="grid gap-2">
<Label htmlFor="link-category">所属分类</Label>
{/* 只列当前场景的分类(跨场景搬分类不做);编辑时预选链接实际分类 */}
<Select
value={form.categoryId}
onValueChange={(v) => setForm({ ...form, categoryId: v })}
>
<SelectTrigger
id="link-category"
aria-label="选择所属分类"
className="w-full"
>
<SelectValue placeholder="选择分类" />
</SelectTrigger>
<SelectContent>
{categories.map((c) => (
<SelectItem key={c.id} value={c.id}>
{c.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="grid gap-2">
<Label htmlFor="link-title">标题</Label>
<Input
Expand Down
14 changes: 13 additions & 1 deletion web/src/lib/mockDb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -521,7 +521,19 @@ export const mockDb = {
const state = load();
const item = state.links.find((l) => 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;
},
Expand Down
62 changes: 57 additions & 5 deletions web/src/lib/nav-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,19 @@ interface NavState {
reorderLinks: (ids: string[]) => Promise<void>;
reorderEngines: (ids: string[]) => Promise<void>;
reorderScenes: (ids: string[]) => Promise<void>;
/**
* 链接换分类前调用:先等在飞的链接排序(/links/reorder)全部落库,再作废本地
* 顺序簿记(localIds/pendingIds/beforeIds)。
*
* 「全部落库」包括在飞期间又拖出的顺序:发送循环会先把 pendingIds 里最新的一轮发完
* 才结束,所以 await 返回时旧顺序既不会再有请求待发,也不会在事后写回本地。
*
* 为什么必须「等」而不是就地清掉:排序请求无法取消,若它在这次 PUT 之后才落库,
* 会把这个链接的 sort_order 改回旧槽位;而它的成功回调还会把旧顺序写回 localIds,
* 让随后的 loadAdmin 投影继续按旧槽位覆盖新位置——等到它落地再作废,才保证这次
* PUT(全局 MAX+1)是链接顺序相关写入的最后一次。
*/
settleLinkOrder: () => Promise<void>;
/** 设置保存成功后就地刷新 store 里所有存活的 settings 切片(三片原子更新) */
patchAdminSettings: (settings: SiteSettings) => void;
loadPrivate: () => Promise<void>;
Expand Down Expand Up @@ -247,6 +260,16 @@ export const useNavStore = create<NavState>((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;
Expand Down Expand Up @@ -280,10 +303,11 @@ export function useAuthenticated(): boolean {
// 与乐观写入本质竞态——排序前发出的 GET 若晚到,会把更晚的乐观顺序盖回旧值。
// 全量刷新只在初始加载与增删改/导入/设置保存后发生,那几次由 projectLocalOrder
// 把本地顺序投影到服务端数据上,所以旧响应同样盖不掉顺序。
// 因此这里不需要版本号/序号/时间戳对账,只需要三件事:
// 因此这里不需要版本号/序号/时间戳对账,只需要四件事:
// localIds 本地权威顺序(投影 + 本轮之后仍以它为准)
// pendingIds 在飞期间又拖出的最新顺序(串行发送,只补发最新一次)
// beforeIds 本轮排序开始前的显示顺序(终止失败时的即时回滚目标)
// inFlight 在飞循环的 Promise(给「必须排在排序写入之后」的操作 await)

type AdminListKey = "scenes" | "categories" | "links" | "searchEngines";

Expand All @@ -297,22 +321,41 @@ interface ReorderTrack {
beforeIds: string[] | null;
/** 是否已有发送循环在跑(保证同一实体同一时刻只有一个请求在飞)。 */
running: boolean;
/**
* 在飞发送循环的 Promise(没有则为 null):给需要「排在排序写入之后」的操作
* (如链接换分类)提供一个可 await 的落地点。
*/
inFlight: Promise<void> | null;
}

const reorderTracks: Record<AdminListKey, ReorderTrack> = {
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,
},
};

Expand All @@ -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;
}
}

Expand Down Expand Up @@ -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;
}

/**
Expand Down Expand Up @@ -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; // 本轮全部落库,下次排序重新取快照
Expand Down
Loading
Loading