fix(web): 规则删除按操作隔离 busy(deletingId/adding) + 全空规则页折叠为单一引导

This commit is contained in:
Yaojia Wang
2026-06-30 08:56:23 +02:00
parent 9d67f237a2
commit 6bb3559e25
3 changed files with 110 additions and 68 deletions

View File

@@ -4,6 +4,7 @@ import { Plus, Trash2 } from "lucide-react";
import { useMemo, useState } from "react"; import { useMemo, useState } from "react";
import { AppShell } from "@/components/AppShell"; import { AppShell } from "@/components/AppShell";
import { Badge } from "@/components/ui/Badge";
import { Button } from "@/components/ui/Button"; import { Button } from "@/components/ui/Button";
import { EmptyState } from "@/components/ui/EmptyState"; import { EmptyState } from "@/components/ui/EmptyState";
import { Field } from "@/components/ui/Field"; import { Field } from "@/components/ui/Field";
@@ -27,7 +28,7 @@ interface RulesPageProps {
// 规则页UX §7四级规则列表 + 新增(乐观 + 回滚)。 // 规则页UX §7四级规则列表 + 新增(乐观 + 回滚)。
export function RulesPage({ project, initialRules }: RulesPageProps) { export function RulesPage({ project, initialRules }: RulesPageProps) {
const { items, busy, add, remove } = useRules(initialRules); const { items, adding, deletingId, add, remove } = useRules(initialRules);
const [level, setLevel] = useState<RuleLevel>("project"); const [level, setLevel] = useState<RuleLevel>("project");
const [content, setContent] = useState(""); const [content, setContent] = useState("");
const groups = useMemo(() => groupByLevel(items), [items]); const groups = useMemo(() => groupByLevel(items), [items]);
@@ -81,41 +82,33 @@ export function RulesPage({ project, initialRules }: RulesPageProps) {
</Field> </Field>
<Button <Button
type="submit" type="submit"
disabled={busy || content.trim().length === 0} disabled={adding || content.trim().length === 0}
className="mt-3" className="mt-3"
variant="primary" variant="primary"
> >
<Plus className="h-4 w-4" aria-hidden="true" /> <Plus className="h-4 w-4" aria-hidden="true" />
{busy ? "保存中…" : "新增规则"} {adding ? "保存中…" : "新增规则"}
</Button> </Button>
</form> </form>
{items.length === 0 ? (
<EmptyState
icon={Plus}
title="还没有任何规则"
description="从上方表单添加第一条,写作与审稿都会共同引用这些规则。"
/>
) : (
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
{RULE_LEVELS.map((lv) => ( {RULE_LEVELS.map((lv) => (
<section key={lv}> <section key={lv}>
<h2 className="mb-2 font-serif text-sm text-ink"> <h2 className="mb-2 flex items-center gap-2 font-serif text-sm text-ink">
{RULE_LEVEL_LABELS[lv]} {RULE_LEVEL_LABELS[lv]}
<span className="ml-2 text-xs text-ink-soft"> <Badge variant="neutral">{groups[lv].length}</Badge>
{groups[lv].length}
</span>
</h2> </h2>
{groups[lv].length === 0 ? ( {groups[lv].length === 0 ? (
<EmptyState <p className="px-1 text-xs text-ink-soft">
icon={Plus} {RULE_LEVEL_LABELS[lv]}
title="暂无规则" </p>
description={`还没有${RULE_LEVEL_LABELS[lv]}规则。`}
action={
<Button
onClick={() => setLevel(lv)}
variant="secondary"
size="sm"
>
<Plus className="h-4 w-4" aria-hidden="true" />
{RULE_LEVEL_LABELS[lv]}
</Button>
}
className="px-4 py-6"
/>
) : ( ) : (
<ul className="flex flex-col gap-2"> <ul className="flex flex-col gap-2">
{groups[lv].map((rule) => ( {groups[lv].map((rule) => (
@@ -131,13 +124,13 @@ export function RulesPage({ project, initialRules }: RulesPageProps) {
<Button <Button
variant="danger" variant="danger"
size="sm" size="sm"
disabled={busy} disabled={deletingId === rule.id}
onClick={() => void remove(project.id, rule.id)} onClick={() => void remove(project.id, rule.id)}
aria-label="删除规则" aria-label="删除规则"
className="shrink-0" className="shrink-0"
> >
<Trash2 className="h-3 w-3" aria-hidden="true" /> <Trash2 className="h-3 w-3" aria-hidden="true" />
{deletingId === rule.id ? "删除中…" : "删除"}
</Button> </Button>
</li> </li>
))} ))}
@@ -146,6 +139,7 @@ export function RulesPage({ project, initialRules }: RulesPageProps) {
</section> </section>
))} ))}
</div> </div>
)}
</div> </div>
</AppShell> </AppShell>
); );

View File

@@ -23,10 +23,11 @@ describe("useRules", () => {
}); });
afterEach(() => vi.clearAllMocks()); afterEach(() => vi.clearAllMocks());
it("初始 items = 传入值,busy=false", () => { it("初始 items = 传入值,adding=false、deletingId=null", () => {
const { result } = renderHook(() => useRules(seed)); const { result } = renderHook(() => useRules(seed));
expect(result.current.items).toEqual(seed); expect(result.current.items).toEqual(seed);
expect(result.current.busy).toBe(false); expect(result.current.adding).toBe(false);
expect(result.current.deletingId).toBeNull();
}); });
it("add 空白正文:弹错、不请求、返回 false", async () => { it("add 空白正文:弹错、不请求、返回 false", async () => {
@@ -52,7 +53,7 @@ describe("useRules", () => {
expect(ok).toBe(true); expect(ok).toBe(true);
expect(result.current.items).toEqual([...seed, authoritative]); expect(result.current.items).toEqual([...seed, authoritative]);
expect(result.current.busy).toBe(false); expect(result.current.adding).toBe(false);
expect(toast).toHaveBeenCalledWith("已新增规则", "success"); expect(toast).toHaveBeenCalledWith("已新增规则", "success");
}); });
@@ -80,6 +81,48 @@ describe("useRules", () => {
expect(toast).toHaveBeenCalledWith("已删除规则", "success"); expect(toast).toHaveBeenCalledWith("已删除规则", "success");
}); });
it("add 进行中adding=true 而 deletingId 仍为 null互不冻结", async () => {
let resolvePost: (v: { data: RuleView; error: null }) => void = () => {};
post.mockReturnValue(
new Promise((res) => {
resolvePost = res;
}),
);
const { result } = renderHook(() => useRules(seed));
let done: Promise<boolean> = Promise.resolve(false);
act(() => {
done = result.current.add("p1", "global", "新规则");
});
expect(result.current.adding).toBe(true);
expect(result.current.deletingId).toBeNull();
await act(async () => {
resolvePost({ data: { id: "r1", level: "global", content: "新规则" }, error: null });
await done;
});
expect(result.current.adding).toBe(false);
});
it("remove 进行中deletingId=目标 id 而 adding 仍为 false只冻结该行", async () => {
let resolveDel: (v: { error: null }) => void = () => {};
del.mockReturnValue(
new Promise((res) => {
resolveDel = res;
}),
);
const { result } = renderHook(() => useRules(seed));
let done: Promise<boolean> = Promise.resolve(false);
act(() => {
done = result.current.remove("p1", "r0");
});
expect(result.current.deletingId).toBe("r0");
expect(result.current.adding).toBe(false);
await act(async () => {
resolveDel({ error: null });
await done;
});
expect(result.current.deletingId).toBeNull();
});
it("remove 后端 error回滚、弹错、返回 false", async () => { it("remove 后端 error回滚、弹错、返回 false", async () => {
del.mockResolvedValue({ error: { detail: "boom" } }); del.mockResolvedValue({ error: { detail: "boom" } });
const { result } = renderHook(() => useRules(seed)); const { result } = renderHook(() => useRules(seed));

View File

@@ -9,7 +9,10 @@ import { buildRuleCreateRequest, hasUsableContent, type RuleLevel } from "./rule
export interface UseRules { export interface UseRules {
items: RuleView[]; items: RuleView[];
busy: boolean; // 正在新增(仅冻结新增表单,不影响删除)。
adding: boolean;
// 正在删除的那一条 id仅冻结该行删除按钮整页其余照常可操作
deletingId: string | null;
// 新增一条规则(乐观追加 + 失败回滚 + Toast // 新增一条规则(乐观追加 + 失败回滚 + Toast
add: ( add: (
projectId: string, projectId: string,
@@ -21,9 +24,11 @@ export interface UseRules {
} }
// 规则页UX §7列出 + 新增规则。乐观追加,失败回滚(仿 useForeshadow // 规则页UX §7列出 + 新增规则。乐观追加,失败回滚(仿 useForeshadow
// add 与 remove 用各自独立的进行中标志,避免删一条就冻结整页。
export function useRules(initial: RuleView[]): UseRules { export function useRules(initial: RuleView[]): UseRules {
const [items, setItems] = useState<RuleView[]>(initial); const [items, setItems] = useState<RuleView[]>(initial);
const [busy, setBusy] = useState(false); const [adding, setAdding] = useState(false);
const [deletingId, setDeletingId] = useState<string | null>(null);
const toast = useToast(); const toast = useToast();
const add = useCallback<UseRules["add"]>( const add = useCallback<UseRules["add"]>(
@@ -40,7 +45,7 @@ export function useRules(initial: RuleView[]): UseRules {
content: content.trim(), content: content.trim(),
}; };
setItems((prev) => [...prev, optimistic]); setItems((prev) => [...prev, optimistic]);
setBusy(true); setAdding(true);
try { try {
const { data, error } = await api.POST( const { data, error } = await api.POST(
"/projects/{project_id}/rules", "/projects/{project_id}/rules",
@@ -59,7 +64,7 @@ export function useRules(initial: RuleView[]): UseRules {
toast("已新增规则", "success"); toast("已新增规则", "success");
return true; return true;
} finally { } finally {
setBusy(false); setAdding(false);
} }
}, },
[items, toast], [items, toast],
@@ -69,7 +74,7 @@ export function useRules(initial: RuleView[]): UseRules {
async (projectId, ruleId) => { async (projectId, ruleId) => {
const snapshot = items; const snapshot = items;
setItems((prev) => prev.filter((r) => r.id !== ruleId)); setItems((prev) => prev.filter((r) => r.id !== ruleId));
setBusy(true); setDeletingId(ruleId);
try { try {
const { error } = await api.DELETE( const { error } = await api.DELETE(
"/projects/{project_id}/rules/{rule_id}", "/projects/{project_id}/rules/{rule_id}",
@@ -83,11 +88,11 @@ export function useRules(initial: RuleView[]): UseRules {
toast("已删除规则", "success"); toast("已删除规则", "success");
return true; return true;
} finally { } finally {
setBusy(false); setDeletingId(null);
} }
}, },
[items, toast], [items, toast],
); );
return { items, busy, add, remove }; return { items, adding, deletingId, add, remove };
} }