chat-ui.js 18 KB

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