Browse Source

refactor(sidepanel): 重构消息处理逻辑

- 优化了表单信息获取流程,使用 Promise 等待异步结果
- 改进了与 background 的通信方式,支持选择表单功能
- 调整了消息内容的处理和格式化逻辑,提高了可读性
- 移除了不必要的代码和注释,精简了整体结构
chd 5 months ago
parent
commit
716abdcc0b
2 changed files with 57 additions and 143 deletions
  1. 8 7
      src/entrypoints/sidepanel/Chat.vue
  2. 49 136
      src/entrypoints/sidepanel/hook/useMsg.ts

+ 8 - 7
src/entrypoints/sidepanel/Chat.vue

@@ -201,9 +201,10 @@ async function handleAsk() {
   // handleSend(inputMessage.value.trim())
   if (type.value === '2') {
     const res = await fetchRes(inputMessage.value.trim())
-    if (res.status === 'ok') formInfo.value = res.data
-    console.log(res, 88452588);
-   
+    if (res.status === 'ok') {
+      formInfo.value = res.data
+      console.log(res);
+    }
   }
   else streamRes(true)
   inputMessage.value = ''
@@ -281,10 +282,10 @@ onMounted(() => {
     if (message.type === 'TO_SIDE_PANEL_PAGE_CHANGE') {
       pageInfo.value = message.data
     }
-     if (message.type === 'TO_SIDE_PANEL_FORM_INFO') {
-       formInfo.value = message.data
-       messages.value[messages.value.length - 1].content = '请上传数据'
-    }
+    //  if (message.type === 'TO_SIDE_PANEL_FORM_INFO') {
+    //    formInfo.value = message.data
+    //    messages.value[messages.value.length - 1].content = '请上传数据'
+    // }
   })
   // 添加标题悬停事件监听
   nextTick(() => {

+ 49 - 136
src/entrypoints/sidepanel/hook/useMsg.ts

@@ -69,10 +69,6 @@ export function useMsg(scrollbar?: any) {
         input_data: file
       })
       return response
-      xlsxData.value = response.data
-      console.log(xlsxData.value)
-      console.log(type.value)
-      await streamRes(buildObjPrompt(response.data, form))
     } catch (error) {
       // obj.content = '解析出错'
     } finally {
@@ -97,6 +93,36 @@ export function useMsg(scrollbar?: any) {
   //     fetchRes(msg)
   //   } 
   // }
+  async function awaitFindForm(obj:any) {
+    return await new Promise((res, rej) => {
+      chrome.runtime.sendMessage({
+        type: 'FROM_SIDE_PANEL_TO_GET_PAGE_FORM'
+      }, ({ status, data }) => {
+        if (status === 'error') {
+          obj.content = '当前页面未找到表单'
+          res({ status })
+        }
+        if (status === 'ok') {
+          obj.content = '请上传数据'
+          res({ status, data })
+        }
+        if (status === 'select') {
+          obj.content = '检测到左侧页面中有多个表单,请选择要填写的表单。'
+          function handle(message, sender, sendResponse)  {
+            if (message.type === 'TO_SIDE_PANEL_FORM_INFO') {
+              console.log('收到一次性消息:', message.data);
+              res({ status: 'ok', data: message.data })
+              obj.content = '请上传数据'
+              console.log(565656);
+              // 销毁监听器(确保只触发一次)
+              chrome.runtime.onMessage.removeListener(handle);
+            }
+          }
+         chrome.runtime.onMessage.addListener(handle);
+        }
+      })
+    })
+  }
   const fetchRes = async (msg: any) => {
     indexTemp.value = 0
     sendLoading.value = true
@@ -113,84 +139,21 @@ export function useMsg(scrollbar?: any) {
     msg = msg.split('/智能填表')[1]
     nextTick(() => scrollbar.value?.setScrollTop(99999))
     if (!msg) {
-      const res = await new Promise((res, rej) => {
-        chrome.runtime.sendMessage({
-          type: 'FROM_SIDE_PANEL_TO_GET_PAGE_FORM'
-        }, ({ status, data }) => {
-          if (status === 'error') {
-            obj.content = '当前页面未找到表单'
-            sendLoading.value = false
-            res({ status })
-          }
-          if (status === 'ok') {
-            obj.content = '请上传数据'
-            sendLoading.value = false
-            res({ status, data })
-          }
-          if (status === 'select') {
-            obj.content = '检测到左侧页面中有多个表单,请选择要填写的表单。'
-            sendLoading.value = false
-            res({ status })
-          }
-        })
-      })
+      sendLoading.value = false
+      const res = await awaitFindForm(obj)
       return res
     }
-    if (!msg) {
-      obj.content = `请选择表单`
-      // ElMessage({
-      //   message: '请选择表单',
-      //   type: 'success',
-      //   duration: 4 * 1000,
-      //   grouping: true
-      // })
-      chrome.runtime.sendMessage({
-        type: 'FROM_SIDE_PANEL_TO_GET_PAGE_FORM'
-      }, (response) => {
-        if (response.status === 'error') {
-          obj.content = '当前页面未找到表单'
-          sendLoading.value = false
-        }
-        if (response.status === 'ok') {
-          obj.content = '请上传数据'
-          sendLoading.value = false
-          return
-        }
-      })
-      return
-    }
     const res = await fetchDataAndProcess(msg, obj)
-    console.log(res);
+    sendLoading.value = false
     if (res.status === 'ok') {
       await new Promise((res: any) =>
         setTimeout(() => {
           res()
         }, 2000)
       )
-      const res = await new Promise((res, rej) => {
-        chrome.runtime.sendMessage({
-          type: 'FROM_SIDE_PANEL_TO_GET_PAGE_FORM'
-        }, ({ status, data }) => {
-          if (status === 'error') {
-            obj.content = '当前页面未找到表单'
-            sendLoading.value = false
-            res({ status })
-          }
-          if (status === 'ok') {
-            obj.content = '请上传数据'
-            sendLoading.value = false
-            res({ status, data })
-          }
-          if (status === 'select') {
-            obj.content = '检测到左侧页面中有多个表单,请选择要填写的表单。'
-            sendLoading.value = false
-            res({ status })
-          }
-        })
-      })
+      const res = await awaitFindForm(obj)
       return res
     }
-    sendLoading.value = false
   }
   let str = ''
 
@@ -217,7 +180,6 @@ export function useMsg(scrollbar?: any) {
         })
       }, 1000)
     })
