730 lines
29 KiB
TypeScript
730 lines
29 KiB
TypeScript
import Link from "next/link";
|
||
import { useRouter } from "next/router";
|
||
import { useEffect, useRef, useState } from "react";
|
||
import {
|
||
ArrowUpRight,
|
||
Braces,
|
||
CheckCircle2,
|
||
FileText,
|
||
Globe2,
|
||
Link2,
|
||
ListChecks,
|
||
Plus,
|
||
ShieldCheck,
|
||
Trash2,
|
||
} from "lucide-react";
|
||
import GuidanceShell, { useGuidanceAccount } from "@/components/GuidanceShell";
|
||
import {
|
||
EmptyState,
|
||
KindBadge,
|
||
Notice,
|
||
PageHeading,
|
||
kindNames,
|
||
} from "@/components/GuidanceUI";
|
||
import { guidanceXml, type Guidance } from "@/content/guides/catalog";
|
||
import s from "@/styles/guidance.module.css";
|
||
const blank: Guidance = {
|
||
id: "",
|
||
revision: 1,
|
||
kind: "guide",
|
||
title: "",
|
||
summary: "",
|
||
applies: "",
|
||
body: "",
|
||
steps: [],
|
||
checks: [],
|
||
links: [],
|
||
tags: [],
|
||
};
|
||
type Preview = {
|
||
document: Guidance;
|
||
xml: string;
|
||
links: { label: string; when: string; resolved: boolean }[];
|
||
};
|
||
function fieldName(path: string) {
|
||
const labels: Record<string, string> = {
|
||
id: "文档短名",
|
||
revision: "版本",
|
||
kind: "文档类型",
|
||
title: "标题",
|
||
summary: "一句话摘要",
|
||
applies: "适用条件",
|
||
body: "正文",
|
||
steps: "建议步骤",
|
||
checks: "完成检查",
|
||
tags: "标签",
|
||
target: "目标文档 ID",
|
||
relation: "关系类型",
|
||
when: "读取条件",
|
||
label: "链接标题",
|
||
};
|
||
const [group, index, field] = path.split(".");
|
||
if (group === "links")
|
||
return (
|
||
"关联文档" +
|
||
(index === undefined ? "" : " " + (Number(index) + 1)) +
|
||
(field ? " · " + (labels[field] || "内容") : "")
|
||
);
|
||
return (
|
||
(labels[group] || "文档内容") +
|
||
(index !== undefined ? " " + (Number(index) + 1) : "")
|
||
);
|
||
}
|
||
async function responseBody(response: Response) {
|
||
const body = await response
|
||
.json()
|
||
.catch(() => ({ error: "服务返回异常,请稍后重试" }));
|
||
if (!response.ok)
|
||
throw Error(
|
||
(body.error || "请求失败") +
|
||
(body.fields?.length
|
||
? ":" + body.fields.map(fieldName).join("、")
|
||
: ""),
|
||
);
|
||
return body;
|
||
}
|
||
export default function Write() {
|
||
return (
|
||
<GuidanceShell title="发布文档">
|
||
<Editor />
|
||
</GuidanceShell>
|
||
);
|
||
}
|
||
function Editor() {
|
||
const account = useGuidanceAccount(),
|
||
router = useRouter(),
|
||
dialog = useRef<HTMLDialogElement>(null);
|
||
const [doc, setDoc] = useState<Guidance>(blank),
|
||
[xml, setXml] = useState(""),
|
||
[mode, setMode] = useState<"form" | "xml">("form"),
|
||
[busy, setBusy] = useState(false),
|
||
[loading, setLoading] = useState(false),
|
||
[error, setError] = useState(""),
|
||
[preview, setPreview] = useState<Preview | null>(null),
|
||
[published, setPublished] = useState<{
|
||
id: string;
|
||
revision: number;
|
||
} | null>(null),
|
||
[dirty, setDirty] = useState(true);
|
||
const prefix = account.user ? "user-" + account.user.id + "-" : "",
|
||
editId = typeof router.query.id === "string" ? router.query.id : "";
|
||
useEffect(() => {
|
||
if (!router.isReady || !account.user) return;
|
||
let active = true;
|
||
setError("");
|
||
setPublished(null);
|
||
setPreview(null);
|
||
setMode("form");
|
||
setDirty(true);
|
||
if (!editId) {
|
||
setDoc({
|
||
...blank,
|
||
id:
|
||
"user-" +
|
||
account.user.id +
|
||
"-document-" +
|
||
Math.random().toString(16).slice(2, 8),
|
||
});
|
||
setLoading(false);
|
||
return;
|
||
}
|
||
if (!editId.startsWith("user-" + account.user.id + "-")) {
|
||
setError("只能编辑你自己发布的文档。");
|
||
setDoc(blank);
|
||
return;
|
||
}
|
||
setLoading(true);
|
||
fetch("/api/documents/" + encodeURIComponent(editId))
|
||
.then(responseBody)
|
||
.then((body) => {
|
||
if (active)
|
||
setDoc({ ...body.document, revision: body.document.revision + 1 });
|
||
})
|
||
.catch((e) => {
|
||
if (active) {
|
||
setError(e.message);
|
||
setDoc(blank);
|
||
}
|
||
})
|
||
.finally(() => {
|
||
if (active) setLoading(false);
|
||
});
|
||
return () => {
|
||
active = false;
|
||
};
|
||
}, [account.user?.id, editId, router.isReady]);
|
||
function change<K extends keyof Guidance>(key: K, value: Guidance[K]) {
|
||
setDoc((current) => ({ ...current, [key]: value }));
|
||
setPreview(null);
|
||
setDirty(true);
|
||
setPublished(null);
|
||
}
|
||
async function request(action: "preview" | "publish" | "convert") {
|
||
setBusy(true);
|
||
setError("");
|
||
setPreview(null);
|
||
try {
|
||
const body = await responseBody(
|
||
await fetch(
|
||
"/api/documents" + (action === "publish" ? "" : "/preview"),
|
||
{
|
||
method: "POST",
|
||
headers: {
|
||
"Content-Type":
|
||
mode === "xml" ? "application/xml" : "application/json",
|
||
},
|
||
body: mode === "xml" ? xml : JSON.stringify(normalized()),
|
||
},
|
||
),
|
||
);
|
||
if (action === "convert") {
|
||
setDoc(body.document);
|
||
setMode("form");
|
||
} else if (action === "preview") {
|
||
setPreview(body);
|
||
dialog.current?.showModal();
|
||
} else {
|
||
setDoc({ ...body.document, revision: body.document.revision + 1 });
|
||
setXml(
|
||
guidanceXml({
|
||
...body.document,
|
||
revision: body.document.revision + 1,
|
||
}),
|
||
);
|
||
setPublished({
|
||
id: body.document.id,
|
||
revision: body.document.revision,
|
||
});
|
||
setDirty(false);
|
||
}
|
||
} catch (e) {
|
||
setError(e instanceof Error ? e.message : "请求失败,请稍后重试");
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
}
|
||
function normalized() {
|
||
return {
|
||
...doc,
|
||
steps: doc.steps.filter((step) => step.trim()),
|
||
checks: doc.checks.filter((check) => check.trim()),
|
||
tags: doc.tags.filter((tag) => tag.trim()),
|
||
};
|
||
}
|
||
function selectXml() {
|
||
setXml(guidanceXml(normalized()));
|
||
setMode("xml");
|
||
setPreview(null);
|
||
}
|
||
const authorized = account.user?.verified_at;
|
||
return (
|
||
<>
|
||
<PageHeading
|
||
title="发布独立文档"
|
||
description="一篇文档,一项清晰的指导。按需关联,让 Agent 自由选择。"
|
||
eyebrow={editId ? "UPDATE DOCUMENT" : "NEW DOCUMENT"}
|
||
/>
|
||
{account.loading ? (
|
||
<div className={s.accountLoading}>正在读取账户…</div>
|
||
) : !authorized ? (
|
||
<section className={`${s.panel} ${s.publishGate}`}>
|
||
<EmptyState
|
||
title={account.user ? "验证邮箱后继续" : "登录后开始编写"}
|
||
description={
|
||
account.error ||
|
||
"公开阅读无需登录。发布和维护文档,需要一个已验证的邮箱账户。"
|
||
}
|
||
>
|
||
<Link className={s.primaryButton} href="/account?next=%2Fwrite">
|
||
<ShieldCheck size={15} />
|
||
{account.user ? "前往验证邮箱" : "登录 / 创建账户"}
|
||
</Link>
|
||
</EmptyState>
|
||
</section>
|
||
) : (
|
||
<>
|
||
{error && <Notice tone="error">{error}</Notice>}
|
||
{published && (
|
||
<Notice tone="success">
|
||
版本 v{published.revision} 已公开发布。
|
||
<div className={s.successActions}>
|
||
<Link
|
||
href={
|
||
"/documents/" +
|
||
published.id +
|
||
"?revision=" +
|
||
published.revision
|
||
}
|
||
>
|
||
查看已发布版本
|
||
<ArrowUpRight size={12} />
|
||
</Link>
|
||
<Link href="/documents?scope=mine">查看我的文档</Link>
|
||
</div>
|
||
</Notice>
|
||
)}
|
||
{loading ? (
|
||
<div className={s.accountLoading}>正在加载最新版本…</div>
|
||
) : (
|
||
doc.id && (
|
||
<fieldset className={s.formFieldset} disabled={busy}>
|
||
<div className={s.editorTabs} aria-label="编辑方式">
|
||
<button
|
||
type="button"
|
||
aria-pressed={mode === "form"}
|
||
onClick={() => {
|
||
if (mode === "xml") void request("convert");
|
||
}}
|
||
>
|
||
可视化编辑
|
||
</button>
|
||
<button
|
||
type="button"
|
||
aria-pressed={mode === "xml"}
|
||
onClick={() => {
|
||
if (mode === "form") selectXml();
|
||
}}
|
||
>
|
||
协议 XML
|
||
</button>
|
||
</div>
|
||
<div className={s.formGrid}>
|
||
<div className={s.formSections}>
|
||
{mode === "xml" ? (
|
||
<section className={`${s.panel} ${s.formPanel}`}>
|
||
<h2 className={s.formSectionTitle}>
|
||
<Braces size={17} />
|
||
协议源文档
|
||
</h2>
|
||
<p className={s.formDescription}>
|
||
可直接粘贴完整
|
||
XML。切回可视化编辑时,会先校验并解析当前内容;校验失败时保留输入。
|
||
</p>
|
||
<label className={s.formField}>
|
||
<span className={s.fieldLabel}>XML 输入</span>
|
||
<textarea
|
||
className={`${s.textarea} ${s.xmlInput}`}
|
||
spellCheck={false}
|
||
value={xml}
|
||
onChange={(e) => {
|
||
setXml(e.target.value);
|
||
setDirty(true);
|
||
setPreview(null);
|
||
setPublished(null);
|
||
}}
|
||
/>
|
||
</label>
|
||
</section>
|
||
) : (
|
||
<>
|
||
<section className={`${s.panel} ${s.formPanel}`}>
|
||
<h2 className={s.formSectionTitle}>
|
||
<FileText size={17} />
|
||
基本信息
|
||
</h2>
|
||
<p className={s.formDescription}>
|
||
帮助读者和 Agent 判断,这篇文档是否适合当前任务。
|
||
</p>
|
||
<div className={s.fieldColumns}>
|
||
<label className={s.formField}>
|
||
<span className={s.fieldLabel}>文档短名</span>
|
||
<input
|
||
className={s.input}
|
||
aria-label="文档短名"
|
||
maxLength={37}
|
||
pattern="[a-z0-9-]+"
|
||
value={doc.id.slice(prefix.length)}
|
||
disabled={!!editId || doc.revision > 1}
|
||
onChange={(e) =>
|
||
change("id", prefix + e.target.value)
|
||
}
|
||
/>
|
||
<small className={s.fieldHint}>
|
||
小写字母、数字和连字符。发布后不可修改。
|
||
</small>
|
||
</label>
|
||
<label className={s.formField}>
|
||
<span className={s.fieldLabel}>文档类型</span>
|
||
<select
|
||
className={s.select}
|
||
value={doc.kind}
|
||
onChange={(e) =>
|
||
change(
|
||
"kind",
|
||
e.target.value as Guidance["kind"],
|
||
)
|
||
}
|
||
>
|
||
{Object.entries(kindNames).map(
|
||
([id, label]) => (
|
||
<option value={id} key={id}>
|
||
{label}
|
||
</option>
|
||
),
|
||
)}
|
||
</select>
|
||
</label>
|
||
</div>
|
||
{(["title", "summary", "applies"] as const).map(
|
||
(key) => (
|
||
<label className={s.formField} key={key}>
|
||
<span className={s.fieldLabel}>
|
||
{
|
||
{
|
||
title: "标题",
|
||
summary: "一句话摘要",
|
||
applies: "适用条件",
|
||
}[key]
|
||
}
|
||
<span className={s.required}>*</span>
|
||
</span>
|
||
{key === "title" ? (
|
||
<input
|
||
className={s.input}
|
||
value={doc[key]}
|
||
placeholder="例如:审查一次代码改动"
|
||
onChange={(e) =>
|
||
change(key, e.target.value)
|
||
}
|
||
/>
|
||
) : (
|
||
<textarea
|
||
className={s.textarea}
|
||
rows={2}
|
||
value={doc[key]}
|
||
placeholder={
|
||
key === "summary"
|
||
? "这篇文档可以帮助完成什么?"
|
||
: "什么情况下应该阅读?哪些情况不适用?"
|
||
}
|
||
onChange={(e) =>
|
||
change(key, e.target.value)
|
||
}
|
||
/>
|
||
)}
|
||
</label>
|
||
),
|
||
)}
|
||
<label className={s.formField}>
|
||
<span className={s.fieldLabel}>标签</span>
|
||
<input
|
||
className={s.input}
|
||
value={doc.tags.join(", ")}
|
||
placeholder="代码审查, 开发协作"
|
||
onChange={(e) =>
|
||
change(
|
||
"tags",
|
||
e.target.value
|
||
.split(/[,,]/)
|
||
.map((tag) => tag.trim()),
|
||
)
|
||
}
|
||
/>
|
||
<small className={s.fieldHint}>
|
||
使用逗号分隔。
|
||
</small>
|
||
</label>
|
||
</section>
|
||
<section className={`${s.panel} ${s.formPanel}`}>
|
||
<h2 className={s.formSectionTitle}>
|
||
<ListChecks size={17} />
|
||
指导内容
|
||
</h2>
|
||
<p className={s.formDescription}>
|
||
正文应当完整、可独立理解。步骤和检查项可以留空。
|
||
</p>
|
||
<label className={s.formField}>
|
||
<span className={s.fieldLabel}>
|
||
正文<span className={s.required}>*</span>
|
||
</span>
|
||
<textarea
|
||
className={`${s.textarea} ${s.bodyInput}`}
|
||
value={doc.body}
|
||
placeholder="写下清晰、具体的指导…"
|
||
onChange={(e) => change("body", e.target.value)}
|
||
/>
|
||
</label>
|
||
{(["steps", "checks"] as const).map((key) => (
|
||
<label className={s.formField} key={key}>
|
||
<span className={s.fieldLabel}>
|
||
{key === "steps" ? "建议步骤" : "完成检查"}
|
||
</span>
|
||
<textarea
|
||
className={s.textarea}
|
||
aria-label={
|
||
key === "steps" ? "建议步骤" : "完成检查"
|
||
}
|
||
rows={3}
|
||
value={doc[key].join("\n")}
|
||
onChange={(e) =>
|
||
change(key, e.target.value.split("\n"))
|
||
}
|
||
/>
|
||
<small className={s.fieldHint}>
|
||
每行一项,空行会在提交时忽略。
|
||
</small>
|
||
</label>
|
||
))}
|
||
</section>
|
||
<section className={`${s.panel} ${s.formPanel}`}>
|
||
<h2 className={s.formSectionTitle}>
|
||
<Link2 size={17} />
|
||
条件链接
|
||
<span className={s.neutralBadge}>
|
||
{doc.links.length}
|
||
</span>
|
||
</h2>
|
||
<p className={s.formDescription}>
|
||
仅当条件适用时,才建议读取关联文档。请指定固定版本;无需链接也可以独立发布。
|
||
</p>
|
||
{!doc.links.length && (
|
||
<div className={s.linkEmpty}>
|
||
还没有关联文档。你可以先完成正文,再为需要的场景补充链接。
|
||
</div>
|
||
)}
|
||
{doc.links.map((link, index) => (
|
||
<div className={s.linkEditor} key={index}>
|
||
<div className={s.linkEditorHeader}>
|
||
关联文档 {index + 1}
|
||
<button
|
||
type="button"
|
||
className={s.quietButton}
|
||
aria-label={"移除关联文档 " + (index + 1)}
|
||
onClick={() =>
|
||
change(
|
||
"links",
|
||
doc.links.filter((_, i) => i !== index),
|
||
)
|
||
}
|
||
>
|
||
<Trash2 size={13} />
|
||
移除
|
||
</button>
|
||
</div>
|
||
<div className={s.fieldColumns}>
|
||
{(
|
||
[
|
||
"target",
|
||
"revision",
|
||
"relation",
|
||
"label",
|
||
"when",
|
||
] as const
|
||
).map((key) => (
|
||
<label className={s.formField} key={key}>
|
||
<span className={s.fieldLabel}>
|
||
{
|
||
{
|
||
target: "目标文档 ID",
|
||
revision: "固定版本",
|
||
relation: "关系类型",
|
||
label: "链接标题",
|
||
when: "什么情况下读取",
|
||
}[key]
|
||
}
|
||
</span>
|
||
{key === "relation" ? (
|
||
<select
|
||
className={s.select}
|
||
value={link.relation}
|
||
onChange={(e) =>
|
||
change(
|
||
"links",
|
||
doc.links.map((item, i) =>
|
||
i === index
|
||
? {
|
||
...item,
|
||
relation: e.target
|
||
.value as Guidance["kind"],
|
||
}
|
||
: item,
|
||
),
|
||
)
|
||
}
|
||
>
|
||
{Object.entries(kindNames).map(
|
||
([id, label]) => (
|
||
<option value={id} key={id}>
|
||
{label}
|
||
</option>
|
||
),
|
||
)}
|
||
</select>
|
||
) : (
|
||
<input
|
||
className={s.input}
|
||
type={
|
||
key === "revision" ? "number" : "text"
|
||
}
|
||
min={key === "revision" ? 1 : undefined}
|
||
value={link[key]}
|
||
onChange={(e) =>
|
||
change(
|
||
"links",
|
||
doc.links.map((item, i) =>
|
||
i === index
|
||
? {
|
||
...item,
|
||
[key]:
|
||
key === "revision"
|
||
? Number(e.target.value)
|
||
: e.target.value,
|
||
}
|
||
: item,
|
||
),
|
||
)
|
||
}
|
||
/>
|
||
)}
|
||
</label>
|
||
))}
|
||
</div>
|
||
</div>
|
||
))}
|
||
<button
|
||
type="button"
|
||
className={s.secondaryButton}
|
||
onClick={() =>
|
||
change("links", [
|
||
...doc.links,
|
||
{
|
||
target: "",
|
||
revision: 1,
|
||
relation: "context",
|
||
when: "",
|
||
label: "",
|
||
},
|
||
])
|
||
}
|
||
>
|
||
<Plus size={14} />
|
||
添加条件链接
|
||
</button>
|
||
</section>
|
||
</>
|
||
)}
|
||
</div>
|
||
<aside className={s.publishSidebar}>
|
||
<section className={s.sideCard}>
|
||
<h3>
|
||
<Globe2 size={15} />
|
||
发布设置
|
||
</h3>
|
||
<div className={s.publishMeta}>
|
||
公开文档 · 待发布版本 v{doc.revision}
|
||
</div>
|
||
<KindBadge kind={doc.kind} />
|
||
<ul className={s.publishChecklist}>
|
||
<li className={s.completed}>
|
||
<CheckCircle2 size={14} />
|
||
邮箱已验证
|
||
</li>
|
||
<li>
|
||
<CheckCircle2 size={14} />
|
||
发布后任何人均可读取
|
||
</li>
|
||
<li>
|
||
<CheckCircle2 size={14} />
|
||
每次发布创建不可变版本
|
||
</li>
|
||
</ul>
|
||
<p>内容暂存在当前页面,请在离开前发布或自行保存 XML。</p>
|
||
<div className={s.publishButtons}>
|
||
<button
|
||
type="button"
|
||
className={s.secondaryButton}
|
||
onClick={() => void request("preview")}
|
||
>
|
||
校验并预览
|
||
</button>
|
||
<button
|
||
type="button"
|
||
className={s.primaryButton}
|
||
disabled={!dirty}
|
||
onClick={() => void request("publish")}
|
||
>
|
||
{busy
|
||
? "正在处理…"
|
||
: doc.revision === 1
|
||
? "发布文档"
|
||
: "发布新版本"}
|
||
</button>
|
||
</div>
|
||
</section>
|
||
<section className={s.sideCard}>
|
||
<h3>独立使用,按需连接</h3>
|
||
<p>
|
||
关系类型和适用条件帮助 Agent
|
||
选择下一篇文档。链接不会继承账户权限,也不要求整组加载。
|
||
</p>
|
||
<Link className={s.textLink} href="/protocol">
|
||
阅读协议说明
|
||
<ArrowUpRight size={12} />
|
||
</Link>
|
||
</section>
|
||
</aside>
|
||
</div>
|
||
</fieldset>
|
||
)
|
||
)}
|
||
</>
|
||
)}
|
||
<dialog
|
||
className={`${s.modal} ${s.largeModal}`}
|
||
ref={dialog}
|
||
aria-labelledby="preview-title"
|
||
>
|
||
<div className={s.modalBody}>
|
||
<h2 id="preview-title">发布预览</h2>
|
||
<p>校验已通过,内容尚未发布。请确认正文和关联条件。</p>
|
||
</div>
|
||
{preview && (
|
||
<div className={s.previewBody}>
|
||
<KindBadge kind={preview.document.kind} />
|
||
<h2 className={s.previewTitle}>{preview.document.title}</h2>
|
||
<p className={s.formDescription}>{preview.document.summary}</p>
|
||
<div className={s.appliesCard}>
|
||
<p>{preview.document.applies}</p>
|
||
</div>
|
||
<div className={s.proseBody}>{preview.document.body}</div>
|
||
{preview.document.steps.length > 0 && (
|
||
<ol className={s.stepList}>
|
||
{preview.document.steps.map((step, i) => (
|
||
<li key={i}>{step}</li>
|
||
))}
|
||
</ol>
|
||
)}
|
||
{preview.document.checks.length > 0 && (
|
||
<ul className={s.checkList}>
|
||
{preview.document.checks.map((check, i) => (
|
||
<li key={i}>{check}</li>
|
||
))}
|
||
</ul>
|
||
)}
|
||
{preview.links.map((link, i) => (
|
||
<div className={s.relationCard} key={i}>
|
||
<div>
|
||
<strong>{link.label}</strong>
|
||
<p>当{link.when}</p>
|
||
<small>
|
||
{link.resolved ? "固定版本可用" : "目标缺失,读取时需跳过"}
|
||
</small>
|
||
</div>
|
||
</div>
|
||
))}
|
||
</div>
|
||
)}
|
||
<div className={s.modalActions}>
|
||
<button
|
||
type="button"
|
||
className={s.secondaryButton}
|
||
onClick={() => dialog.current?.close()}
|
||
>
|
||
返回编辑
|
||
</button>
|
||
</div>
|
||
</dialog>
|
||
</>
|
||
);
|
||
}
|