wujingjing
2024-12-14 1476d27514874e9c95002451a81878bd9bec8382
src/components/chat/components/playBar/PlayBar.vue
@@ -1,64 +1,508 @@
<template>
   <div class="playInput hl_input">
   <div class="playInput hl_input rounded-[22px] input-border input-shadow">
      <!-- 应用场景 -->
      <div class="application-scenarios absolute bottom-[114%] left-4">
         <div class="flex-items-center space-x-2" :class="isHome ? 'set-next-group-type' : ''">
            <div
               class="border border-gray-400 border-solid h-8 flex-items-center px-3 py-2 rounded-2xl cursor-pointer space-x-1 hover:bg-[#cae3ff]"
               :class="{ 'bg-[#c5e0ff]': activeGroupType === item, '!text-[#1c86ff]': activeGroupType === item }"
               v-for="item in groupTypeList"
               @click="groupTypeClick(item)"
            >
               <span :class="['ywifont', groupTypeMapIcon[item]]"></span>
               <div class="">{{ item }}</div>
            </div>
         </div>
      </div>
      <!-- 当前应用场景 -->
      <!-- <div
         class="bg-[#f9fafb] rounded-t-[22px] absolute bottom-[100%] left-0 w-full input-border h-11 flex-items-center justify-between text-[14px]"
         style="padding: 4px 4px 4px 18px; border-bottom: none"
      >
         <div class="flex-items-center">
            <span :class="[groupTypeMapIcon[activeGroupType]]" class="ywifont mr-2 !text-[14px]"></span>
            <div>{{ activeGroupType }}</div>
         </div>
         <el-tooltip content="退出应用场景" placement="top">
            <span
               @click="closeCurrentGroupType"
               class="ywifont ywicon-guanbi mr-3 rounded-sm p-1 hover:bg-[#eaebec] cursor-pointer"
            ></span>
         </el-tooltip>
      </div> -->
      <div class="assembly flex">
         <el-button title="插件菜单" class="label flex items-center cursor-pointer" link>
         <el-button
            title="输入常用语标题,可快捷调用常用语"
            class="label flex items-center cursor-pointer"
            link
            @click="commonPhrasesClick"
         >
            <img src="/static/images/wave/PlugIn.png" class="set-icon box-border" />
         </el-button>
      </div>
      <InfoDetail class="text-base" v-model="infoDetailIsShow" :item="detailMapRow" />
      <div class="set-input">
         <!-- @input="inputText" -->
         <el-input
            ref="inputRef"
            class="relative align-bottom set-inputAnswer"
            type="textarea"
            resize="none"
            maxlength="1024"
            :autosize="{ minRows: 1, maxRows: 8 }"
            v-elInputFocus
            @keydown="enterInput"
            show-word-limit
            @keydown="keydownInput"
            @input="inputText"
            v-model="inputValue"
            placeholder="在这里输入您的问题开始和AI对话"
         />
         >
         </el-input>
         <div
            v-show="tipIsShow"
            ref="tipEleRef"
            class="absolute rounded-md bg-white border border-solid border-gray-400 py-2 z-10"
            :style="{ left: popUpPosition.left + 'px', bottom: popUpPosition.bottom + 'px' }"
         >
            <div class="font-bold text-nowrap overflow-hidden text-ellipsis max-w-80 mb-1 px-2">Ctrl+数字快捷输入</div>
            <div class="text-gray-400 text-nowrap overflow-hidden text-ellipsis max-w-80 mb-1 px-2">{{ inputValue }}</div>
            <div class="max-w-96 flex flex-col">
               <div
                  class="hover:bg-gray-300 py-2 cursor-pointer px-5 text-nowrap overflow-hidden text-ellipsis"
                  v-for="(item, index) in similarList"
                  :key="index"
                  @click="similarClick(item)"
               >
                  <span class="text-gray-500 pr-1.5">{{ index + 1 }}</span>
                  <template v-if="sentenceSplitMap?.[item.question]">
                     <template v-for="part in sentenceSplitMap[item.question]">
                        <span v-if="part.isKeyword" class="text-blue-400 font-bold cursor-pointer">{{ part.partStr }}</span>
                        <span v-else>{{ part.partStr }}</span>
                     </template>
                  </template>
               </div>
            </div>
         </div>
      </div>
      <div class="h100 flex items-center">
         <div class="upload_img space-y">
            <div class="imgbox cursor-pointer flex items-center">
               <el-button title="AI看图" class="cursor-pointer" link style="margin-left: unset">
                  <img src="/static/images/wave/LookImg.png" class="set-img-icon box-border" />
               <!-- <el-button title="AI看图" class="cursor-pointer" link style="margin-left: unset">
            <img src="/static/images/wave/LookImg.png" class="set-img-icon box-border" />
         </el-button> -->
               <!-- <el-button title="AI语音对话" class="cursor-pointer" link style="margin-left: unset" @click="audioChangeWord">
            <img src="/static/images/wave/HeadImg.png" class="set-img-icon box-border" />
         </el-button> -->
               <el-button
                  title="清除"
                  class="cursor-pointer"
                  link
                  style="margin-left: unset"
                  @click="clearTextarea"
                  icon="ele-Close"
                  v-if="inputValue"
               >
               </el-button>
               <el-button title="AI语音对话" class="cursor-pointer" link style="margin-left: unset">
                  <img src="/static/images/wave/HeadImg.png" class="set-img-icon box-border" />
               </el-button>
               <el-button class="cursor-pointer" link >
                  <el-tooltip v-if="isTalking" placement="top" content="停止生成">
                     <div class="size-[36px] rounded-full flex-center border-2 border-solid border-black text-black" @click="emits('stopGenClick')">
                        <span class="ywifont ywicon-jieshu"></span>
                     </div>
                  </el-tooltip>
               <el-button title="发送" :disabled="isTalking" class="cursor-pointer" link @click="emits('sendClick')">
                  <div class="send">
                     <img src="/static/images/wave/QueryImg.png" />
                  </div>
                  <el-tooltip v-else placement="top" content="发送">
                     <div class="size-[36px] rounded-full bg-black flex-center" @click="emits('sendClick')">
                        <img src="/static/images/wave/QueryImg.png" />
                     </div>
                  </el-tooltip>
               </el-button>
            </div>
         </div>
      </div>
      <VoicePage
         v-model:isShow="voicePageIsShow"
         v-show="voicePageIsShow"
         @submit="(cb) => emits('sendClick', cb)"
         @updateInputValue="updateInputValue"
         :isHome="isHome"
      />
      <CommonPhrases
         v-model:isShow="isShowPhrase"
         v-show="isShowPhrase"
         :isHome="isHome"
         ref="commonPhrasesRef"
         @updateCommonChatInput="updateCommonChatInput"
      />
   </div>