-    const data = res.data
     if (!res.data.tag || res.data.tag === 'undefined') {
       ElMessage({
         message: '未找到标签,请重试',
@@ -226,10 +188,8 @@ export function useMsg(scrollbar?: any) {
         grouping: true
       })
       obj.content = '未找到标签,请重试'
-      return
+      return {status: 'error'}
     }
-    console.log(res);
-
     await new Promise((resolve) => setTimeout(resolve, 2000))
     obj.content = `点击${res.data.tag}元素`
     const res2 = await new Promise((resolve, rej) => {
@@ -277,52 +237,6 @@ export function useMsg(scrollbar?: any) {
     })
     return res2
   }
-
-  async function handleClick(res: any, msgObj: any) {
-    await new Promise((resolve) => setTimeout(resolve, 2000))
-    msgObj.content = `点击${res.tag}元素`
-    chrome.runtime.sendMessage(
-      {
-        type: 'FROM_SIDE_PANEL_TO_ACTION',
-        data: res
-      },
-      async ({ data, status }) => {
-        if (chrome.runtime.lastError) {
-          console.error('消息发送错误:', chrome.runtime.lastError)
-        } else {
-          if (status === 'error') {
-            msgObj.content = data
-            return
-          }
-          if (res.next === '是') {
-            const arr = str.split(',')
-            arr.shift()
-            str = arr.join(',')
-            indexTemp.value++
-            fetchDataAndProcess(str, msgObj)
-          } else {
-            await new Promise((resolve, reject) => {
-              setTimeout(() => {
-                resolve(1)
-              }, 2000)
-            })
-            msgObj.content = `请选择表单`
-            ElMessage({
-              message: '请选择表单',
-              type: 'success',
-              duration: 4 * 1000,
-              grouping: true
-            })
-            chrome.runtime.sendMessage({
-              type: 'FROM_SIDE_PANEL_TO_GET_PAGE_FORM'
-            })
-          }
-        }
-        return true
-      }
-    )
-  }
-
   /**
    *
    * @param addHtml 是否添加页面信息
@@ -375,7 +289,7 @@ export function useMsg(scrollbar?: any) {
           obj.rawContent += decodedChunk
           // 实时格式化显示内容
           obj.content = formatMessage(obj.rawContent)
-          if (type.value === '2') obj.content = obj.content.replace(/item/g, '表单项').replace(/excelColumn/g, '对应数据源')
+          // if (type.value === '2') obj.content = obj.content.replace(/item/g, '表单项').replace(/excelColumn/g, '对应数据源')
 
         }
       }
@@ -390,21 +304,20 @@ export function useMsg(scrollbar?: any) {
     nextTick(() => {
       scrollbar.value?.setScrollTop(99999)
     })
-    console.log();
-    // if (type.value === '2') {
-    //   const arr = JSON.parse(obj.rawContent.split('json')[1].split('```')[0])
-    //   const newArr = arr.map((i:any) => {
-    //     return {
-    //       '表单项': i.label ?? i.placeholder,
-    //       '对应数据': i.excleColumn
-    //     }
-    //   })
-    //   obj.content = formatMessage('```json' + JSON.stringify(newArr) + '```')
-    //   console.log(formatMessage('```json' + JSON.stringify(newArr) + '```'));
-
-    // }
-    console.log(obj.content);
+    if (type.value === '2') {
+      const arr = JSON.parse(obj.rawContent.split('json')[1].split('```')[0])
+      const newArr = arr.map(obj => {
+        return `| ${[
+          `“findBy”: \` "label",`,
+          `"findByValue" \` “${obj.findByValue}”,`,
+          `"数据来源字段" \` “${obj.excelColumn}”,`,
+          `"表单项" \` “${obj.item}"`
+        ].join(' ')} |`;
+      }).join('\n');
+      obj.content = formatMessage('```json' + JSON.stringify(newArr) + '```')
+      console.log(formatMessage('```json' + JSON.stringify(newArr) + '```'));
 
+    }
     return obj.rawContent
   }
   return {