chat-ui.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. class ChatUI {
  2. constructor() {
  3. this.messageContainer = document.getElementById("chat-messages");
  4. this.input = document.getElementById("chat-input");
  5. this.sendButton = document.getElementById("send-button");
  6. this.promptButton = document.getElementById("prompt-button");
  7. this.promptPanel = document.getElementById("prompt-panel");
  8. // 确保AI服务已经初始化
  9. if (!window.aiService) {
  10. throw new Error("AI Service not initialized");
  11. }
  12. this.aiService = window.aiService;
  13. this.typingSpeed = 50;
  14. this.inputWrapper = document.querySelector(".input-wrapper");
  15. // 先添加过渡动画类
  16. this.input.classList.add("input-transition");
  17. // 设置初始高度
  18. this.input.style.height = "40px";
  19. // 获取总结按钮
  20. this.summarizeButton = document.querySelector(".summarize-button");
  21. // 初始化其他组件
  22. this.setupEventListeners();
  23. this.init();
  24. // 使用微任务确保DOM更新后再调整高度
  25. Promise.resolve().then(() => {
  26. // 第一帧:等待过渡动画类生效
  27. requestAnimationFrame(() => {
  28. // 第二帧:执行高度调整
  29. requestAnimationFrame(() => {
  30. this.adjustInputHeight();
  31. // 触发一次输入框focus以确保正确的高度
  32. this.input.focus();
  33. });
  34. });
  35. });
  36. // 添加新消息指示器
  37. this.createNewMessageIndicator();
  38. // 监听滚动事件
  39. this.messageContainer.addEventListener(
  40. "scroll",
  41. this.handleScroll.bind(this)
  42. );
  43. // 创建打断按钮
  44. this.stopButton = document.createElement("button");
  45. this.stopButton.className = "stop-button";
  46. this.stopButton.innerHTML = `
  47. <svg viewBox="0 0 24 24" fill="currentColor">
  48. <path d="M6 6h12v12H6z"/>
  49. </svg>
  50. <span>停止生成</span>
  51. `;
  52. // 将打断按钮添加到输入按钮区域
  53. document.querySelector(".input-buttons").appendChild(this.stopButton);
  54. // 添加打断按钮事件监听
  55. this.stopButton.addEventListener("click", () => this.handleStop());
  56. this.isTyping = false; // 添加打字状态标记
  57. this.loadingDiv = null; // 添加加载动画的引用
  58. // 初始化页面信息卡片
  59. this.initPageInfoCard();
  60. }
  61. async init() {
  62. try {
  63. await this.aiService.init();
  64. await this.checkApiKey();
  65. } catch (error) {
  66. console.error("ChatUI initialization failed:", error);
  67. this.addMessage("初始化失败,请刷新页面重试。", "assistant");
  68. }
  69. }
  70. setupEventListeners() {
  71. // 发送消息
  72. this.sendButton.addEventListener("click", () => this.handleSend());
  73. this.input.addEventListener("keydown", (e) => {
  74. if (e.key === "Enter" && !e.shiftKey) {
  75. e.preventDefault();
  76. this.handleSend();
  77. }
  78. });
  79. // 自动调整输入框高度
  80. this.input.addEventListener("input", () => this.adjustInputHeight());
  81. // 添加focus事件监听,确保在获得焦点时高度正确
  82. this.input.addEventListener("focus", () => {
  83. requestAnimationFrame(() => this.adjustInputHeight());
  84. });
  85. // 快捷指令面板
  86. this.promptButton.addEventListener("click", () => this.togglePromptPanel());
  87. document.querySelector(".close-prompt").addEventListener("click", () => {
  88. this.promptPanel.classList.remove("show");
  89. });
  90. // 点击快捷指令
  91. document.querySelectorAll(".prompt-item").forEach((item) => {
  92. item.addEventListener("click", () => {
  93. // 获取文本内容并处理格式
  94. const text = item.textContent
  95. .trim() // 移除首尾空白
  96. .replace(/\s+/g, " ") // 将多个空白字符替换为单个空格
  97. .replace(/[\n\r]+/g, ""); // 移除所有换行符
  98. // 设置到输入框
  99. this.input.value = text;
  100. this.promptPanel.classList.remove("show");
  101. // 调整输入框高度并聚焦
  102. this.adjustInputHeight();
  103. this.input.focus();
  104. });
  105. });
  106. // 点击外部关闭快捷指令面板
  107. document.addEventListener("click", (e) => {
  108. if (
  109. !this.promptPanel.contains(e.target) &&
  110. !this.promptButton.contains(e.target)
  111. ) {
  112. this.promptPanel.classList.remove("show");
  113. }
  114. });
  115. // 添加总结按钮点击事件
  116. if (this.summarizeButton) {
  117. this.summarizeButton.addEventListener("click", () => {
  118. this.handleSummarize();
  119. });
  120. }
  121. }
  122. async handleSend() {
  123. const message = this.input.value.trim();
  124. if (!message) return;
  125. // 处理命令
  126. if (message.startsWith("/setapi ")) {
  127. const apiKey = message.substring(8).trim();
  128. await this.aiService.setApiKey(apiKey);
  129. // 根据是否使用默认密钥显示不同消息
  130. if (apiKey === CONFIG.AI_API.DEFAULT_API_KEY) {
  131. this.addMessage("已恢复使用默认API密钥", "assistant", false);
  132. } else {
  133. this.addMessage("自定义API密钥已设置", "assistant", false);
  134. }
  135. this.input.value = "";
  136. return;
  137. }
  138. // 添加用户消息
  139. this.addMessage(message, "user", false);
  140. // 更新上下文
  141. this.aiService.updateContext(message, "user");
  142. // 清空输入框
  143. this.input.value = "";
  144. this.adjustInputHeight();
  145. try {
  146. this.stopButton.classList.add("show");
  147. this.setInputState(true); // 禁用输入框
  148. this.loadingDiv = this.createLoadingMessage();
  149. const response = await this.aiService.sendMessage(message);
  150. if (this.loadingDiv) {
  151. this.loadingDiv.remove();
  152. this.loadingDiv = null;
  153. }
  154. if (!response) return;
  155. this.isTyping = false;
  156. await this.addMessage(response, "assistant", true);
  157. this.stopButton.classList.remove("show");
  158. this.setInputState(false); // 这里会自动聚焦输入框
  159. this.aiService.updateContext(response, "assistant");
  160. } catch (error) {
  161. if (this.loadingDiv) {
  162. this.loadingDiv.remove();
  163. this.loadingDiv = null;
  164. }
  165. this.stopButton.classList.remove("show");
  166. this.setInputState(false); // 这里也会自动聚焦输入框
  167. this.isTyping = false;
  168. if (error.message === "REQUEST_ABORTED") {
  169. return;
  170. }
  171. this.addMessage("抱歉,发生了一些错误,请稍后重试。", "assistant", false);
  172. console.error("AI response error:", error);
  173. }
  174. }
  175. /**
  176. * 添加消息到聊天界面
  177. * @param {string} content 消息内容
  178. * @param {string} type 消息类型(user/assistant)
  179. * @param {boolean} typing 是否使用打字效果
  180. * @param {boolean} isInterrupted 是否是中断消息
  181. */
  182. async addMessage(
  183. content,
  184. type,
  185. typing = type === "assistant",
  186. isInterrupted = false
  187. ) {
  188. const messageDiv = document.createElement("div");
  189. messageDiv.className = `message ${type}`;
  190. const messageContent = document.createElement("div");
  191. messageContent.className = "message-content";
  192. if (isInterrupted) {
  193. messageContent.classList.add("interrupted");
  194. }
  195. const paragraph = document.createElement("p");
  196. messageContent.appendChild(paragraph);
  197. // 创建操作栏(时间戳和复制按钮)
  198. const actionsDiv = document.createElement("div");
  199. actionsDiv.className = "message-actions";
  200. // 只为非中断的AI消息添加复制按钮
  201. if (type === "assistant" && !isInterrupted) {
  202. const copyButton = this.createCopyButton(content);
  203. actionsDiv.appendChild(copyButton);
  204. }
  205. // 添加时间戳
  206. const timestamp = document.createElement("div");
  207. timestamp.className = "message-timestamp";
  208. timestamp.textContent = this.formatTime(new Date());
  209. actionsDiv.appendChild(timestamp);
  210. messageContent.appendChild(actionsDiv);
  211. messageDiv.appendChild(messageContent);
  212. this.messageContainer.appendChild(messageDiv);
  213. if (typing) {
  214. messageContent.classList.add("typing");
  215. await this.typeMessage(paragraph, content);
  216. messageContent.classList.remove("typing");
  217. } else {
  218. paragraph.innerHTML = this.formatMessage(content);
  219. }
  220. const { scrollTop, scrollHeight, clientHeight } = this.messageContainer;
  221. const wasAtBottom = scrollHeight - scrollTop - clientHeight < 100;
  222. if (wasAtBottom) {
  223. this.scrollToBottom();
  224. } else {
  225. this.newMessageIndicator.classList.add("show");
  226. }
  227. }
  228. /**
  229. * 实现打字机效果
  230. * @param {HTMLElement} element 要添加文字的元素
  231. * @param {string} text 要显示的文字
  232. */
  233. async typeMessage(element, text) {
  234. let index = 0;
  235. const rawText = text;
  236. const tempDiv = document.createElement("div");
  237. this.isTyping = true; // 开始打字
  238. return new Promise((resolve) => {
  239. const type = () => {
  240. // 检查是否被中断
  241. if (!this.isTyping) {
  242. resolve();
  243. return;
  244. }
  245. if (index < rawText.length) {
  246. const currentText = rawText.substring(0, index + 1);
  247. tempDiv.innerHTML = this.formatMessage(currentText);
  248. element.innerHTML = tempDiv.innerHTML;
  249. index++;
  250. this.scrollToBottom();
  251. setTimeout(type, this.typingSpeed);
  252. } else {
  253. this.isTyping = false; // 打字结束
  254. resolve();
  255. }
  256. };
  257. type();
  258. });
  259. }
  260. adjustInputHeight() {
  261. const scrollPos = this.input.scrollTop;
  262. // 获取当前高度
  263. const currentHeight = this.input.style.height;
  264. // 重置高度
  265. this.input.style.height = "auto";
  266. // 计算新高度
  267. const newHeight = Math.min(this.input.scrollHeight, 120);
  268. // 如果高度有变化才设置
  269. if (currentHeight !== `${newHeight}px`) {
  270. this.input.style.height = `${newHeight}px`;
  271. }
  272. // 恢复滚动位置
  273. this.input.scrollTop = scrollPos;
  274. }
  275. scrollToBottom() {
  276. this.messageContainer.scrollTop = this.messageContainer.scrollHeight;
  277. }
  278. togglePromptPanel() {
  279. this.promptPanel.classList.toggle("show");
  280. }
  281. escapeHtml(html) {
  282. const div = document.createElement("div");
  283. div.textContent = html;
  284. return div.innerHTML;
  285. }
  286. async checkApiKey() {
  287. // 只有当没有任何API密钥时才显示提示
  288. if (!this.aiService.apiKey) {
  289. this.addMessage(
  290. "请先设置DeepSeek API密钥。输入格式:/setapi YOUR_API_KEY",
  291. "assistant"
  292. );
  293. }
  294. }
  295. /**
  296. * 创建加载动画消息
  297. */
  298. createLoadingMessage() {
  299. const loadingDiv = document.createElement("div");
  300. loadingDiv.className = "message assistant";
  301. loadingDiv.innerHTML = `
  302. <div class="message-content loading">
  303. <div class="typing-indicator">
  304. <span></span>
  305. <span></span>
  306. <span></span>
  307. </div>
  308. </div>
  309. `;
  310. this.messageContainer.appendChild(loadingDiv);
  311. this.scrollToBottom();
  312. return loadingDiv;
  313. }
  314. /**
  315. * 格式化时间
  316. */
  317. formatTime(date) {
  318. const hours = date.getHours().toString().padStart(2, "0");
  319. const minutes = date.getMinutes().toString().padStart(2, "0");
  320. return `${hours}:${minutes}`;
  321. }
  322. createNewMessageIndicator() {
  323. this.newMessageIndicator = document.createElement("div");
  324. this.newMessageIndicator.className = "new-messages-indicator";
  325. this.newMessageIndicator.textContent = "新消息";
  326. this.newMessageIndicator.addEventListener("click", () => {
  327. this.scrollToBottom();
  328. });
  329. document
  330. .querySelector(".chat-container")
  331. .appendChild(this.newMessageIndicator);
  332. }
  333. handleScroll() {
  334. const { scrollTop, scrollHeight, clientHeight } = this.messageContainer;
  335. const isNearBottom = scrollHeight - scrollTop - clientHeight < 100;
  336. if (isNearBottom) {
  337. this.newMessageIndicator.classList.remove("show");
  338. }
  339. }
  340. /**
  341. * 格式化消息内容
  342. * @param {string} text 原始文本
  343. * @returns {string} 格式化后的HTML
  344. */
  345. formatMessage(text) {
  346. if (!text) return "";
  347. return (
  348. text
  349. // 处理标题 (h1 ~ h6)
  350. .replace(/^#{1,6}\s+(.+)$/gm, (match, content) => {
  351. const level = match.trim().split("#").length - 1;
  352. return `<h${level}>${content.trim()}</h${level}>`;
  353. })
  354. // 处理换行
  355. .replace(/\n/g, "<br>")
  356. // 处理连续空格
  357. .replace(/ {2,}/g, (match) => "&nbsp;".repeat(match.length))
  358. // 处理代码块
  359. .replace(
  360. /```([\s\S]*?)```/g,
  361. (match, code) =>
  362. `<pre><code>${this.escapeHtml(code.trim())}</code></pre>`
  363. )
  364. // 处理行内代码
  365. .replace(
  366. /`([^`]+)`/g,
  367. (match, code) => `<code>${this.escapeHtml(code)}</code>`
  368. )
  369. // 处理粗体
  370. .replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>")
  371. // 处理斜体
  372. .replace(/\*(.*?)\*/g, "<em>$1</em>")
  373. // 处理链接
  374. .replace(
  375. /\[([^\]]+)\]\(([^)]+)\)/g,
  376. '<a href="$2" target="_blank">$1</a>'
  377. )
  378. // 处理无序列表
  379. .replace(/^[*-]\s+(.+)$/gm, "<li>$1</li>")
  380. .replace(/(<li>.*<\/li>)/gs, "<ul>$1</ul>")
  381. // 处理有序列表
  382. .replace(/^\d+\.\s+(.+)$/gm, "<li>$1</li>")
  383. .replace(/(<li>.*<\/li>)/gs, "<ol>$1</ol>")
  384. // 处理分隔线
  385. .replace(/^---+$/gm, "<hr>")
  386. // 处理引用
  387. .replace(/^>\s+(.+)$/gm, "<blockquote>$1</blockquote>")
  388. );
  389. }
  390. /**
  391. * 创建复制按钮
  392. * @param {string} content 要复制的内容
  393. * @returns {HTMLElement} 复制按钮元素
  394. */
  395. createCopyButton(content) {
  396. const button = document.createElement("button");
  397. button.className = "copy-button";
  398. button.innerHTML = `
  399. <svg viewBox="0 0 24 24" fill="currentColor">
  400. <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"/>
  401. </svg>
  402. <span>复制</span>
  403. `;
  404. button.addEventListener("click", async () => {
  405. try {
  406. // 直接使用传入的原始内容
  407. await this.copyToClipboard(content);
  408. // 显示复制成功状态
  409. button.classList.add("copied");
  410. button.innerHTML = `
  411. <svg viewBox="0 0 24 24" fill="currentColor">
  412. <path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"/>
  413. </svg>
  414. <span>已复制</span>
  415. `;
  416. // 2秒后恢复原始状态
  417. setTimeout(() => {
  418. button.classList.remove("copied");
  419. button.innerHTML = `
  420. <svg viewBox="0 0 24 24" fill="currentColor">
  421. <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"/>
  422. </svg>
  423. <span>复制</span>
  424. `;
  425. }, 2000);
  426. } catch (err) {
  427. console.error("Failed to copy text:", err);
  428. }
  429. });
  430. return button;
  431. }
  432. /**
  433. * 复制文本到剪贴板
  434. * @param {string} text 要复制的文本
  435. */
  436. async copyToClipboard(text) {
  437. try {
  438. // 通过postMessage发送复制请求到content script
  439. window.parent.postMessage(
  440. {
  441. type: "COPY_TO_CLIPBOARD",
  442. text: text,
  443. },
  444. "*"
  445. );
  446. return true;
  447. } catch (err) {
  448. console.error("Failed to copy text:", err);
  449. throw err;
  450. }
  451. }
  452. // 处理打断请求
  453. async handleStop() {
  454. try {
  455. this.aiService.abortRequest();
  456. if (this.isTyping) {
  457. this.isTyping = false;
  458. }
  459. if (this.loadingDiv) {
  460. this.loadingDiv.remove();
  461. this.loadingDiv = null;
  462. }
  463. this.stopButton.classList.remove("show");
  464. this.setInputState(false); // 中断后也自动聚焦输入框
  465. this.addMessage("用户手动停止生成", "assistant", false, true);
  466. } catch (error) {
  467. console.error("Failed to stop generation:", error);
  468. }
  469. }
  470. // 设置输入框状态
  471. setInputState(isGenerating) {
  472. this.input.disabled = isGenerating;
  473. this.input.placeholder = isGenerating ? "回复生成中..." : "输入消息...";
  474. if (isGenerating) {
  475. this.inputWrapper.classList.add("generating");
  476. } else {
  477. this.inputWrapper.classList.remove("generating");
  478. // AI回复完成后,自动聚焦到输入框
  479. this.input.focus();
  480. }
  481. }
  482. /**
  483. * 初始化页面信息卡片
  484. */
  485. initPageInfoCard() {
  486. // 从父窗口获取页面信息
  487. window.addEventListener("message", (event) => {
  488. if (event.data.type === "PAGE_INFO") {
  489. const pageInfo = event.data.pageInfo;
  490. // 更新卡片内容
  491. const favicon = document.querySelector(".page-favicon");
  492. const title = document.querySelector(".page-title");
  493. // 设置网站图标
  494. favicon.src = pageInfo.favicon;
  495. favicon.onerror = () => {
  496. // 如果图标加载失败,使用默认图标
  497. favicon.src = chrome.runtime.getURL("images/icon16.png");
  498. };
  499. // 设置页面标题
  500. title.textContent = pageInfo.title;
  501. }
  502. });
  503. }
  504. /**
  505. * 获取页面favicon
  506. * @returns {string} favicon URL
  507. */
  508. getPageFavicon() {
  509. // 尝试获取页面favicon
  510. const iconLink = document.querySelector('link[rel*="icon"]');
  511. if (iconLink) return iconLink.href;
  512. // 如果没有找到,返回网站根目录的favicon.ico
  513. const url = new URL(window.location.href);
  514. return `${url.protocol}//${url.hostname}/favicon.ico`;
  515. }
  516. /**
  517. * 处理总结请求
  518. */
  519. async handleSummarize() {
  520. try {
  521. // 显示加载状态
  522. this.setInputState(true);
  523. this.loadingDiv = this.createLoadingMessage();
  524. // 通过postMessage请求页面分析结果
  525. const pageInfo = await new Promise((resolve) => {
  526. // 创建一次性消息监听器
  527. const messageHandler = (event) => {
  528. if (event.data.type === "PAGE_ANALYSIS_RESULT") {
  529. window.removeEventListener("message", messageHandler);
  530. resolve(event.data.pageInfo);
  531. }
  532. };
  533. // 添加消息监听
  534. window.addEventListener("message", messageHandler);
  535. // 发送分析请求到父页面
  536. window.parent.postMessage({ type: "ANALYZE_PAGE" }, "*");
  537. });
  538. // 构建提示词
  539. const prompt = this.aiService.getSummaryPrompt(pageInfo);
  540. // 发送分析请求
  541. const response = await this.aiService.sendMessage(prompt);
  542. // 显示分析结果
  543. if (this.loadingDiv) {
  544. this.loadingDiv.remove();
  545. this.loadingDiv = null;
  546. }
  547. await this.addMessage(response, "assistant", true);
  548. this.setInputState(false);
  549. } catch (error) {
  550. console.error("Failed to summarize page:", error);
  551. this.addMessage(
  552. "抱歉,页面总结过程中出现错误,请稍后重试。",
  553. "assistant",
  554. false
  555. );
  556. this.setInputState(false);
  557. }
  558. }
  559. }
  560. // 等待DOM加载完成后再初始化
  561. document.addEventListener("DOMContentLoaded", () => {
  562. try {
  563. const chatUI = new ChatUI();
  564. } catch (error) {
  565. console.error("Failed to initialize ChatUI:", error);
  566. }
  567. });