chat-ui.js 27 KB

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