Files
role-user/src/components/digital-home.tsx
T
湛兮 ae2b58e0b8 fix(chat): 恢复提前停止后的继续入口
- 以最近有效台词判断继续能力,停止前未出字时仍可重试
2026-10-27 18:20:49 +08:00

2105 lines
72 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";
/* eslint-disable @next/next/no-img-element -- 本地封面直接读取,避免在小型服务器上运行图片转换。 */
/** 星港数字人空间:探索、会话、世界书和身份资料的响应式入口。 */
import Link from "next/link";
import {
useCallback,
useEffect,
useRef,
useState,
type FormEvent,
type KeyboardEvent,
} from "react";
import {
ArrowLeft,
ArrowUp,
BookOpen,
Check,
Copy,
GitBranch,
Heart,
LoaderCircle,
LogOut,
MessageCircle,
MoreHorizontal,
Pin,
Plus,
Search,
Settings2,
Sparkles,
Square,
Trash2,
UserRound,
WandSparkles,
X,
RefreshCw,
Download,
ChevronDown,
ChevronRight,
} from "lucide-react";
import {
digital,
readStream,
type Card,
type Profile,
type Message,
type Settings,
type Conversation,
type Summary,
type Bootstrap,
} from "@/lib/digital";
import { ConversationRow, ConversationDeleteDialog } from "./conversation-row";
import "./digital.css";
type Tab = "discover" | "chats" | "library" | "me";
/** 接收文本与视觉打字分离;减少动画设置下直接呈现完整文本。 */
function TypedText({ text, animate }: { text: string; animate: boolean }) {
const [shown, setShown] = useState(animate ? "" : text);
const latest = useRef(text);
useEffect(() => {
latest.current = text;
}, [text]);
useEffect(() => {
if (!animate) return;
const instant = window.matchMedia(
"(prefers-reduced-motion: reduce)",
).matches;
const timer = setInterval(
() =>
setShown((current) => {
const target = latest.current;
if (instant || !target.startsWith(current)) return target;
const rest = Array.from(target.slice(current.length));
return (
current +
rest
.slice(0, Math.max(1, Math.min(10, Math.ceil(rest.length / 15))))
.join("")
);
}),
24,
);
return () => clearInterval(timer);
}, [animate]);
return <>{animate ? shown : text}</>;
}
/** 内容完全作为文本渲染,角色对白不允许注入 HTML。 */
function MessageText({
message,
animate,
}: {
message: Message;
animate: boolean;
}) {
if (message.status === "generating" && !message.content.trim())
return (
<span className="dh-thinking" role="status" aria-label="正在思考">
<i aria-hidden />
<i aria-hidden />
<i aria-hidden />
</span>
);
return (
<div className="dh-message-text">
<TypedText
text={
message.content ||
(message.status === "generating" ? "" : "这次没有生成内容。")
}
animate={animate}
/>
{message.status === "generating" && (
<span className="dh-caret" aria-hidden />
)}
</div>
);
}
/** 前台管理个人会话偏好;后台方案仅展示覆盖提示,不开放实验操作。 */
export function DigitalHome({
initial,
initialSummaries,
}: {
initial: Bootstrap;
initialSummaries: Summary[];
}) {
const [tab, setTab] = useState<Tab>("discover"),
[boot, setBoot] = useState<Bootstrap | null>(initial),
[summaries, setSummaries] = useState<Summary[]>(initialSummaries);
const [query, setQuery] = useState(""),
[tag, setTag] = useState("全部"),
[onlyFavorites, setOnlyFavorites] = useState(false);
const [detail, setDetail] = useState<Card | null>(null),
[conversation, setConversation] = useState<Conversation | null>(null);
const [draft, setDraft] = useState(""),
[busy, setBusy] = useState(false),
[opening, setOpening] = useState(false),
[error, setError] = useState(""),
[notice, setNotice] = useState("");
const [stylePolicy, setStylePolicy] = useState<
"loading" | "personal" | "managed" | "unknown"
>("loading");
const [showSettings, setShowSettings] = useState(false),
[settings, setSettings] = useState<Settings | null>(null),
[profile, setProfile] = useState<Profile | null>(initial.profile);
const [profileDraft, setProfileDraft] = useState<Profile | null>(
initial.profile,
);
const [selectionSheet, setSelectionSheet] = useState<
"style" | "books" | null
>(null);
const [choiceDraft, setChoiceDraft] = useState<{
presetId?: string;
bookIds: string[];
}>({ bookIds: [] });
const selectionTrigger = useRef<HTMLElement | null>(null);
const [swipedConversation, setSwipedConversation] = useState<string | null>(
null,
);
const [deleteTarget, setDeleteTarget] = useState<Summary | null>(null),
[deleting, setDeleting] = useState(false),
[deleteError, setDeleteError] = useState("");
const [ideasOpen, setIdeasOpen] = useState(false),
[ideasLoading, setIdeasLoading] = useState(false),
[ideas, setIdeas] = useState<string[]>([]),
[ideasError, setIdeasError] = useState("");
const ideasRequest = useRef<AbortController | null>(null),
imeComposing = useRef(false),
deleteLock = useRef(false);
const favoritePending = useRef(false);
const [activeMessage, setActiveMessage] = useState<string | null>(null),
[showJump, setShowJump] = useState(false),
[showMenu, setShowMenu] = useState(false);
const decisionReceived = useRef(0);
const stream = useRef<AbortController | null>(null),
streamingId = useRef<string | null>(null),
viewport = useRef<HTMLDivElement>(null),
messagesElement = useRef<HTMLDivElement>(null),
textarea = useRef<HTMLTextAreaElement>(null),
// 跟随是用户意图,内容增高导致暂时离底不能自动退出跟随。
atBottom = useRef(true),
touchY = useRef<number | null>(null),
draggingScroll = useRef(false),
currentId = useRef<string | null>(null),
openSequence = useRef(0);
const cards = boot?.catalog.filter((c) => c.kind === "character") ?? [],
books = boot?.catalog.filter((c) => c.kind === "worldbook") ?? [],
presets = boot?.catalog.filter((c) => c.kind === "preset") ?? [];
const conversationId = conversation?.id;
// 尚未产生正文的失败/停止不算新台词,继续时接回上一段;真实用户消息仍是边界。
const lastReply = conversation?.messages.findLast(
(m) =>
!(
m.role === "assistant" &&
["stopped", "failed"].includes(m.status) &&
!m.content.trim()
),
);
const canContinue =
lastReply?.role === "assistant" &&
["complete", "stopped"].includes(lastReply.status) &&
!!lastReply.content.trim();
// 状态提示走只读接口,打开设定不应写入实验分组、决策或曝光。
useEffect(() => {
if (!showSettings || !conversationId) return;
const controller = new AbortController();
digital<{ managed: boolean }>(
`conversations/${conversationId}/style-policy`,
"GET",
undefined,
controller.signal,
)
.then((policy) => {
if (!controller.signal.aborted)
setStylePolicy(policy.managed ? "managed" : "personal");
})
.catch(() => {
if (!controller.signal.aborted) setStylePolicy("unknown");
});
return () => controller.abort();
}, [showSettings, conversationId]);
const decisionExpiresAt = boot?.decision.expiresAt,
decisionServerNow = boot?.serverNow;
const currentCard = cards.find((c) => c.id === conversation?.characterId);
const reportError = useCallback(
(e: unknown) =>
setError(e instanceof Error ? e.message : "请求失败,请重试"),
[],
);
const refreshSummaries = useCallback(
async () => setSummaries(await digital<Summary[]>("conversations")),
[],
);
const reloadBootstrap = useCallback(async () => {
const data = await digital<Bootstrap>("bootstrap");
decisionReceived.current = performance.now();
setBoot(data);
setProfile(data.profile);
}, []);
useEffect(() => {
decisionReceived.current = performance.now();
}, [initial]);
useEffect(() => {
const timer = setInterval(() => {
if (!document.hidden && !streamingId.current)
reloadBootstrap().catch(() => {});
}, 45000);
const onVisible = () => {
if (!document.hidden && !streamingId.current)
reloadBootstrap().catch(() => {});
};
document.addEventListener("visibilitychange", onVisible);
return () => {
clearInterval(timer);
document.removeEventListener("visibilitychange", onVisible);
stream.current?.abort();
};
}, [reloadBootstrap]);
useEffect(() => {
if (!decisionExpiresAt || !decisionServerNow) return;
const lifetime = Math.max(
0,
Math.min(60000, decisionExpiresAt - decisionServerNow),
);
const remaining = Math.max(
0,
lifetime - (performance.now() - decisionReceived.current),
);
const timer = setTimeout(
() =>
setBoot((current) =>
current
? {
...current,
decision: {
...current.decision,
variant: current.decision.fallbackVariant,
value: current.decision.fallbackValue,
decisionId: null,
},
}
: current,
),
remaining,
);
return () => clearTimeout(timer);
}, [decisionExpiresAt, decisionServerNow]);
useEffect(() => {
if (!notice) return;
const timer = setTimeout(() => setNotice(""), 3500);
return () => clearTimeout(timer);
}, [notice]);
useEffect(() => {
const el = messagesElement.current,
view = viewport.current;
if (!el || !view) return;
let frame = 0;
const follow = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
if (!atBottom.current) return;
view.scrollTo({ top: view.scrollHeight, behavior: "instant" });
setShowJump(false);
});
};
// 同时观察内容与可视区:视觉打字、结束后的操作栏、输入框和软键盘都会改变底部位置。
const observer = new ResizeObserver(follow);
observer.observe(el);
observer.observe(view);
const endDrag = () => {
draggingScroll.current = false;
};
window.addEventListener("pointerup", endDrag);
window.addEventListener("pointercancel", endDrag);
follow();
return () => {
observer.disconnect();
cancelAnimationFrame(frame);
window.removeEventListener("pointerup", endDrag);
window.removeEventListener("pointercancel", endDrag);
};
}, [conversationId]);
useEffect(() => {
if (!conversationId) return;
const resize = () =>
document.documentElement.style.setProperty(
"--dh-viewport",
`${window.visualViewport?.height ?? window.innerHeight}px`,
);
resize();
window.visualViewport?.addEventListener("resize", resize);
return () => {
window.visualViewport?.removeEventListener("resize", resize);
document.documentElement.style.removeProperty("--dh-viewport");
};
}, [conversationId]);
useEffect(() => {
if (!conversationId) return;
try {
sessionStorage.setItem(`dh-draft:${conversationId}`, draft);
} catch {}
}, [draft, conversationId]);
useEffect(() => {
if (!detail && !showSettings) return;
const previous = document.activeElement as HTMLElement | null;
const dialog = document.querySelector<HTMLElement>(
'.dh-overlay [role="dialog"]',
);
const controls = () =>
Array.from(
(
document.querySelector<HTMLElement>(".dh-selection-sheet") ?? dialog
)?.querySelectorAll<HTMLElement>(
'button:not([disabled]),input,textarea,select,[tabindex="0"]',
) ?? [],
);
const frame = requestAnimationFrame(() => controls()[0]?.focus());
const onKey = (event: globalThis.KeyboardEvent) => {
if (event.key === "Escape") {
event.preventDefault();
if (document.querySelector(".dh-selection-sheet")) {
setSelectionSheet(null);
return;
}
setDetail(null);
setShowSettings(false);
}
if (event.key === "Tab") {
const items = controls(),
first = items[0],
last = items.at(-1);
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last?.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first?.focus();
}
}
};
document.addEventListener("keydown", onKey);
return () => {
cancelAnimationFrame(frame);
document.removeEventListener("keydown", onKey);
previous?.focus();
};
}, [detail, showSettings]);
/** 抽屉聚焦当前选项并限制滚动;取消、确认及切回桌面后恢复入口焦点。 */
useEffect(() => {
if (!selectionSheet) return;
const previous = selectionTrigger.current;
const media = window.matchMedia("(max-width: 600px)");
const resize = () => {
if (!media.matches) setSelectionSheet(null);
};
resize();
media.addEventListener("change", resize);
const frame = requestAnimationFrame(() => {
const panel = document.querySelector<HTMLElement>(".dh-selection-sheet");
(
panel?.querySelector<HTMLElement>("input:checked") ??
panel?.querySelector<HTMLElement>("input") ??
panel?.querySelector<HTMLElement>("button")
)?.focus();
});
return () => {
cancelAnimationFrame(frame);
media.removeEventListener("change", resize);
if (previous?.isConnected && previous.getClientRects().length)
previous.focus();
else
document
.querySelector<HTMLElement>(".dh-desktop-choices input:checked")
?.focus();
};
}, [selectionSheet]);
useEffect(() => {
const id = boot?.decision.decisionId;
if (!id || document.hidden) return;
const frame = requestAnimationFrame(() =>
digital("exposure", "POST", { decisionId: id }).catch(() => {}),
);
return () => cancelAnimationFrame(frame);
}, [boot?.decision.decisionId]);
useEffect(() => {
if (!busy || !conversationId || streamingId.current) return;
let cancelled = false;
const timer = setInterval(async () => {
if (document.hidden) return;
try {
const saved = await digital<Conversation>(
`conversations/${conversationId}`,
);
if (!cancelled && currentId.current === conversationId) {
setConversation(saved);
setBusy(saved.busy);
}
} catch {}
}, 2000);
return () => {
cancelled = true;
clearInterval(timer);
};
}, [busy, conversationId]);
async function openConversation(id: string) {
closeIdeas();
imeComposing.current = false;
setSwipedConversation(null);
if (streamingId.current && streamingId.current !== id) {
setNotice("请先停止当前回复,再切换会话");
return;
}
const sequence = ++openSequence.current;
setOpening(true);
setError("");
try {
const c = await digital<Conversation>(`conversations/${id}`);
if (sequence !== openSequence.current) return;
setConversation(c);
currentId.current = id;
setSettings(c.settings);
setBusy(c.busy);
setActiveMessage(null);
setShowMenu(false);
atBottom.current = true;
setShowJump(false);
try {
setDraft(sessionStorage.getItem(`dh-draft:${id}`) ?? "");
} catch {
setDraft("");
}
setTab("chats");
setDetail(null);
} catch (e) {
reportError(e);
} finally {
if (sequence === openSequence.current) setOpening(false);
}
}
async function start(card: Card, index = 0) {
if (opening) return;
setOpening(true);
setError("");
try {
const c = await digital<{ id: string }>("conversations", "POST", {
characterId: card.id,
greetingIndex: index,
uiDecisionId: boot?.decision.decisionId ?? undefined,
});
await openConversation(c.id);
await refreshSummaries();
} catch (e) {
reportError(e);
} finally {
setOpening(false);
}
}
async function favorite(card: Card) {
if (!profile || favoritePending.current) return;
favoritePending.current = true;
const next = {
...profile,
favorites: profile.favorites.includes(card.id)
? profile.favorites.filter((v) => v !== card.id)
: [...profile.favorites, card.id],
};
try {
await digital("profile", "PUT", next);
setProfile(next);
} catch (e) {
reportError(e);
} finally {
favoritePending.current = false;
}
}
async function send(mode: "send" | "regenerate" | "continue" = "send") {
if (
!conversation ||
busy ||
streamingId.current ||
(mode === "send" && !draft.trim())
)
return;
closeIdeas();
const id = conversation.id,
content = mode === "send" ? draft.trim() : "",
requestId = crypto.randomUUID();
let assistantId = `pending-${requestId}`;
setBusy(true);
setError("");
setNotice("");
atBottom.current = true;
setShowJump(false);
streamingId.current = id;
if (mode === "send") {
setDraft("");
if (textarea.current) textarea.current.style.height = "auto";
}
const local: Message[] = [
...(mode === "send"
? [
{
id: `user-${requestId}`,
role: "user" as const,
content,
status: "complete",
pinned: false,
},
]
: []),
{
id: assistantId,
role: "assistant",
content: "",
status: "generating",
pinned: false,
},
];
setConversation((c) =>
c && c.id === id ? { ...c, messages: [...c.messages, ...local] } : c,
);
setActiveMessage(assistantId);
const controller = new AbortController();
stream.current = controller;
let accepted = false;
try {
const response = await fetch(`/api/digital/conversations/${id}/stream`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
requestId,
content,
mode,
uiDecisionId: boot?.decision.decisionId ?? undefined,
}),
signal: controller.signal,
});
if (response.status === 401) {
window.location.assign("/login");
return;
}
accepted = response.ok;
await readStream(response, (event, data) => {
if (event === "start") {
const next = String(data.messageId);
setConversation((c) =>
c && c.id === id
? {
...c,
messages: c.messages.map((m) =>
m.id === assistantId ? { ...m, id: next } : m,
),
}
: c,
);
assistantId = next;
setActiveMessage(next);
}
if (event === "delta")
setConversation((c) =>
c && c.id === id
? {
...c,
messages: c.messages.map((m) =>
m.id === assistantId
? { ...m, content: m.content + String(data.text ?? "") }
: m,
),
}
: c,
);
if (event === "done")
setConversation((c) =>
c && c.id === id
? {
...c,
messages: c.messages.map((m) =>
m.id === assistantId
? { ...m, status: String(data.status) }
: m,
),
}
: c,
);
if (event === "notice" || event === "error")
setNotice(String(data.message ?? ""));
});
} catch (e) {
if (!controller.signal.aborted) reportError(e);
if (!accepted && mode === "send") setDraft(content);
} finally {
streamingId.current = null;
stream.current = null;
setBusy(false);
// 从数据库收敛临时消息和最终状态;取消后服务端可能仍在提交,延后一帧刷新。
await new Promise((resolve) => setTimeout(resolve, 200));
if (currentId.current === id)
try {
const saved = await digital<Conversation>(`conversations/${id}`);
setConversation(saved);
setBusy(saved.busy);
} catch (e) {
reportError(e);
}
refreshSummaries().catch(() => {});
}
}
async function stop() {
if (!conversation) return;
try {
await digital(`conversations/${conversation.id}/stop`, "POST", {});
if (!stream.current) {
await openConversation(conversation.id);
}
} catch (e) {
reportError(e);
}
}
function onKey(event: KeyboardEvent<HTMLTextAreaElement>) {
if (
event.key === "Enter" &&
!event.shiftKey &&
!imeComposing.current &&
!event.nativeEvent.isComposing &&
event.nativeEvent.keyCode !== 229
) {
event.preventDefault();
if (!event.repeat) void send();
}
}
async function pin(message: Message) {
if (!conversation) return;
try {
await digital(
`conversations/${conversation.id}/messages/${message.id}`,
"PATCH",
{ pinned: !message.pinned },
);
setConversation((c) =>
c
? {
...c,
messages: c.messages.map((m) =>
m.id === message.id ? { ...m, pinned: !m.pinned } : m,
),
}
: c,
);
setNotice(message.pinned ? "已取消固定" : "已加入固定记忆");
} catch (e) {
reportError(e);
}
}
async function branch(message: Message) {
if (!conversation || busy) return;
try {
const result = await digital<{ id: string }>(
`conversations/${conversation.id}/branch`,
"POST",
{ messageId: message.id },
);
await openConversation(result.id);
await refreshSummaries();
setNotice("已从这里开启新分支,原会话仍然保留");
} catch (e) {
reportError(e);
}
}
function requestDelete(target: Summary) {
if (target.id === conversation?.id && busy) {
setNotice("请先停止当前回复,再删除对话");
return;
}
setDeleteError("");
setDeleteTarget(target);
setShowMenu(false);
}
function removeConversation() {
if (conversation)
requestDelete({
id: conversation.id,
title: conversation.title,
characterId: conversation.characterId,
updatedAt: "",
});
}
async function confirmDelete() {
if (!deleteTarget || deleteLock.current) return;
const id = deleteTarget.id;
deleteLock.current = true;
setDeleting(true);
setDeleteError("");
try {
await digital(`conversations/${id}`, "DELETE");
setSummaries((current) => current.filter((s) => s.id !== id));
setSwipedConversation(null);
if (currentId.current === id) {
closeIdeas();
setConversation(null);
currentId.current = null;
setDraft("");
}
try {
sessionStorage.removeItem(`dh-draft:${id}`);
} catch {}
setDeleteTarget(null);
setNotice("对话已删除");
} catch (e) {
setDeleteError(e instanceof Error ? e.message : "删除失败,请重试");
} finally {
deleteLock.current = false;
setDeleting(false);
}
}
/** 灵感建议只填入草稿,旧请求和已离开的会话不能覆盖当前输入。 */
function closeIdeas() {
ideasRequest.current?.abort();
ideasRequest.current = null;
setIdeasOpen(false);
setIdeasLoading(false);
setIdeasError("");
setIdeas([]);
}
async function generateIdeas() {
if (!conversation || busy || streamingId.current || ideasRequest.current)
return;
const id = conversation.id,
anchor = conversation.messages.at(-1)?.id ?? null,
controller = new AbortController();
ideasRequest.current = controller;
setIdeasOpen(true);
setIdeasLoading(true);
setIdeasError("");
setIdeas([]);
try {
const result = await digital<{
suggestions: string[];
anchorId: string | null;
}>(
`conversations/${id}/suggestions`,
"POST",
{ draft: draft.slice(0, 1000) },
controller.signal,
);
if (ideasRequest.current !== controller || currentId.current !== id)
return;
if (result.anchorId !== anchor) {
setIdeasError("对话已更新,请重新打开会话后再试");
return;
}
setIdeas(result.suggestions);
} catch (e) {
if (!controller.signal.aborted && currentId.current === id)
setIdeasError(e instanceof Error ? e.message : "灵感生成失败,请重试");
} finally {
if (ideasRequest.current === controller) {
ideasRequest.current = null;
setIdeasLoading(false);
}
}
}
function chooseIdea(value: string) {
const next = draft
? `${draft}${draft.endsWith("\n") ? "" : "\n"}${value}`
: value;
if (next.length > 4000) {
setIdeasError("草稿已接近字数上限,请先缩短内容");
return;
}
setDraft(next);
closeIdeas();
setNotice("已加入草稿,可修改后发送");
requestAnimationFrame(() => {
const input = textarea.current;
if (input) {
input.focus();
input.style.height = "auto";
input.style.height = `${Math.min(input.scrollHeight, 160)}px`;
input.setSelectionRange(next.length, next.length);
}
});
}
function insertLineBreak() {
const input = textarea.current;
if (!input || draft.length >= 4000) return;
const start = input.selectionStart,
end = input.selectionEnd,
next = draft.slice(0, start) + "\n" + draft.slice(end);
setDraft(next);
requestAnimationFrame(() => {
input.focus();
input.setSelectionRange(start + 1, start + 1);
input.style.height = "auto";
input.style.height = `${Math.min(input.scrollHeight, 160)}px`;
});
}
/** 抽屉仅编辑临时值;确认后回填设定,取消不改动已有选择。 */
function openSelection(kind: "style" | "books") {
if (!settings) return;
selectionTrigger.current = document.activeElement as HTMLElement;
setChoiceDraft({
presetId: settings.presetId,
bookIds: [...settings.bookIds],
});
setSelectionSheet(kind);
}
function confirmSelection() {
if (settings)
setSettings({
...settings,
...(selectionSheet === "style"
? { presetId: choiceDraft.presetId }
: { bookIds: choiceDraft.bookIds }),
});
setSelectionSheet(null);
}
async function saveSettings(event: FormEvent) {
event.preventDefault();
if (!conversation || !settings) return;
try {
await digital(`conversations/${conversation.id}`, "PATCH", { settings });
setConversation((c) => (c ? { ...c, settings } : c));
setShowSettings(false);
setNotice(
stylePolicy === "managed"
? "设定已保存;当前叙事风格仍由统一方案控制"
: "对话设定已保存,下次回复生效",
);
} catch (e) {
reportError(e);
}
}
async function saveProfile(event: FormEvent) {
event.preventDefault();
if (!profile || !profileDraft) return;
const next = {
...profile,
userName: profileDraft.userName,
persona: profileDraft.persona,
};
try {
await digital("profile", "PUT", next);
setProfile(next);
setNotice("身份资料已保存");
} catch (e) {
reportError(e);
}
}
async function copy(text: string) {
try {
await navigator.clipboard.writeText(text);
setNotice("已复制");
} catch {
setNotice("当前浏览器无法访问剪贴板");
}
}
function exportChat() {
if (!conversation) return;
const text = conversation.messages
.map(
(m) =>
`${m.role === "user" ? "我" : (currentCard?.name ?? "角色")}:\n${m.content}`,
)
.join("\n\n");
const url = URL.createObjectURL(
new Blob([text], { type: "text/plain;charset=utf-8" }),
);
const a = document.createElement("a");
a.href = url;
a.download = `${conversation.title}.txt`;
a.click();
URL.revokeObjectURL(url);
}
function switchTab(value: Tab) {
closeIdeas();
setSwipedConversation(null);
if (conversation && busy) {
setNotice("请先停止当前回复,再离开会话");
return;
}
setConversation(null);
currentId.current = null;
setTab(value);
setError("");
}
const tags = [
"全部",
...new Set(cards.flatMap((c) => c.tags).slice(0, 30)),
].slice(0, 12);
const filtered = cards.filter(
(c) =>
(!query ||
`${c.name} ${c.description} ${c.tags.join(" ")}`
.toLowerCase()
.includes(query.toLowerCase())) &&
(tag === "全部" || c.tags.includes(tag)) &&
(!onlyFavorites || profile?.favorites.includes(c.id)),
);
const styleChoices = (
value: string | undefined,
onChange: (value: string | undefined) => void,
inSheet = false,
) => (
<fieldset className="dh-style-picker">
<legend className={inSheet ? "dh-visually-hidden" : undefined}>
叙事风格
</legend>
<p className="dh-style-help" role="status">
{stylePolicy === "loading"
? "正在确认风格设置…"
: stylePolicy === "managed"
? "当前使用统一叙事风格。可以保存个人偏好,统一风格解除后采用。"
: stylePolicy === "unknown"
? "暂时无法确认当前风格,可以先保存个人偏好。"
: "为这段故事选一种氛围,也可以跟随角色默认风格。"}
</p>
<div className="dh-style-options">
{[
{
id: "",
name: "角色默认风格",
description: "沿用角色原有的语气与叙事节奏。",
},
...presets,
...(value && !presets.some((p) => p.id === value)
? [
{
id: value,
name: "当前会话风格",
description: "这个风格暂不可用,回复时会采用可用的默认风格。",
},
]
: []),
].map((p) => (
<label className="dh-style-option" key={p.id}>
<input
type="radio"
name={
inSheet
? "conversation-preset-sheet"
: "conversation-preset-inline"
}
value={p.id}
checked={(value ?? "") === p.id}
onChange={() => onChange(p.id || undefined)}
/>
<span className="dh-style-card">
<span className="dh-style-symbol" aria-hidden="true">
{p.id ? <WandSparkles /> : <Sparkles />}
</span>
<span className="dh-style-copy">
<strong>{p.name}</strong>
<small>{p.description || "以这套风格继续你们的故事。"}</small>
</span>
<span className="dh-style-check" aria-hidden="true">
<Check />
</span>
</span>
</label>
))}
</div>
</fieldset>
);
const bookChoices = (
value: string[],
onChange: (value: string[]) => void,
inSheet = false,
) => (
<fieldset className="dh-book-picker">
<legend className={inSheet ? "dh-visually-hidden" : undefined}>
加入世界书
</legend>
{books.map((b) => (
<label
className={`dh-checkbox ${value.includes(b.id) ? "is-selected" : ""}`}
key={b.id}
>
<input
type="checkbox"
checked={value.includes(b.id)}
onChange={(e) =>
onChange(
e.target.checked
? [...value, b.id]
: value.filter((v) => v !== b.id),
)
}
/>
<span>
{b.name}
<small>{b.description}</small>
</span>
</label>
))}
</fieldset>
);
useEffect(
() => () => {
ideasRequest.current?.abort();
},
[],
);
// UI按消费者返回值决定,组名仅用于归因;C到Z同样可以返回新版UI。
// 缺少value时兼容尚未升级的服务响应。
const modern =
boot?.decision.value !== undefined
? boot.decision.value === "new" || boot.decision.value === true
: boot?.decision.variant === "B";
return (
<div
className={`dh-app ${modern ? "dh-modern" : "dh-classic"} ${conversation ? "dh-in-chat" : ""}`}
>
<aside className="dh-sidebar">
<Link className="dh-brand" href="/discover">
<span className="dh-brand-mark">✦</span> 星港
<span className="dh-brand-en">STELLAR</span>
</Link>
<p className="dh-sidebar-caption">每一段相遇,都有下一章</p>
<nav aria-label="主要导航">
{(
[
{ id: "discover", label: "发现角色", icon: Sparkles },
{ id: "chats", label: "我的对话", icon: MessageCircle },
{ id: "library", label: "灵感书架", icon: BookOpen },
{ id: "me", label: "我的身份", icon: UserRound },
] as const
).map((item) => (
<button
key={item.id}
className={tab === item.id ? "is-active" : ""}
onClick={() => switchTab(item.id)}
>
<item.icon size={19} />
<span>{item.label}</span>
{item.id === "chats" && summaries.length > 0 && (
<small>{summaries.length}</small>
)}
</button>
))}
</nav>
<div className="dh-sidebar-bottom">
<span className="dh-avatar">
{profile?.userName?.slice(0, 1) || "旅"}
</span>
<div>
<strong>{profile?.userName || "旅人"}</strong>
<small>你的私人数字人空间</small>
</div>
<a aria-label="退出登录" href="/api/auth/logout?next=/login">
<LogOut size={17} />
</a>
</div>
</aside>
<main className="dh-main">
{error && (
<div className="dh-error" role="alert">
{error}
<button aria-label="关闭错误" onClick={() => setError("")}>
<X size={16} />
</button>
</div>
)}
{notice && (
<div className="dh-toast" role="status">
{notice}
</div>
)}
{!boot ? (
<div className="dh-loading">
<LoaderCircle className="dh-spin" />
<span>正在开启你的星港…</span>
</div>
) : conversation ? (
<section className="dh-chat">
<header className="dh-chat-header">
<button
className="dh-icon"
aria-label="返回对话列表"
disabled={busy}
onClick={() => {
setConversation(null);
currentId.current = null;
}}
>
<ArrowLeft size={21} />
</button>
{currentCard?.cover && <img src={currentCard.cover} alt="" />}
<div>
<h1>{currentCard?.name ?? conversation.title}</h1>
<small>
<i /> {busy ? "正在回应你" : "故事由你们续写"}
</small>
</div>
<button
className="dh-icon"
aria-label="对话设定"
onClick={() => {
setSettings(conversation.settings);
setStylePolicy("loading");
setShowSettings(true);
}}
>
<Settings2 size={20} />
</button>
<button
className="dh-icon"
aria-label="更多对话操作"
aria-expanded={showMenu}
onClick={() => setShowMenu(!showMenu)}
>
<MoreHorizontal size={21} />
</button>
{showMenu && (
<div className="dh-chat-menu">
<button onClick={exportChat}>
<Download size={16} />
导出对话
</button>
<button disabled={busy} onClick={removeConversation}>
<Trash2 size={16} />
删除会话
</button>
</div>
)}
</header>
<div
className="dh-chat-backdrop"
style={{
backgroundImage: currentCard?.cover
? `url("${currentCard.cover.replaceAll('"', "%22")}")`
: undefined,
}}
/>
<div
className="dh-messages"
ref={viewport}
tabIndex={0}
aria-label="聊天消息"
onWheel={(event) => {
if (event.deltaY < 0 && event.currentTarget.scrollTop > 0)
atBottom.current = false;
}}
onTouchStart={(event) => {
touchY.current = event.touches[0]?.clientY ?? null;
}}
onTouchMove={(event) => {
const y = event.touches[0]?.clientY;
if (
y !== undefined &&
touchY.current !== null &&
y > touchY.current &&
event.currentTarget.scrollTop > 0
)
atBottom.current = false;
touchY.current = y ?? null;
}}
onTouchEnd={() => {
touchY.current = null;
}}
onPointerDown={(event) => {
draggingScroll.current =
event.pointerType === "mouse" &&
event.target === event.currentTarget;
}}
onKeyDown={(event) => {
if (["ArrowUp", "PageUp", "Home"].includes(event.key))
atBottom.current = false;
}}
onScroll={() => {
const v = viewport.current;
if (v) {
const gap = v.scrollHeight - v.scrollTop - v.clientHeight;
if (gap <= 2) atBottom.current = true;
else if (draggingScroll.current) atBottom.current = false;
setShowJump(!atBottom.current && gap > 80);
}
}}
>
<div ref={messagesElement} className="dh-messages-inner">
<div className="dh-chat-intro">
<span>✦</span>
<p>这里是你与 {currentCard?.name} 的私人故事</p>
<small>内容由 AI 生成,虚构世界中的角色可能会犯错。</small>
</div>
{conversation.messages.map((m, index) => (
<article
className={`dh-message dh-message-${m.role}`}
key={m.id}
>
{m.role === "assistant" && (
<img
className="dh-message-avatar"
src={currentCard?.cover || "/icon.svg"}
alt=""
/>
)}
<div className="dh-message-body">
<span className="dh-message-name">
{m.role === "user"
? conversation.settings.userName
: currentCard?.name}
{m.pinned && <Pin size={11} />}
</span>
<div className="dh-bubble">
<MessageText
message={m}
animate={
m.id === activeMessage && m.status === "generating"
}
/>
</div>
{!busy && m.content && (
<div className="dh-message-actions">
<button
aria-label="复制消息"
title="复制"
onClick={() => copy(m.content)}
>
<Copy size={13} />
</button>
<button
aria-label={
m.pinned ? "取消固定记忆" : "固定为记忆"
}
title="固定记忆"
className={m.pinned ? "is-active" : ""}
onClick={() => pin(m)}
>
<Pin size={13} />
</button>
<button
aria-label="从此处分支"
title="从此处创建分支"
onClick={() => branch(m)}
>
<GitBranch size={13} />
</button>
{m.role === "assistant" &&
index === conversation.messages.length - 1 &&
conversation.messages.some(
(v) => v.role === "user",
) && (
<button
aria-label="重新生成"
title="换一个回答"
onClick={() => send("regenerate")}
>
<RefreshCw size={13} />
</button>
)}
</div>
)}
{!busy &&
!m.content &&
m.role === "assistant" &&
index === conversation.messages.length - 1 &&
conversation.messages.some(
(v) => v.role === "user",
) && (
<button
className="dh-text-button"
aria-label="重新生成"
onClick={() => send("regenerate")}
>
<RefreshCw size={13} /> 重新生成
</button>
)}
{m.status === "failed" && (
<small className="dh-message-status">
生成失败,可重新生成
</small>
)}
{m.status === "superseded" && (
<small className="dh-message-status">此前回答</small>
)}
{m.status === "stopped" && (
<small className="dh-message-status">已停止</small>
)}
</div>
</article>
))}
</div>
</div>
{showJump && (
<button
className="dh-jump"
onClick={() => {
atBottom.current = true;
setShowJump(false);
viewport.current?.scrollTo({
top: viewport.current.scrollHeight,
behavior: "instant",
});
}}
>
<ChevronDown size={16} />
回到最新
</button>
)}
<div className="dh-composer-wrap">
{ideasOpen && (
<section
className="dh-reply-ideas"
aria-label="灵感回复"
aria-busy={ideasLoading}
>
<header>
<strong>
<Sparkles size={14} />
灵感回复
</strong>
<button
type="button"
className="dh-icon"
aria-label="关闭灵感回复"
onClick={closeIdeas}
>
<X size={16} />
</button>
</header>
<p className="dh-ideas-note">
{draft
? "选择后追加到现有草稿,不会自动发送。"
: "根据当前对话生成,选择后可编辑再发送。"}
</p>
{ideasLoading ? (
<p className="dh-ideas-loading" role="status">
<LoaderCircle size={16} className="dh-spin" />
正在寻找合适的接话方式…
</p>
) : ideasError ? (
<p className="dh-ideas-error" role="alert">
{ideasError}
</p>
) : (
<div className="dh-ideas-list">
{ideas.map((idea, i) => (
<button
type="button"
key={i}
onClick={() => chooseIdea(idea)}
>
<small>{i + 1}</small>
<span>{idea}</span>
</button>
))}
</div>
)}
{!ideasLoading && (
<button
type="button"
className="dh-ideas-refresh"
onClick={generateIdeas}
>
<RefreshCw size={13} />
{ideasError ? "重新生成" : "换一组"}
</button>
)}
</section>
)}
<div className="dh-compose-tools">
<div className="dh-compose-actions">
<button
type="button"
disabled={busy || ideasLoading}
onClick={generateIdeas}
>
<Sparkles size={14} />
{ideasLoading ? "灵感生成中…" : "灵感回复"}
</button>
<button
type="button"
aria-label="让角色继续"
title="不发送输入框里的草稿,让角色接着说"
disabled={busy || ideasLoading || !canContinue}
onClick={() => send("continue")}
>
<ChevronRight size={14} />
继续
</button>
</div>
<button
type="button"
className="dh-mobile-linebreak"
onClick={insertLineBreak}
>
换行
</button>
</div>
<div className="dh-composer">
<textarea
ref={textarea}
aria-label="消息"
placeholder={`对 ${currentCard?.name ?? "角色"} 说点什么…`}
value={draft}
maxLength={4000}
rows={1}
onChange={(e) => {
setDraft(e.target.value);
e.target.style.height = "auto";
e.target.style.height = `${Math.min(e.target.scrollHeight, 160)}px`;
}}
enterKeyHint="send"
onCompositionStart={() => {
imeComposing.current = true;
}}
onCompositionEnd={() => {
imeComposing.current = false;
}}
onKeyDown={onKey}
/>
{busy ? (
<button
className="dh-send is-stop"
aria-label="停止生成"
onClick={stop}
>
<Square size={17} fill="currentColor" />
</button>
) : (
<button
className="dh-send"
aria-label="发送消息"
disabled={!draft.trim()}
onClick={() => send()}
>
<ArrowUp size={21} />
</button>
)}
</div>
<small className="dh-composer-hint">
{busy
? "正在生成 · 点击方块随时停止"
: "Enter 发送 · Shift + Enter 换行"}
<span>
{draft.length > 3500
? `${draft.length}/4000`
: "一段对白,一个新的可能"}
</span>
</small>
</div>
</section>
) : (
<div className="dh-page">
<header className="dh-page-header">
<div>
<p className="dh-eyebrow">YOUR PRIVATE UNIVERSE</p>
<h1>
{tab === "discover"
? "遇见,让故事开始"
: tab === "chats"
? "故事还在继续"
: tab === "library"
? "为想象力,留一盏灯"
: "你想以谁的身份相遇?"}
</h1>
</div>
<span className="dh-header-orbit" aria-hidden>
✦
</span>
</header>
{tab === "discover" && (
<>
<section className="dh-hero">
<div>
<span className="dh-pill">今晚,有人等你开口</span>
<h2>
不止聊天。
<br />
走进另一个人的世界。
</h2>
<p>
一封未寄出的信,一次雨夜的重逢。
<br />
挑选你心动的角色,写下只属于你们的下一章。
</p>
<button
className="dh-primary"
onClick={() => {
const card =
cards.find(
(c) => !profile?.favorites.includes(c.id),
) ?? cards[0];
if (card) setDetail(card);
}}
>
<WandSparkles size={16} />
给我一次奇遇
</button>
</div>
<div className="dh-hero-art" aria-hidden>
{cards.slice(0, 3).map((c) => (
<img key={c.id} src={c.cover} alt="" />
))}
<span className="dh-orbit">✧</span>
</div>
</section>
<div className="dh-discovery-tools">
<label className="dh-search">
<Search size={18} />
<input
aria-label="搜索角色"
placeholder="搜索名字、性格或故事…"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
{query && (
<button
aria-label="清空搜索"
onClick={() => setQuery("")}
>
<X size={15} />
</button>
)}
</label>
<button
className={`dh-favorite-filter ${onlyFavorites ? "is-active" : ""}`}
onClick={() => setOnlyFavorites(!onlyFavorites)}
>
<Heart
size={17}
fill={onlyFavorites ? "currentColor" : "none"}
/>
我的收藏
</button>
</div>
<div className="dh-tags" aria-label="角色标签">
{tags.map((t) => (
<button
key={t}
className={tag === t ? "is-active" : ""}
onClick={() => setTag(t)}
>
{t}
</button>
))}
</div>
<div className="dh-section-heading">
<h2>{onlyFavorites ? "心动收藏" : "为你发现"}</h2>
<span>{filtered.length} 位角色 · 全部成年</span>
</div>
<div className="dh-card-grid">
{filtered.map((c) => (
<article className="dh-card" key={c.id}>
<button
className="dh-card-open"
onClick={() => setDetail(c)}
>
<img
src={c.cover || "/icon.svg"}
alt={c.name}
loading="lazy"
/>
<div className="dh-card-shade" />
<div className="dh-card-content">
<span className="dh-card-kicker">
{c.tags[0] ?? "初次相遇"} · {c.age}+
</span>
<h3>{c.name}</h3>
<p>{c.description}</p>
<div className="dh-card-tags">
{c.tags.slice(1, 3).map((t) => (
<span key={t}>{t}</span>
))}
</div>
</div>
</button>
<button
className={`dh-card-favorite ${profile?.favorites.includes(c.id) ? "is-active" : ""}`}
aria-label={`收藏${c.name}`}
onClick={() => favorite(c)}
>
<Heart
size={17}
fill={
profile?.favorites.includes(c.id)
? "currentColor"
: "none"
}
/>
</button>
</article>
))}
</div>
{!filtered.length && (
<div className="dh-empty">
<Search />
<h3>暂时没有找到</h3>
<p>换一个关键词,或者看看其他故事。</p>
<button
onClick={() => {
setTag("全部");
setQuery("");
setOnlyFavorites(false);
}}
>
看看全部角色
</button>
</div>
)}
</>
)}
{tab === "chats" && (
<>
<div className="dh-section-heading">
<h2>最近对话</h2>
<button onClick={() => switchTab("discover")}>
<Plus size={16} />
开启新故事
</button>
</div>
{summaries.length > 0 && (
<p className="dh-swipe-hint">向左滑动对话可删除</p>
)}
<div className="dh-conversation-list">
{summaries.map((s) => (
<ConversationRow
key={s.id}
summary={s}
card={cards.find((c) => c.id === s.characterId)}
revealed={swipedConversation === s.id}
disabled={opening || deleting}
onReveal={setSwipedConversation}
onOpen={() => openConversation(s.id)}
onDelete={() => requestDelete(s)}
/>
))}
</div>
{!summaries.length && (
<div className="dh-empty">
<MessageCircle />
<h3>第一句话,交给你</h3>
<p>每个角色都准备好了一段开场,等你接下去。</p>
<button
className="dh-primary"
onClick={() => switchTab("discover")}
>
去发现角色
</button>
</div>
)}
</>
)}
{tab === "library" && (
<>
<p className="dh-page-lead">
角色是灵魂,世界书是背景,预设决定叙事方式。在对话设定中组合它们,形成你自己的故事。
</p>
<div className="dh-section-heading">
<h2>世界书</h2>
<span>按关键词触发的故事背景</span>
</div>
<div className="dh-library-grid">
{books.map((b) => (
<button
key={b.id}
className="dh-library-card"
onClick={() => setDetail(b)}
>
<BookOpen size={24} />
<small>{b.entriesCount} 条设定</small>
<h3>{b.name}</h3>
<p>{b.description}</p>
<span>查看详情 →</span>
</button>
))}
</div>
<div className="dh-section-heading">
<h2>叙事预设</h2>
<span>切换文字的节奏与温度</span>
</div>
<div className="dh-library-grid">
{presets.map((b) => (
<button
key={b.id}
className="dh-library-card"
onClick={() => setDetail(b)}
>
<WandSparkles size={24} />
<small>对话风格</small>
<h3>{b.name}</h3>
<p>{b.description}</p>
<span>查看详情 →</span>
</button>
))}
</div>
</>
)}
{tab === "me" && profile && profileDraft && (
<form className="dh-profile-form" onSubmit={saveProfile}>
<div className="dh-profile-banner">
<span className="dh-avatar">
{profile.userName.slice(0, 1)}
</span>
<div>
<h2>{profile.userName || "旅人"}</h2>
<p>角色会记住你选择的称呼与身份。</p>
</div>
</div>
<label>
你的称呼
<input
value={profileDraft.userName}
required
maxLength={60}
onChange={(e) =>
setProfileDraft({
...profileDraft,
userName: e.target.value,
})
}
/>
</label>
<label>
身份与背景
<textarea
rows={6}
value={profileDraft.persona}
maxLength={2000}
placeholder="例如:独自在星港旅行的摄影师,喜欢雨天和旧唱片。"
onChange={(e) =>
setProfileDraft({
...profileDraft,
persona: e.target.value,
})
}
/>
</label>
<p className="dh-form-note">
此资料可在新会话的「对话设定」中使用。每个会话的设定相互独立。
</p>
<button className="dh-primary" type="submit">
<Check size={16} />
保存身份
</button>
<div className="dh-profile-stats">
<div>
<strong>{summaries.length}</strong>
<span>段故事</span>
</div>
<div>
<strong>{profile.favorites.length}</strong>
<span>次心动</span>
</div>
<div>
<strong>{books.length}</strong>
<span>本世界书</span>
</div>
</div>
<a className="dh-logout" href="/api/auth/logout?next=/login">
<LogOut size={16} />
退出当前账号
</a>
</form>
)}
<footer className="dh-footer">
星港 STELLAR <span>✧</span> 虚构相遇,真实灵感
</footer>
</div>
)}
</main>
{detail && (
<div
className="dh-overlay"
onClick={(e) => {
if (e.target === e.currentTarget) setDetail(null);
}}
>
<section
className="dh-detail"
role="dialog"
aria-modal="true"
aria-label={detail.name}
>
<button
className="dh-close"
aria-label="关闭详情"
onClick={() => setDetail(null)}
>
<X />
</button>
{detail.kind === "character" && (
<div className="dh-detail-cover">
<img src={detail.cover || "/icon.svg"} alt={detail.name} />
</div>
)}
<div className="dh-detail-body">
<span className="dh-eyebrow">
{detail.kind === "character"
? `${detail.age} 岁 · ${detail.gender === "male" ? "男性" : "女性"}角色`
: detail.kind === "worldbook"
? "WORLD BOOK"
: "STORY PRESET"}
</span>
<h2>{detail.name}</h2>
<div className="dh-card-tags">
{detail.tags.map((t) => (
<span key={t}>{t}</span>
))}
</div>
<p className="dh-detail-description">{detail.description}</p>
{detail.greeting && (
<blockquote>
{detail.greeting
.replaceAll("{{user}}", profile?.userName ?? "旅人")
.replaceAll("{{char}}", detail.name)}
</blockquote>
)}
{detail.kind === "character" ? (
<>
<button
className="dh-primary"
disabled={opening}
onClick={() => start(detail)}
>
{opening ? (
<LoaderCircle className="dh-spin" size={17} />
) : (
<MessageCircle size={17} />
)}
开启这段故事
</button>
{detail.alternateGreetings.map((g, i) => (
<button
className="dh-alt-greeting"
key={i}
disabled={opening}
onClick={() => start(detail, i + 1)}
>
<small>另一种相遇 {i + 1}</small>
<p>{g.slice(0, 110)}</p>
</button>
))}
</>
) : (
<p className="dh-form-note">
进入任意对话,点击右上角「对话设定」即可使用。
</p>
)}
<small className="dh-source">{detail.source}</small>
</div>
</section>
</div>
)}
{showSettings && settings && (
<div className={`dh-overlay ${selectionSheet ? "dh-sheet-open" : ""}`}>
<form
className="dh-settings"
role="dialog"
aria-modal="true"
aria-label="对话设定"
aria-hidden={selectionSheet ? true : undefined}
inert={selectionSheet ? true : undefined}
onSubmit={saveSettings}
>
<header>
<div>
<span className="dh-eyebrow">MAKE IT YOUR STORY</span>
<h2>对话设定</h2>
</div>
<button
type="button"
className="dh-icon"
aria-label="关闭设定"
onClick={() => setShowSettings(false)}
>
<X />
</button>
</header>
<div className="dh-settings-body">
<label>
你的称呼
<input
maxLength={60}
value={settings.userName}
onChange={(e) =>
setSettings({ ...settings, userName: e.target.value })
}
/>
</label>
<label>
本次身份
<textarea
rows={3}
maxLength={2000}
value={settings.persona}
onChange={(e) =>
setSettings({ ...settings, persona: e.target.value })
}
/>
</label>
<button
className="dh-text-button"
type="button"
onClick={() =>
setSettings({
...settings,
userName: profile?.userName ?? "旅人",
persona: profile?.persona ?? "",
})
}
>
使用我的身份资料
</button>
<label>
固定记忆
<textarea
rows={3}
maxLength={3000}
value={settings.memory}
placeholder="记录你们共同经历的重要事实…"
onChange={(e) =>
setSettings({ ...settings, memory: e.target.value })
}
/>
</label>
<div className="dh-mobile-choices">
<button
type="button"
className="dh-choice-trigger"
aria-label="选择叙事风格"
onClick={() => openSelection("style")}
>
<WandSparkles aria-hidden="true" />
<span>
<strong>叙事风格</strong>
<small>
{presets.find((p) => p.id === settings.presetId)?.name ??
(settings.presetId ? "当前会话风格" : "角色默认风格")}
</small>
</span>
<ChevronRight aria-hidden="true" />
</button>
<button
type="button"
className="dh-choice-trigger"
aria-label="选择世界书"
onClick={() => openSelection("books")}
>
<BookOpen aria-hidden="true" />
<span>
<strong>加入世界书</strong>
<small>
{settings.bookIds.length
? `已选 ${settings.bookIds.length} 本 · ${books
.filter((b) => settings.bookIds.includes(b.id))
.map((b) => b.name)
.join("、")}`
: "未加入世界书"}
</small>
</span>
<ChevronRight aria-hidden="true" />
</button>
</div>
<div className="dh-desktop-choices">
{styleChoices(settings.presetId, (value) =>
setSettings({ ...settings, presetId: value }),
)}
{bookChoices(settings.bookIds, (value) =>
setSettings({ ...settings, bookIds: value }),
)}
</div>
<p className="dh-form-note">
保存后用于接下来的回复。固定单条消息,可将它加入对话记忆。
</p>
</div>
<button className="dh-primary" type="submit">
保存设定
</button>
</form>
{selectionSheet && (
<div className="dh-selection-layer">
<button
type="button"
className="dh-selection-backdrop"
aria-label="取消选择"
tabIndex={-1}
onClick={() => setSelectionSheet(null)}
/>
<section
className="dh-selection-sheet"
role="dialog"
aria-modal="true"
aria-label={
selectionSheet === "style" ? "选择叙事风格" : "选择世界书"
}
>
<div className="dh-sheet-handle" aria-hidden="true" />
<header>
<div>
<h2>
{selectionSheet === "style" ? "叙事风格" : "加入世界书"}
</h2>
<p>
{selectionSheet === "style"
? "选择你喜欢的故事氛围"
: "可选择多本,丰富角色的故事背景"}
</p>
</div>
<button
type="button"
className="dh-icon"
aria-label="关闭选择抽屉"
onClick={() => setSelectionSheet(null)}
>
<X />
</button>
</header>
<div className="dh-selection-body">
{selectionSheet === "style"
? styleChoices(
choiceDraft.presetId,
(value) =>
setChoiceDraft({ ...choiceDraft, presetId: value }),
true,
)
: bookChoices(
choiceDraft.bookIds,
(value) =>
setChoiceDraft({ ...choiceDraft, bookIds: value }),
true,
)}
</div>
<footer>
<button
type="button"
className="dh-sheet-reset"
onClick={() =>
setChoiceDraft(
selectionSheet === "style"
? { ...choiceDraft, presetId: undefined }
: { ...choiceDraft, bookIds: [] },
)
}
>
{selectionSheet === "style" ? "恢复默认" : "清空选择"}
</button>
<button
type="button"
className="dh-primary"
onClick={confirmSelection}
>
确认选择
{selectionSheet === "books"
? `(${choiceDraft.bookIds.length})`
: ""}
</button>
</footer>
</section>
</div>
)}
</div>
)}
{deleteTarget && (
<ConversationDeleteDialog
title={deleteTarget.title}
busy={deleting}
error={deleteError}
onCancel={() => {
if (!deleting) setDeleteTarget(null);
}}
onConfirm={confirmDelete}
/>
)}
</div>
);
}