Files
writer-work-flow/apps/web/lib/workbench/useInjection.ts
Yaojia Wang c6651b74b9 fix(web): stale-closure + focus trap + 去边界强转 + a11y/性能打磨 + 类型化客户端
P1-6 useStyleLearn/useKimiOauth 修 stale-closure 依赖。
P1-7 CommandPalette/Drawer 加 focus trap(新 lib/a11y/focusTrap)。
P1-8 SSE 解析与 server.ts 去 as 强转改类型守卫/运行时校验。
P2 删冗余强转、开 noUncheckedIndexedAccess、Toast 清理+稳定 key、列表 key 稳定化、
  rel=noopener、useMemo 大文本、ConflictCard role=group、useInjection 加锁、
  client.test 真断言。
codegen 重生成 schema.d.ts + 消费 DimensionEntry/ReviewConflictView 强类型。
2026-06-21 19:32:49 +02:00

119 lines
3.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { api } from "@/lib/api/client";
import {
currentOverride,
withExcluded,
withPinToggled,
withRecentN,
withRestored,
type InjectionEntityRef,
type InjectionOverrideRequest,
type InjectionResponse,
} from "./injection";
export interface UseInjection {
data: InjectionResponse | null;
loading: boolean;
saving: boolean;
error: string | null;
togglePin: (ref: InjectionEntityRef) => Promise<void>;
exclude: (ref: InjectionEntityRef) => Promise<void>;
restore: (ref: InjectionEntityRef) => Promise<void>;
setRecentN: (n: number) => Promise<void>;
}
const INJECTION_PATH =
"/projects/{project_id}/chapters/{chapter_no}/injection" as const;
// 本章注入透明B0 可控版):读确定性 SelectionTrace + 作者覆盖;
// pin/排除/recent_n 经 PUT 覆盖 → 服务端回放新的确定结果(看到的=写章用的)。
// 写失败给可读文案、不改本地状态(天然回滚),不抛。
export function useInjection(projectId: string, chapterNo: number): UseInjection {
const [data, setData] = useState<InjectionResponse | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
// 并发锁:保存在途时 ref 同步置位,拦下连点/快速切换造成的乱序覆盖state 异步不可靠)。
const savingRef = useRef(false);
useEffect(() => {
let cancelled = false;
setLoading(true);
setError(null);
void (async () => {
const { data: body, error: err } = await api.GET(INJECTION_PATH, {
params: { path: { project_id: projectId, chapter_no: chapterNo } },
});
if (cancelled) return;
if (err || !body) {
setError("注入信息暂不可用");
setData(null);
} else {
setData(body);
}
setLoading(false);
})();
return () => {
cancelled = true;
};
}, [projectId, chapterNo]);
const save = useCallback(
async (override: InjectionOverrideRequest) => {
// 已有保存在途 → 早返回(避免并发 PUT 互相覆盖、回放结果乱序)。
if (savingRef.current) return;
savingRef.current = true;
setSaving(true);
setError(null);
try {
const { data: body, error: err } = await api.PUT(INJECTION_PATH, {
params: { path: { project_id: projectId, chapter_no: chapterNo } },
body: override,
});
if (err || !body) {
setError("保存注入设置失败,请重试");
} else {
setData(body); // 以服务端确定结果为准(不变量 #6
}
} finally {
savingRef.current = false;
setSaving(false);
}
},
[projectId, chapterNo],
);
const mutate = useCallback(
(fn: (o: InjectionOverrideRequest) => InjectionOverrideRequest) =>
async (): Promise<void> => {
if (!data) return;
await save(fn(currentOverride(data)));
},
[data, save],
);
const togglePin = useCallback(
(ref: InjectionEntityRef) => mutate((o) => withPinToggled(o, ref))(),
[mutate],
);
const exclude = useCallback(
(ref: InjectionEntityRef) => mutate((o) => withExcluded(o, ref))(),
[mutate],
);
const restore = useCallback(
(ref: InjectionEntityRef) => mutate((o) => withRestored(o, ref))(),
[mutate],
);
const setRecentN = useCallback(
(n: number) => mutate((o) => withRecentN(o, n))(),
[mutate],
);
return { data, loading, saving, error, togglePin, exclude, restore, setRecentN };
}