feat(web): 审稿改稿闭环——一键采纳/AI改写/正文高亮定位编辑/伏笔确认/草稿自动保存/章节目录
- 冲突「采纳改法」:有补丁瞬时改入终稿并选中;无补丁但可定位则采纳时调 AI(refiner)重写该段套入;定位不到提示手改 - 正文改为行内高亮叠层编辑器(与页面同底色、随内容增高、无滚动条),点冲突卡/锚点整页滚到并选中+闪烁 - 仅对可在正文定位的冲突显示「跳转」/锚点;locate 支持从 where 引号抽原文,杜绝定位失败刷屏 - 伏笔建议卡:新埋一键登记(预填表单)/ 疑似回收一键标记 CLOSED(复用现有端点) - 审稿页草稿自动保存(防抖 PUT /draft),与「验收本章」解耦,刷新不丢 - 写作路由带章号 ?chapter=N + 验收成功面板/大纲页「写下一章」入口;写作目录从大纲列出全部章节 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -40,6 +40,25 @@ body {
|
||||
transition: background-color 0.15s ease;
|
||||
}
|
||||
|
||||
/* 终稿正文:冲突原文持续高亮(朱砂淡底),点锚点定位时闪烁一下(UX §8.3)。 */
|
||||
.draft-mark {
|
||||
background-color: #b5543a26; /* --color-conflict @ ~15% */
|
||||
border-radius: 2px;
|
||||
}
|
||||
.draft-mark-flash {
|
||||
animation: draft-mark-flash 0.9s ease-out;
|
||||
}
|
||||
|
||||
@keyframes draft-mark-flash {
|
||||
0%,
|
||||
100% {
|
||||
background-color: #b5543a26;
|
||||
}
|
||||
30% {
|
||||
background-color: #b5543a8c; /* --color-conflict @ ~55% */
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.typewriter-cursor {
|
||||
animation: none;
|
||||
@@ -47,4 +66,8 @@ body {
|
||||
.conflict-anchor {
|
||||
transition: none;
|
||||
}
|
||||
.draft-mark-flash {
|
||||
animation: none;
|
||||
outline: 2px solid var(--color-conflict);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,23 @@
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { Workbench } from "@/components/workbench/Workbench";
|
||||
import { fetchDraft, fetchProject } from "@/lib/api/server";
|
||||
import { fetchDraft, fetchOutline, fetchProject } from "@/lib/api/server";
|
||||
import type { ProjectResponse } from "@/lib/api/types";
|
||||
import { WORKBENCH_CHAPTER_NO } from "@/lib/workbench/chapter";
|
||||
import { parseChapterParam, type ChapterEntry } from "@/lib/workbench/chapter";
|
||||
|
||||
interface PageProps {
|
||||
params: Promise<{ id: string }>;
|
||||
searchParams: Promise<{ chapter?: string | string[] }>;
|
||||
}
|
||||
|
||||
// 写作工作台页(UX §6.3)。Server Component 取项目 + 当前章已存草稿(GET .../draft,
|
||||
// 写作工作台页(UX §6.3)。Server Component 取项目 + 该章已存草稿(GET .../draft,
|
||||
// 404→null=空编辑器),把正文作为编辑器初值种入,重访时重载已写章节;Workbench
|
||||
// 负责编辑/流式/保存(流式照常覆盖初值)。
|
||||
export default async function WritePage({ params }: PageProps) {
|
||||
// 负责编辑/流式/保存(流式照常覆盖初值)。章号由 `?chapter=N` 指定(缺省=第 1 章),
|
||||
// 支持写下一章。
|
||||
export default async function WritePage({ params, searchParams }: PageProps) {
|
||||
const { id } = await params;
|
||||
const { chapter } = await searchParams;
|
||||
const chapterNo = parseChapterParam(chapter);
|
||||
|
||||
// 仅当项目确实取不到时才判 404;草稿/瞬时错误不应把整页变成「找不到页面」。
|
||||
let project: ProjectResponse;
|
||||
@@ -23,14 +27,27 @@ export default async function WritePage({ params }: PageProps) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
// 草稿读取失败(后端瞬时错误 / 尚无草稿)→ 空编辑器初值,绝不 404。
|
||||
// 草稿读取失败(后端瞬时错误 / 新章尚无草稿)→ 空编辑器初值,绝不 404。
|
||||
let initialText = "";
|
||||
try {
|
||||
const draft = await fetchDraft(id, WORKBENCH_CHAPTER_NO);
|
||||
const draft = await fetchDraft(id, chapterNo);
|
||||
initialText = draft?.content ?? "";
|
||||
} catch {
|
||||
initialText = "";
|
||||
}
|
||||
|
||||
return <Workbench project={project} initialText={initialText} />;
|
||||
// 大纲章节作目录(fetchOutline 已对空/错误降级为 []);首个节拍当短标题。
|
||||
const chapters: ChapterEntry[] = (await fetchOutline(id)).map((c) => ({
|
||||
no: c.no,
|
||||
title: c.beats?.[0],
|
||||
}));
|
||||
|
||||
return (
|
||||
<Workbench
|
||||
project={project}
|
||||
chapterNo={chapterNo}
|
||||
initialText={initialText}
|
||||
chapters={chapters}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
|
||||
import type { OutlineChapterView } from "@/lib/api/types";
|
||||
import {
|
||||
isCloseWindow,
|
||||
@@ -8,11 +10,12 @@ import {
|
||||
|
||||
interface OutlineChapterRowProps {
|
||||
chapter: OutlineChapterView;
|
||||
projectId: string;
|
||||
}
|
||||
|
||||
// 单章大纲行(UX §6.7):章号 + beats + 伏笔窗口徽标(⚑)。
|
||||
// 单章大纲行(UX §6.7):章号 + beats + 伏笔窗口徽标(⚑)+ 「写此章」入口。
|
||||
// 接近回收窗口的徽标用琥珀 + 「可回收」提示(a11y:图标 + 文案,不单靠色)。
|
||||
export function OutlineChapterRow({ chapter }: OutlineChapterRowProps) {
|
||||
export function OutlineChapterRow({ chapter, projectId }: OutlineChapterRowProps) {
|
||||
const windows = chapter.foreshadow_windows ?? [];
|
||||
return (
|
||||
<li className="border-l-2 border-line py-2 pl-3">
|
||||
@@ -20,6 +23,12 @@ export function OutlineChapterRow({ chapter }: OutlineChapterRowProps) {
|
||||
<span className="font-mono text-xs text-ink-soft">
|
||||
第 {chapter.no} 章
|
||||
</span>
|
||||
<Link
|
||||
href={`/projects/${projectId}/write?chapter=${chapter.no}`}
|
||||
className="rounded border border-line px-1.5 py-0.5 text-xs text-ink-soft hover:border-cinnabar hover:text-cinnabar"
|
||||
>
|
||||
✍ 写此章
|
||||
</Link>
|
||||
{windows.map((w) => {
|
||||
const close = isCloseWindow(chapter, w);
|
||||
return (
|
||||
|
||||
@@ -84,7 +84,11 @@ export function OutlineEditor({
|
||||
</h2>
|
||||
<ul className="space-y-1">
|
||||
{group.chapters.map((ch) => (
|
||||
<OutlineChapterRow key={ch.no} chapter={ch} />
|
||||
<OutlineChapterRow
|
||||
key={ch.no}
|
||||
chapter={ch}
|
||||
projectId={project.id}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
|
||||
import type { AcceptResponse } from "@/lib/api/types";
|
||||
import { buildAcceptPreview } from "@/lib/review/accept-preview";
|
||||
import { ThinkingIndicator } from "@/components/ThinkingIndicator";
|
||||
|
||||
interface AcceptPanelProps {
|
||||
projectId: string;
|
||||
chapterNo: number;
|
||||
conflictCount: number;
|
||||
unresolvedCount: number;
|
||||
// R3:当前伏笔建议数(验收前清单提醒,只读不自动落库)。
|
||||
@@ -16,6 +20,8 @@ interface AcceptPanelProps {
|
||||
|
||||
// 验收 gate(UX §9 / §8.4):未决禁验收(置灰 + 文案),验收后呈现「本次将更新」清单。
|
||||
export function AcceptPanel({
|
||||
projectId,
|
||||
chapterNo,
|
||||
conflictCount,
|
||||
unresolvedCount,
|
||||
foreshadowCount,
|
||||
@@ -54,6 +60,21 @@ export function AcceptPanel({
|
||||
</li>
|
||||
) : null}
|
||||
</ul>
|
||||
{/* 验收闭环 → 写下一章入口(修「验收后无路可走」的断点)。 */}
|
||||
<div className="mt-3 flex flex-wrap items-center gap-2">
|
||||
<Link
|
||||
href={`/projects/${projectId}/write?chapter=${chapterNo + 1}`}
|
||||
className="rounded bg-cinnabar px-4 py-2 text-sm text-panel hover:opacity-90"
|
||||
>
|
||||
→ 写第 {chapterNo + 1} 章
|
||||
</Link>
|
||||
<Link
|
||||
href={`/projects/${projectId}/outline`}
|
||||
className="rounded border border-line px-4 py-2 text-sm text-ink hover:border-cinnabar hover:text-cinnabar"
|
||||
>
|
||||
返回大纲
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,30 +1,79 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, type ReactNode, type RefObject } from "react";
|
||||
|
||||
import { locateInDraft } from "@/lib/review/locate";
|
||||
import type { ReviewConflict } from "@/lib/review/sse";
|
||||
|
||||
interface AnnotatedTextProps {
|
||||
text: string;
|
||||
value: string;
|
||||
onChange: (next: string) => void;
|
||||
conflicts: ReviewConflict[];
|
||||
// 当前聚焦的冲突下标(来自报告卡「跳转」),用于锚点联动。
|
||||
// 当前聚焦的冲突下标(来自报告卡「跳转」/锚点),用于锚点高亮联动。
|
||||
focusedIndex: number | null;
|
||||
onAnchorClick: (index: number) => void;
|
||||
// 转发给可编辑 textarea,供父组件 setSelectionRange 定位/高亮问题区域。
|
||||
editorRef?: RefObject<HTMLTextAreaElement | null>;
|
||||
}
|
||||
|
||||
// 正文就地标注(UX §8.3 / §6.1)。
|
||||
// M2 占位(R6):`where` 是文字定位(如「第4段」),M2 不做精确字符 range —
|
||||
// 改为段级/锚点联动:每个冲突渲染为一枚朱砂波浪线锚点挂在正文上方,点击=回跳报告卡。
|
||||
// 精确 inline range 标注留 M3+(需后端给字符 offset)。
|
||||
// 高亮叠层编辑器:背景层渲染带 <mark> 高亮的正文,前景透明 textarea 负责编辑。
|
||||
// 两层必须共享同一盒模型/排版常量,否则高亮与文字像素错位。
|
||||
const TYPO =
|
||||
"box-border w-full font-serif text-[17px] leading-[1.9] tracking-normal whitespace-pre-wrap break-words";
|
||||
|
||||
// 把终稿按已定位的冲突区间切成 [纯文本 | <mark> | …];<mark> 带 id 供父组件滚动定位。
|
||||
// 区间按 start 排序,重叠区间保留先到者(跳过后者),避免标签嵌套。
|
||||
function buildSegments(value: string, conflicts: ReviewConflict[]): ReactNode[] {
|
||||
const spans = conflicts
|
||||
.map((c, i) => ({ i, loc: locateInDraft(value, c) }))
|
||||
.filter(
|
||||
(x): x is { i: number; loc: { start: number; end: number } } =>
|
||||
x.loc !== null,
|
||||
)
|
||||
.sort((a, b) => a.loc.start - b.loc.start);
|
||||
|
||||
const nodes: ReactNode[] = [];
|
||||
let cursor = 0;
|
||||
for (const { i, loc } of spans) {
|
||||
if (loc.start < cursor) continue; // 与已保留区间重叠 → 跳过
|
||||
if (loc.start > cursor) nodes.push(value.slice(cursor, loc.start));
|
||||
nodes.push(
|
||||
<mark
|
||||
key={`mark-${i}`}
|
||||
id={`draft-mark-${i}`}
|
||||
className="draft-mark text-ink"
|
||||
>
|
||||
{value.slice(loc.start, loc.end)}
|
||||
</mark>,
|
||||
);
|
||||
cursor = loc.end;
|
||||
}
|
||||
if (cursor < value.length) nodes.push(value.slice(cursor));
|
||||
return nodes;
|
||||
}
|
||||
|
||||
// 正文就地编辑 + 冲突锚点(UX §8.3 / §6.1)。
|
||||
// 顶部一排朱砂锚点:每条冲突一枚,点击=定位到正文对应区域(父组件在 textarea 选中并滚动)。
|
||||
// 正文本体=高亮叠层编辑器:可直接改稿;冲突原文以朱砂淡底持续高亮,点锚点滚到并闪烁。
|
||||
export function AnnotatedText({
|
||||
text,
|
||||
value,
|
||||
onChange,
|
||||
conflicts,
|
||||
focusedIndex,
|
||||
onAnchorClick,
|
||||
editorRef,
|
||||
}: AnnotatedTextProps) {
|
||||
const backdropRef = useRef<HTMLDivElement>(null);
|
||||
const segments = buildSegments(value, conflicts);
|
||||
// 只为能在正文里定位到的冲突渲染锚点(其余如涉及摘要/跨章的冲突不在正文,点了也定位不到)。
|
||||
const anchorable = conflicts
|
||||
.map((c, i) => ({ c, i }))
|
||||
.filter(({ c }) => locateInDraft(value, c) !== null);
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
{conflicts.length > 0 ? (
|
||||
<div className="mb-3 flex flex-wrap gap-2 border-b border-line pb-3">
|
||||
{conflicts.map((c, i) => (
|
||||
<div className="flex flex-col gap-3">
|
||||
{anchorable.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-2 border-b border-line pb-3">
|
||||
{anchorable.map(({ c, i }) => (
|
||||
<button
|
||||
key={`${c.type}-${c.where}-${i}`}
|
||||
type="button"
|
||||
@@ -36,7 +85,7 @@ export function AnnotatedText({
|
||||
? "bg-cinnabar text-panel"
|
||||
: "text-conflict hover:bg-[var(--color-conflict)]/10"
|
||||
}`}
|
||||
title={`${c.type}:${c.where || "正文"}`}
|
||||
title={`${c.type}:${c.where || "正文"} — 点击定位到正文`}
|
||||
>
|
||||
<span aria-hidden="true">⌇</span> {c.type}
|
||||
{c.where ? ` · ${c.where}` : ""}
|
||||
@@ -44,11 +93,36 @@ export function AnnotatedText({
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<article className="flex-1 overflow-auto whitespace-pre-wrap font-serif text-[17px] leading-[1.9] text-ink">
|
||||
{text || (
|
||||
<span className="text-ink-soft/60">(无待审正文,先去写作页起草本章)</span>
|
||||
)}
|
||||
</article>
|
||||
<label htmlFor="final-text" className="sr-only">
|
||||
终稿正文
|
||||
</label>
|
||||
<div className="relative min-h-[40vh] w-full bg-transparent">
|
||||
{/* 背景高亮层:在文档流中决定高度(撑满全文),仅展示(不可交互)。 */}
|
||||
<div
|
||||
ref={backdropRef}
|
||||
data-draft-backdrop
|
||||
aria-hidden="true"
|
||||
className={`${TYPO} pointer-events-none relative select-none text-ink`}
|
||||
>
|
||||
{value ? (
|
||||
segments
|
||||
) : (
|
||||
<span className="text-ink-soft/60">
|
||||
(无待审正文,先去写作页起草本章)
|
||||
</span>
|
||||
)}
|
||||
{"\n"}
|
||||
</div>
|
||||
{/* 前景编辑层:文字透明(由背景层显示),仅保留光标;无内部滚动(页面滚动)。 */}
|
||||
<textarea
|
||||
ref={editorRef}
|
||||
id="final-text"
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
spellCheck={false}
|
||||
className={`${TYPO} absolute inset-0 resize-none overflow-hidden border-0 bg-transparent text-transparent caret-[color:var(--color-ink)] outline-none focus:outline-none`}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,10 @@ interface ConflictCardProps {
|
||||
missing: boolean;
|
||||
// R1:命中段内联预览(无段号/越界时为 null,回退到「跳转」按钮)。
|
||||
snippet: string | null;
|
||||
// 该冲突能否在正文里定位(决定是否显示「跳转」——定位不到就别给会失败的入口)。
|
||||
locatable: boolean;
|
||||
// 正在 AI 改写(采纳无补丁冲突时):禁用按钮 + 显示进度,避免重复点。
|
||||
rewriting: boolean;
|
||||
onVerdict: (index: number, verdict: Verdict) => void;
|
||||
onNote: (index: number, note: string) => void;
|
||||
onJump: (index: number) => void;
|
||||
@@ -37,6 +41,8 @@ export function ConflictCard({
|
||||
draft,
|
||||
missing,
|
||||
snippet,
|
||||
locatable,
|
||||
rewriting,
|
||||
onVerdict,
|
||||
onNote,
|
||||
onJump,
|
||||
@@ -63,6 +69,18 @@ export function ConflictCard({
|
||||
<p className="flex-1 text-sm text-ink">{conflict.suggestion}</p>
|
||||
</div>
|
||||
|
||||
{conflict.original && conflict.replacement ? (
|
||||
<div className="mt-2 rounded border border-pass/30 bg-bg/40 px-3 py-1.5 text-xs leading-relaxed">
|
||||
<span className="mr-1 text-ink-soft">改法:</span>
|
||||
<span className="text-conflict line-through">{conflict.original}</span>
|
||||
<span className="mx-1 text-ink-soft" aria-hidden="true">
|
||||
→
|
||||
</span>
|
||||
<span className="text-pass">{conflict.replacement}</span>
|
||||
<span className="ml-2 text-ink-soft">(点「采纳改法」改入终稿)</span>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{snippet ? (
|
||||
<blockquote className="mt-2 border-l-2 border-conflict/40 bg-bg/50 py-1 pl-3 text-xs leading-relaxed text-ink-soft">
|
||||
<span className="mr-1 text-conflict" aria-hidden="true">
|
||||
@@ -73,7 +91,7 @@ export function ConflictCard({
|
||||
) : null}
|
||||
|
||||
<div className="mt-2 flex flex-wrap items-center gap-2 pl-1 text-xs text-ink-soft">
|
||||
{conflict.where ? (
|
||||
{conflict.where && locatable ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onJump(index)}
|
||||
@@ -101,8 +119,9 @@ export function ConflictCard({
|
||||
key={opt.value}
|
||||
type="button"
|
||||
aria-pressed={active}
|
||||
disabled={rewriting}
|
||||
onClick={() => onVerdict(index, opt.value)}
|
||||
className={`rounded px-3 py-1 text-xs ${verdictClass(
|
||||
className={`rounded px-3 py-1 text-xs disabled:cursor-not-allowed disabled:opacity-40 ${verdictClass(
|
||||
active,
|
||||
opt.primary,
|
||||
)}`}
|
||||
@@ -111,7 +130,9 @@ export function ConflictCard({
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{resolved ? (
|
||||
{rewriting ? (
|
||||
<span className="text-xs text-info">✦ AI 改写中…</span>
|
||||
) : resolved ? (
|
||||
<span className="text-xs text-pass" aria-hidden="true">
|
||||
✓ 已裁决
|
||||
</span>
|
||||
|
||||
@@ -1,19 +1,89 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { suggestForeshadowCode } from "@/lib/foreshadow/board";
|
||||
import { useForeshadow } from "@/lib/foreshadow/useForeshadow";
|
||||
import type { ForeshadowSuggestion } from "@/lib/review/sse";
|
||||
|
||||
interface ForeshadowSuggestionsProps {
|
||||
suggestions: ForeshadowSuggestion[];
|
||||
// 审项是否未完成(incomplete)。
|
||||
incomplete: boolean;
|
||||
projectId: string;
|
||||
chapterNo: number;
|
||||
}
|
||||
|
||||
// 伏笔建议区(UX §6.4 ②):planted「新埋待确认」/ resolved「疑似回收」,只读建议。
|
||||
// 不静默写库(不变量#3):仅展示,登记/回收经伏笔看板显式确认。
|
||||
interface RegisterFormState {
|
||||
code: string;
|
||||
title: string;
|
||||
plantedAt: number;
|
||||
content: string;
|
||||
}
|
||||
|
||||
// 伏笔建议区(UX §6.4 ②):planted「新埋待确认」/ resolved「疑似回收」。
|
||||
// 四审只读(不变量#3),但作者可在此**显式确认**:新埋→登记(POST),疑似回收→标记回收(PATCH→CLOSED)。
|
||||
// 这是作者确认动作,非 AI 静默写库;复用伏笔看板端点(lib/foreshadow)。
|
||||
export function ForeshadowSuggestions({
|
||||
suggestions,
|
||||
incomplete,
|
||||
projectId,
|
||||
chapterNo,
|
||||
}: ForeshadowSuggestionsProps) {
|
||||
const fs = useForeshadow([]);
|
||||
const [openIdx, setOpenIdx] = useState<number | null>(null);
|
||||
const [form, setForm] = useState<RegisterFormState | null>(null);
|
||||
const [registered, setRegistered] = useState<Set<number>>(new Set());
|
||||
const [resolved, setResolved] = useState<Set<number>>(new Set());
|
||||
const [pending, setPending] = useState<Set<number>>(new Set());
|
||||
|
||||
const openRegister = (i: number, s: ForeshadowSuggestion): void => {
|
||||
setOpenIdx(i);
|
||||
setForm({
|
||||
code: suggestForeshadowCode(s.code, i),
|
||||
title: s.title,
|
||||
plantedAt: chapterNo,
|
||||
content: s.note ?? s.where ?? "",
|
||||
});
|
||||
};
|
||||
|
||||
const closeForm = (): void => {
|
||||
setOpenIdx(null);
|
||||
setForm(null);
|
||||
};
|
||||
|
||||
const markPending = (i: number, on: boolean): void =>
|
||||
setPending((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (on) next.add(i);
|
||||
else next.delete(i);
|
||||
return next;
|
||||
});
|
||||
|
||||
const submitRegister = async (i: number): Promise<void> => {
|
||||
if (!form || !form.code.trim() || !form.title.trim()) return;
|
||||
markPending(i, true);
|
||||
const ok = await fs.register({
|
||||
projectId,
|
||||
code: form.code,
|
||||
title: form.title,
|
||||
plantedAt: form.plantedAt,
|
||||
content: form.content,
|
||||
});
|
||||
markPending(i, false);
|
||||
if (ok) {
|
||||
setRegistered((prev) => new Set(prev).add(i));
|
||||
closeForm();
|
||||
}
|
||||
};
|
||||
|
||||
const markResolved = async (i: number, code: string): Promise<void> => {
|
||||
markPending(i, true);
|
||||
const ok = await fs.transition(code, { projectId, toStatus: "CLOSED" });
|
||||
markPending(i, false);
|
||||
if (ok) setResolved((prev) => new Set(prev).add(i));
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="mb-4">
|
||||
<h2 className="text-xs font-semibold uppercase tracking-wide text-ink-soft">
|
||||
@@ -25,34 +95,171 @@ export function ForeshadowSuggestions({
|
||||
<p className="mt-1 text-xs text-ink-soft">无伏笔建议。</p>
|
||||
) : (
|
||||
<ul className="mt-2 space-y-2">
|
||||
{suggestions.map((s, i) => (
|
||||
<li
|
||||
key={i}
|
||||
className="rounded border border-line bg-panel p-2 text-xs"
|
||||
>
|
||||
<span
|
||||
className={`mr-1 rounded px-1.5 py-0.5 ${
|
||||
s.kind === "resolved"
|
||||
? "bg-pass/15 text-pass"
|
||||
: "bg-[var(--color-cinnabar-wash)] text-cinnabar"
|
||||
}`}
|
||||
{suggestions.map((s, i) => {
|
||||
const code = s.code;
|
||||
const isResolved = s.kind === "resolved";
|
||||
const done = isResolved ? resolved.has(i) : registered.has(i);
|
||||
const busy = pending.has(i);
|
||||
return (
|
||||
<li
|
||||
key={i}
|
||||
className="rounded border border-line bg-panel p-2 text-xs"
|
||||
>
|
||||
{s.kind === "resolved" ? "⚑ 疑似回收" : "+ 新埋待确认"}
|
||||
</span>
|
||||
{s.code ? (
|
||||
<span className="font-mono text-ink-soft"> {s.code}</span>
|
||||
) : null}
|
||||
<p className="mt-1 text-ink">{s.title}</p>
|
||||
{s.where ? (
|
||||
<span className="text-ink-soft">{s.where}</span>
|
||||
) : null}
|
||||
{s.note ? (
|
||||
<p className="mt-0.5 text-ink-soft">{s.note}</p>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
<span
|
||||
className={`mr-1 rounded px-1.5 py-0.5 ${
|
||||
isResolved
|
||||
? "bg-pass/15 text-pass"
|
||||
: "bg-[var(--color-cinnabar-wash)] text-cinnabar"
|
||||
}`}
|
||||
>
|
||||
{isResolved ? "⚑ 疑似回收" : "+ 新埋待确认"}
|
||||
</span>
|
||||
{code ? (
|
||||
<span className="font-mono text-ink-soft"> {code}</span>
|
||||
) : null}
|
||||
<p className="mt-1 text-ink">{s.title}</p>
|
||||
{s.where ? (
|
||||
<span className="text-ink-soft">{s.where}</span>
|
||||
) : null}
|
||||
{s.note ? <p className="mt-0.5 text-ink-soft">{s.note}</p> : null}
|
||||
|
||||
{/* 作者确认动作区 */}
|
||||
{done ? (
|
||||
<p className="mt-1.5 text-pass">
|
||||
✓ {isResolved ? "已标记回收" : "已登记"}
|
||||
</p>
|
||||
) : isResolved ? (
|
||||
code ? (
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void markResolved(i, code)}
|
||||
className="mt-1.5 rounded border border-pass px-2 py-0.5 text-pass hover:bg-pass/10 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
{busy ? "处理中…" : "✓ 标记回收"}
|
||||
</button>
|
||||
) : (
|
||||
<p className="mt-1.5 text-ink-soft">
|
||||
未关联编码,去伏笔看板处理。
|
||||
</p>
|
||||
)
|
||||
) : openIdx === i && form ? (
|
||||
<RegisterFormInline
|
||||
form={form}
|
||||
busy={busy}
|
||||
onChange={setForm}
|
||||
onSubmit={() => void submitRegister(i)}
|
||||
onCancel={closeForm}
|
||||
/>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => openRegister(i, s)}
|
||||
className="mt-1.5 rounded border border-cinnabar px-2 py-0.5 text-cinnabar hover:bg-cinnabar/10"
|
||||
>
|
||||
+ 登记此伏笔
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
interface RegisterFormInlineProps {
|
||||
form: RegisterFormState;
|
||||
busy: boolean;
|
||||
onChange: (form: RegisterFormState) => void;
|
||||
onSubmit: () => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
// 新埋伏笔登记表单:预填标题/埋设章/线索,code 给建议值可改(code/title 必填)。
|
||||
function RegisterFormInline({
|
||||
form,
|
||||
busy,
|
||||
onChange,
|
||||
onSubmit,
|
||||
onCancel,
|
||||
}: RegisterFormInlineProps) {
|
||||
const canSubmit =
|
||||
!busy && form.code.trim().length > 0 && form.title.trim().length > 0;
|
||||
const field =
|
||||
"w-full rounded border border-line bg-bg px-2 py-1 text-xs text-ink focus:border-cinnabar focus:outline-none";
|
||||
return (
|
||||
<div className="mt-2 space-y-1.5 border-t border-line pt-2">
|
||||
<div>
|
||||
<label htmlFor="fs-reg-code" className="text-ink-soft">
|
||||
编码
|
||||
</label>
|
||||
<input
|
||||
id="fs-reg-code"
|
||||
type="text"
|
||||
value={form.code}
|
||||
onChange={(e) => onChange({ ...form, code: e.target.value })}
|
||||
className={field}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="fs-reg-title" className="text-ink-soft">
|
||||
标题
|
||||
</label>
|
||||
<input
|
||||
id="fs-reg-title"
|
||||
type="text"
|
||||
value={form.title}
|
||||
onChange={(e) => onChange({ ...form, title: e.target.value })}
|
||||
className={field}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="fs-reg-planted" className="text-ink-soft">
|
||||
埋设章号
|
||||
</label>
|
||||
<input
|
||||
id="fs-reg-planted"
|
||||
type="number"
|
||||
min={1}
|
||||
value={form.plantedAt}
|
||||
onChange={(e) =>
|
||||
onChange({ ...form, plantedAt: Number(e.target.value) || 1 })
|
||||
}
|
||||
className={field}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="fs-reg-content" className="text-ink-soft">
|
||||
线索/正文(可选)
|
||||
</label>
|
||||
<textarea
|
||||
id="fs-reg-content"
|
||||
value={form.content}
|
||||
onChange={(e) => onChange({ ...form, content: e.target.value })}
|
||||
rows={2}
|
||||
className={`${field} resize-y`}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2 pt-0.5">
|
||||
<button
|
||||
type="button"
|
||||
disabled={!canSubmit}
|
||||
onClick={onSubmit}
|
||||
className="rounded bg-cinnabar px-2 py-0.5 text-panel hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
{busy ? "登记中…" : "确认登记"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={onCancel}
|
||||
className="rounded border border-line px-2 py-0.5 text-ink-soft hover:border-cinnabar hover:text-ink disabled:opacity-40"
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -25,8 +25,12 @@ import {
|
||||
groupConflicts,
|
||||
nextUnresolvedInOrder,
|
||||
} from "@/lib/review/grouping";
|
||||
import { applyConflictFix } from "@/lib/review/applyFix";
|
||||
import { locateInDraft } from "@/lib/review/locate";
|
||||
import { conflictSnippet } from "@/lib/review/snippet";
|
||||
import { useAccept } from "@/lib/review/useAccept";
|
||||
import { useAutosave } from "@/lib/autosave/useAutosave";
|
||||
import { useRefine } from "@/lib/style/useRefine";
|
||||
import { useReviewStream } from "@/lib/review/useReviewStream";
|
||||
import type { ReviewConflict, StyleDriftSegment } from "@/lib/review/sse";
|
||||
import { normalizeStyleDrift } from "@/lib/style/style";
|
||||
@@ -58,6 +62,10 @@ export function ReviewReport({
|
||||
}: ReviewReportProps) {
|
||||
const review = useReviewStream();
|
||||
const accept = useAccept();
|
||||
const conflictFix = useRefine(); // 采纳无补丁冲突时,临时调 AI 重写定位段
|
||||
// 审稿页草稿自动保存:采纳/手改/AI 改写后防抖 PUT /draft,改动随时留存、刷新不丢
|
||||
// (与「验收本章」解耦——验收前也能保存,修「采纳后没保存」)。
|
||||
const autosave = useAutosave(project.id, chapterNo, initialDraft);
|
||||
const toast = useToast();
|
||||
|
||||
const [finalText, setFinalText] = useState(initialDraft);
|
||||
@@ -66,6 +74,10 @@ export function ReviewReport({
|
||||
);
|
||||
const [focusedIndex, setFocusedIndex] = useState<number | null>(null);
|
||||
const [missing, setMissing] = useState<Set<number>>(new Set());
|
||||
// 正在 AI 改写的冲突下标(采纳无补丁 → 调 refine 重写定位段;用于卡片 loading/禁用)。
|
||||
const [rewriting, setRewriting] = useState<Set<number>>(new Set());
|
||||
// 可编辑终稿 textarea 引用:供「跳转」/采纳后在正文里选中定位问题区域。
|
||||
const editorRef = useRef<HTMLTextAreaElement>(null);
|
||||
// 回炉中的漂移段(null=未打开 RefineView)。
|
||||
const [refineSegment, setRefineSegment] = useState<StyleDriftSegment | null>(
|
||||
null,
|
||||
@@ -130,6 +142,18 @@ export function ReviewReport({
|
||||
}
|
||||
}, [review.state.phase, conflictCount]);
|
||||
|
||||
// 终稿改动(采纳/手改/AI 改写/直接编辑均经 setFinalText)→ 防抖自动保存草稿。
|
||||
// 跳过首帧:初值=已存草稿,useAutosave 基线即它,无需保存。
|
||||
const autosaveOnChange = autosave.onChange;
|
||||
const skipFirstAutosave = useRef(true);
|
||||
useEffect(() => {
|
||||
if (skipFirstAutosave.current) {
|
||||
skipFirstAutosave.current = false;
|
||||
return;
|
||||
}
|
||||
autosaveOnChange(finalText);
|
||||
}, [finalText, autosaveOnChange]);
|
||||
|
||||
const onReReview = (): void => {
|
||||
setMissing(new Set());
|
||||
void review.start(project.id, chapterNo, finalText);
|
||||
@@ -143,6 +167,65 @@ export function ReviewReport({
|
||||
next.delete(index);
|
||||
return next;
|
||||
});
|
||||
// 采纳改法:①带预出补丁(original→replacement)→ 瞬时改入终稿并选中;
|
||||
// ②有补丁但原文找不到(已手改/漂移)→ 提示手改;③无补丁但能在正文定位 →
|
||||
// 临时调 AI 重写该段并套入;④定位不到(摘要/跨章)→ 提示手改或忽略。
|
||||
if (verdict === "accept") {
|
||||
const c = conflicts[index];
|
||||
if (c) {
|
||||
const out = applyConflictFix(finalText, c.original, c.replacement);
|
||||
if (out.status === "applied") {
|
||||
const at = finalText.indexOf(c.original ?? "");
|
||||
setFinalText(out.text);
|
||||
toast("已采纳改入终稿,验收时请复核。", "success");
|
||||
if (at !== -1 && c.replacement) {
|
||||
selectRegionSoon(at, at + c.replacement.length, index);
|
||||
}
|
||||
} else if (out.status === "not-found") {
|
||||
toast("未在终稿中找到原文(可能已手改),请在左侧正文手改。", "error");
|
||||
} else {
|
||||
void aiFixOnAccept(index, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 无预出补丁的冲突,采纳时临时调 AI(refiner)重写定位到的那段原文,套入终稿并选中。
|
||||
// 定位不到(多为摘要/跨章问题)→ 不调 AI,提示手改/忽略。复用既有 refine 端点(不变量#3)。
|
||||
const aiFixOnAccept = async (
|
||||
index: number,
|
||||
c: ReviewConflict,
|
||||
): Promise<void> => {
|
||||
const loc = locateInDraft(finalText, c);
|
||||
if (loc === null) {
|
||||
toast("这条无法在正文定位(多为摘要/跨章问题),请手改或忽略。", "info");
|
||||
return;
|
||||
}
|
||||
const prevText = finalText;
|
||||
const segment = prevText.slice(loc.start, loc.end);
|
||||
setRewriting((s) => new Set(s).add(index));
|
||||
const res = await conflictFix.refine(
|
||||
project.id,
|
||||
chapterNo,
|
||||
segment,
|
||||
c.suggestion,
|
||||
);
|
||||
setRewriting((s) => {
|
||||
const next = new Set(s);
|
||||
next.delete(index);
|
||||
return next;
|
||||
});
|
||||
if (!res) return; // useRefine 已就失败 toast
|
||||
const at = prevText.indexOf(segment);
|
||||
if (at === -1) {
|
||||
toast("正文已变动,未能自动套用,请手改。", "error");
|
||||
return;
|
||||
}
|
||||
const next =
|
||||
prevText.slice(0, at) + res.refined + prevText.slice(at + segment.length);
|
||||
setFinalText(next);
|
||||
toast("已用 AI 改写并套入正文,请复核。", "success");
|
||||
selectRegionSoon(at, at + res.refined.length, index);
|
||||
};
|
||||
const onNote = (index: number, note: string): void =>
|
||||
setDrafts((prev) => setNote(prev, index, note));
|
||||
@@ -150,6 +233,14 @@ export function ReviewReport({
|
||||
// R2:按 type 分组 + 严重度排序(仅改显示顺序,每条仍携原始 index)。
|
||||
const groups = useMemo(() => groupConflicts(conflicts), [conflicts]);
|
||||
const order = useMemo(() => displayOrder(groups), [groups]);
|
||||
// 能在当前终稿里定位的冲突下标集合——只对这些显示「跳转」/锚点,避免点了定位不到刷错误提示。
|
||||
const locatable = useMemo(() => {
|
||||
const s = new Set<number>();
|
||||
conflicts.forEach((c, i) => {
|
||||
if (locateInDraft(finalText, c) !== null) s.add(i);
|
||||
});
|
||||
return s;
|
||||
}, [conflicts, finalText]);
|
||||
|
||||
const jumpToCard = (index: number): void => {
|
||||
setFocusedIndex(index);
|
||||
@@ -167,11 +258,54 @@ export function ReviewReport({
|
||||
}
|
||||
jumpToCard(next);
|
||||
};
|
||||
const jumpToAnchor = (index: number): void => {
|
||||
// 把命中区滚到视野(页面级 scrollIntoView,无内部滚动条);有对应 <mark> 用它居中,
|
||||
// 否则退回滚动编辑器本体。instant 滚动,天然尊重 prefers-reduced-motion。
|
||||
const scrollRegionIntoView = (index?: number): void => {
|
||||
const mark =
|
||||
index !== undefined
|
||||
? document.getElementById(`draft-mark-${index}`)
|
||||
: null;
|
||||
if (mark) {
|
||||
mark.scrollIntoView({ block: "center", behavior: "auto" });
|
||||
} else {
|
||||
editorRef.current?.scrollIntoView({ block: "center", behavior: "auto" });
|
||||
}
|
||||
};
|
||||
|
||||
// 在正文里选中 [start,end) 并滚动到视野;下一帧执行(等 value 落定)。
|
||||
const selectRegionSoon = (start: number, end: number, index?: number): void => {
|
||||
requestAnimationFrame(() => {
|
||||
const el = editorRef.current;
|
||||
if (!el) return;
|
||||
el.focus();
|
||||
el.setSelectionRange(start, end);
|
||||
scrollRegionIntoView(index);
|
||||
});
|
||||
};
|
||||
|
||||
// 闪烁高亮 <mark>(朱砂脉冲 0.9s);尊重 prefers-reduced-motion(CSS 内降级为描边)。
|
||||
const flashMark = (index: number): void => {
|
||||
const mark = document.getElementById(`draft-mark-${index}`);
|
||||
if (!mark) return;
|
||||
mark.classList.add("draft-mark-flash");
|
||||
window.setTimeout(() => mark.classList.remove("draft-mark-flash"), 900);
|
||||
};
|
||||
|
||||
// 跳转/锚点:在可编辑正文里定位、选中并滚动到该冲突对应区域 + 闪烁;定位不到则提示手动查找。
|
||||
const focusRegion = (index: number): void => {
|
||||
setFocusedIndex(index);
|
||||
document
|
||||
.getElementById(`anchor-${index}`)
|
||||
?.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||
const c = conflicts[index];
|
||||
const el = editorRef.current;
|
||||
if (!c || !el) return;
|
||||
const loc = locateInDraft(finalText, c);
|
||||
if (loc === null) {
|
||||
toast("未能在正文中定位该处,可能已改动,请手动查找。", "error");
|
||||
return;
|
||||
}
|
||||
el.focus();
|
||||
el.setSelectionRange(loc.start, loc.end);
|
||||
scrollRegionIntoView(index);
|
||||
flashMark(index);
|
||||
};
|
||||
|
||||
const onAccept = async (): Promise<void> => {
|
||||
@@ -252,26 +386,26 @@ export function ReviewReport({
|
||||
) : null}
|
||||
|
||||
<div className="flex-1 overflow-auto px-6 py-6">
|
||||
<div className="mb-2 flex items-start justify-between gap-3">
|
||||
<p className="text-xs text-ink-soft">
|
||||
可直接在下方正文修改(改动自动保存草稿 — 摘要从终稿提炼);点冲突的「跳转」或顶部锚点定位到对应文字。
|
||||
</p>
|
||||
<span className="shrink-0 font-mono text-xs text-ink-soft">
|
||||
{autosave.status === "saving"
|
||||
? "保存中…"
|
||||
: autosave.status === "error"
|
||||
? "保存失败"
|
||||
: (autosave.savedLabel ?? "")}
|
||||
</span>
|
||||
</div>
|
||||
<AnnotatedText
|
||||
text={finalText}
|
||||
value={finalText}
|
||||
onChange={setFinalText}
|
||||
conflicts={conflicts}
|
||||
focusedIndex={focusedIndex}
|
||||
onAnchorClick={jumpToCard}
|
||||
onAnchorClick={focusRegion}
|
||||
editorRef={editorRef}
|
||||
/>
|
||||
<details className="mt-4">
|
||||
<summary className="cursor-pointer text-xs text-ink-soft hover:text-cinnabar">
|
||||
展开/编辑终稿(裁决时可改稿 — 摘要从终稿提炼)
|
||||
</summary>
|
||||
<label htmlFor="final-text" className="sr-only">
|
||||
终稿正文
|
||||
</label>
|
||||
<textarea
|
||||
id="final-text"
|
||||
value={finalText}
|
||||
onChange={(e) => setFinalText(e.target.value)}
|
||||
className="mt-2 min-h-[20vh] w-full resize-y rounded border border-line bg-panel p-3 font-serif text-[16px] leading-[1.9] text-ink focus:border-cinnabar focus:outline-none"
|
||||
/>
|
||||
</details>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -341,9 +475,11 @@ export function ReviewReport({
|
||||
draft={drafts[i] ?? { verdict: null, note: "" }}
|
||||
missing={missing.has(i)}
|
||||
snippet={conflictSnippet(finalText, c.where)}
|
||||
locatable={locatable.has(i)}
|
||||
rewriting={rewriting.has(i)}
|
||||
onVerdict={onVerdict}
|
||||
onNote={onNote}
|
||||
onJump={jumpToAnchor}
|
||||
onJump={focusRegion}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
@@ -357,6 +493,8 @@ export function ReviewReport({
|
||||
<ForeshadowSuggestions
|
||||
suggestions={foreshadow}
|
||||
incomplete={sectionStatus("foreshadow") === "incomplete"}
|
||||
projectId={project.id}
|
||||
chapterNo={chapterNo}
|
||||
/>
|
||||
<PacePanel
|
||||
pace={pace}
|
||||
@@ -380,6 +518,8 @@ export function ReviewReport({
|
||||
|
||||
<section className="mt-4">
|
||||
<AcceptPanel
|
||||
projectId={project.id}
|
||||
chapterNo={chapterNo}
|
||||
conflictCount={conflictCount}
|
||||
unresolvedCount={resolved ? 0 : unresolved}
|
||||
foreshadowCount={foreshadow.length}
|
||||
|
||||
@@ -1,33 +1,84 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { buildChapterEntries, type ChapterEntry } from "@/lib/workbench/chapter";
|
||||
|
||||
interface ChapterListProps {
|
||||
projectId: string;
|
||||
// 大纲章节(来自 GET .../outline,无大纲时为空);当前章会被并入并去重。
|
||||
chapters: ChapterEntry[];
|
||||
currentChapterNo: number;
|
||||
}
|
||||
|
||||
// 左栏目录(UX §6.3)。M1 无章节列表端点 → 仅展示当前章占位。
|
||||
// 左栏目录(UX §6.3):列出大纲全部章节 + 当前章,点击切换写作章号(`?chapter=N`)。
|
||||
// 桌面 aside 包裹;移动端经 Workbench 抽屉复用 ChapterListContent。
|
||||
export function ChapterList({ currentChapterNo }: ChapterListProps) {
|
||||
export function ChapterList({
|
||||
projectId,
|
||||
chapters,
|
||||
currentChapterNo,
|
||||
}: ChapterListProps) {
|
||||
return (
|
||||
<aside className="hidden border-r border-line bg-panel py-4 lg:block">
|
||||
<ChapterListContent currentChapterNo={currentChapterNo} />
|
||||
<ChapterListContent
|
||||
projectId={projectId}
|
||||
chapters={chapters}
|
||||
currentChapterNo={currentChapterNo}
|
||||
/>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
export function ChapterListContent({ currentChapterNo }: ChapterListProps) {
|
||||
export function ChapterListContent({
|
||||
projectId,
|
||||
chapters,
|
||||
currentChapterNo,
|
||||
}: ChapterListProps) {
|
||||
const entries = buildChapterEntries(chapters, currentChapterNo);
|
||||
const hasOutline = chapters.length > 0;
|
||||
return (
|
||||
<>
|
||||
<h2 className="px-4 text-xs font-semibold uppercase tracking-wide text-ink-soft">
|
||||
目录
|
||||
</h2>
|
||||
<ul className="mt-2">
|
||||
<li>
|
||||
<span className="flex items-center gap-2 border-l-2 border-cinnabar bg-[var(--color-cinnabar-wash)] px-4 py-2 text-sm text-cinnabar">
|
||||
<span aria-hidden="true">●</span>第 {currentChapterNo} 章
|
||||
</span>
|
||||
</li>
|
||||
{entries.map((entry) => {
|
||||
const active = entry.no === currentChapterNo;
|
||||
return (
|
||||
<li key={entry.no}>
|
||||
<Link
|
||||
href={`/projects/${projectId}/write?chapter=${entry.no}`}
|
||||
aria-current={active ? "page" : undefined}
|
||||
className={
|
||||
active
|
||||
? "flex flex-col gap-0.5 border-l-2 border-cinnabar bg-[var(--color-cinnabar-wash)] px-4 py-2 text-sm text-cinnabar"
|
||||
: "flex flex-col gap-0.5 border-l-2 border-transparent px-4 py-2 text-sm text-ink hover:border-cinnabar hover:text-cinnabar"
|
||||
}
|
||||
>
|
||||
<span className="flex items-center gap-2">
|
||||
{active ? <span aria-hidden="true">●</span> : null}第{" "}
|
||||
{entry.no} 章
|
||||
</span>
|
||||
{entry.title ? (
|
||||
<span className="truncate text-xs text-ink-soft">
|
||||
{entry.title}
|
||||
</span>
|
||||
) : null}
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
<p className="mt-4 px-4 text-xs text-ink-soft/70">
|
||||
多卷多章目录将在大纲模块开放(后续里程碑)。
|
||||
</p>
|
||||
{!hasOutline ? (
|
||||
<p className="mt-4 px-4 text-xs text-ink-soft/70">
|
||||
还没有章节目录。
|
||||
<Link
|
||||
href={`/projects/${projectId}/outline`}
|
||||
className="text-cinnabar hover:underline"
|
||||
>
|
||||
去「大纲」生成
|
||||
</Link>
|
||||
。
|
||||
</p>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,10 @@ import type { ProjectResponse } from "@/lib/api/types";
|
||||
import { friendlyError } from "@/lib/errors/messages";
|
||||
import { useAutosave } from "@/lib/autosave/useAutosave";
|
||||
import { useDraftStream } from "@/lib/stream/useDraftStream";
|
||||
import { WORKBENCH_CHAPTER_NO } from "@/lib/workbench/chapter";
|
||||
import {
|
||||
WORKBENCH_CHAPTER_NO,
|
||||
type ChapterEntry,
|
||||
} from "@/lib/workbench/chapter";
|
||||
import { composeDirective, STYLE_PRESETS } from "@/lib/workbench/directive";
|
||||
import { ChapterList, ChapterListContent } from "./ChapterList";
|
||||
import { ChapterAssistant, AssistantContent } from "./ChapterAssistant";
|
||||
@@ -17,8 +20,12 @@ import { Editor } from "./Editor";
|
||||
|
||||
interface WorkbenchProps {
|
||||
project: ProjectResponse;
|
||||
// 当前章号(来自写作路由 `?chapter=N`);缺省回退第 1 章。
|
||||
chapterNo?: number;
|
||||
// RSC 种入的已存草稿正文(GET .../draft);无草稿(404)→ ""(空编辑器)。
|
||||
initialText?: string;
|
||||
// 大纲章节目录(GET .../outline);无大纲 → 空数组(目录回退到仅当前章 + 去大纲提示)。
|
||||
chapters?: ChapterEntry[];
|
||||
}
|
||||
|
||||
// 移动端右栏(目录/助手)经抽屉触达;桌面用三栏栅格。
|
||||
@@ -27,8 +34,12 @@ type MobilePanel = "chapters" | "assistant" | null;
|
||||
// M1:单章工作台。章节列表为占位(无章节列表端点);默认第 1 章。
|
||||
// WORKBENCH_CHAPTER_NO 移到 lib/workbench/chapter.ts(非客户端模块),供 Server Component 安全导入。
|
||||
|
||||
export function Workbench({ project, initialText = "" }: WorkbenchProps) {
|
||||
const chapterNo = WORKBENCH_CHAPTER_NO;
|
||||
export function Workbench({
|
||||
project,
|
||||
chapterNo = WORKBENCH_CHAPTER_NO,
|
||||
initialText = "",
|
||||
chapters = [],
|
||||
}: WorkbenchProps) {
|
||||
// 用已存草稿作初值;流式开始后由下方 effect 覆盖(流不会被初值反扑——
|
||||
// stream.state.text 起始为空,仅当 streaming/done/aborted 且变化才写回)。
|
||||
const [text, setText] = useState(initialText);
|
||||
@@ -85,7 +96,11 @@ export function Workbench({ project, initialText = "" }: WorkbenchProps) {
|
||||
activeNav="write"
|
||||
>
|
||||
<div className="grid h-[calc(100vh-var(--chrome,4rem))] grid-cols-1 lg:grid-cols-[12rem_1fr_18rem]">
|
||||
<ChapterList currentChapterNo={chapterNo} />
|
||||
<ChapterList
|
||||
projectId={project.id}
|
||||
chapters={chapters}
|
||||
currentChapterNo={chapterNo}
|
||||
/>
|
||||
|
||||
<section className="flex min-w-0 flex-col bg-bg">
|
||||
<DirectivePanel
|
||||
@@ -126,7 +141,11 @@ export function Workbench({ project, initialText = "" }: WorkbenchProps) {
|
||||
side="left"
|
||||
label="目录"
|
||||
>
|
||||
<ChapterListContent currentChapterNo={chapterNo} />
|
||||
<ChapterListContent
|
||||
projectId={project.id}
|
||||
chapters={chapters}
|
||||
currentChapterNo={chapterNo}
|
||||
/>
|
||||
</Drawer>
|
||||
<Drawer
|
||||
open={mobilePanel === "assistant"}
|
||||
|
||||
@@ -7,9 +7,23 @@ import {
|
||||
extractReason,
|
||||
groupByStatus,
|
||||
isWindowApproaching,
|
||||
suggestForeshadowCode,
|
||||
validationReasonMessage,
|
||||
} from "./board";
|
||||
|
||||
describe("suggestForeshadowCode", () => {
|
||||
it("prefers the suggestion's own code when present", () => {
|
||||
expect(suggestForeshadowCode("F-007", 3)).toBe("F-007");
|
||||
expect(suggestForeshadowCode(" F-008 ", 3)).toBe("F-008");
|
||||
});
|
||||
|
||||
it("falls back to FS-<2-digit index> when code is empty/null", () => {
|
||||
expect(suggestForeshadowCode(null, 0)).toBe("FS-01");
|
||||
expect(suggestForeshadowCode("", 4)).toBe("FS-05");
|
||||
expect(suggestForeshadowCode(" ", 11)).toBe("FS-12");
|
||||
});
|
||||
});
|
||||
|
||||
const view = (over: Partial<ForeshadowView>): ForeshadowView => ({
|
||||
code: "F-001",
|
||||
title: "线索",
|
||||
|
||||
@@ -59,6 +59,17 @@ export function isWindowApproaching(
|
||||
return currentChapter >= from && currentChapter <= to;
|
||||
}
|
||||
|
||||
// 为「新埋待确认」建议预填一个建议代号:优先用建议自带 code,否则 FS-<两位序号>。
|
||||
// 纯函数(可单测);作者可在登记表单里改。
|
||||
export function suggestForeshadowCode(
|
||||
code: string | null | undefined,
|
||||
index: number,
|
||||
): string {
|
||||
const trimmed = code?.trim();
|
||||
if (trimmed) return trimmed;
|
||||
return `FS-${String(index + 1).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export interface RegisterInput {
|
||||
projectId: string;
|
||||
code: string;
|
||||
|
||||
@@ -105,8 +105,22 @@ describe("extractIngestConflicts", () => {
|
||||
expect(out).toEqual({
|
||||
conflictCount: 2,
|
||||
conflicts: [
|
||||
{ type: "性格漂移", where: "第3章", refs: ["甲"], suggestion: "改" },
|
||||
{ type: "未分类", where: "", refs: [], suggestion: "" },
|
||||
{
|
||||
type: "性格漂移",
|
||||
where: "第3章",
|
||||
refs: ["甲"],
|
||||
suggestion: "改",
|
||||
original: null,
|
||||
replacement: null,
|
||||
},
|
||||
{
|
||||
type: "未分类",
|
||||
where: "",
|
||||
refs: [],
|
||||
suggestion: "",
|
||||
original: null,
|
||||
replacement: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
Binary file not shown.
44
apps/web/lib/review/applyFix.test.ts
Normal file
44
apps/web/lib/review/applyFix.test.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { applyConflictFix, hasApplicableFix } from "./applyFix";
|
||||
|
||||
describe("hasApplicableFix", () => {
|
||||
it("requires non-empty original and string replacement", () => {
|
||||
expect(hasApplicableFix("迈巴赫", "奔驰")).toBe(true);
|
||||
expect(hasApplicableFix("删我", "")).toBe(true); // 空串=删除,仍可应用
|
||||
expect(hasApplicableFix(null, "奔驰")).toBe(false);
|
||||
expect(hasApplicableFix("", "奔驰")).toBe(false);
|
||||
expect(hasApplicableFix("迈巴赫", null)).toBe(false);
|
||||
expect(hasApplicableFix(undefined, undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyConflictFix", () => {
|
||||
it("replaces the first occurrence of original with replacement", () => {
|
||||
const out = applyConflictFix(
|
||||
"他乘坐迈巴赫扬长而去,迈巴赫的尾灯。",
|
||||
"迈巴赫",
|
||||
"奔驰",
|
||||
);
|
||||
expect(out.status).toBe("applied");
|
||||
expect(out.text).toBe("他乘坐奔驰扬长而去,迈巴赫的尾灯。");
|
||||
});
|
||||
|
||||
it("returns not-found and leaves text untouched when original is absent (drift)", () => {
|
||||
const out = applyConflictFix("作者已经手改过的终稿。", "迈巴赫", "奔驰");
|
||||
expect(out.status).toBe("not-found");
|
||||
expect(out.text).toBe("作者已经手改过的终稿。");
|
||||
});
|
||||
|
||||
it("returns no-patch when conflict carries no applicable patch", () => {
|
||||
const out = applyConflictFix("正文", null, null);
|
||||
expect(out.status).toBe("no-patch");
|
||||
expect(out.text).toBe("正文");
|
||||
});
|
||||
|
||||
it("does not mutate the input string", () => {
|
||||
const original = "迈巴赫尾灯";
|
||||
applyConflictFix(original, "迈巴赫", "奔驰");
|
||||
expect(original).toBe("迈巴赫尾灯");
|
||||
});
|
||||
});
|
||||
42
apps/web/lib/review/applyFix.ts
Normal file
42
apps/web/lib/review/applyFix.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
// 一键采纳改法:把审稿提议的补丁(original→replacement)应用到终稿。
|
||||
// 纯逻辑(可单测,不依赖 DOM)。粒度=最小句段;找不到原文则不动正文(作者手改)。
|
||||
|
||||
export type FixOutcome =
|
||||
| { status: "applied"; text: string } // 命中原文并替换:text=改后终稿
|
||||
| { status: "not-found"; text: string } // 有补丁但终稿里找不到原文(作者已改稿/漂移):text 原样
|
||||
| { status: "no-patch"; text: string }; // 该冲突无可自动应用的补丁:text 原样
|
||||
|
||||
// 是否带可应用补丁:original 非空 + replacement 为字符串(容许空串=删除)。
|
||||
export function hasApplicableFix(
|
||||
original: string | null | undefined,
|
||||
replacement: string | null | undefined,
|
||||
): boolean {
|
||||
return (
|
||||
typeof original === "string" &&
|
||||
original.length > 0 &&
|
||||
typeof replacement === "string"
|
||||
);
|
||||
}
|
||||
|
||||
// 把首个匹配的 original 替换为 replacement(不可变:返回新串,不改入参)。
|
||||
// 无补丁 → no-patch;有补丁但未命中 → not-found(终稿不变);命中 → applied。
|
||||
export function applyConflictFix(
|
||||
text: string,
|
||||
original: string | null | undefined,
|
||||
replacement: string | null | undefined,
|
||||
): FixOutcome {
|
||||
if (!hasApplicableFix(original, replacement)) {
|
||||
return { status: "no-patch", text };
|
||||
}
|
||||
// hasApplicableFix 已收窄为 string。
|
||||
const from = original as string;
|
||||
const to = replacement as string;
|
||||
const idx = text.indexOf(from);
|
||||
if (idx === -1) {
|
||||
return { status: "not-found", text };
|
||||
}
|
||||
return {
|
||||
status: "applied",
|
||||
text: text.slice(0, idx) + to + text.slice(idx + from.length),
|
||||
};
|
||||
}
|
||||
@@ -9,7 +9,14 @@ import {
|
||||
import type { ReviewConflict } from "./sse";
|
||||
|
||||
function conflict(type: string, suggestion = "x"): ReviewConflict {
|
||||
return { type, where: "", refs: [], suggestion };
|
||||
return {
|
||||
type,
|
||||
where: "",
|
||||
refs: [],
|
||||
suggestion,
|
||||
original: null,
|
||||
replacement: null,
|
||||
};
|
||||
}
|
||||
|
||||
describe("groupConflicts", () => {
|
||||
|
||||
@@ -31,8 +31,22 @@ describe("normalizeConflicts", () => {
|
||||
]),
|
||||
);
|
||||
expect(out).toEqual([
|
||||
{ type: "设定违例", where: "第4段", refs: ["第30章"], suggestion: "统一血脉" },
|
||||
{ type: "时间线倒错", where: "第8段", refs: [], suggestion: "调整" },
|
||||
{
|
||||
type: "设定违例",
|
||||
where: "第4段",
|
||||
refs: ["第30章"],
|
||||
suggestion: "统一血脉",
|
||||
original: null,
|
||||
replacement: null,
|
||||
},
|
||||
{
|
||||
type: "时间线倒错",
|
||||
where: "第8段",
|
||||
refs: [],
|
||||
suggestion: "调整",
|
||||
original: null,
|
||||
replacement: null,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -41,7 +55,14 @@ describe("normalizeConflicts", () => {
|
||||
item([{ type: "", where: "", suggestion: "" }]),
|
||||
);
|
||||
expect(out).toEqual([
|
||||
{ type: "未分类", where: "", refs: [], suggestion: "" },
|
||||
{
|
||||
type: "未分类",
|
||||
where: "",
|
||||
refs: [],
|
||||
suggestion: "",
|
||||
original: null,
|
||||
replacement: null,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
@@ -34,6 +34,9 @@ export function normalizeConflicts(
|
||||
where: c.where,
|
||||
refs: c.refs ?? [],
|
||||
suggestion: c.suggestion,
|
||||
// 一键采纳补丁对:留痕里带则透传,供「采纳改法」find-replace 进终稿(缺省 null)。
|
||||
original: c.original ?? null,
|
||||
replacement: c.replacement ?? null,
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
54
apps/web/lib/review/locate.test.ts
Normal file
54
apps/web/lib/review/locate.test.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { extractDraftQuotes, locateInDraft } from "./locate";
|
||||
|
||||
const TEXT = "第一段没问题。\n\n他乘坐迈巴赫扬长而去,留下一地尘土。\n\n结尾。";
|
||||
|
||||
describe("locateInDraft", () => {
|
||||
it("locates the exact original fragment", () => {
|
||||
const loc = locateInDraft(TEXT, { original: "迈巴赫", where: "第2段" });
|
||||
expect(loc).not.toBeNull();
|
||||
expect(TEXT.slice(loc!.start, loc!.end)).toBe("迈巴赫");
|
||||
});
|
||||
|
||||
it("falls back to the paragraph snippet when no original", () => {
|
||||
const loc = locateInDraft(TEXT, { original: null, where: "第2段" });
|
||||
expect(loc).not.toBeNull();
|
||||
expect(TEXT.slice(loc!.start, loc!.end)).toBe(
|
||||
"他乘坐迈巴赫扬长而去,留下一地尘土。",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns null when original is absent from text and no paragraph hint", () => {
|
||||
expect(
|
||||
locateInDraft(TEXT, { original: "保时捷", where: "无段号" }),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when the snippet paragraph is out of range", () => {
|
||||
expect(locateInDraft(TEXT, { original: null, where: "第9段" })).toBeNull();
|
||||
});
|
||||
|
||||
it("locates via quoted draft text inside where (no original, no 段号)", () => {
|
||||
// 真实形态:where = 草稿中写"<草稿原文>",引号内即正文精确子串。
|
||||
const loc = locateInDraft(TEXT, {
|
||||
original: null,
|
||||
where: '草稿中写"迈巴赫扬长而去"',
|
||||
});
|
||||
expect(loc).not.toBeNull();
|
||||
expect(TEXT.slice(loc!.start, loc!.end)).toBe("迈巴赫扬长而去");
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractDraftQuotes", () => {
|
||||
it("extracts quoted spans (multiple quote styles) longest-first, deduped", () => {
|
||||
expect(extractDraftQuotes('草稿中写"长一些的原文",又如「短的」')).toEqual([
|
||||
"长一些的原文",
|
||||
"短的",
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns empty when there are no quotes", () => {
|
||||
expect(extractDraftQuotes("第3段,主角忽然示弱")).toEqual([]);
|
||||
});
|
||||
});
|
||||
66
apps/web/lib/review/locate.ts
Normal file
66
apps/web/lib/review/locate.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
// 在终稿里定位某条冲突对应的正文区间(供编辑器 setSelectionRange 高亮)。
|
||||
// 纯逻辑(可单测,不依赖 DOM)。定位优先级:精确 original → where 引号内原文 → 段级 snippet。
|
||||
|
||||
import type { ReviewConflict } from "./sse";
|
||||
import { conflictSnippet } from "./snippet";
|
||||
|
||||
export interface DraftRange {
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
// 抽取一段文本里所有成对引号内的内容(「」/“”/‘’/ 直双引号 / 直单引号)。
|
||||
// where 多形如 草稿中写"<草稿原文>" —— 引号里就是正文精确子串,是最可靠的定位锚。
|
||||
// 返回去重后按长度降序(长串更具体、误命中概率低)。
|
||||
const QUOTE_PATTERNS: RegExp[] = [
|
||||
/「([^」]{2,})」/g,
|
||||
/“([^”]{2,})”/g,
|
||||
/"([^"]{2,})"/g,
|
||||
/‘([^’]{2,})’/g,
|
||||
/'([^']{2,})'/g,
|
||||
];
|
||||
|
||||
export function extractDraftQuotes(where: string): string[] {
|
||||
const found = new Set<string>();
|
||||
for (const re of QUOTE_PATTERNS) {
|
||||
for (const m of where.matchAll(re)) {
|
||||
const inner = m[1]?.trim();
|
||||
if (inner && inner.length >= 2) found.add(inner);
|
||||
}
|
||||
}
|
||||
return [...found].sort((a, b) => b.length - a.length);
|
||||
}
|
||||
|
||||
// 返回冲突在 text 中的字符区间;定位不到(无 original/引号/段号,或已被改动)→ null。
|
||||
export function locateInDraft(
|
||||
text: string,
|
||||
conflict: Pick<ReviewConflict, "original" | "where">,
|
||||
): DraftRange | null {
|
||||
// 1) 精确原文片段(审稿提议的 original)逐字匹配——最可靠。
|
||||
if (conflict.original) {
|
||||
const idx = text.indexOf(conflict.original);
|
||||
if (idx !== -1) {
|
||||
return { start: idx, end: idx + conflict.original.length };
|
||||
}
|
||||
}
|
||||
// 2) 从 where 的引号里抽出草稿原文逐字匹配(覆盖 `草稿中写"…"` 这类定位)。
|
||||
for (const quote of extractDraftQuotes(conflict.where)) {
|
||||
const idx = text.indexOf(quote);
|
||||
if (idx !== -1) {
|
||||
return { start: idx, end: idx + quote.length };
|
||||
}
|
||||
}
|
||||
// 3) 回退:按 where 段号取段级预览,定位该段。snippet 超长会带省略号,
|
||||
// 去掉末尾「…」后用其前缀(仍是该段真实前缀)做 indexOf。
|
||||
const snippet = conflictSnippet(text, conflict.where);
|
||||
if (snippet) {
|
||||
const needle = snippet.endsWith("…") ? snippet.slice(0, -1) : snippet;
|
||||
if (needle.length > 0) {
|
||||
const idx = text.indexOf(needle);
|
||||
if (idx !== -1) {
|
||||
return { start: idx, end: idx + needle.length };
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -30,6 +30,8 @@ describe("parseReviewBlock", () => {
|
||||
where: "第4段",
|
||||
refs: ["第30章"],
|
||||
suggestion: "统一血脉设定",
|
||||
original: null,
|
||||
replacement: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -108,6 +110,8 @@ describe("parseReviewBlock", () => {
|
||||
where: "第1段",
|
||||
refs: ["第3章"],
|
||||
suggestion: "s",
|
||||
original: null,
|
||||
replacement: null,
|
||||
},
|
||||
});
|
||||
expect(
|
||||
@@ -142,7 +146,14 @@ describe("ReviewFrameBuffer", () => {
|
||||
expect(second).toEqual([
|
||||
{
|
||||
event: "conflict",
|
||||
data: { type: "性格漂移", where: "第2段", refs: [], suggestion: "x" },
|
||||
data: {
|
||||
type: "性格漂移",
|
||||
where: "第2段",
|
||||
refs: [],
|
||||
suggestion: "x",
|
||||
original: null,
|
||||
replacement: null,
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -165,11 +176,25 @@ describe("reduceReview", () => {
|
||||
const events: ReviewSseEvent[] = [
|
||||
{
|
||||
event: "conflict",
|
||||
data: { type: "设定违例", where: "a", refs: [], suggestion: "s1" },
|
||||
data: {
|
||||
type: "设定违例",
|
||||
where: "a",
|
||||
refs: [],
|
||||
suggestion: "s1",
|
||||
original: null,
|
||||
replacement: null,
|
||||
},
|
||||
},
|
||||
{
|
||||
event: "conflict",
|
||||
data: { type: "时间线倒错", where: "b", refs: ["第3章"], suggestion: "s2" },
|
||||
data: {
|
||||
type: "时间线倒错",
|
||||
where: "b",
|
||||
refs: ["第3章"],
|
||||
suggestion: "s2",
|
||||
original: null,
|
||||
replacement: null,
|
||||
},
|
||||
},
|
||||
];
|
||||
const state = events.reduce(reduceReview, initialReviewState);
|
||||
@@ -222,7 +247,14 @@ describe("reduceReview", () => {
|
||||
|
||||
let e = reduceReview(initialReviewState, {
|
||||
event: "conflict",
|
||||
data: { type: "能力不符", where: "x", refs: [], suggestion: "y" },
|
||||
data: {
|
||||
type: "能力不符",
|
||||
where: "x",
|
||||
refs: [],
|
||||
suggestion: "y",
|
||||
original: null,
|
||||
replacement: null,
|
||||
},
|
||||
});
|
||||
e = reduceReview(e, {
|
||||
event: "error",
|
||||
|
||||
@@ -15,6 +15,9 @@ export interface ReviewConflict {
|
||||
where: string;
|
||||
refs: string[];
|
||||
suggestion: string;
|
||||
// 一键采纳补丁对(可缺):可局部修复时审稿提议,前端「采纳改法」据此 find-replace 进终稿。
|
||||
original: string | null;
|
||||
replacement: string | null;
|
||||
}
|
||||
|
||||
export type SectionStatus = "started" | "done" | "incomplete";
|
||||
@@ -197,6 +200,8 @@ function narrowReviewEvent(event: string, data: unknown): ReviewSseEvent | null
|
||||
where: data.where,
|
||||
refs: asStringArray(data.refs),
|
||||
suggestion: data.suggestion,
|
||||
original: nullableString(data.original),
|
||||
replacement: nullableString(data.replacement),
|
||||
},
|
||||
}
|
||||
: null;
|
||||
|
||||
55
apps/web/lib/workbench/chapter.test.ts
Normal file
55
apps/web/lib/workbench/chapter.test.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
WORKBENCH_CHAPTER_NO,
|
||||
buildChapterEntries,
|
||||
parseChapterParam,
|
||||
} from "./chapter";
|
||||
|
||||
describe("parseChapterParam", () => {
|
||||
it("parses a valid positive chapter number", () => {
|
||||
expect(parseChapterParam("2")).toBe(2);
|
||||
expect(parseChapterParam("17")).toBe(17);
|
||||
});
|
||||
|
||||
it("takes the first value when given an array", () => {
|
||||
expect(parseChapterParam(["3", "9"])).toBe(3);
|
||||
});
|
||||
|
||||
it("falls back to chapter 1 for missing/invalid/<1 values", () => {
|
||||
expect(parseChapterParam(undefined)).toBe(WORKBENCH_CHAPTER_NO);
|
||||
expect(parseChapterParam("")).toBe(WORKBENCH_CHAPTER_NO);
|
||||
expect(parseChapterParam("abc")).toBe(WORKBENCH_CHAPTER_NO);
|
||||
expect(parseChapterParam("0")).toBe(WORKBENCH_CHAPTER_NO);
|
||||
expect(parseChapterParam("-4")).toBe(WORKBENCH_CHAPTER_NO);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildChapterEntries", () => {
|
||||
it("dedupes by no and sorts ascending", () => {
|
||||
const out = buildChapterEntries(
|
||||
[
|
||||
{ no: 3, title: "c3" },
|
||||
{ no: 1, title: "c1" },
|
||||
{ no: 3, title: "dup" },
|
||||
],
|
||||
1,
|
||||
);
|
||||
expect(out.map((e) => e.no)).toEqual([1, 3]);
|
||||
expect(out[1]?.title).toBe("c3"); // first wins on duplicate
|
||||
});
|
||||
|
||||
it("always includes the current chapter even if beyond the outline", () => {
|
||||
const out = buildChapterEntries([{ no: 1 }, { no: 2 }], 5);
|
||||
expect(out.map((e) => e.no)).toEqual([1, 2, 5]);
|
||||
});
|
||||
|
||||
it("returns just the current chapter when the outline is empty", () => {
|
||||
expect(buildChapterEntries([], 1)).toEqual([{ no: 1 }]);
|
||||
});
|
||||
|
||||
it("drops invalid chapter numbers from the outline", () => {
|
||||
const out = buildChapterEntries([{ no: 0 }, { no: -2 }, { no: 2 }], 1);
|
||||
expect(out.map((e) => e.no)).toEqual([1, 2]);
|
||||
});
|
||||
});
|
||||
@@ -3,3 +3,36 @@
|
||||
// 若从客户端组件(Workbench.tsx,"use client")导入,Next 会把它替换成客户端引用代理,
|
||||
// 服务端使用时变成抛错的函数 → draft URL 变成 `/chapters/function(){…}/draft`(422)。
|
||||
export const WORKBENCH_CHAPTER_NO = 1;
|
||||
|
||||
// 从写作路由的 `?chapter=N` 解析章号:取正整数,非法/缺省/<1 → 默认第 1 章。
|
||||
// 纯函数(可单测),供 write/page.tsx(Server Component)解析 searchParams。
|
||||
export function parseChapterParam(raw: string | string[] | undefined): number {
|
||||
const value = Array.isArray(raw) ? raw[0] : raw;
|
||||
if (value === undefined) return WORKBENCH_CHAPTER_NO;
|
||||
const n = Number.parseInt(value, 10);
|
||||
return Number.isInteger(n) && n >= 1 ? n : WORKBENCH_CHAPTER_NO;
|
||||
}
|
||||
|
||||
// 目录条目:章号 + 可选短标题(大纲无 title,用首个节拍当摘要)。
|
||||
export interface ChapterEntry {
|
||||
no: number;
|
||||
title?: string;
|
||||
}
|
||||
|
||||
// 合并大纲章节与「当前章」成目录:按章号去重 + 升序;当前章即使超出大纲也必含
|
||||
// (否则在写大纲外的新章时会从目录里消失,作者迷路)。纯函数(可单测)。
|
||||
export function buildChapterEntries(
|
||||
chapters: readonly ChapterEntry[],
|
||||
currentChapterNo: number,
|
||||
): ChapterEntry[] {
|
||||
const byNo = new Map<number, ChapterEntry>();
|
||||
for (const c of chapters) {
|
||||
if (Number.isInteger(c.no) && c.no >= 1 && !byNo.has(c.no)) {
|
||||
byNo.set(c.no, { no: c.no, title: c.title });
|
||||
}
|
||||
}
|
||||
if (!byNo.has(currentChapterNo)) {
|
||||
byNo.set(currentChapterNo, { no: currentChapterNo });
|
||||
}
|
||||
return [...byNo.values()].sort((a, b) => a.no - b.no);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user