From d0442f5bb9f4f207835035551ac44c24f30e0754 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B9=9B=E5=85=AE?= Date: Tue, 27 Oct 2026 12:29:48 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(chat):=20=E6=94=AF=E6=8C=81=E6=BB=91?= =?UTF-8?q?=E5=8A=A8=E5=88=A0=E9=99=A4=E7=81=B5=E6=84=9F=E5=9B=9E=E5=A4=8D?= =?UTF-8?q?=E4=B8=8EH5=E5=9B=9E=E8=BD=A6=E5=8F=91=E9=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 会话列表:水平滑动展开删除、桌面快捷入口、模态确认及失败重试 - 灵感回复:按上下文生成建议,仅加入草稿,保留原输入并取消过期请求 - 输入交互:移除回车发送的屏宽限制,保护中文输入法,支持Shift换行与手机换行按钮 --- README.md | 2 + src/app/api/digital/[...path]/route.ts | 7 +- src/components/conversation-row.tsx | 209 +++++++++++++++++ src/components/digital-home.tsx | 307 +++++++++++++++++++++---- src/components/digital.css | 272 +++++++++++++++++++++- 5 files changed, 751 insertions(+), 46 deletions(-) create mode 100644 src/components/conversation-row.tsx diff --git a/README.md b/README.md index 844cdef..b2de611 100644 --- a/README.md +++ b/README.md @@ -132,3 +132,5 @@ pnpm start:prod 标签页图标采用 `public/stellar-icon-v2.svg`,同时提供多尺寸 `favicon.ico`、180/192/512 PNG,覆盖浏览器、Apple 主屏幕和 PWA。版本化资源路径用于刷新旧图标缓存。 通用实验消费者可经 `GET /api/digital/decisions/:key` 读取本人类型决策的 `data.value`,沿用 HttpOnly 会话与不缓存策略。类型、测试方案和用户分组全部在后台管理;新类型需要应用真实使用返回值并完成后台接入验收后才可启动。 + +`src/components/conversation-row.tsx` 提供会话列表横滑删除、桌面删除入口与模态确认。灵感回复读取本人会话上下文,选择后只加入草稿,原草稿保留;回车发送覆盖 H5/Web,支持中文输入法、Shift+Enter 与手机换行按钮。 diff --git a/src/app/api/digital/[...path]/route.ts b/src/app/api/digital/[...path]/route.ts index 107d9df..e5766ae 100644 --- a/src/app/api/digital/[...path]/route.ts +++ b/src/app/api/digital/[...path]/route.ts @@ -33,13 +33,16 @@ async function proxy( const { path } = await context.params; const joined = path.join("/"); if ( - !/^(bootstrap|profile|exposure|decisions\/[a-zA-Z0-9_-]+|conversations(?:\/[a-zA-Z0-9_-]+(?:\/(?:stream|stop|branch|messages\/[a-zA-Z0-9_-]+))?)?)$/.test( + !/^(bootstrap|profile|exposure|decisions\/[a-zA-Z0-9_-]+|conversations(?:\/[a-zA-Z0-9_-]+(?:\/(?:stream|stop|branch|suggestions|messages\/[a-zA-Z0-9_-]+))?)?)$/.test( joined, ) ) return Response.json({ message: "接口不存在" }, { status: 404 }); if (joined.startsWith("decisions/") && request.method !== "GET") - return Response.json({ message: "仅支持读取决策" }, {status:405,headers:{Allow:"GET"}}); + return Response.json( + { message: "仅支持读取决策" }, + { status: 405, headers: { Allow: "GET" } }, + ); if (request.method !== "GET") { const origin = request.headers.get("origin"); try { diff --git a/src/components/conversation-row.tsx b/src/components/conversation-row.tsx new file mode 100644 index 0000000..d5d7d62 --- /dev/null +++ b/src/components/conversation-row.tsx @@ -0,0 +1,209 @@ +"use client"; +/** 会话列表的水平滑动操作与删除确认;纵向滑动继续交给页面滚动。 */ +import { useEffect, useId, useRef, useState, type PointerEvent } from "react"; +import { LoaderCircle, Trash2 } from "lucide-react"; +import type { Card, Summary } from "@/lib/digital"; + +/** 一次只展开一条会话;拖动不会触发进入会话,桌面和键盘保留显式删除入口。 */ +export function ConversationRow({ + summary, + card, + revealed, + disabled, + onReveal, + onOpen, + onDelete, +}: { + summary: Summary; + card?: Card; + revealed: boolean; + disabled: boolean; + onReveal: (id: string | null) => void; + onOpen: () => void; + onDelete: () => void; +}) { + const [drag, setDrag] = useState(null); + const gesture = useRef<{ + x: number; + y: number; + base: number; + offset: number; + axis: "pending" | "x" | "y"; + } | null>(null), + suppressClick = useRef(false); + const distance = 88; + function start(e: PointerEvent) { + if (disabled || e.button !== 0) return; + suppressClick.current = false; + gesture.current = { + x: e.clientX, + y: e.clientY, + base: revealed ? -distance : 0, + offset: revealed ? -distance : 0, + axis: "pending", + }; + e.currentTarget.setPointerCapture(e.pointerId); + } + function move(e: PointerEvent) { + const g = gesture.current; + if (!g) return; + const dx = e.clientX - g.x, + dy = e.clientY - g.y; + if (g.axis === "pending" && Math.max(Math.abs(dx), Math.abs(dy)) > 8) { + g.axis = Math.abs(dx) > Math.abs(dy) * 1.2 ? "x" : "y"; + if (g.axis === "x") onReveal(summary.id); + } + if (g.axis !== "x") return; + g.offset = Math.max(-distance, Math.min(0, g.base + dx)); + setDrag(g.offset); + } + function finish(e: PointerEvent, cancelled = false) { + const g = gesture.current; + if (!g) return; + gesture.current = null; + if (g.axis === "x") { + suppressClick.current = true; + onReveal( + (cancelled ? g.base : g.offset) < -distance / 2 ? summary.id : null, + ); + } + setDrag(null); + if (e.currentTarget.hasPointerCapture(e.pointerId)) + e.currentTarget.releasePointerCapture(e.pointerId); + } + const exposed = revealed || (drag !== null && drag < 0); + return ( +
+ + + +
+ ); +} + +/** 原生模态对话框负责焦点约束,删除成功前保留原会话,失败可在原处重试。 */ +export function ConversationDeleteDialog({ + title, + busy, + error, + onCancel, + onConfirm, +}: { + title: string; + busy: boolean; + error: string; + onCancel: () => void; + onConfirm: () => void; +}) { + const ref = useRef(null), + id = useId(); + useEffect(() => { + const dialog = ref.current; + dialog?.showModal(); + return () => dialog?.close(); + }, []); + return ( + { + e.preventDefault(); + if (!busy) onCancel(); + }} + > + + + +

删除这段对话?

+

+ 「{title}」的对话记录将被永久删除,无法恢复。 +

+ {error && ( +

+ {error} +

+ )} +
+ + +
+
+ ); +} diff --git a/src/components/digital-home.tsx b/src/components/digital-home.tsx index 0c6362b..19bb140 100644 --- a/src/components/digital-home.tsx +++ b/src/components/digital-home.tsx @@ -48,6 +48,7 @@ import { type Summary, type Bootstrap, } from "@/lib/digital"; +import { ConversationRow, ConversationDeleteDialog } from "./conversation-row"; import "./digital.css"; type Tab = "discover" | "chats" | "library" | "me"; /** 接收文本与视觉打字分离;减少动画设置下直接呈现完整文本。 */ @@ -139,6 +140,19 @@ export function DigitalHome({ bookIds: string[]; }>({ bookIds: [] }); const selectionTrigger = useRef(null); + const [swipedConversation, setSwipedConversation] = useState( + null, + ); + const [deleteTarget, setDeleteTarget] = useState(null), + [deleting, setDeleting] = useState(false), + [deleteError, setDeleteError] = useState(""); + const [ideasOpen, setIdeasOpen] = useState(false), + [ideasLoading, setIdeasLoading] = useState(false), + [ideas, setIdeas] = useState([]), + [ideasError, setIdeasError] = useState(""); + const ideasRequest = useRef(null), + imeComposing = useRef(false), + deleteLock = useRef(false); const favoritePending = useRef(false); const [activeMessage, setActiveMessage] = useState(null), [showJump, setShowJump] = useState(false), @@ -362,6 +376,9 @@ export function DigitalHome({ }; }, [busy, conversationId]); async function openConversation(id: string) { + closeIdeas(); + imeComposing.current = false; + setSwipedConversation(null); if (streamingId.current && streamingId.current !== id) { setNotice("请先停止当前回复,再切换会话"); return; @@ -436,6 +453,7 @@ export function DigitalHome({ (mode === "send" && !draft.trim()) ) return; + closeIdeas(); const id = conversation.id, content = draft.trim(), requestId = crypto.randomUUID(); @@ -445,7 +463,10 @@ export function DigitalHome({ setNotice(""); atBottom.current = true; streamingId.current = id; - if (mode === "send") setDraft(""); + if (mode === "send") { + setDraft(""); + if (textarea.current) textarea.current.style.height = "auto"; + } const local: Message[] = [ ...(mode === "send" ? [ @@ -570,11 +591,12 @@ export function DigitalHome({ if ( event.key === "Enter" && !event.shiftKey && + !imeComposing.current && !event.nativeEvent.isComposing && - window.matchMedia("(min-width: 768px)").matches + event.nativeEvent.keyCode !== 229 ) { event.preventDefault(); - void send(); + if (!event.repeat) void send(); } } async function pin(message: Message) { @@ -615,21 +637,133 @@ export function DigitalHome({ reportError(e); } } - async function removeConversation() { - if ( - !conversation || - busy || - !window.confirm("删除此会话和全部消息?此操作无法撤销。") - ) + function requestDelete(target: Summary) { + if (target.id === conversation?.id && busy) { + setNotice("请先停止当前回复,再删除对话"); return; - try { - await digital(`conversations/${conversation.id}`, "DELETE"); - setConversation(null); - currentId.current = null; - await refreshSummaries(); - } catch (e) { - reportError(e); } + 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") { @@ -705,6 +839,8 @@ export function DigitalHome({ URL.revokeObjectURL(url); } function switchTab(value: Tab) { + closeIdeas(); + setSwipedConversation(null); if (conversation && busy) { setNotice("请先停止当前回复,再离开会话"); return; @@ -818,6 +954,12 @@ export function DigitalHome({ ))} ); + useEffect( + () => () => { + ideasRequest.current?.abort(); + }, + [], + ); const modern = boot?.decision.variant === "B"; return (
)}
+ {ideasOpen && ( +
+
+ + + 灵感回复 + + +
+

+ {draft + ? "选择后追加到现有草稿,不会自动发送。" + : "根据当前对话生成,选择后可编辑再发送。"} +

+ {ideasLoading ? ( +

+ + 正在寻找合适的接话方式… +

+ ) : ideasError ? ( +

+ {ideasError} +

+ ) : ( +
+ {ideas.map((idea, i) => ( + + ))} +
+ )} + {!ideasLoading && ( + + )} +
+ )} +
+ + +