chat-ui.js 28 KB

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