Compare commits

..

4 Commits

Author SHA1 Message Date
zhanxi da4f45525b merge(chat): 修复键盘布局和输入缩放并优化删除弹窗 2026-10-28 08:10:12 +00:00
湛兮 caa54c9b34 fix(mobile): 修复键盘视口与输入缩放并优化删除交互
- 同步 Safari 可视高度和偏移,限制聊天页面滚动并保留手动缩放
- 统一移动输入字号并限制消息输入框高度
- 分离滑动删除按钮,将确认和选择弹窗改为居中样式
2026-10-28 16:08:15 +08:00
zhanxi 5fed13b6fb merge(chat): 区分角色对白与故事叙述 2026-10-27 14:21:14 +00:00
湛兮 ebb8a50eb6 feat(chat): 区分角色对白与故事叙述
- digital-message.tsx: 统一流式与完成态展示,保留用户纯文本和停止后的尾部
- digital-message-format.ts: 解析星号叙述、中英文对白及旧版括号格式
- digital-home.tsx、digital.css: 接入独立消息组件并区分对白与叙述样式
- tests、README.md: 补齐累计流式、旧消息和文本安全回归及中文说明
2026-10-27 22:19:05 +08:00
8 changed files with 492 additions and 99 deletions
+12
View File
@@ -125,6 +125,8 @@ pnpm start:prod
- `/discover` 为默认入口,使用独立 C 端账号和 HttpOnly Cookie。 - `/discover` 为默认入口,使用独立 C 端账号和 HttpOnly Cookie。
- `src/components/digital-home.tsx`、`digital.css`:深色双 UI、移动/桌面适配、探索、流式对话、停止、重生成、分支、固定记忆、世界书与用户身份。 - `src/components/digital-home.tsx`、`digital.css`:深色双 UI、移动/桌面适配、探索、流式对话、停止、重生成、分支、固定记忆、世界书与用户身份。
- `src/lib/digital.ts`:前台协议、请求和 SSE 解码。 - `src/lib/digital.ts`:前台协议、请求和 SSE 解码。
- `src/components/digital-message.tsx`:对白与故事叙述分段展示、视觉出字和纯文本用户消息。
- `src/lib/digital-message-format.ts`:受限格式解析;与管理端同名工具同步规则,不执行 HTML。
- `src/app/api/digital/[...path]/route.ts`:白名单 BFF,只转发前台接口,禁止访问后台实验管理,写入校验同源。 - `src/app/api/digital/[...path]/route.ts`:白名单 BFF,只转发前台接口,禁止访问后台实验管理,写入校验同源。
- 实验控制仅在 role-admin。前台没有切换实验或分组入口。 - 实验控制仅在 role-admin。前台没有切换实验或分组入口。
- `DEEPSEEK_API_KEY` 仅在业务后端配置,前端不读取、不保存。 - `DEEPSEEK_API_KEY` 仅在业务后端配置,前端不读取、不保存。
@@ -161,3 +163,13 @@ NPC 尚未出字就停止或失败时,“继续”仍可接续此前已完成
### NSFW 账号偏好 ### NSFW 账号偏好
「我的」提供 NSFW 成人内容开关,登录账号未保存偏好时默认开启,已保存的关闭选择继续保留。保存后对已有及新会话的后续回复生效,包括发送、继续、重生成与回复灵感;游客仍须先登录。偏好由 `access-manage` 保存在本人资料中,前台不使用本地存储伪造保存结果。前后端需配套发布。 「我的」提供 NSFW 成人内容开关,登录账号未保存偏好时默认开启,已保存的关闭选择继续保留。保存后对已有及新会话的后续回复生效,包括发送、继续、重生成与回复灵感;游客仍须先登录。偏好由 `access-manage` 保存在本人资料中,前台不使用本地存储伪造保存结果。前后端需配套发布。
### 对白与叙述排版
角色消息使用 `*动作、神态、心理或环境叙述*` 与 `“实际对白”`,切换时空一行。对白加粗,叙述使用较柔和颜色,英文叙述增加斜体,中文保持正体。开场白、流式回复和历史记录共用同一个渲染组件,用户消息保持纯文本。
历史括号叙述兼容嵌套括号,同一段中括号外文字作为对白;有引号的旧开场白将引号外文字作为叙述。没有明确边界的普通文本保留原样。不完整历史标记默认原样显示,生成中及停止/失败的尾部允许未闭合标记,避免星号闪现。所有片段均为文本节点,不解释 HTML。
数据库与 SSE 继续使用原始 `content`,复制、导出、固定记忆、分支和重新生成仍以整条消息操作。后端公共格式规则由 `access-manage/src/modules/digital/digital.prompt.ts` 管理;管理端解析器与本仓保持同一实现和回归用例。
运行 `node --experimental-strip-types --test tests/*.test.mjs` 验证格式解析与登录跳转;格式用例覆盖中英文、旧括号、逐字累计流、不完整标记与 HTML 字面量。
+13
View File
@@ -1123,3 +1123,16 @@ textarea:focus-visible {
width: calc(100% - 32px); width: calc(100% - 32px);
} }
} }
/* 移动表单保持可读字号,避免 Safari 聚焦后自动放大且不复原。 */
@media (pointer: coarse) {
body input:not([type="checkbox"]):not([type="radio"]),
body textarea,
body select {
font-size: max(16px, 1em);
}
}
html {
-webkit-text-size-adjust: 100%;
text-size-adjust: 100%;
}
+2 -2
View File
@@ -177,7 +177,7 @@ export function ConversationDeleteDialog({
</span> </span>
<h2 id={id}>删除这段对话?</h2> <h2 id={id}>删除这段对话?</h2>
<p id={`${id}-description`}> <p id={`${id}-description`}>
「{title}」的对话记录将被永久删除,无法恢复。 「{title}」将从你的对话列表中移除,你将无法继续查看。后台仍保留聊天记录。
</p> </p>
{error && ( {error && (
<p className="dh-delete-error" role="alert"> <p className="dh-delete-error" role="alert">
@@ -185,7 +185,7 @@ export function ConversationDeleteDialog({
</p> </p>
)} )}
<div className="dh-delete-actions"> <div className="dh-delete-actions">
<button type="button" disabled={busy} onClick={onCancel}> <button type="button" autoFocus disabled={busy} onClick={onCancel}>
取消 取消
</button> </button>
<button <button
+41 -76
View File
@@ -49,70 +49,9 @@ import {
type Bootstrap, type Bootstrap,
} from "@/lib/digital"; } from "@/lib/digital";
import { ConversationRow, ConversationDeleteDialog } from "./conversation-row"; import { ConversationRow, ConversationDeleteDialog } from "./conversation-row";
import { DigitalMessage } from "./digital-message";
import "./digital.css"; import "./digital.css";
type Tab = "discover" | "chats" | "library" | "me"; 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({ export function DigitalHome({
initial, initial,
@@ -319,16 +258,44 @@ export function DigitalHome({
}, [conversationId]); }, [conversationId]);
useEffect(() => { useEffect(() => {
if (!conversationId) return; if (!conversationId) return;
const resize = () => const root = document.documentElement;
document.documentElement.style.setProperty( const viewport = window.visualViewport;
"--dh-viewport", const body = document.body;
`${window.visualViewport?.height ?? window.innerHeight}px`, const scrollY = window.scrollY;
); const previousOverflow = body.style.overflow;
let frame = 0;
// 聊天只滚动消息区;Safari 键盘可能同时改变可视高度和偏移,必须一起同步。
body.style.overflow = "hidden";
root.classList.add("dh-chat-active");
const resize = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
// 用户手动捏合时保留浏览器缩放,不把缩放后的高度再次施加给布局。
if (viewport && Math.abs(viewport.scale - 1) > 0.01) return;
root.style.setProperty(
"--dh-viewport",
`${viewport?.height ?? window.innerHeight}px`,
);
root.style.setProperty(
"--dh-viewport-top",
`${viewport?.offsetTop ?? 0}px`,
);
});
};
resize(); resize();
window.visualViewport?.addEventListener("resize", resize); viewport?.addEventListener("resize", resize);
viewport?.addEventListener("scroll", resize);
window.addEventListener("resize", resize);
return () => { return () => {
window.visualViewport?.removeEventListener("resize", resize); cancelAnimationFrame(frame);
document.documentElement.style.removeProperty("--dh-viewport"); viewport?.removeEventListener("resize", resize);
viewport?.removeEventListener("scroll", resize);
window.removeEventListener("resize", resize);
body.style.overflow = previousOverflow;
root.classList.remove("dh-chat-active");
root.style.removeProperty("--dh-viewport");
root.style.removeProperty("--dh-viewport-top");
window.scrollTo(0, scrollY);
}; };
}, [conversationId]); }, [conversationId]);
useEffect(() => { useEffect(() => {
@@ -382,7 +349,7 @@ export function DigitalHome({
previous?.focus(); previous?.focus();
}; };
}, [detail, showSettings]); }, [detail, showSettings]);
/** 抽屉聚焦当前选项并限制滚动;取消、确认及切回桌面后恢复入口焦点。 */ /** 选择弹窗聚焦当前选项并限制滚动;取消、确认及切回桌面后恢复入口焦点。 */
useEffect(() => { useEffect(() => {
if (!selectionSheet) return; if (!selectionSheet) return;
const previous = selectionTrigger.current; const previous = selectionTrigger.current;
@@ -836,7 +803,7 @@ export function DigitalHome({
input.style.height = `${Math.min(input.scrollHeight, 160)}px`; input.style.height = `${Math.min(input.scrollHeight, 160)}px`;
}); });
} }
/** 抽屉仅编辑临时值;确认后回填设定,取消不改动已有选择。 */ /** 选择弹窗仅编辑临时值;确认后回填设定,取消不改动已有选择。 */
function openSelection(kind: "style" | "books") { function openSelection(kind: "style" | "books") {
if (!settings) return; if (!settings) return;
selectionTrigger.current = document.activeElement as HTMLElement; selectionTrigger.current = document.activeElement as HTMLElement;
@@ -1246,11 +1213,9 @@ export function DigitalHome({
{m.pinned && <Pin size={11} />} {m.pinned && <Pin size={11} />}
</span> </span>
<div className="dh-bubble"> <div className="dh-bubble">
<MessageText <DigitalMessage
message={m} message={m}
animate={ animate={m.id === activeMessage}
m.id === activeMessage && m.status === "generating"
}
/> />
</div> </div>
{!busy && m.content && ( {!busy && m.content && (
+93
View File
@@ -0,0 +1,93 @@
"use client";
/** 角色对白与故事叙述的安全展示;流式与完成态共用排版,用户消息保持纯文本。 */
import { memo, useEffect, useMemo, useRef, useState } from "react";
import type { Message } from "@/lib/digital";
import { parseDigitalMessage } from "@/lib/digital-message-format";
/** 网络接收与视觉出字分离,结束后继续显示已收到的尾部,减少动画设置下直接显示。 */
function useRevealedText(text: string, animate: boolean, generating: boolean) {
const [shown, setShown] = useState(animate ? "" : text);
const latest = useRef(text);
useEffect(() => {
latest.current = text;
}, [text]);
const revealing = animate && (generating || shown !== text);
useEffect(() => {
if (!revealing) 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);
}, [revealing]);
return animate ? shown : text;
}
/** 一条消息仍是一个操作单元;片段均渲染为文本节点,角色内容不能注入 HTML。 */
export const DigitalMessage = memo(function DigitalMessage({
message,
animate,
}: {
message: Message;
animate: boolean;
}) {
const generating = message.status === "generating";
const text = useRevealedText(message.content, animate, generating);
const blocks = useMemo(
() =>
message.role === "assistant"
? parseDigitalMessage(
text,
generating ||
["stopped", "failed"].includes(message.status) ||
text !== message.content,
)
: [],
[generating, message.content, message.role, message.status, text],
);
if (generating && !message.content.trim())
return (
<span className="dh-thinking" role="status" aria-label="正在思考">
<i aria-hidden />
<i aria-hidden />
<i aria-hidden />
</span>
);
const cursor = generating ? <span className="dh-caret" aria-hidden /> : null;
return (
<div
className={`dh-message-text${message.role === "assistant" ? " dh-message-prose" : ""}`}
>
{message.role === "assistant"
? blocks.map((block, index) => (
<p
key={index}
className={`dh-prose-${block.kind}${/[A-Za-z]/.test(block.text) && !/[\u3400-\u9fff]/.test(block.text) ? " dh-prose-latin" : ""}`}
>
{block.kind === "dialogue" ? (
<strong>{block.text}</strong>
) : (
block.text
)}
{index === blocks.length - 1 ? cursor : null}
</p>
))
: text}
{!blocks.length ? cursor : null}
{!message.content && !generating ? "这次没有生成内容。" : null}
</div>
);
});
+73 -21
View File
@@ -636,9 +636,9 @@
/* 横滑只移动会话卡片,删除在明确确认后才执行。 */ /* 横滑只移动会话卡片,删除在明确确认后才执行。 */
.dh-conversation-row { .dh-conversation-row {
position: relative; position: relative;
overflow: hidden; overflow: visible;
border-radius: 14px; border-radius: 14px;
background: #9a394b; background: transparent;
} }
.dh-conversation-list .dh-conversation-open { .dh-conversation-list .dh-conversation-open {
position: relative; position: relative;
@@ -659,9 +659,11 @@
gap: 5px; gap: 5px;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
width: 88px; width: 76px;
color: #fff; color: #fff;
background: #9a394b; background: #a3374c;
border-radius: 14px;
box-shadow: 0 4px 16px #0003;
visibility: hidden; visibility: hidden;
} }
.dh-conversation-row.is-revealed .dh-row-delete-swipe { .dh-conversation-row.is-revealed .dh-row-delete-swipe {
@@ -699,7 +701,11 @@
} }
.dh-delete-dialog { .dh-delete-dialog {
width: min(420px, calc(100% - 32px)); width: min(420px, calc(100% - 32px));
max-height: 90dvh; max-height: calc(100dvh - 48px);
margin: auto;
overflow-y: auto;
overscroll-behavior: contain;
box-shadow: 0 24px 80px #0008;
padding: 26px; padding: 26px;
color: var(--dh-text); color: var(--dh-text);
background: var(--dh-panel); background: var(--dh-panel);
@@ -882,12 +888,10 @@
font-size: 10px; font-size: 10px;
} }
.dh-delete-dialog { .dh-delete-dialog {
width: 100%; width: min(380px, calc(100% - 40px));
max-width: 100%; margin: auto;
margin: auto 0 0; padding: 24px;
padding: 24px 22px calc(22px + env(safe-area-inset-bottom)); border-radius: 22px;
border-radius: 22px 22px 0 0;
border-bottom: 0;
} }
.dh-app .dh-compose-tools .dh-mobile-linebreak { .dh-app .dh-compose-tools .dh-mobile-linebreak {
display: flex; display: flex;
@@ -1313,7 +1317,7 @@
min-height: 76px; min-height: 76px;
} }
} }
/* H5 选择项以底部抽屉编辑草稿,确认后才回填到对话设定。 */ /* H5 选择项在居中弹窗编辑草稿,确认后才回填到对话设定。 */
.dh-mobile-choices { .dh-mobile-choices {
display: none; display: none;
} }
@@ -1328,8 +1332,9 @@
inset: 0; inset: 0;
z-index: 2; z-index: 2;
display: flex; display: flex;
align-items: flex-end; align-items: center;
justify-content: center; justify-content: center;
padding: 20px;
overscroll-behavior: contain; overscroll-behavior: contain;
} }
.dh-selection-backdrop { .dh-selection-backdrop {
@@ -1343,15 +1348,14 @@
position: relative; position: relative;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
width: 100%; width: min(520px, 100%);
max-height: 86dvh; max-height: 86dvh;
min-height: 0; min-height: 0;
overflow: hidden; overflow: hidden;
background: var(--dh-panel); background: var(--dh-panel);
border: 1px solid #ffffff1c; border: 1px solid #ffffff1c;
border-bottom: 0; border-radius: 22px;
border-radius: 24px 24px 0 0; box-shadow: 0 24px 80px #0008;
box-shadow: 0 -16px 60px #0005;
animation: dh-sheet-enter 180ms ease-out; animation: dh-sheet-enter 180ms ease-out;
} }
.dh-sheet-handle { .dh-sheet-handle {
@@ -1442,10 +1446,12 @@
} }
@keyframes dh-sheet-enter { @keyframes dh-sheet-enter {
from { from {
transform: translateY(100%); opacity: 0;
transform: translateY(8px) scale(0.98);
} }
to { to {
transform: translateY(0); opacity: 1;
transform: translateY(0) scale(1);
} }
} }
@media (width > 600px) { @media (width > 600px) {
@@ -1701,6 +1707,28 @@
font-size: 14px; font-size: 14px;
color: #e6dfe7; color: #e6dfe7;
} }
.dh-message-prose {
white-space: normal;
}
.dh-message-prose > p {
margin: 0;
white-space: pre-wrap;
}
.dh-message-prose > p + p {
margin-top: 12px;
}
.dh-prose-dialogue {
color: #fff5fc;
}
.dh-prose-dialogue strong {
font-weight: 600;
}
.dh-prose-narration {
color: #c2b6c4;
}
.dh-prose-narration.dh-prose-latin {
font-style: italic;
}
.dh-message-user { .dh-message-user {
justify-content: flex-end; justify-content: flex-end;
} }
@@ -1811,7 +1839,7 @@
width: 100%; width: 100%;
resize: none; resize: none;
min-height: 36px; min-height: 36px;
max-height: 160px; max-height: min(160px, calc(var(--dh-viewport, 100dvh) * 0.28));
border: 0; border: 0;
background: none; background: none;
padding: 7px 0; padding: 7px 0;
@@ -2206,7 +2234,7 @@
} }
.dh-chat { .dh-chat {
position: fixed; position: fixed;
inset: 0; inset: var(--dh-viewport-top, 0px) 0 auto;
width: 100%; width: 100%;
height: var(--dh-viewport, 100dvh); height: var(--dh-viewport, 100dvh);
z-index: 20; z-index: 20;
@@ -2370,3 +2398,27 @@ body:has(.dh-app) .environment-badge {
width: 16px; width: 16px;
height: 16px; height: 16px;
} }
/* 聊天独立占据可视区域,防止焦点滚动带动整个文档。 */
html.dh-chat-active,
html.dh-chat-active body {
overflow: hidden;
overscroll-behavior: none;
}
.dh-composer-wrap {
flex-shrink: 0;
}
@media (pointer: coarse) {
/* iOS 会自动放大不足 16px 的表单;覆盖各页面局部小字号,同时保留手动缩放。 */
.dh-app input:not([type="checkbox"]):not([type="radio"]),
.dh-app textarea,
.dh-app select {
font-size: 16px;
}
.dh-conversation-list .dh-conversation-open {
overflow: hidden;
}
.dh-conversation-list .dh-row-delete-desktop {
display: none;
}
}
+151
View File
@@ -0,0 +1,151 @@
/** 数字人消息的受限文本格式:对白、故事叙述与旧版括号;始终返回文本,不解释 HTML。 */
/** 有序展示片段;原始 content 继续用于存储、复制、记忆和上下文。 */
export type DigitalMessageBlock = {
kind: "dialogue" | "narration" | "plain";
text: string;
};
const quotePairs: Record<string, string> = {
'"': '"',
"“": "”",
"「": "」",
"『": "』",
"«": "»",
""": """,
};
/** 跳过转义字符;引号不跨行,括号按同类型嵌套匹配,避免误吞后续内容。 */
function closingIndex(
text: string,
from: number,
open: string,
close: string,
nested = false,
) {
let depth = 1;
for (let i = from; i < text.length; i++) {
if (text[i] === "\\") {
i++;
continue;
}
if (!nested && quotePairs[open] && text[i] === "\n") return -1;
if (nested && text.startsWith(open, i)) depth++;
if (text.startsWith(close, i)) {
depth--;
if (depth === 0) return i;
}
}
return -1;
}
/** 星号需要处于词边界,避免把乘法、文件名或普通单词里的星号视为排版。 */
function markerBoundary(text: string, index: number) {
return (
index === 0 || /[\s。!?!?,,;;::))\]”"」』»]/u.test(text[index - 1])
);
}
/**
* 解析累计正文而非单个 SSE delta。未闭合标记仅在流式/中断展示时延续当前样式;
* 旧版括号外文本按对白处理,有引号的旧开场白将引号外文字作为叙述,其他纯文本保留。
* 与 role-admin/src/utils/digital-message-format.ts 保持同一实现和用例,独立构建时无需跨仓引用。
*/
export function parseDigitalMessage(
source: string,
streaming = false,
): DigitalMessageBlock[] {
const blocks: DigitalMessageBlock[] = [];
for (const paragraph of source.replace(/\r\n?/g, "\n").split(/\n\s*\n/)) {
const parts: DigitalMessageBlock[] = [];
let legacyNarration = false;
const push = (kind: DigitalMessageBlock["kind"], text: string) => {
if (!text) return;
const last = parts[parts.length - 1];
if (last?.kind === kind) last.text += text;
else parts.push({ kind, text });
};
for (let i = 0; i < paragraph.length; ) {
const char = paragraph[i];
if (
char === "\\" &&
/[*"\\()()“”「」『』]/u.test(paragraph[i + 1] ?? "")
) {
push("plain", paragraph[i + 1]);
i += 2;
continue;
}
const quoteEnd = quotePairs[char];
if (quoteEnd) {
const close = closingIndex(paragraph, i + 1, char, quoteEnd);
const lineEnd = paragraph.indexOf("\n", i + 1);
const end =
close >= 0 ? close + 1 : lineEnd >= 0 ? lineEnd : paragraph.length;
push("dialogue", paragraph.slice(i, end));
i = end;
continue;
}
if (
char === "*" &&
markerBoundary(paragraph, i) &&
!/\s/u.test(paragraph[i + 1] ?? "")
) {
const marker = paragraph.startsWith("**", i) ? "**" : "*";
const close = closingIndex(
paragraph,
i + marker.length,
marker,
marker,
);
if (close >= 0 || streaming) {
push(
marker === "**" ? "dialogue" : "narration",
paragraph.slice(i + marker.length, close >= 0 ? close : undefined),
);
i = close >= 0 ? close + marker.length : paragraph.length;
continue;
}
// 格式不完整的历史正文原样保留,不猜测后面的哪些字符属于标记。
push("plain", paragraph.slice(i));
break;
}
if ((char === "(" || char === "(") && markerBoundary(paragraph, i)) {
const close = closingIndex(
paragraph,
i + 1,
char,
char === "(" ? ")" : ")",
true,
);
if (close >= 0 || streaming) {
legacyNarration = true;
push(
"narration",
paragraph.slice(i + 1, close >= 0 ? close : undefined),
);
i = close >= 0 ? close + 1 : paragraph.length;
continue;
}
push("plain", paragraph.slice(i));
break;
}
push("plain", char);
i++;
}
const hasDialogue = parts.some((part) => part.kind === "dialogue");
for (const part of parts) {
const kind =
part.kind !== "plain"
? part.kind
: legacyNarration
? "dialogue"
: hasDialogue
? "narration"
: "plain";
for (const line of part.text.split(/\n+/)) {
if (line.trim()) blocks.push({ kind, text: line.trim() });
}
}
}
return blocks;
}
+107
View File
@@ -0,0 +1,107 @@
/** 对白、叙述、旧消息与累计流式文本的格式回归,不依赖浏览器或真实模型。 */
import test from "node:test";
import assert from "node:assert/strict";
import { parseDigitalMessage as parse } from "../src/lib/digital-message-format.ts";
test("标准消息按剧情顺序拆分叙述、对白与心理,隐藏星号并保留引号", () => {
assert.deepEqual(parse("*她合上书。*\n\n“你来了。”\n\n*她终于放松下来。*"), [
{ kind: "narration", text: "她合上书。" },
{ kind: "dialogue", text: "“你来了。”" },
{ kind: "narration", text: "她终于放松下来。" },
]);
});
test("旧消息的成对括号与括号外对白兼容,内层括号不会提前关闭叙述", () => {
assert.deepEqual(
parse(
"(她抱起书(封面有些旧),笑了笑)你来了。\n(她心里有些高兴)坐吧。",
),
[
{ kind: "narration", text: "她抱起书(封面有些旧),笑了笑" },
{ kind: "dialogue", text: "你来了。" },
{ kind: "narration", text: "她心里有些高兴" },
{ kind: "dialogue", text: "坐吧。" },
],
);
});
test("旧开场白的无标记叙述与引号对白分别展示,英文撇号不作为对白", () => {
assert.deepEqual(
parse('She picked up her book.\n"You’re early. Don\'t wait outside."'),
[
{ kind: "narration", text: "She picked up her book." },
{ kind: "dialogue", text: '"You’re early. Don\'t wait outside."' },
],
);
for (const [open, close] of [
["“", "”"],
["「", "」"],
["『", "』"],
["«", "»"],
[""", """],
]) {
assert.deepEqual(parse(`${open}你好${close}`), [
{ kind: "dialogue", text: `${open}你好${close}` },
]);
}
});
test("纯文本、普通备注、乘法与不完整的历史标记保留原文", () => {
for (const text of [
"普通文本",
"说明(选填)",
"3 * 4 = 12",
"file*name.txt",
"*未闭合",
"(未闭合",
]) {
assert.deepEqual(parse(text), [{ kind: "plain", text }]);
}
assert.deepEqual(parse(" \n\r\n"), []);
assert.deepEqual(parse("第一段\r\n\r\n第二段"), [
{ kind: "plain", text: "第一段" },
{ kind: "plain", text: "第二段" },
]);
});
test("显式叙述里的引号保持为故事文本,不再二次推断", () => {
assert.deepEqual(parse("*她想到“明天”这个词,轻轻笑了。*"), [
{ kind: "narration", text: "她想到“明天”这个词,轻轻笑了。" },
]);
assert.deepEqual(parse("**“你好。”**"), [
{ kind: "dialogue", text: "“你好。”" },
]);
assert.deepEqual(parse("\\*字面星号\\*"), [
{ kind: "plain", text: "*字面星号*" },
]);
});
test("累计流式输入的每个字符前缀都隐藏未闭合星号,完成态排版相同", () => {
const source = "*她推开门。*\n\n“你来了。”\n\n*她松了口气。*";
for (let end = 1; end <= source.length; end++) {
const blocks = parse(source.slice(0, end), true);
assert.equal(
blocks.some((block) => block.text.includes("*")),
false,
`前缀 ${end}`,
);
}
assert.deepEqual(parse(source, true), parse(source));
assert.deepEqual(parse("*她推开门", true), [
{ kind: "narration", text: "她推开门" },
]);
assert.deepEqual(parse("(她推开门", true), [
{ kind: "narration", text: "她推开门" },
]);
assert.deepEqual(parse("“你来了", true), [
{ kind: "dialogue", text: "“你来了" },
]);
assert.deepEqual(parse("**Hello", true), [
{ kind: "dialogue", text: "Hello" },
]);
});
test("HTML 与脚本内容只作为文本保留,格式解析不会生成任何标签", () => {
const text = "<script>globalThis.injected = true</script>";
assert.deepEqual(parse(text), [{ kind: "plain", text }]);
});