Files
role-user/src/components/digital-home.tsx
T
湛兮 b7433acba4 feat(digital): 打造星港响应式数字人对话空间
新增角色探索、收藏、世界书和身份资料;接入流式打字、停止重生成、固定记忆、会话分支与导出;适配手机和桌面并保持实验只由后台控制。
2026-10-27 10:25:40 +08:00

1509 lines
51 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,
} from "lucide-react";
import {
digital,
readStream,
type Card,
type Profile,
type Message,
type Settings,
type Conversation,
type Summary,
type Bootstrap,
} from "@/lib/digital";
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;
}) {
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 [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 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),
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 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,
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;
if (!el) return;
const observer = new ResizeObserver(() => {
if (atBottom.current)
viewport.current?.scrollTo({
top: viewport.current.scrollHeight,
behavior: "instant",
});
});
observer.observe(el);
return () => observer.disconnect();
}, [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(
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") {
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(() => {
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) {
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;
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" = "send") {
if (
!conversation ||
busy ||
streamingId.current ||
(mode === "send" && !draft.trim())
)
return;
const id = conversation.id,
content = draft.trim(),
requestId = crypto.randomUUID();
let assistantId = `pending-${requestId}`;
setBusy(true);
setError("");
setNotice("");
atBottom.current = true;
streamingId.current = id;
if (mode === "send") setDraft("");
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 &&
!event.nativeEvent.isComposing &&
window.matchMedia("(min-width: 768px)").matches
) {
event.preventDefault();
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);
}
}
async function removeConversation() {
if (
!conversation ||
busy ||
!window.confirm("删除此会话和全部消息?此操作无法撤销。")
)
return;
try {
await digital(`conversations/${conversation.id}`, "DELETE");
setConversation(null);
currentId.current = null;
await refreshSummaries();
} catch (e) {
reportError(e);
}
}
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("对话设定已保存,下次回复生效");
} 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) {
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 modern = 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);
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}
onScroll={() => {
const v = viewport.current;
if (v) {
atBottom.current =
v.scrollHeight - v.scrollTop - v.clientHeight < 110;
setShowJump(!atBottom.current);
}
}}
>
<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"
}
/>
{!m.content && m.status === "generating" && (
<span className="dh-thinking">
<i />
<i />
<i />
</span>
)}
</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;
viewport.current?.scrollTo({
top: viewport.current.scrollHeight,
behavior: "smooth",
});
}}
>
<ChevronDown size={16} />
回到最新
</button>
)}
<div className="dh-composer-wrap">
<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`;
}}
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>
<div className="dh-conversation-list">
{summaries.map((s) => {
const c = cards.find((c) => c.id === s.characterId);
return (
<button
key={s.id}
onClick={() => openConversation(s.id)}
disabled={opening}
>
<img src={c?.cover || "/icon.svg"} alt="" />
<div>
<h3>{s.title}</h3>
<p>{c?.description || "继续这段私人对话"}</p>
</div>
<small>
{new Date(s.updatedAt).toLocaleDateString("zh-CN", {
month: "short",
day: "numeric",
})}
</small>
<MessageCircle size={18} />
</button>
);
})}
</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">
<form
className="dh-settings"
role="dialog"
aria-modal="true"
aria-label="对话设定"
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>
<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>
<label>
叙事风格
<select
value={settings.presetId ?? ""}
onChange={(e) =>
setSettings({
...settings,
presetId: e.target.value || undefined,
})
}
>
<option value="">角色默认风格</option>
{presets.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
</option>
))}
</select>
</label>
<fieldset>
<legend>加入世界书</legend>
{books.map((b) => (
<label className="dh-checkbox" key={b.id}>
<input
type="checkbox"
checked={settings.bookIds.includes(b.id)}
onChange={(e) =>
setSettings({
...settings,
bookIds: e.target.checked
? [...settings.bookIds, b.id]
: settings.bookIds.filter((v) => v !== b.id),
})
}
/>
<span>
{b.name}
<small>{b.description}</small>
</span>
</label>
))}
</fieldset>
<p className="dh-form-note">
保存后从下一次回复生效。可以固定单条消息,将它加入对话记忆。
</p>
<button className="dh-primary" type="submit">
保存设定
</button>
</form>
</div>
)}
</div>
);
}