chat-ui.js 18 KB

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