This commit is contained in:
mlogclub
2026-04-09 10:01:23 +08:00
commit efe801b8bf
707 changed files with 110595 additions and 0 deletions
+322
View File
@@ -0,0 +1,322 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import {
Maximize2Icon,
Minimize2Icon,
MinusIcon,
RotateCwIcon,
ShieldCheckIcon,
XIcon,
} from "lucide-react";
import { useShallow } from "zustand/react/shallow";
import { useChatStore } from "@/lib/store/chat-store";
import { closeConversation } from "@/lib/services/conversation";
import {
bindHostBridge,
requestHostClose,
requestHostMinimize,
requestHostToggleMaximize,
} from "@/lib/widget/host-bridge";
import { ConnectionStatus } from "@/components/im/connection-status";
import { MessageEditor } from "@/components/im/message-editor";
import {
MessageList,
type MessageListHandle,
} from "@/components/im/message-list";
export function ChatShell() {
const messageListRef = useRef<MessageListHandle | null>(null);
const [isMaximized, setIsMaximized] = useState(false);
const [isCloseDialogOpen, setIsCloseDialogOpen] = useState(false);
const [isClosingConversation, setIsClosingConversation] = useState(false);
const {
title,
subtitle,
themeColor,
conversation,
messages,
messagesHasMore,
messagesLoadingMore,
loadOlderMessages,
status,
error,
isOpen,
isVisible,
setIsOpen,
setIsVisible,
bootstrap,
handleSendMessage,
uploadMessageImage,
sendAttachment,
retry,
disconnectSocket,
markConversationRead,
} = useChatStore(
useShallow((state) => ({
title: state.title,
subtitle: state.subtitle,
themeColor: state.themeColor,
conversation: state.conversation,
messages: state.messages,
messagesHasMore: state.messagesHasMore,
messagesLoadingMore: state.messagesLoadingMore,
loadOlderMessages: state.loadOlderMessages,
status: state.status,
error: state.error,
isOpen: state.isOpen,
isVisible: state.isVisible,
setIsOpen: state.setIsOpen,
setIsVisible: state.setIsVisible,
bootstrap: state.bootstrap,
handleSendMessage: state.handleSendMessage,
uploadMessageImage: state.uploadMessageImage,
sendAttachment: state.sendAttachment,
retry: state.retry,
disconnectSocket: state.disconnectSocket,
markConversationRead: state.markConversationRead,
})),
);
const maybeMarkConversationRead = useCallback(() => {
if (!isVisible || !conversation || typeof document === "undefined") {
return;
}
if (document.visibilityState !== "visible") {
return;
}
void markConversationRead().catch((error) => {
console.error("Failed to mark widget conversation read", error);
});
}, [conversation, isVisible, markConversationRead]);
useEffect(() => {
return bindHostBridge({
onOpen: () => {
setIsOpen(true);
setIsVisible(true);
},
onMinimize: () => {
setIsVisible(false);
},
onMaximizedChange: (nextIsMaximized) => {
setIsMaximized(nextIsMaximized);
},
});
}, [setIsOpen, setIsVisible]);
useEffect(() => {
bootstrap();
return () => {
if (!isOpen) {
disconnectSocket();
}
};
}, [isOpen, bootstrap, disconnectSocket]);
useEffect(() => {
maybeMarkConversationRead();
}, [maybeMarkConversationRead, messages.length]);
useEffect(() => {
const handleVisibilityChange = () => {
if (document.visibilityState === "visible") {
maybeMarkConversationRead();
}
};
const handleFocus = () => {
maybeMarkConversationRead();
};
document.addEventListener("visibilitychange", handleVisibilityChange);
window.addEventListener("focus", handleFocus);
return () => {
document.removeEventListener("visibilitychange", handleVisibilityChange);
window.removeEventListener("focus", handleFocus);
};
}, [maybeMarkConversationRead]);
async function handleSend(content: string) {
await handleSendMessage(content);
messageListRef.current?.scrollToBottom();
}
function handleMinimize() {
setIsVisible(false);
requestHostMinimize();
}
function handleToggleMaximize() {
requestHostToggleMaximize();
}
async function confirmCloseConversation() {
if (isClosingConversation) {
return;
}
setIsClosingConversation(true);
try {
if (conversation?.id) {
await closeConversation(conversation.id);
}
setIsCloseDialogOpen(false);
requestHostClose();
} catch (closeError) {
window.alert(
closeError instanceof Error ? closeError.message : "关闭会话失败",
);
} finally {
setIsClosingConversation(false);
}
}
useEffect(() => {
if (!isCloseDialogOpen) {
return;
}
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape" && !isClosingConversation) {
setIsCloseDialogOpen(false);
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [isCloseDialogOpen, isClosingConversation]);
return (
<main
className="cs-agent-shell relative flex h-screen overflow-hidden bg-(--background)"
style={{ "--primary": themeColor } as React.CSSProperties}
>
<section className="cs-agent-panel flex h-full w-full flex-col overflow-hidden border border-white/70">
<header className="relative shrink-0 overflow-hidden border-b border-white/60 px-4 pb-3 pt-3 shadow-[0_10px_24px_rgba(15,23,42,0.05)]">
<div className="absolute inset-x-0 top-0 h-20 bg-[radial-gradient(circle_at_top_right,rgba(37,99,235,0.14),transparent_52%)]" />
<div className="relative flex items-center justify-between gap-3">
<div className="min-w-0">
<div className="truncate text-[16px] font-semibold tracking-[0.01em] text-slate-950">
{title}
</div>
<div className="mt-1 text-[12px] text-slate-500">
{subtitle}
</div>
</div>
<div className="flex items-center gap-2">
<div className="inline-flex items-center gap-1.5 rounded-full border border-white/70 bg-white/65 px-2.5 py-1 text-[11px] text-slate-500 shadow-[0_6px_18px_rgba(15,23,42,0.04)]">
<ShieldCheckIcon className="size-3.5 text-emerald-600" />
</div>
<ConnectionStatus status={status} />
<div className="inline-flex items-center gap-1 rounded-[18px] border border-white/70 bg-[linear-gradient(180deg,rgba(255,255,255,0.88),rgba(241,245,249,0.82))] p-1 shadow-[inset_0_1px_0_rgba(255,255,255,0.9),0_12px_28px_rgba(15,23,42,0.07)] backdrop-blur-xl">
<button
type="button"
onClick={retry}
aria-label="重新连接"
title="重新连接"
className="group inline-flex h-6 w-6 items-center justify-center rounded-[14px] text-slate-400 transition duration-200 hover:-translate-y-0.5 hover:bg-[linear-gradient(180deg,rgba(255,255,255,0.98),rgba(239,246,255,0.96))] hover:text-sky-600 hover:shadow-[inset_0_1px_0_rgba(255,255,255,0.95),0_10px_18px_rgba(56,189,248,0.16)]"
>
<RotateCwIcon className="size-3.75 transition duration-200 group-hover:rotate-[-20deg]" />
</button>
<button
type="button"
onClick={handleMinimize}
aria-label="收起聊天窗口"
title="收起聊天窗口"
className="group inline-flex h-6 w-6 items-center justify-center rounded-[14px] text-slate-400 transition duration-200 hover:-translate-y-0.5 hover:bg-[linear-gradient(180deg,rgba(255,255,255,0.98),rgba(248,250,252,0.96))] hover:text-slate-700 hover:shadow-[inset_0_1px_0_rgba(255,255,255,0.95),0_10px_18px_rgba(15,23,42,0.10)]"
>
<MinusIcon className="size-3.75 transition duration-200 group-hover:scale-x-[0.88]" />
</button>
<button
type="button"
onClick={handleToggleMaximize}
aria-label={isMaximized ? "取消最大化" : "最大化聊天窗口"}
title={isMaximized ? "取消最大化" : "最大化聊天窗口"}
className="group inline-flex h-6 w-6 items-center justify-center rounded-[14px] text-slate-400 transition duration-200 hover:-translate-y-0.5 hover:bg-[linear-gradient(180deg,rgba(255,255,255,0.98),rgba(238,249,244,0.96))] hover:text-emerald-700 hover:shadow-[inset_0_1px_0_rgba(255,255,255,0.95),0_10px_18px_rgba(16,185,129,0.14)]"
>
{isMaximized ? (
<Minimize2Icon className="size-3.75 transition duration-200 group-hover:scale-[0.94]" />
) : (
<Maximize2Icon className="size-3.75 transition duration-200 group-hover:scale-[1.04]" />
)}
</button>
<button
type="button"
onClick={() => setIsCloseDialogOpen(true)}
aria-label="关闭聊天窗口"
title="关闭聊天窗口"
className="group inline-flex h-6 w-6 items-center justify-center rounded-[14px] text-rose-400 transition duration-200 hover:-translate-y-0.5 hover:bg-[linear-gradient(180deg,rgba(255,255,255,0.98),rgba(255,241,242,0.98))] hover:text-rose-600 hover:shadow-[inset_0_1px_0_rgba(255,255,255,0.95),0_10px_18px_rgba(244,63,94,0.16)]"
>
<XIcon className="size-3.75 transition duration-200 group-hover:scale-[0.92]" />
</button>
</div>
</div>
</div>
</header>
<div className=".cs-agent-grid-bg grid min-h-0 flex-1 overflow-hidden grid-rows-[minmax(0,1fr)_auto]">
<MessageList
ref={messageListRef}
messages={messages}
onNearBottomVisible={maybeMarkConversationRead}
hasMoreOlder={messagesHasMore}
loadingOlder={messagesLoadingMore}
onLoadOlder={loadOlderMessages}
/>
<MessageEditor
disabled={!conversation}
onSend={handleSend}
onUploadImage={uploadMessageImage}
onSendAttachment={sendAttachment}
/>
</div>
{error ? (
<div className="border-t border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">
{error}
</div>
) : null}
</section>
{isCloseDialogOpen ? (
<div className="absolute inset-0 z-50 flex items-center justify-center bg-[radial-gradient(circle_at_top,rgba(37,99,235,0.16),transparent_38%),rgba(15,23,42,0.24)] px-5 backdrop-blur-sm">
<div className="cs-agent-fade-up w-full max-w-[320px] rounded-[26px] border border-white/70 bg-[linear-gradient(180deg,rgba(255,255,255,0.96),rgba(241,245,249,0.94))] p-5 shadow-[0_28px_80px_rgba(15,23,42,0.18),inset_0_1px_0_rgba(255,255,255,0.92)]">
<div className="flex items-start gap-3">
{/* <div className="mt-0.5 inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl bg-linear-to-b from-rose-50 to-rose-100 text-rose-500 shadow-[inset_0_1px_0_rgba(255,255,255,0.95),0_12px_22px_rgba(244,63,94,0.12)]">
<XIcon className="size-4" />
</div> */}
<div className="min-w-0">
<div className="text-[15px] font-semibold tracking-[0.01em] text-slate-950">
</div>
<div className="mt-1.5 text-[12px] leading-5 text-slate-500">
</div>
</div>
</div>
<div className="mt-5 flex items-center justify-end gap-2">
<button
type="button"
disabled={isClosingConversation}
onClick={() => setIsCloseDialogOpen(false)}
className="inline-flex h-9 items-center justify-center rounded-2xl border border-slate-200/80 bg-white/80 px-4 text-[12px] font-medium text-slate-600 shadow-[0_10px_20px_rgba(15,23,42,0.05)] transition hover:-translate-y-0.5 hover:border-slate-300 hover:bg-white hover:text-slate-800 disabled:translate-y-0 disabled:cursor-not-allowed disabled:opacity-60"
>
</button>
<button
type="button"
disabled={isClosingConversation}
onClick={() => void confirmCloseConversation()}
className="inline-flex h-9 items-center justify-center rounded-2xl bg-[linear-gradient(135deg,#f43f5e,#fb7185)] px-4 text-[12px] font-semibold text-white shadow-[0_14px_28px_rgba(244,63,94,0.24)] transition hover:-translate-y-0.5 hover:opacity-92 disabled:translate-y-0 disabled:cursor-not-allowed disabled:opacity-60"
>
{isClosingConversation ? "结束中..." : "确认结束"}
</button>
</div>
</div>
</div>
) : null}
</main>
);
}
@@ -0,0 +1,43 @@
"use client";
import { cn } from "@/lib/utils";
type ConnectionStatusProps = {
status: "connecting" | "connected" | "disconnected";
};
const statusText: Record<ConnectionStatusProps["status"], string> = {
connecting: "连接中",
connected: "在线服务",
disconnected: "连接已断开",
};
export function ConnectionStatus({ status }: ConnectionStatusProps) {
const toneClass =
status === "connected"
? "border-emerald-200/80 bg-emerald-50 text-emerald-700"
: status === "connecting"
? "border-amber-200/80 bg-amber-50 text-amber-700"
: "border-slate-200/80 bg-slate-100 text-slate-600";
return (
<div
className={cn(
"inline-flex items-center gap-2 rounded-full border px-2.5 py-1 text-[11px] font-medium tracking-[0.02em] shadow-[0_6px_16px_rgba(15,23,42,0.06)]",
toneClass,
)}
>
<span
className={cn(
"cs-agent-status-dot inline-block size-2 rounded-full",
status === "connected"
? "bg-emerald-500 shadow-[0_0_0_4px_rgba(16,185,129,0.14)]"
: status === "connecting"
? "bg-amber-500 shadow-[0_0_0_4px_rgba(245,158,11,0.16)]"
: "bg-slate-400 shadow-[0_0_0_4px_rgba(148,163,184,0.14)]",
)}
/>
<span>{statusText[status]}</span>
</div>
);
}
+339
View File
@@ -0,0 +1,339 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { EditorContent, useEditor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Image from "@tiptap/extension-image";
import Placeholder from "@tiptap/extension-placeholder";
import { ImageIcon, PaperclipIcon, SendHorizonalIcon } from "lucide-react";
import { generateUUID } from "@/lib/utils";
type UploadedImage = {
url: string;
filename?: string;
};
type MessageEditorProps = {
disabled?: boolean;
uploadingAsset?: boolean;
onSend: (html: string) => Promise<void>;
onUploadImage: (file: File) => Promise<UploadedImage | null>;
onSendAttachment: (file: File) => Promise<void>;
};
export function MessageEditor({
disabled = false,
uploadingAsset = false,
onSend,
onUploadImage,
onSendAttachment,
}: MessageEditorProps) {
const [localUploading, setLocalUploading] = useState(false);
const imageInputRef = useRef<HTMLInputElement | null>(null);
const attachmentInputRef = useRef<HTMLInputElement | null>(null);
const onSendRef = useRef(onSend);
const onUploadImageRef = useRef(onUploadImage);
const onSendAttachmentRef = useRef(onSendAttachment);
const shouldRestoreFocusRef = useRef(false);
const isUploading = uploadingAsset || localUploading;
useEffect(() => {
onSendRef.current = onSend;
}, [onSend]);
useEffect(() => {
onUploadImageRef.current = onUploadImage;
}, [onUploadImage]);
useEffect(() => {
onSendAttachmentRef.current = onSendAttachment;
}, [onSendAttachment]);
const editor = useEditor({
immediatelyRender: false,
extensions: [
StarterKit.configure({
heading: false,
blockquote: false,
codeBlock: false,
bulletList: false,
orderedList: false,
horizontalRule: false,
}),
Image,
Placeholder.configure({
placeholder: "输入消息,Enter 发送,Shift + Enter 换行",
}),
],
content: "",
editorProps: {
attributes: {
class:
"cs-agent-scrollbar min-h-12 max-h-40 overflow-y-auto px-1.5 py-1 text-[13px] leading-6 text-slate-900 outline-none [&_p]:m-0 [&_p+*]:mt-2 [&_img]:my-2 [&_img]:max-h-64 [&_img]:rounded-xl [&_img]:object-contain",
},
handleKeyDown: (_view, event) => {
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
void handleSend();
return true;
}
return false;
},
handlePaste: (_view, event) => {
if (disabled || isUploading) {
return false;
}
const imageFile = getClipboardImageFile(event.clipboardData);
if (!imageFile) {
return false;
}
event.preventDefault();
void insertUploadedImage(imageFile);
return true;
},
},
});
useEffect(() => {
if (!editor) {
return;
}
editor.setEditable(!disabled && !isUploading);
}, [disabled, editor, isUploading]);
useEffect(() => {
if (!editor || disabled || isUploading || !shouldRestoreFocusRef.current) {
return;
}
requestAnimationFrame(() => {
editor.commands.focus();
});
}, [disabled, editor, isUploading]);
async function handleSend() {
if (!editor || disabled || isUploading) {
return;
}
const html = editor.getHTML();
if (!isMeaningfulHTML(html)) {
return;
}
await onSendRef.current(html);
editor.commands.clearContent(true);
}
async function handleSelectImage(event: React.ChangeEvent<HTMLInputElement>) {
const file = event.target.files?.[0];
event.target.value = "";
if (!file || !editor || disabled || isUploading) {
if (editor && shouldRestoreFocusRef.current) {
requestAnimationFrame(() => {
editor.commands.focus();
});
}
return;
}
await insertUploadedImage(file);
}
async function insertUploadedImage(file: File) {
if (!editor || disabled || isUploading) {
return;
}
shouldRestoreFocusRef.current = true;
const objectUrl = URL.createObjectURL(file);
const placeholderId = `uploading-${generateUUID()}`;
editor
.chain()
.focus()
.setImage({
src: objectUrl,
alt: file.name || "uploading-image",
title: placeholderId,
})
.run();
try {
setLocalUploading(true);
const uploaded = await onUploadImageRef.current(file);
if (!uploaded?.url) {
removeImageByTitle(editor, placeholderId);
return;
}
replaceImageSourceByTitle(
editor,
placeholderId,
uploaded.url,
uploaded.filename || "image",
);
} finally {
setLocalUploading(false);
URL.revokeObjectURL(objectUrl);
requestAnimationFrame(() => {
if (!disabled && shouldRestoreFocusRef.current) {
editor.commands.focus();
}
});
}
}
async function handleSelectAttachment(
event: React.ChangeEvent<HTMLInputElement>,
) {
const file = event.target.files?.[0];
event.target.value = "";
if (!file || disabled || isUploading) {
if (editor && shouldRestoreFocusRef.current) {
requestAnimationFrame(() => {
editor.commands.focus();
});
}
return;
}
shouldRestoreFocusRef.current = editor?.isFocused ?? true;
setLocalUploading(true);
try {
await onSendAttachmentRef.current(file);
} finally {
setLocalUploading(false);
requestAnimationFrame(() => {
if (editor && !disabled && shouldRestoreFocusRef.current) {
editor.commands.focus();
}
});
}
}
return (
<div className="px-3 pb-3 pt-2">
<div className="rounded-3xl border border-white/60 bg-white/78 p-2 shadow-[0_10px_24px_rgba(15,23,42,0.05)] backdrop-blur">
<input
ref={imageInputRef}
type="file"
accept="image/*"
className="hidden"
onChange={handleSelectImage}
/>
<input
ref={attachmentInputRef}
type="file"
className="hidden"
onChange={handleSelectAttachment}
/>
<div className="min-h-10">
<EditorContent editor={editor} />
</div>
<div className="mt-1.5 flex items-center justify-between">
<div className="flex items-center gap-1.5">
<button
type="button"
onMouseDown={(event) => event.preventDefault()}
onClick={() => {
shouldRestoreFocusRef.current = editor?.isFocused ?? true;
imageInputRef.current?.click();
}}
disabled={disabled || isUploading}
aria-label={isUploading ? "图片上传中" : "发送图片"}
className="inline-flex size-8 shrink-0 items-center justify-center rounded-xl border border-slate-200/80 bg-white/90 text-slate-500 shadow-[0_8px_18px_rgba(15,23,42,0.05)] transition duration-200 hover:-translate-y-0.5 hover:text-slate-700 disabled:translate-y-0 disabled:cursor-not-allowed disabled:bg-slate-100 disabled:text-slate-300"
>
<ImageIcon className="size-4" />
</button>
<button
type="button"
onMouseDown={(event) => event.preventDefault()}
onClick={() => {
shouldRestoreFocusRef.current = editor?.isFocused ?? true;
attachmentInputRef.current?.click();
}}
disabled={disabled || isUploading}
aria-label={isUploading ? "附件上传中" : "发送附件"}
className="inline-flex size-8 shrink-0 items-center justify-center rounded-xl border border-slate-200/80 bg-white/90 text-slate-500 shadow-[0_8px_18px_rgba(15,23,42,0.05)] transition duration-200 hover:-translate-y-0.5 hover:text-slate-700 disabled:translate-y-0 disabled:cursor-not-allowed disabled:bg-slate-100 disabled:text-slate-300"
>
<PaperclipIcon className="size-4" />
</button>
</div>
<div className="flex items-center gap-1">
<p className="text-[10px] text-slate-400">Enter </p>
<button
type="button"
onClick={() => void handleSend()}
disabled={disabled || isUploading}
aria-label="发送"
className="inline-flex size-8 shrink-0 items-center justify-center rounded-xl bg-[linear-gradient(135deg,var(--primary),color-mix(in_srgb,var(--primary)_75%,white_25%))] text-white shadow-[0_10px_20px_color-mix(in_srgb,var(--primary)_28%,transparent)] transition duration-200 hover:-translate-y-0.5 hover:brightness-105 disabled:translate-y-0 disabled:cursor-not-allowed disabled:bg-slate-300 disabled:shadow-none"
>
<SendHorizonalIcon className="size-4" />
</button>
</div>
</div>
</div>
</div>
);
}
function isMeaningfulHTML(html: string) {
const normalized = html
.replace(/<p><\/p>/g, "")
.replace(/<p><br><\/p>/g, "")
.replace(/\s+/g, "");
if (/<img[\s\S]*?>/i.test(normalized)) {
return true;
}
const plainText = normalized.replace(/<[^>]+>/g, "").trim();
return plainText !== "";
}
function getClipboardImageFile(clipboardData: DataTransfer | null) {
if (!clipboardData) {
return null;
}
for (const item of Array.from(clipboardData.items)) {
if (item.kind === "file" && item.type.startsWith("image/")) {
return item.getAsFile();
}
}
return null;
}
function removeImageByTitle(editor: NonNullable<ReturnType<typeof useEditor>>, title: string) {
const { state } = editor;
let targetPos: number | null = null;
state.doc.descendants((node, pos) => {
if (node.type.name === "image" && node.attrs.title === title) {
targetPos = pos;
return false;
}
return true;
});
if (targetPos === null) {
return;
}
editor.chain().focus().deleteRange({ from: targetPos, to: targetPos + 1 }).run();
}
function replaceImageSourceByTitle(
editor: NonNullable<ReturnType<typeof useEditor>>,
title: string,
src: string,
alt: string,
) {
const { state, view } = editor;
let targetPos: number | null = null;
state.doc.descendants((node, pos) => {
if (node.type.name === "image" && node.attrs.title === title) {
targetPos = pos;
return false;
}
return true;
});
if (targetPos === null) {
return;
}
const transaction = view.state.tr.setNodeMarkup(targetPos, undefined, {
...view.state.doc.nodeAt(targetPos)?.attrs,
src,
alt,
title: "",
});
view.dispatch(transaction);
}
+82
View File
@@ -0,0 +1,82 @@
"use client";
import { memo, useEffect, useRef } from "react";
type MessageHTMLProps = {
html: string;
className?: string;
onImageSettled?: () => void;
onImageClick?: (src: string, alt?: string) => void;
};
function MessageHTMLComponent({
html,
className = "",
onImageSettled,
onImageClick,
}: MessageHTMLProps) {
const containerRef = useRef<HTMLDivElement>(null);
const onImageSettledRef = useRef(onImageSettled);
const onImageClickRef = useRef(onImageClick);
useEffect(() => {
onImageSettledRef.current = onImageSettled;
}, [onImageSettled]);
useEffect(() => {
onImageClickRef.current = onImageClick;
}, [onImageClick]);
useEffect(() => {
const container = containerRef.current;
if (!container) {
return;
}
const images = Array.from(container.querySelectorAll("img"));
if (images.length === 0) {
return;
}
const cleanups = images.map((image) => {
const handleSettled = () => onImageSettledRef.current?.();
const handleClick = () => {
const src = image.getAttribute("src");
if (src) {
const alt = image.getAttribute("alt") ?? undefined;
onImageClickRef.current?.(src, alt);
}
};
image.addEventListener("load", handleSettled);
image.addEventListener("error", handleSettled);
image.addEventListener("click", handleClick);
if (image.complete) {
onImageSettledRef.current?.();
}
image.classList.add("cursor-zoom-in");
return () => {
image.removeEventListener("load", handleSettled);
image.removeEventListener("error", handleSettled);
image.removeEventListener("click", handleClick);
};
});
return () => {
cleanups.forEach((cleanup) => cleanup());
};
}, [html, onImageSettled, onImageClick]);
return (
<div
ref={containerRef}
className={`break-words [&_p]:m-0 [&_p+*]:mt-2 [&_img]:my-2 [&_img]:max-h-64 [&_img]:rounded-xl [&_img]:object-contain [&_img]:max-w-full [&_.im-attachment]:min-w-0 [&_.im-attachment-link]:flex [&_.im-attachment-link]:min-w-0 [&_.im-attachment-link]:items-center [&_.im-attachment-link]:gap-3 [&_.im-attachment-link]:rounded-2xl [&_.im-attachment-link]:no-underline [&_.im-attachment-link]:transition-colors hover:[&_.im-attachment-link]:bg-black/5 [&_.im-attachment-icon]:flex [&_.im-attachment-icon]:size-10 [&_.im-attachment-icon]:shrink-0 [&_.im-attachment-icon]:items-center [&_.im-attachment-icon]:justify-center [&_.im-attachment-icon]:rounded-2xl [&_.im-attachment-icon]:bg-black/5 [&_.im-attachment-icon_svg]:size-5 [&_.im-attachment-content]:flex [&_.im-attachment-content]:min-w-0 [&_.im-attachment-content]:flex-col [&_.im-attachment-title]:truncate [&_.im-attachment-title]:font-medium [&_.im-attachment-meta]:text-xs [&_.im-attachment-meta]:opacity-70 ${className}`}
dangerouslySetInnerHTML={{ __html: html }}
/>
);
}
export const MessageHTML = memo(
MessageHTMLComponent,
(prevProps, nextProps) =>
prevProps.html === nextProps.html &&
prevProps.className === nextProps.className &&
prevProps.onImageSettled === nextProps.onImageSettled &&
prevProps.onImageClick === nextProps.onImageClick,
);
+123
View File
@@ -0,0 +1,123 @@
"use client";
import { useLayoutEffect, useRef, useState } from "react";
import { ImageIcon, SendHorizonalIcon } from "lucide-react";
type MessageInputProps = {
disabled?: boolean;
uploadingImage?: boolean;
onSend: (content: string) => Promise<void>;
onSendImage: (file: File) => Promise<void>;
};
export function MessageInput({
disabled,
uploadingImage = false,
onSend,
onSendImage,
}: MessageInputProps) {
const [value, setValue] = useState("");
const [submitting, setSubmitting] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
const imageInputRef = useRef<HTMLInputElement | null>(null);
useLayoutEffect(() => {
const textarea = textareaRef.current;
if (!textarea) {
return;
}
const lineHeight = 20;
const maxHeight = lineHeight * 8;
textarea.style.height = "0px";
textarea.style.height = `${Math.min(textarea.scrollHeight, maxHeight)}px`;
textarea.style.overflowY =
textarea.scrollHeight > maxHeight ? "auto" : "hidden";
}, [value]);
async function handleSubmit() {
const content = value.trim();
if (!content || disabled || submitting) {
return;
}
setSubmitting(true);
try {
await onSend(content);
setValue("");
} finally {
setSubmitting(false);
requestAnimationFrame(() => {
textareaRef.current?.focus();
});
}
}
async function handleSelectImage(event: React.ChangeEvent<HTMLInputElement>) {
const file = event.target.files?.[0];
event.target.value = "";
if (!file || disabled || uploadingImage || submitting) {
return;
}
if (!file.type.startsWith("image/")) {
return;
}
try {
await onSendImage(file);
} finally {
requestAnimationFrame(() => {
textareaRef.current?.focus();
});
}
}
return (
<div className="px-3 pb-3 pt-2">
<div className="rounded-3xl border border-white/60 bg-white/78 p-2.5 shadow-[0_10px_24px_rgba(15,23,42,0.05)] backdrop-blur">
<input
ref={imageInputRef}
type="file"
accept="image/*"
className="hidden"
onChange={handleSelectImage}
/>
<div className="flex items-start gap-3">
<textarea
ref={textareaRef}
value={value}
onChange={(event) => setValue(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
void handleSubmit();
}
}}
placeholder="输入消息,Enter 发送,Shift + Enter 换行"
disabled={disabled || uploadingImage}
rows={2}
className="cs-agent-scrollbar min-h-12 flex-1 resize-none bg-transparent px-1.5 pt-1 text-[13px] leading-6 text-slate-900 outline-none placeholder:text-slate-400 disabled:cursor-not-allowed"
/>
<button
type="button"
onClick={() => imageInputRef.current?.click()}
disabled={disabled || uploadingImage || submitting}
aria-label={uploadingImage ? "图片上传中" : "发送图片"}
className="mt-1 inline-flex size-11 shrink-0 items-center justify-center rounded-2xl border border-slate-200/80 bg-white/90 text-slate-500 shadow-[0_10px_24px_rgba(15,23,42,0.05)] transition duration-200 hover:-translate-y-0.5 hover:text-slate-700 disabled:translate-y-0 disabled:cursor-not-allowed disabled:bg-slate-100 disabled:text-slate-300"
>
<ImageIcon className="size-4" />
</button>
<button
type="button"
onClick={handleSubmit}
disabled={disabled || submitting || uploadingImage}
aria-label={submitting ? "发送中" : "发送"}
className="mt-1 inline-flex size-11 shrink-0 items-center justify-center rounded-2xl bg-[linear-gradient(135deg,var(--primary),color-mix(in_srgb,var(--primary)_75%,white_25%))] text-white shadow-[0_12px_26px_color-mix(in_srgb,var(--primary)_28%,transparent)] transition duration-200 hover:-translate-y-0.5 hover:brightness-105 disabled:translate-y-0 disabled:cursor-not-allowed disabled:bg-slate-300 disabled:shadow-none"
>
<SendHorizonalIcon className="size-4" />
</button>
</div>
<div className="mt-2 px-1.5 text-[11px] text-slate-400">
Enter
</div>
</div>
</div>
);
}
+348
View File
@@ -0,0 +1,348 @@
"use client";
import {
forwardRef,
memo,
useCallback,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
} from "react";
import Image from "next/image";
import { MessageHTML } from "@/components/im/message-html";
import { useImageLightbox } from "@/components/image-lightbox";
import { renderMessageHTML } from "@/lib/services/message-asset";
import type { WidgetMessage } from "@/lib/services/types";
import { cn, formatDateTime } from "@/lib/utils";
type MessageListProps = {
messages: WidgetMessage[];
onNearBottomVisible?: () => void;
hasMoreOlder?: boolean;
loadingOlder?: boolean;
onLoadOlder?: () => Promise<void>;
};
export type MessageListHandle = {
scrollToBottom: () => void;
};
function getDayKey(value?: string) {
if (!value) {
return "unknown";
}
const date = new Date(value);
if (Number.isNaN(date.getTime())) {
return value.slice(0, 10);
}
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(
date.getDate(),
).padStart(2, "0")}`;
}
function getTimelineLabel(value?: string) {
if (!value) {
return "刚刚";
}
const date = new Date(value);
if (Number.isNaN(date.getTime())) {
return value;
}
const now = new Date();
const currentDayKey = getDayKey(value);
const todayDayKey = getDayKey(now.toISOString());
const timeText = `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
if (currentDayKey === todayDayKey) {
return `今天 ${timeText}`;
}
return `${currentDayKey} ${timeText}`;
}
export const MessageList = forwardRef<MessageListHandle, MessageListProps>(
function MessageList(
{
messages,
onNearBottomVisible,
hasMoreOlder = false,
loadingOlder = false,
onLoadOlder,
},
ref,
) {
const containerRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const frameRef = useRef<number | null>(null);
const shouldStickToBottomRef = useRef(true);
const lastMessageId = messages.at(-1)?.id;
const isNearBottom = useCallback(
(element: HTMLElement, threshold = 80) =>
element.scrollHeight - element.scrollTop - element.clientHeight <=
threshold,
[],
);
const scrollToBottom = useCallback(() => {
const container = containerRef.current;
if (!container) {
return;
}
container.scrollTop = container.scrollHeight;
}, []);
const scheduleScrollToBottom = useCallback(
(attempts = 4) => {
if (frameRef.current !== null) {
cancelAnimationFrame(frameRef.current);
}
const run = (remaining: number, previousHeight = -1) => {
frameRef.current = requestAnimationFrame(() => {
const container = containerRef.current;
if (!container) {
frameRef.current = null;
return;
}
const currentHeight = container.scrollHeight;
scrollToBottom();
if (remaining > 1 && currentHeight !== previousHeight) {
run(remaining - 1, currentHeight);
return;
}
frameRef.current = null;
});
};
run(attempts);
},
[scrollToBottom],
);
const handleImageSettled = useCallback(() => {
if (shouldStickToBottomRef.current) {
scheduleScrollToBottom();
onNearBottomVisible?.();
}
}, [onNearBottomVisible, scheduleScrollToBottom]);
useImperativeHandle(ref, () => ({
scrollToBottom,
}));
useLayoutEffect(() => {
shouldStickToBottomRef.current = true;
scheduleScrollToBottom();
return () => {
if (frameRef.current !== null) {
cancelAnimationFrame(frameRef.current);
frameRef.current = null;
}
};
}, [lastMessageId, scheduleScrollToBottom]);
useEffect(() => {
const container = containerRef.current;
const content = contentRef.current;
if (!container || !content) {
return;
}
const handleScroll = () => {
shouldStickToBottomRef.current = isNearBottom(container);
if (shouldStickToBottomRef.current) {
onNearBottomVisible?.();
}
};
const resizeObserver = new ResizeObserver(() => {
if (shouldStickToBottomRef.current) {
scheduleScrollToBottom();
}
});
handleScroll();
container.addEventListener("scroll", handleScroll);
resizeObserver.observe(content);
scrollToBottom();
return () => {
container.removeEventListener("scroll", handleScroll);
resizeObserver.disconnect();
};
}, [
isNearBottom,
onNearBottomVisible,
scheduleScrollToBottom,
scrollToBottom,
]);
const handleLoadOlder = useCallback(async () => {
if (!onLoadOlder || loadingOlder || !hasMoreOlder) {
return;
}
const container = containerRef.current;
if (!container) {
return;
}
const anchor = {
height: container.scrollHeight,
top: container.scrollTop,
};
try {
await onLoadOlder();
} catch {
return;
}
requestAnimationFrame(() => {
requestAnimationFrame(() => {
const c = containerRef.current;
if (!c) {
return;
}
c.scrollTop = c.scrollHeight - anchor.height + anchor.top;
});
});
}, [hasMoreOlder, loadingOlder, onLoadOlder]);
return (
<div
ref={containerRef}
className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-4 py-4 cs-agent-scrollbar"
>
<div ref={contentRef} className="flex flex-col gap-4">
{hasMoreOlder && onLoadOlder ? (
<div className="flex justify-center py-1">
<button
type="button"
disabled={loadingOlder}
onClick={() => void handleLoadOlder()}
className="rounded-full border border-white/70 bg-white/75 px-3 py-1 text-[11px] font-medium text-slate-500 shadow-[0_8px_18px_rgba(15,23,42,0.04)] backdrop-blur transition hover:-translate-y-0.5 hover:border-sky-200 hover:text-sky-700 disabled:translate-y-0 disabled:opacity-60"
>
{loadingOlder ? "加载中…" : "加载更早的消息"}
</button>
</div>
) : null}
{/* <WelcomePanel title={title} welcomeText={welcomeText} /> */}
{/* {messages.length === 0 ? (
<div className="cs-agent-fade-up rounded-3xl border border-dashed border-slate-200 bg-white/72 px-4 py-5 text-sm leading-6 text-slate-500 shadow-[0_10px_22px_rgba(15,23,42,0.04)] backdrop-blur">
开始发送第一条消息后,会在这里保留完整会话记录。
</div>
) : null} */}
{messages.map((message, index) => {
const previousMessage = index > 0 ? messages[index - 1] : null;
const showTimeline =
index === 0 ||
getDayKey(previousMessage?.sentAt) !== getDayKey(message.sentAt);
return (
<MessageItem
key={message.id}
message={message}
showTimeline={showTimeline}
onImageSettled={handleImageSettled}
/>
);
})}
</div>
</div>
);
},
);
type MessageItemProps = {
message: WidgetMessage;
showTimeline: boolean;
onImageSettled: () => void;
};
const MessageItem = memo(
function MessageItem({
message,
showTimeline,
onImageSettled,
}: MessageItemProps) {
const { open: openImageLightbox } = useImageLightbox();
const isCustomer = message.senderType === "customer";
const senderName = isCustomer ? "我" : message.senderName?.trim() || "客服";
const agentAvatarSrc =
!isCustomer && message.senderAvatar?.trim()
? message.senderAvatar.trim()
: undefined;
const htmlContent = buildMessageHTML(message);
return (
<div className="cs-agent-fade-up">
{showTimeline ? (
<div className="mb-3 flex items-center justify-center">
<div className="rounded-full border border-white/70 bg-white/80 px-3 py-1 text-[11px] font-medium text-slate-500 shadow-[0_8px_18px_rgba(15,23,42,0.04)] backdrop-blur">
{getTimelineLabel(message.sentAt)}
</div>
</div>
) : null}
<div
className={cn(
"flex gap-2",
isCustomer ? "justify-end" : "justify-start",
)}
>
{!isCustomer && agentAvatarSrc ? (
<Image
src={agentAvatarSrc}
alt=""
width={32}
height={32}
className="size-8 shrink-0 rounded-full object-cover ring-1 ring-white/80"
/>
) : null}
<div
className={cn(
"flex max-w-[86%] flex-col gap-1",
isCustomer ? "items-end" : "items-start",
)}
>
<div className="flex items-center gap-2 px-1 text-[11px] text-slate-400">
<span className="font-medium">{senderName}</span>
<span>{formatDateTime(message.sentAt)}</span>
{isCustomer ? (
<span>{message.agentRead ? "客服已读" : "客服未读"}</span>
) : null}
</div>
<div
className={cn(
"rounded-lg px-3 py-2 text-sm leading-normal shadow-[0_14px_28px_rgba(15,23,42,0.08)]",
isCustomer
? "bg-[linear-gradient(135deg,var(--primary),color-mix(in_srgb,var(--primary)_78%,white_22%))] text-white"
: "border border-white/80 bg-white/94 text-slate-900",
)}
>
<MessageHTML
html={htmlContent}
className={cn(
isCustomer
? "[&_p]:text-white [&_a]:text-white [&_a]:underline [&_img]:cursor-zoom-in"
: "[&_a]:text-slate-900 [&_a]:underline [&_img]:cursor-zoom-in",
)}
onImageSettled={onImageSettled}
onImageClick={openImageLightbox}
/>
</div>
</div>
</div>
</div>
);
},
(prevProps, nextProps) =>
prevProps.message === nextProps.message &&
prevProps.showTimeline === nextProps.showTimeline &&
prevProps.onImageSettled === nextProps.onImageSettled,
);
function buildMessageHTML(message: WidgetMessage) {
return renderMessageHTML(message);
}