chat-ui.js 25 KB

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