</template>
<script setup lang="ts">
import { reactive } from 'vue';
import { onClickOutside } from '@vueuse/core';
import type { InputInstance } from 'element-plus';
import { ElMessage } from 'element-plus';
import { sortBy } from 'lodash-es';
import getCaretCoordinates from 'textarea-caret';
import { computed, nextTick, ref, toRefs, watch } from 'vue';
import InfoDetail from './InfoDetail.vue';
import CommonPhrases from './phrase/CommonPhrases.vue';
import VoicePage from './voicePage/VoicePage.vue';
import { getMetricsNames, querySimilarityHistory } from '/@/api/ai/chat';
import { activeGroupType, groupTypeList, groupTypeMapIcon } from '/@/stores/chatRoom';
const emits = defineEmits(['sendClick', 'showUpChatClick', 'showDownChatClick','stopGenClick']);
const props = defineProps({
   isTalking: Boolean,
   isHome: Boolean,
   setCommonQuestionInfo: {
      type: Object,
      default: {},
   },
});
const emits = defineEmits(['sendClick']);
const props = defineProps(['isTalking']);
const { setCommonQuestionInfo } = toRefs(props);
const voicePageIsShow = defineModel('voicePageIsShow', {
   type: Boolean,
   default: false,
});
const isShowPhrase = defineModel('isShowPhrase', {
   type: Boolean,
   default: false,
});
const inputValue = defineModel({
   type: String,
});
const enterInput = (e) => {
const tipIsShow = computed(() => !!inputValue.value?.trim() && similarList.value?.length > 0 && triggerShow.value);
const triggerShow = ref(false);
const inputRef = ref<InputInstance>(null);
const updateInputValue = (val) => {
   inputValue.value = val;
};
const keydownInput = (e) => {
   if (props.isTalking) return;
   if (!e.shiftKey && e.keyCode == 13) {
   const isEnterInput = !e.shiftKey && e.key == 'Enter';
   const isDigitalInput = e.ctrlKey && e.code.startsWith('Digit') && tipIsShow.value;
   const arrowUp = e.key === 'ArrowUp';
   const arrowDown = e.key === 'ArrowDown';
   if (isEnterInput || isDigitalInput || arrowUp || arrowDown) {
      e.cancelBubble = true; //ie阻止冒泡行为
      e.stopPropagation(); //Firefox阻止冒泡行为
      e.preventDefault(); //取消事件的默认动作*换行
      //以下处理发送消息代码
      emits('sendClick');
      if (isEnterInput) {
         //以下处理发送消息代码
         emits('sendClick');
      } else if (isDigitalInput) {
         const num = Number(e.code.replace('Digit', ''));
         const mapValue = similarList.value[num - 1]?.question;
         if (mapValue) {
            inputValue.value = mapValue;
            triggerShow.value = false;
         }
      } else if (arrowUp) {
         emits('showUpChatClick');
      } else if (arrowDown) {
         emits('showDownChatClick');
      }
   }
};
const similarClick = (item) => {
   if (item.question) {
      inputValue.value = item.question;
      triggerShow.value = false;
   }
};
const tipEleRef = ref<HTMLDivElement>(null);
const popUpPosition = ref({
   left: null,
   bottom: null,
});
onClickOutside(tipEleRef, () => {
   triggerShow.value = false;
});
const clearTextarea = () => {
   inputValue.value = '';
};
const inputText = (text) => {
   nextTick(() => {
      setTimeout(() => {
         const container = inputRef.value.$el;
         const textAreaEl = inputRef.value.$el.firstElementChild;
         const caret = getCaretCoordinates(textAreaEl, textAreaEl.selectionEnd);
         const bottomOffset = 10;
         const leftOffset = 9;
         popUpPosition.value.left = caret.left + leftOffset;
         popUpPosition.value.bottom = container.offsetHeight + bottomOffset;
         triggerShow.value = true;
         if (lastIsFinish) {
            querySimilarityApi(text);
         }
      }, 0);
   });
};
// 对 question 进行分割
const sentenceSplitMap = ref<
   Record<
      string,
      {
         partStr: string;
         startIndex: number;
         endIndex: number;
         isKeyword: boolean;
      }[]
   >
>({});
const similarList = ref([]);
let lastIsFinish = true;
const querySimilarityApi = async (text: string) => {
   if (!text) return;
   lastIsFinish = false;
   const res = await querySimilarityHistory({
      question: text,
      group_type: activeGroupType.value,
   });
   lastIsFinish = true;
   const handleValues = res?.values ?? [];
   similarList.value = props.isHome ? handleValues.slice(0, 3) : handleValues;
   metricsNamesPromise.then((value) => {
      sentenceSplitMap.value = getSentenceMatchMap(
         similarList.value.map((item) => item.question),
         value as string[]
      );
   });
};
const audioChangeWord = () => {
   navigator.getUserMedia(
      { audio: true },
      function onSuccess(stream) {
         voicePageIsShow.value = true;
      },
      function onError(error) {
         ElMessage.warning('请打开麦克风权限');
      }
   );
};
/**
 * 切分句子,匹配词用 isKeyword 标记
 * @param sentences
 * @param keywords
 */
const getSentenceMatchMap = (sentences: string[], keywords: any[]) => {
   if (!sentences || sentences.length === 0) return null;
   if (!keywords || keywords.length === 0) {
      return sentences.map((item) => ({
         partStr: item,
         startIndex: 0,
         endIndex: item.length,
         isKeyword: false,
      }));
   }
   let sentenceMatchMap = {};
   sentences.map((sentence) => {
      if (!sentenceMatchMap[sentence]) {
         let sentenceMatchList = [];
         keywords.map((keyword) => {
            const matchList = [...sentence.matchAll(keyword)].map((item) => {
               return {
                  partStr: item[0],
                  startIndex: item.index,
                  endIndex: item.index + item[0].length,
               };
            });
            sentenceMatchList = sentenceMatchList.concat(matchList);
         });
         let nextIsMerge = false;
         const checkNextIsMerge = (value, index, array) => {
            nextIsMerge = false;
            if (index === array.length - 1) return;
            const nextValue = array[index + 1];
            // 通过 nextIsMerge 控制下一元素是否需要使用
            if (value.endIndex > nextValue.startIndex) {
               nextIsMerge = true;
            }
         };
         // 按 startIndex 排序,消除彼此之间重合元素
         sentenceMatchList = sortBy(sentenceMatchList, (item) => item.startIndex).filter((value, index, array) => {
            if (nextIsMerge) {
               checkNextIsMerge(value, index, array);
               return false;
            }
            checkNextIsMerge(value, index, array);
            return true;
         });
         sentenceMatchMap[sentence] = sentenceMatchList;
      }
   });
   for (const sentence of Object.keys(sentenceMatchMap)) {
      const matchList = sentenceMatchMap[sentence];
      const result = [];
      if (matchList.length === 0) {
         result.push({
            partStr: sentence,
            startIndex: 0,
            endIndex: sentence.length,
            isKeyword: false,
         });
         sentenceMatchMap[sentence] = result;
         continue;
      }
      matchList.forEach((value, index, array) => {
         // 匹配词恰好不是位于结束位置
         if (array.length - 1 === index && value.endIndex !== array.length) {
            result.push({
               ...value,
               isKeyword: true,
            });
            if (value.endIndex !== sentence.length) {
               result.push({
                  partStr: sentence.slice(value.endIndex, sentence.length),
                  startIndex: value.endIndex,
                  endIndex: sentence.length,
                  isKeyword: false,
               });
            }
            // 如果数组只有一个元素,前面的也需要加进去
            if (array.length === 1 && value.startIndex !== 0) {
               result.unshift({
                  partStr: sentence.slice(0, value.startIndex),
                  startIndex: 0,
                  endIndex: value.startIndex,
                  isKeyword: false,
               });
            }
            return;
         }
         // 匹配词恰好不是位于起始位置
         if (value.startIndex !== 0 && index === 0) {
            result.push({
               ...value,
               isKeyword: true,
            });
            result.unshift({
               partStr: sentence.slice(0, value.startIndex),
               startIndex: 0,
               endIndex: value.startIndex,
               isKeyword: false,
            });
            return;
         }
         // 恰好位于第一个
         if (index === 0) {
            result.push({
               ...value,
               isKeyword: true,
            });
            return;
         }
         // 中间有非关键词
         if (array[index - 1].endIndex !== value.startIndex) {
            result.push({
               partStr: sentence.slice(array[index - 1].endIndex, value.startIndex),
               startIndex: array[index - 1].endIndex,
               endIndex: value.startIndex,
               isKeyword: false,
            });
            result.push({
               ...value,
               isKeyword: true,
            });
         }
      });
      sentenceMatchMap[sentence] = result;
   }
   return sentenceMatchMap;
};
const metricsNamesPromise = new Promise(async (resolve, reject) => {
   const metricNames = (await getMetricsNames())?.values ?? [];
   resolve(metricNames);
});
//#region ======================  高亮指标点击======================
const infoDetailIsShow = ref(false);
const detailMapRow = ref(null);
const tipMetricsClick = (row) => {
   detailMapRow.value = row;
   infoDetailIsShow.value = true;
};
//#endregion
//#region ====================== 当前应用场景 ======================
const currentGroupTypeIsShow = computed(() => !!activeGroupType.value);
const groupTypeClick = (item) => {
   activeGroupType.value = item;
   inputRef.value.focus();
   commonPhrasesRef.value.getCommonPhrases();
};
// 关闭当前 groupType 面板
const closeCurrentGroupType = () => {
   activeGroupType.value = null;
};
//#endregion
//#region ====================== 常用语功能 ======================
const commonPhrasesRef = ref(null);
// 常用语功能点击
const commonPhrasesClick = () => {
   isShowPhrase.value = true;
};
// 区域关闭常用语功能面板
onClickOutside(
   commonPhrasesRef,
   () => {
      isShowPhrase.value = false;
   },
   {
      ignore: ['.el-message-box'],
   }
);
// 常用语功能输入框更新
const updateCommonChatInput = (val) => {
   inputValue.value = val;
   isShowPhrase.value = false;
};
watch(setCommonQuestionInfo, (val) => {
   if (!props.isHome) {
      let obj = {
         id: val?.historyId,
         question: val?.content.values,
      };
      commonPhrasesRef.value.commonChatByUser(obj);
      isShowPhrase.value = true;
   }
});
//#endregion
</script>
<style scoped lang="scss">
.set-waterTitle {
@@ -110,6 +554,21 @@
   border-color: #1c86ff;
   color: #fff;
}
.input-shadow {
   -webkit-box-shadow: 0 0 0 1px transparent, 0 3px 16px 0 #dee0f3;
   box-shadow: 0 0 0 1px transparent, 0 3px 16px 0 #dee0f3;
}
.input-border {
   border: 1px solid #00000030;
   -webkit-transition: border-color 0.1s ease-in-out, -webkit-box-shadow 0.1s ease-in-out;
   transition: border-color 0.1s ease-in-out, -webkit-box-shadow 0.1s ease-in-out;
   -o-transition: border-color 0.1s ease-in-out, box-shadow 0.1s ease-in-out;
   transition: border-color 0.1s ease-in-out, box-shadow 0.1s ease-in-out;
   transition: border-color 0.1s ease-in-out, box-shadow 0.1s ease-in-out, -webkit-box-shadow 0.1s ease-in-out;
}
.playInput {
   align-items: flex-start;
   width: 760px;
@@ -122,15 +581,7 @@
   align-items: flex-end;
   -webkit-box-sizing: border-box;
   box-sizing: border-box;
   border-radius: 22px;
   border: 1px solid #00000030;
   -webkit-box-shadow: 0 0 0 1px transparent, 0 3px 16px 0 #dee0f3;
   box-shadow: 0 0 0 1px transparent, 0 3px 16px 0 #dee0f3;
   -webkit-transition: border-color 0.1s ease-in-out, -webkit-box-shadow 0.1s ease-in-out;
   transition: border-color 0.1s ease-in-out, -webkit-box-shadow 0.1s ease-in-out;
   -o-transition: border-color 0.1s ease-in-out, box-shadow 0.1s ease-in-out;
   transition: border-color 0.1s ease-in-out, box-shadow 0.1s ease-in-out;
   transition: border-color 0.1s ease-in-out, box-shadow 0.1s ease-in-out, -webkit-box-shadow 0.1s ease-in-out;
   background-color: #fff;
   .assembly {
      position: relative;
@@ -147,14 +598,13 @@
      display: inline-block;
      width: 100%;
      .set-inputAnswer {
         padding: 3px 0;
         line-height: 20px;
         border: none;
         background-color: transparent;
         color: #333;
         font-size: 15px;
         :deep(.el-textarea__inner){
         :deep(.el-textarea__inner) {
            // 去除线
            box-shadow: none;
         }