chat-ui.js 14 KB

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