123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723 |
- class ChatUI {
- constructor() {
- this.messageContainer = document.getElementById("chat-messages");
- this.input = document.getElementById("chat-input");
- this.sendButton = document.getElementById("send-button");
- this.promptButton = document.getElementById("prompt-button");
- this.promptPanel = document.getElementById("prompt-panel");
- // 确保AI服务已经初始化
- if (!window.aiService) {
- throw new Error("AI Service not initialized");
- }
- this.aiService = window.aiService;
- this.typingSpeed = 50;
- this.inputWrapper = document.querySelector(".input-wrapper");
- // 先添加过渡动画类
- this.input.classList.add("input-transition");
- // 设置初始高度
- this.input.style.height = "40px";
- // 获取总结按钮
- this.summarizeButton = document.querySelector(".summarize-button");
- // 初始化其他组件
- this.setupEventListeners();
- this.init();
- // 使用微任务确保DOM更新后再调整高度
- Promise.resolve().then(() => {
- // 第一帧:等待过渡动画类生效
- requestAnimationFrame(() => {
- // 第二帧:执行高度调整
- requestAnimationFrame(() => {
- this.adjustInputHeight();
- // 触发一次输入框focus以确保正确的高度
- this.input.focus();
- });
- });
- });
- // 添加新消息指示器
- this.createNewMessageIndicator();
- // 监听滚动事件
- this.messageContainer.addEventListener(
- "scroll",
- this.handleScroll.bind(this)
- );
- // 创建打断按钮
- this.stopButton = document.createElement("button");
- this.stopButton.className = "stop-button";
- this.stopButton.innerHTML = `
- <svg viewBox="0 0 24 24" fill="currentColor">
- <path d="M6 6h12v12H6z"/>
- </svg>
- <span>停止生成</span>
- `;
- // 将打断按钮添加到输入按钮区域
- document.querySelector(".input-buttons").appendChild(this.stopButton);
- // 添加打断按钮事件监听
- this.stopButton.addEventListener("click", () => this.handleStop());
- this.isTyping = false; // 添加打字状态标记
- this.loadingDiv = null; // 添加加载动画的引用
- // 初始化页面信息卡片
- this.initPageInfoCard();
- }
- async init() {
- try {
- await this.aiService.init();
- await this.checkApiKey();
- } catch (error) {
- console.error("ChatUI initialization failed:", error);
- this.addMessage("初始化失败,请刷新页面重试。", "assistant");
- }
- }
- setupEventListeners() {
- // 发送消息
- this.sendButton.addEventListener("click", () => this.handleSend());
- this.input.addEventListener("keydown", (e) => {
- if (e.key === "Enter" && !e.shiftKey) {
- e.preventDefault();
- this.handleSend();
- }
- });
- // 自动调整输入框高度
- this.input.addEventListener("input", () => this.adjustInputHeight());
- // 添加focus事件监听,确保在获得焦点时高度正确
- this.input.addEventListener("focus", () => {
- requestAnimationFrame(() => this.adjustInputHeight());
- });
- // 快捷指令面板
- this.promptButton.addEventListener("click", () => this.togglePromptPanel());
- document.querySelector(".close-prompt").addEventListener("click", () => {
- this.promptPanel.classList.remove("show");
- });
- // 点击快捷指令
- document.querySelectorAll(".prompt-item").forEach((item) => {
- item.addEventListener("click", () => {
- // 获取文本内容并处理格式
- const text = item.textContent
- .trim() // 移除首尾空白
- .replace(/\s+/g, " ") // 将多个空白字符替换为单个空格
- .replace(/[\n\r]+/g, ""); // 移除所有换行符
- // 设置到输入框
- this.input.value = text;
- this.promptPanel.classList.remove("show");
- // 调整输入框高度并聚焦
- this.adjustInputHeight();
- this.input.focus();
- });
- });
- // 点击外部关闭快捷指令面板
- document.addEventListener("click", (e) => {
- if (
- !this.promptPanel.contains(e.target) &&
- !this.promptButton.contains(e.target)
- ) {
- this.promptPanel.classList.remove("show");
- }
- });
- // 添加总结按钮点击事件
- if (this.summarizeButton) {
- this.summarizeButton.addEventListener("click", () => {
- this.handleSummarize();
- });
- }
- // 工具箱面板
- const toolsButton = document.getElementById("tools-button");
- const toolsPanel = document.getElementById("tools-panel");
- const closeTools = document.querySelector(".close-tools");
- toolsButton.addEventListener("click", () => {
- toolsPanel.classList.toggle("show");
- // 关闭其他面板
- this.promptPanel.classList.remove("show");
- });
- closeTools.addEventListener("click", () => {
- toolsPanel.classList.remove("show");
- });
- // 点击外部关闭工具箱面板
- document.addEventListener("click", (e) => {
- if (!toolsPanel.contains(e.target) && !toolsButton.contains(e.target)) {
- toolsPanel.classList.remove("show");
- }
- });
- // 文件上传功能
- const uploadButton = document.getElementById("upload-button");
- const fileInput = document.getElementById("file-input");
- uploadButton.addEventListener("click", () => {
- fileInput.click();
- });
- fileInput.addEventListener("change", (e) => {
- const files = Array.from(e.target.files);
- if (files.length > 0) {
- // 处理文件上传
- this.handleFileUpload(files);
- }
- // 清空文件输入框,以便可以重复选择同一文件
- fileInput.value = "";
- });
- }
- async handleSend() {
- const message = this.input.value.trim();
- if (!message) return;
- // 处理命令
- if (message.startsWith("/setapi ")) {
- const apiKey = message.substring(8).trim();
- await this.aiService.setApiKey(apiKey);
- // 根据是否使用默认密钥显示不同消息
- if (apiKey === CONFIG.AI_API.DEFAULT_API_KEY) {
- this.addMessage("已恢复使用默认API密钥", "assistant", false);
- } else {
- this.addMessage("自定义API密钥已设置", "assistant", false);
- }
- this.input.value = "";
- return;
- }
- // 添加用户消息
- this.addMessage(message, "user", false);
- // 更新上下文
- this.aiService.updateContext(message, "user");
- // 清空输入框
- this.input.value = "";
- this.adjustInputHeight();
- try {
- this.stopButton.classList.add("show");
- this.setInputState(true); // 禁用输入框
- this.loadingDiv = this.createLoadingMessage();
- const response = await this.aiService.sendMessage(message);
- if (this.loadingDiv) {
- this.loadingDiv.remove();
- this.loadingDiv = null;
- }
- if (!response) return;
- this.isTyping = false;
- await this.addMessage(response, "assistant", true);
- this.stopButton.classList.remove("show");
- this.setInputState(false); // 这里会自动聚焦输入框
- this.aiService.updateContext(response, "assistant");
- } catch (error) {
- if (this.loadingDiv) {
- this.loadingDiv.remove();
- this.loadingDiv = null;
- }
- this.stopButton.classList.remove("show");
- this.setInputState(false); // 这里也会自动聚焦输入框
- this.isTyping = false;
- if (error.message === "REQUEST_ABORTED") {
- return;
- }
- this.addMessage("抱歉,发生了一些错误,请稍后重试。", "assistant", false);
- console.error("AI response error:", error);
- }
- }
- /**
- * 添加消息到聊天界面
- * @param {string} content 消息内容
- * @param {string} type 消息类型(user/assistant)
- * @param {boolean} typing 是否使用打字效果
- * @param {boolean} isInterrupted 是否是中断消息
- */
- async addMessage(
- content,
- type,
- typing = type === "assistant",
- isInterrupted = false
- ) {
- const messageDiv = document.createElement("div");
- messageDiv.className = `message ${type}`;
- const messageContent = document.createElement("div");
- messageContent.className = "message-content";
- if (isInterrupted) {
- messageContent.classList.add("interrupted");
- }
- const paragraph = document.createElement("p");
- messageContent.appendChild(paragraph);
- // 创建操作栏(时间戳和复制按钮)
- const actionsDiv = document.createElement("div");
- actionsDiv.className = "message-actions";
- // 只为非中断的AI消息添加复制按钮
- if (type === "assistant" && !isInterrupted) {
- const copyButton = this.createCopyButton(content);
- actionsDiv.appendChild(copyButton);
- }
- // 添加时间戳
- const timestamp = document.createElement("div");
- timestamp.className = "message-timestamp";
- timestamp.textContent = this.formatTime(new Date());
- actionsDiv.appendChild(timestamp);
- messageContent.appendChild(actionsDiv);
- messageDiv.appendChild(messageContent);
- this.messageContainer.appendChild(messageDiv);
- if (typing) {
- messageContent.classList.add("typing");
- await this.typeMessage(paragraph, content);
- messageContent.classList.remove("typing");
- } else {
- paragraph.innerHTML = this.formatMessage(content);
- }
- const { scrollTop, scrollHeight, clientHeight } = this.messageContainer;
- const wasAtBottom = scrollHeight - scrollTop - clientHeight < 100;
- if (wasAtBottom) {
- this.scrollToBottom();
- } else {
- this.newMessageIndicator.classList.add("show");
- }
- }
- /**
- * 实现打字机效果
- * @param {HTMLElement} element 要添加文字的元素
- * @param {string} text 要显示的文字
- */
- async typeMessage(element, text) {
- let index = 0;
- const rawText = text;
- const tempDiv = document.createElement("div");
- this.isTyping = true; // 开始打字
- return new Promise((resolve) => {
- const type = () => {
- // 检查是否被中断
- if (!this.isTyping) {
- resolve();
- return;
- }
- if (index < rawText.length) {
- const currentText = rawText.substring(0, index + 1);
- tempDiv.innerHTML = this.formatMessage(currentText);
- element.innerHTML = tempDiv.innerHTML;
- index++;
- this.scrollToBottom();
- setTimeout(type, this.typingSpeed);
- } else {
- this.isTyping = false; // 打字结束
- resolve();
- }
- };
- type();
- });
- }
- adjustInputHeight() {
- const scrollPos = this.input.scrollTop;
- // 获取当前高度
- const currentHeight = this.input.style.height;
- // 重置高度
- this.input.style.height = "auto";
- // 计算新高度
- const newHeight = Math.min(this.input.scrollHeight, 120);
- // 如果高度有变化才设置
- if (currentHeight !== `${newHeight}px`) {
- this.input.style.height = `${newHeight}px`;
- }
- // 恢复滚动位置
- this.input.scrollTop = scrollPos;
- }
- scrollToBottom() {
- this.messageContainer.scrollTop = this.messageContainer.scrollHeight;
- }
- togglePromptPanel() {
- this.promptPanel.classList.toggle("show");
- }
- escapeHtml(html) {
- const div = document.createElement("div");
- div.textContent = html;
- return div.innerHTML;
- }
- async checkApiKey() {
- // 只有当没有任何API密钥时才显示提示
- if (!this.aiService.apiKey) {
- this.addMessage(
- "请先设置DeepSeek API密钥。输入格式:/setapi YOUR_API_KEY",
- "assistant"
- );
- }
- }
- /**
- * 创建加载动画消息
- */
- createLoadingMessage() {
- const loadingDiv = document.createElement("div");
- loadingDiv.className = "message assistant";
- loadingDiv.innerHTML = `
- <div class="message-content loading">
- <div class="typing-indicator">
- <span></span>
- <span></span>
- <span></span>
- </div>
- </div>
- `;
- this.messageContainer.appendChild(loadingDiv);
- this.scrollToBottom();
- return loadingDiv;
- }
- /**
- * 格式化时间
- */
- formatTime(date) {
- const hours = date.getHours().toString().padStart(2, "0");
- const minutes = date.getMinutes().toString().padStart(2, "0");
- return `${hours}:${minutes}`;
- }
- createNewMessageIndicator() {
- this.newMessageIndicator = document.createElement("div");
- this.newMessageIndicator.className = "new-messages-indicator";
- this.newMessageIndicator.textContent = "新消息";
- this.newMessageIndicator.addEventListener("click", () => {
- this.scrollToBottom();
- });
- document
- .querySelector(".chat-container")
- .appendChild(this.newMessageIndicator);
- }
- handleScroll() {
- const { scrollTop, scrollHeight, clientHeight } = this.messageContainer;
- const isNearBottom = scrollHeight - scrollTop - clientHeight < 100;
- if (isNearBottom) {
- this.newMessageIndicator.classList.remove("show");
- }
- }
- /**
- * 格式化消息内容
- * @param {string} text 原始文本
- * @returns {string} 格式化后的HTML
- */
- formatMessage(text) {
- if (!text) return "";
- return (
- text
- // 处理标题 (h1 ~ h6)
- .replace(/^#{1,6}\s+(.+)$/gm, (match, content) => {
- const level = match.trim().split("#").length - 1;
- return `<h${level}>${content.trim()}</h${level}>`;
- })
- // 处理换行
- .replace(/\n/g, "<br>")
- // 处理连续空格
- .replace(/ {2,}/g, (match) => " ".repeat(match.length))
- // 处理代码块
- .replace(
- /```([\s\S]*?)```/g,
- (match, code) =>
- `<pre><code>${this.escapeHtml(code.trim())}</code></pre>`
- )
- // 处理行内代码
- .replace(
- /`([^`]+)`/g,
- (match, code) => `<code>${this.escapeHtml(code)}</code>`
- )
- // 处理粗体
- .replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>")
- // 处理斜体
- .replace(/\*(.*?)\*/g, "<em>$1</em>")
- // 处理链接
- .replace(
- /\[([^\]]+)\]\(([^)]+)\)/g,
- '<a href="$2" target="_blank">$1</a>'
- )
- // 处理无序列表
- .replace(/^[*-]\s+(.+)$/gm, "<li>$1</li>")
- .replace(/(<li>.*<\/li>)/gs, "<ul>$1</ul>")
- // 处理有序列表
- .replace(/^\d+\.\s+(.+)$/gm, "<li>$1</li>")
- .replace(/(<li>.*<\/li>)/gs, "<ol>$1</ol>")
- // 处理分隔线
- .replace(/^---+$/gm, "<hr>")
- // 处理引用
- .replace(/^>\s+(.+)$/gm, "<blockquote>$1</blockquote>")
- );
- }
- /**
- * 创建复制按钮
- * @param {string} content 要复制的内容
- * @returns {HTMLElement} 复制按钮元素
- */
- createCopyButton(content) {
- const button = document.createElement("button");
- button.className = "copy-button";
- button.innerHTML = `
- <svg viewBox="0 0 24 24" fill="currentColor">
- <path d="M16 1H4C2.9 1 2 1.9 2 3v14h2V3h12V1zm3 4H8C6.9 5 6 5.9 6 7v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/>
- </svg>
- <span>复制</span>
- `;
- button.addEventListener("click", async () => {
- try {
- // 直接使用传入的原始内容
- await this.copyToClipboard(content);
- // 显示复制成功状态
- button.classList.add("copied");
- button.innerHTML = `
- <svg viewBox="0 0 24 24" fill="currentColor">
- <path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"/>
- </svg>
- <span>已复制</span>
- `;
- // 2秒后恢复原始状态
- setTimeout(() => {
- button.classList.remove("copied");
- button.innerHTML = `
- <svg viewBox="0 0 24 24" fill="currentColor">
- <path d="M16 1H4C2.9 1 2 1.9 2 3v14h2V3h12V1zm3 4H8C6.9 5 6 5.9 6 7v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/>
- </svg>
- <span>复制</span>
- `;
- }, 2000);
- } catch (err) {
- console.error("Failed to copy text:", err);
- }
- });
- return button;
- }
- /**
- * 复制文本到剪贴板
- * @param {string} text 要复制的文本
- */
- async copyToClipboard(text) {
- try {
- // 通过postMessage发送复制请求到content script
- window.parent.postMessage(
- {
- type: "COPY_TO_CLIPBOARD",
- text: text,
- },
- "*"
- );
- return true;
- } catch (err) {
- console.error("Failed to copy text:", err);
- throw err;
- }
- }
- // 处理打断请求
- async handleStop() {
- try {
- this.aiService.abortRequest();
- if (this.isTyping) {
- this.isTyping = false;
- }
- if (this.loadingDiv) {
- this.loadingDiv.remove();
- this.loadingDiv = null;
- }
- this.stopButton.classList.remove("show");
- this.setInputState(false); // 中断后也自动聚焦输入框
- this.addMessage("用户手动停止生成", "assistant", false, true);
- } catch (error) {
- console.error("Failed to stop generation:", error);
- }
- }
- // 设置输入框状态
- setInputState(isGenerating) {
- this.input.disabled = isGenerating;
- this.input.placeholder = isGenerating ? "回复生成中..." : "输入消息...";
- if (isGenerating) {
- this.inputWrapper.classList.add("generating");
- } else {
- this.inputWrapper.classList.remove("generating");
- // AI回复完成后,自动聚焦到输入框
- this.input.focus();
- }
- }
- /**
- * 初始化页面信息卡片
- */
- initPageInfoCard() {
- // 从父窗口获取页面信息
- window.addEventListener("message", (event) => {
- if (event.data.type === "PAGE_INFO") {
- const pageInfo = event.data.pageInfo;
- this.updatePageInfoCard(pageInfo);
- }
- });
- }
- updatePageInfoCard(pageInfo) {
- // 更新卡片内容
- const favicon = document.querySelector(".page-favicon");
- const title = document.querySelector(".page-title");
- // 如果favicon发生变化,更新图标
- if (favicon.src !== pageInfo.favicon) {
- favicon.src = pageInfo.favicon;
- favicon.onerror = () => {
- // 如果图标加载失败,使用默认图标
- favicon.src = chrome.runtime.getURL("images/icon16.png");
- };
- }
- // 如果标题发生变化,更新标题
- if (title.textContent !== pageInfo.title) {
- title.textContent = pageInfo.title;
- }
- }
- /**
- * 获取页面favicon
- * @returns {string} favicon URL
- */
- getPageFavicon() {
- // 尝试获取页面favicon
- const iconLink = document.querySelector('link[rel*="icon"]');
- if (iconLink) return iconLink.href;
- // 如果没有找到,返回网站根目录的favicon.ico
- const url = new URL(window.location.href);
- return `${url.protocol}//${url.hostname}/favicon.ico`;
- }
- /**
- * 处理总结请求
- */
- async handleSummarize() {
- try {
- // 显示加载状态
- this.setInputState(true);
- this.loadingDiv = this.createLoadingMessage();
- // 通过postMessage请求页面分析结果
- const pageInfo = await new Promise((resolve) => {
- // 创建一次性消息监听器
- const messageHandler = (event) => {
- if (event.data.type === "PAGE_ANALYSIS_RESULT") {
- window.removeEventListener("message", messageHandler);
- resolve(event.data.pageInfo);
- }
- };
- // 添加消息监听
- window.addEventListener("message", messageHandler);
- // 发送分析请求到父页面
- window.parent.postMessage({ type: "ANALYZE_PAGE" }, "*");
- });
- // 构建提示词
- const prompt = this.aiService.getSummaryPrompt(pageInfo);
- // 发送分析请求
- const response = await this.aiService.sendMessage(prompt);
- // 显示分析结果
- if (this.loadingDiv) {
- this.loadingDiv.remove();
- this.loadingDiv = null;
- }
- await this.addMessage(response, "assistant", true);
- this.setInputState(false);
- } catch (error) {
- console.error("Failed to summarize page:", error);
- this.addMessage(
- "抱歉,页面总结过程中出现错误,请稍后重试。",
- "assistant",
- false
- );
- this.setInputState(false);
- }
- }
- /**
- * 处理文件上传
- * @param {File[]} files 上传的文件数组
- */
- async handleFileUpload(files) {
- // 目前仅显示文件信息,后续可以添加实际的上传和处理逻辑
- const fileNames = files.map((file) => file.name).join(", ");
- this.addMessage(`已选择文件:${fileNames}`, "user", false);
- }
- }
- // 等待DOM加载完成后再初始化
- document.addEventListener("DOMContentLoaded", () => {
- try {
- const chatUI = new ChatUI();
- } catch (error) {
- console.error("Failed to initialize ChatUI:", error);
- }
- });
|