chat-ui.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  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.stopButton = document.getElementById("stop-button");
  7. this.promptButton = document.getElementById("prompt-button");
  8. this.promptPanel = document.getElementById("prompt-panel");
  9. this.uploadButton = document.getElementById("upload-button");
  10. this.fileInput = document.getElementById("file-input");
  11. // 确保AI服务已经初始化
  12. if (!window.aiService) {
  13. throw new Error("AI Service not initialized");
  14. }
  15. this.aiService = window.aiService;
  16. this.typingSpeed = 50;
  17. this.inputWrapper = document.querySelector(".input-wrapper");
  18. // 先添加过渡动画类
  19. this.input.classList.add("input-transition");
  20. // 设置初始高度
  21. this.input.style.height = "40px";
  22. // 获取总结按钮
  23. this.summarizeButton = document.querySelector(".summarize-button");
  24. // 支持的Excel文件类型
  25. this.excelTypes = {
  26. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  27. xls: "application/vnd.ms-excel",
  28. csv: "text/csv",
  29. };
  30. // 初始化其他组件
  31. this.setupEventListeners();
  32. this.init();
  33. // 使用微任务确保DOM更新后再调整高度
  34. Promise.resolve().then(() => {
  35. // 第一帧:等待过渡动画类生效
  36. requestAnimationFrame(() => {
  37. // 第二帧:执行高度调整
  38. requestAnimationFrame(() => {
  39. this.adjustInputHeight();
  40. // 触发一次输入框focus以确保正确的高度
  41. this.input.focus();
  42. });
  43. });
  44. });
  45. // 添加新消息指示器
  46. this.createNewMessageIndicator();
  47. // 监听滚动事件
  48. this.messageContainer.addEventListener(
  49. "scroll",
  50. this.handleScroll.bind(this)
  51. );
  52. // 创建打断按钮
  53. this.stopButton.className = "stop-button";
  54. this.stopButton.innerHTML = `
  55. <svg viewBox="0 0 24 24" fill="currentColor">
  56. <path d="M6 6h12v12H6z"/>
  57. </svg>
  58. <span>停止生成</span>
  59. `;
  60. // 将打断按钮添加到输入按钮区域
  61. document.querySelector(".input-buttons").appendChild(this.stopButton);
  62. // 添加打断按钮事件监听
  63. this.stopButton.addEventListener("click", () => this.handleStop());
  64. this.isTyping = false; // 添加打字状态标记
  65. this.loadingDiv = null; // 添加加载动画的引用
  66. // 初始化页面信息卡片
  67. this.initPageInfoCard();
  68. }
  69. async init() {
  70. try {
  71. await this.aiService.init();
  72. await this.checkApiKey();
  73. } catch (error) {
  74. console.error("ChatUI initialization failed:", error);
  75. this.addMessage("初始化失败,请刷新页面重试。", "assistant");
  76. }
  77. }
  78. setupEventListeners() {
  79. // 发送消息
  80. this.sendButton.addEventListener("click", () => this.handleSend());
  81. this.input.addEventListener("keydown", (e) => {
  82. if (e.key === "Enter" && !e.shiftKey) {
  83. e.preventDefault();
  84. this.handleSend();
  85. }
  86. });
  87. // 自动调整输入框高度
  88. this.input.addEventListener("input", () => this.adjustInputHeight());
  89. // 添加focus事件监听,确保在获得焦点时高度正确
  90. this.input.addEventListener("focus", () => {
  91. requestAnimationFrame(() => this.adjustInputHeight());
  92. });
  93. // 快捷指令面板
  94. this.promptButton.addEventListener("click", () => this.togglePromptPanel());
  95. document.querySelector(".close-prompt").addEventListener("click", () => {
  96. this.promptPanel.classList.remove("show");
  97. });
  98. // 点击快捷指令
  99. document.querySelectorAll(".prompt-item").forEach((item) => {
  100. item.addEventListener("click", () => {
  101. // 获取文本内容并处理格式
  102. const text = item.textContent
  103. .trim() // 移除首尾空白
  104. .replace(/\s+/g, " ") // 将多个空白字符替换为单个空格
  105. .replace(/[\n\r]+/g, ""); // 移除所有换行符
  106. // 设置到输入框
  107. this.input.value = text;
  108. this.promptPanel.classList.remove("show");
  109. // 调整输入框高度并聚焦
  110. this.adjustInputHeight();
  111. this.input.focus();
  112. });
  113. });
  114. // 点击外部关闭快捷指令面板
  115. document.addEventListener("click", (e) => {
  116. if (
  117. !this.promptPanel.contains(e.target) &&
  118. !this.promptButton.contains(e.target)
  119. ) {
  120. this.promptPanel.classList.remove("show");
  121. }
  122. });
  123. // 添加总结按钮点击事件
  124. if (this.summarizeButton) {
  125. this.summarizeButton.addEventListener("click", () => {
  126. this.handleSummarize();
  127. });
  128. }
  129. // 工具箱面板
  130. const toolsButton = document.getElementById("tools-button");
  131. const toolsPanel = document.getElementById("tools-panel");
  132. const closeTools = document.querySelector(".close-tools");
  133. toolsButton.addEventListener("click", () => {
  134. toolsPanel.classList.toggle("show");
  135. // 关闭其他面板
  136. this.promptPanel.classList.remove("show");
  137. });
  138. closeTools.addEventListener("click", () => {
  139. toolsPanel.classList.remove("show");
  140. });
  141. // 点击外部关闭工具箱面板
  142. document.addEventListener("click", (e) => {
  143. if (!toolsPanel.contains(e.target) && !toolsButton.contains(e.target)) {
  144. toolsPanel.classList.remove("show");
  145. }
  146. });
  147. // 上传按钮点击事件
  148. this.uploadButton.addEventListener("click", () => {
  149. this.fileInput.click();
  150. });
  151. // 文件选择事件
  152. this.fileInput.addEventListener("change", (event) => {
  153. const files = event.target.files;
  154. if (files.length > 0) {
  155. this.handleFileUpload(files);
  156. }
  157. // 清空文件输入框,确保同一文件可以重复上传
  158. event.target.value = "";
  159. });
  160. }
  161. async handleSend() {
  162. const message = this.input.value.trim();
  163. if (!message) return;
  164. // 处理命令
  165. if (message.startsWith("/setapi ")) {
  166. const apiKey = message.substring(8).trim();
  167. await this.aiService.setApiKey(apiKey);
  168. // 根据是否使用默认密钥显示不同消息
  169. if (apiKey === CONFIG.AI_API.DEFAULT_API_KEY) {
  170. this.addMessage("已恢复使用默认API密钥", "assistant", false);
  171. } else {
  172. this.addMessage("自定义API密钥已设置", "assistant", false);
  173. }
  174. this.input.value = "";
  175. return;
  176. }
  177. // 添加用户消息
  178. this.addMessage(message, "user", false);
  179. // 更新上下文
  180. this.aiService.updateContext(message, "user");
  181. // 清空输入框
  182. this.input.value = "";
  183. this.adjustInputHeight();
  184. try {
  185. this.stopButton.classList.add("show");
  186. this.setInputState(true); // 禁用输入框
  187. this.loadingDiv = this.createLoadingMessage();
  188. // 如果存在Excel数据,添加上下文提示
  189. let prompt = message;
  190. if (this.aiService.currentExcelData) {
  191. const { fileName, headers, totalRows } =
  192. this.aiService.currentExcelData;
  193. prompt = `请记住之前我们正在讨论的Excel文件:
  194. - 文件名:${fileName}
  195. - 列标题:${headers.join(", ")}
  196. - 总行数:${totalRows}
  197. 基于这个Excel文件的内容,请回答以下问题:
  198. ${message}`;
  199. }
  200. const response = await this.aiService.sendMessage(prompt);
  201. if (this.loadingDiv) {
  202. this.loadingDiv.remove();
  203. this.loadingDiv = null;
  204. }
  205. if (!response) return;
  206. this.isTyping = false;
  207. await this.addMessage(response, "assistant", true);
  208. this.stopButton.classList.remove("show");
  209. this.setInputState(false); // 这里会自动聚焦输入框
  210. this.aiService.updateContext(response, "assistant");
  211. } catch (error) {
  212. if (this.loadingDiv) {
  213. this.loadingDiv.remove();
  214. this.loadingDiv = null;
  215. }
  216. this.stopButton.classList.remove("show");
  217. this.setInputState(false); // 这里也会自动聚焦输入框
  218. this.isTyping = false;
  219. if (error.message === "REQUEST_ABORTED") {
  220. return;
  221. }
  222. this.addMessage("抱歉,发生了一些错误,请稍后重试。", "assistant", false);
  223. console.error("AI response error:", error);
  224. }
  225. }
  226. /**
  227. * 添加消息到聊天界面
  228. * @param {string} content 消息内容
  229. * @param {string} type 消息类型(user/assistant)
  230. * @param {boolean} typing 是否使用打字效果
  231. * @param {boolean} isInterrupted 是否是中断消息
  232. */
  233. async addMessage(
  234. content,
  235. type,
  236. typing = type === "assistant",
  237. isInterrupted = false
  238. ) {
  239. const messageDiv = document.createElement("div");
  240. messageDiv.className = `message ${type}`;
  241. const messageContent = document.createElement("div");
  242. messageContent.className = "message-content";
  243. if (isInterrupted) {
  244. messageContent.classList.add("interrupted");
  245. }
  246. const paragraph = document.createElement("p");
  247. messageContent.appendChild(paragraph);
  248. // 创建操作栏(时间戳和复制按钮)
  249. const actionsDiv = document.createElement("div");
  250. actionsDiv.className = "message-actions";
  251. // 只为非中断的AI消息添加复制按钮
  252. if (type === "assistant" && !isInterrupted) {
  253. const copyButton = this.createCopyButton(content);
  254. actionsDiv.appendChild(copyButton);
  255. }
  256. // 添加时间戳
  257. const timestamp = document.createElement("div");
  258. timestamp.className = "message-timestamp";
  259. timestamp.textContent = this.formatTime(new Date());
  260. actionsDiv.appendChild(timestamp);
  261. messageContent.appendChild(actionsDiv);
  262. messageDiv.appendChild(messageContent);
  263. this.messageContainer.appendChild(messageDiv);
  264. if (typing) {
  265. messageContent.classList.add("typing");
  266. await this.typeMessage(paragraph, content);
  267. messageContent.classList.remove("typing");
  268. } else {
  269. paragraph.innerHTML = this.formatMessage(content);
  270. }
  271. const { scrollTop, scrollHeight, clientHeight } = this.messageContainer;
  272. const wasAtBottom = scrollHeight - scrollTop - clientHeight < 100;
  273. if (wasAtBottom) {
  274. this.scrollToBottom();
  275. } else {
  276. this.newMessageIndicator.classList.add("show");
  277. }
  278. }
  279. /**
  280. * 实现打字机效果
  281. * @param {HTMLElement} element 要添加文字的元素
  282. * @param {string} text 要显示的文字
  283. */
  284. async typeMessage(element, text) {
  285. let index = 0;
  286. const rawText = text;
  287. const tempDiv = document.createElement("div");
  288. this.isTyping = true; // 开始打字
  289. return new Promise((resolve) => {
  290. const type = () => {
  291. // 检查是否被中断
  292. if (!this.isTyping) {
  293. resolve();
  294. return;
  295. }
  296. if (index < rawText.length) {
  297. const currentText = rawText.substring(0, index + 1);
  298. tempDiv.innerHTML = this.formatMessage(currentText);
  299. element.innerHTML = tempDiv.innerHTML;
  300. index++;
  301. this.scrollToBottom();
  302. setTimeout(type, this.typingSpeed);
  303. } else {
  304. this.isTyping = false; // 打字结束
  305. resolve();
  306. }
  307. };
  308. type();
  309. });
  310. }
  311. adjustInputHeight() {
  312. const scrollPos = this.input.scrollTop;
  313. // 获取当前高度
  314. const currentHeight = this.input.style.height;
  315. // 重置高度
  316. this.input.style.height = "auto";
  317. // 计算新高度
  318. const newHeight = Math.min(this.input.scrollHeight, 120);
  319. // 如果高度有变化才设置
  320. if (currentHeight !== `${newHeight}px`) {
  321. this.input.style.height = `${newHeight}px`;
  322. }
  323. // 恢复滚动位置
  324. this.input.scrollTop = scrollPos;
  325. }
  326. scrollToBottom() {
  327. this.messageContainer.scrollTop = this.messageContainer.scrollHeight;
  328. }
  329. togglePromptPanel() {
  330. this.promptPanel.classList.toggle("show");
  331. }
  332. escapeHtml(html) {
  333. const div = document.createElement("div");
  334. div.textContent = html;
  335. return div.innerHTML;
  336. }
  337. async checkApiKey() {
  338. // 只有当没有任何API密钥时才显示提示
  339. if (!this.aiService.apiKey) {
  340. this.addMessage(
  341. "请先设置DeepSeek API密钥。输入格式:/setapi YOUR_API_KEY",
  342. "assistant"
  343. );
  344. }
  345. }
  346. /**
  347. * 创建加载动画消息
  348. */
  349. createLoadingMessage() {
  350. const loadingDiv = document.createElement("div");
  351. loadingDiv.className = "message assistant";
  352. loadingDiv.innerHTML = `
  353. <div class="message-content loading">
  354. <div class="typing-indicator">
  355. <span></span>
  356. <span></span>
  357. <span></span>
  358. </div>
  359. </div>
  360. `;
  361. this.messageContainer.appendChild(loadingDiv);
  362. this.scrollToBottom();
  363. return loadingDiv;
  364. }
  365. /**
  366. * 格式化时间
  367. */
  368. formatTime(date) {
  369. const hours = date.getHours().toString().padStart(2, "0");
  370. const minutes = date.getMinutes().toString().padStart(2, "0");
  371. return `${hours}:${minutes}`;
  372. }
  373. createNewMessageIndicator() {
  374. this.newMessageIndicator = document.createElement("div");
  375. this.newMessageIndicator.className = "new-messages-indicator";
  376. this.newMessageIndicator.textContent = "新消息";
  377. this.newMessageIndicator.addEventListener("click", () => {
  378. this.scrollToBottom();
  379. });
  380. document
  381. .querySelector(".chat-container")
  382. .appendChild(this.newMessageIndicator);
  383. }
  384. handleScroll() {
  385. const { scrollTop, scrollHeight, clientHeight } = this.messageContainer;
  386. const isNearBottom = scrollHeight - scrollTop - clientHeight < 100;
  387. if (isNearBottom) {
  388. this.newMessageIndicator.classList.remove("show");
  389. }
  390. }
  391. /**
  392. * 格式化消息内容
  393. * @param {string} text 原始文本
  394. * @returns {string} 格式化后的HTML
  395. */
  396. formatMessage(text) {
  397. if (!text) return "";
  398. return (
  399. text
  400. // 处理标题 (h1 ~ h6)
  401. .replace(/^#{1,6}\s+(.+)$/gm, (match, content) => {
  402. const level = match.trim().split("#").length - 1;
  403. return `<h${level}>${content.trim()}</h${level}>`;
  404. })
  405. // 处理换行
  406. .replace(/\n/g, "<br>")
  407. // 处理连续空格
  408. .replace(/ {2,}/g, (match) => "&nbsp;".repeat(match.length))
  409. // 处理代码块
  410. .replace(
  411. /```([\s\S]*?)```/g,
  412. (match, code) =>
  413. `<pre><code>${this.escapeHtml(code.trim())}</code></pre>`
  414. )
  415. // 处理行内代码
  416. .replace(
  417. /`([^`]+)`/g,
  418. (match, code) => `<code>${this.escapeHtml(code)}</code>`
  419. )
  420. // 处理粗体
  421. .replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>")
  422. // 处理斜体
  423. .replace(/\*(.*?)\*/g, "<em>$1</em>")
  424. // 处理链接
  425. .replace(
  426. /\[([^\]]+)\]\(([^)]+)\)/g,
  427. '<a href="$2" target="_blank">$1</a>'
  428. )
  429. // 处理无序列表
  430. .replace(/^[*-]\s+(.+)$/gm, "<li>$1</li>")
  431. .replace(/(<li>.*<\/li>)/gs, "<ul>$1</ul>")
  432. // 处理有序列表
  433. .replace(/^\d+\.\s+(.+)$/gm, "<li>$1</li>")
  434. .replace(/(<li>.*<\/li>)/gs, "<ol>$1</ol>")
  435. // 处理分隔线
  436. .replace(/^---+$/gm, "<hr>")
  437. // 处理引用
  438. .replace(/^>\s+(.+)$/gm, "<blockquote>$1</blockquote>")
  439. );
  440. }
  441. /**
  442. * 创建复制按钮
  443. * @param {string} content 要复制的内容
  444. * @returns {HTMLElement} 复制按钮元素
  445. */
  446. createCopyButton(content) {
  447. const button = document.createElement("button");
  448. button.className = "copy-button";
  449. button.innerHTML = `
  450. <svg viewBox="0 0 24 24" fill="currentColor">
  451. <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"/>
  452. </svg>
  453. <span>复制</span>
  454. `;
  455. button.addEventListener("click", async () => {
  456. try {
  457. // 直接使用传入的原始内容
  458. await this.copyToClipboard(content);
  459. // 显示复制成功状态
  460. button.classList.add("copied");
  461. button.innerHTML = `
  462. <svg viewBox="0 0 24 24" fill="currentColor">
  463. <path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"/>
  464. </svg>
  465. <span>已复制</span>
  466. `;
  467. // 2秒后恢复原始状态
  468. setTimeout(() => {
  469. button.classList.remove("copied");
  470. button.innerHTML = `
  471. <svg viewBox="0 0 24 24" fill="currentColor">
  472. <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"/>
  473. </svg>
  474. <span>复制</span>
  475. `;
  476. }, 2000);
  477. } catch (err) {
  478. console.error("Failed to copy text:", err);
  479. }
  480. });
  481. return button;
  482. }
  483. /**
  484. * 复制文本到剪贴板
  485. * @param {string} text 要复制的文本
  486. */
  487. async copyToClipboard(text) {
  488. try {
  489. // 通过postMessage发送复制请求到content script
  490. window.parent.postMessage(
  491. {
  492. type: "COPY_TO_CLIPBOARD",
  493. text: text,
  494. },
  495. "*"
  496. );
  497. return true;
  498. } catch (err) {
  499. console.error("Failed to copy text:", err);
  500. throw err;
  501. }
  502. }
  503. // 处理打断请求
  504. async handleStop() {
  505. try {
  506. this.aiService.abortRequest();
  507. if (this.isTyping) {
  508. this.isTyping = false;
  509. }
  510. if (this.loadingDiv) {
  511. this.loadingDiv.remove();
  512. this.loadingDiv = null;
  513. }
  514. this.stopButton.classList.remove("show");
  515. this.setInputState(false); // 中断后也自动聚焦输入框
  516. this.addMessage("用户手动停止生成", "assistant", false, true);
  517. } catch (error) {
  518. console.error("Failed to stop generation:", error);
  519. }
  520. }
  521. // 设置输入框状态
  522. setInputState(isGenerating) {
  523. this.input.disabled = isGenerating;
  524. this.input.placeholder = isGenerating ? "回复生成中..." : "输入消息...";
  525. if (isGenerating) {
  526. this.inputWrapper.classList.add("generating");
  527. this.stopButton.classList.add("show");
  528. } else {
  529. this.inputWrapper.classList.remove("generating");
  530. this.stopButton.classList.remove("show");
  531. // AI回复完成后,自动聚焦到输入框
  532. this.input.focus();
  533. }
  534. }
  535. /**
  536. * 初始化页面信息卡片
  537. */
  538. initPageInfoCard() {
  539. // 从父窗口获取页面信息
  540. window.addEventListener("message", (event) => {
  541. if (event.data.type === "PAGE_INFO") {
  542. const pageInfo = event.data.pageInfo;
  543. // 更新卡片内容
  544. const favicon = document.querySelector(".page-favicon");
  545. const title = document.querySelector(".page-title");
  546. // 设置网站图标
  547. favicon.src = pageInfo.favicon;
  548. favicon.onerror = () => {
  549. // 如果图标加载失败,使用默认图标
  550. favicon.src = chrome.runtime.getURL("images/icon16.png");
  551. };
  552. // 设置页面标题
  553. title.textContent = pageInfo.title;
  554. }
  555. });
  556. }
  557. /**
  558. * 获取页面favicon
  559. * @returns {string} favicon URL
  560. */
  561. getPageFavicon() {
  562. // 尝试获取页面favicon
  563. const iconLink = document.querySelector('link[rel*="icon"]');
  564. if (iconLink) return iconLink.href;
  565. // 如果没有找到,返回网站根目录的favicon.ico
  566. const url = new URL(window.location.href);
  567. return `${url.protocol}//${url.hostname}/favicon.ico`;
  568. }
  569. /**
  570. * 处理总结请求
  571. */
  572. async handleSummarize() {
  573. try {
  574. // 显示加载状态
  575. this.setInputState(true);
  576. this.loadingDiv = this.createLoadingMessage();
  577. // 通过postMessage请求页面分析结果
  578. const pageInfo = await new Promise((resolve) => {
  579. // 创建一次性消息监听器
  580. const messageHandler = (event) => {
  581. if (event.data.type === "PAGE_ANALYSIS_RESULT") {
  582. window.removeEventListener("message", messageHandler);
  583. resolve(event.data.pageInfo);
  584. }
  585. };
  586. // 添加消息监听
  587. window.addEventListener("message", messageHandler);
  588. // 发送分析请求到父页面
  589. window.parent.postMessage({ type: "ANALYZE_PAGE" }, "*");
  590. });
  591. // 构建提示词
  592. const prompt = this.aiService.getSummaryPrompt(pageInfo);
  593. // 发送分析请求
  594. const response = await this.aiService.sendMessage(prompt);
  595. // 显示分析结果
  596. if (this.loadingDiv) {
  597. this.loadingDiv.remove();
  598. this.loadingDiv = null;
  599. }
  600. await this.addMessage(response, "assistant", true);
  601. // 将总结内容添加到上下文
  602. this.aiService.updateContext(prompt, "user");
  603. this.aiService.updateContext(response, "assistant");
  604. // 保存页面信息到上下文
  605. this.aiService.setPageInfo(pageInfo);
  606. this.setInputState(false);
  607. } catch (error) {
  608. console.error("Failed to summarize page:", error);
  609. this.addMessage(
  610. "抱歉,页面总结过程中出现错误,请稍后重试。",
  611. "assistant",
  612. false
  613. );
  614. this.setInputState(false);
  615. }
  616. }
  617. /**
  618. * 处理文件上传
  619. * @param {FileList} files 上传的文件列表
  620. */
  621. async handleFileUpload(files) {
  622. try {
  623. for (const file of files) {
  624. const extension = file.name.split(".").pop().toLowerCase();
  625. // 显示文件上传消息
  626. this.addMessage(`已上传文件:${file.name}`, "user", false);
  627. if (this.excelTypes[extension]) {
  628. try {
  629. this.setInputState(true);
  630. this.loadingDiv = this.createLoadingMessage();
  631. // 读取Excel文件
  632. const data = await this.readExcelFile(file);
  633. // 保存Excel数据到AI服务
  634. this.aiService.setExcelData({
  635. fileName: file.name,
  636. headers: data[0],
  637. rows: data.slice(1),
  638. totalRows: data.length - 1,
  639. });
  640. // 构建Excel理解提示词
  641. const prompt = this.buildExcelUnderstandingPrompt(data, file.name);
  642. // 调用AI服务理解数据
  643. const response = await this.aiService.sendMessage(prompt);
  644. if (this.loadingDiv) {
  645. this.loadingDiv.remove();
  646. this.loadingDiv = null;
  647. }
  648. // 显示AI的理解结果
  649. this.addMessage(response, "assistant", true);
  650. } catch (error) {
  651. console.error("Excel processing error:", error);
  652. this.addMessage(
  653. "Excel文件处理过程中出现错误,请重试。",
  654. "assistant",
  655. false
  656. );
  657. } finally {
  658. this.setInputState(false);
  659. }
  660. }
  661. }
  662. } catch (error) {
  663. console.error("File upload error:", error);
  664. this.addMessage("文件上传过程中出现错误,请重试。", "assistant", false);
  665. }
  666. }
  667. /**
  668. * 构建Excel理解提示词
  669. */
  670. buildExcelUnderstandingPrompt(data, fileName) {
  671. if (!data || data.length < 2) {
  672. return "这是一个空的Excel文件,请检查文件内容。";
  673. }
  674. const headers = data[0];
  675. const rows = data.slice(1);
  676. const sampleRows = rows.slice(0, 2);
  677. return `我将向你展示一个通过SheetJS库读取的Excel文件内容。请帮我理解这些数据:
  678. 文件名:${fileName}
  679. 列标题:${headers.join(", ")}
  680. 数据行数:${rows.length}
  681. 示例数据(前2行):
  682. ${sampleRows
  683. .map((row, index) => {
  684. return `第${index + 1}行: ${row
  685. .map((cell, i) => `${headers[i]}=${cell}`)
  686. .join(", ")}`;
  687. })
  688. .join("\n")}
  689. 请简要说明:
  690. 1. 这个表格的主要用途
  691. 2. 数据之间的关系
  692. 3. 可能的使用场景
  693. 请记住这些数据内容,因为后续我可能会询问更多相关问题。
  694. 请用简洁的语言回复,避免过多修饰词。`;
  695. }
  696. /**
  697. * 读取Excel文件
  698. * @param {File} file
  699. * @returns {Promise<Array>}
  700. */
  701. async readExcelFile(file) {
  702. return new Promise((resolve, reject) => {
  703. const reader = new FileReader();
  704. reader.onload = (e) => {
  705. try {
  706. const data = new Uint8Array(e.target.result);
  707. const workbook = XLSX.read(data, {
  708. type: "array",
  709. cellDates: true,
  710. cellNF: false,
  711. cellText: false,
  712. });
  713. // 获取第一个工作表
  714. const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
  715. // 转换为JSON数据
  716. const jsonData = XLSX.utils.sheet_to_json(firstSheet, {
  717. header: 1,
  718. raw: true,
  719. defval: "",
  720. });
  721. resolve(jsonData);
  722. } catch (error) {
  723. reject(error);
  724. }
  725. };
  726. reader.onerror = () => reject(reader.error);
  727. reader.readAsArrayBuffer(file);
  728. });
  729. }
  730. }
  731. // 等待DOM加载完成后再初始化
  732. document.addEventListener("DOMContentLoaded", () => {
  733. try {
  734. const chatUI = new ChatUI();
  735. } catch (error) {
  736. console.error("Failed to initialize ChatUI:", error);
  737. }
  738. });