AiChat.vue 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. <template>
  2. <div class="chat-content-ai">
  3. <div ref="chatArea" class="chat-message">
  4. <div v-if="showMore" class="more" @click="handleMoreHistory"> 查看历史记录 </div>
  5. <div class="chat-message-scroll" :class="{ 'is-full': isFull }">
  6. <!-- sender:发送人,replyer:回复人 -->
  7. <div
  8. v-for="(message, index) in messageList"
  9. :key="message.id || index"
  10. class="chat-message-box"
  11. :class="[message.author === 'sender' ? 'message-sender' : 'message-replyer']"
  12. >
  13. <div v-if="message.showTime" class="other time">
  14. <span>{{ dateFormatter(message.showTime, 'yyyy年M月d日 HH:mm:ss', true) }}</span>
  15. </div>
  16. <!-- 双方头像 -->
  17. <div class="chat-message-avatar">
  18. <img :src="message.author === 'sender' ? ManAvatar : AiAvatar" alt="" />
  19. </div>
  20. <div class="chat-message-content">
  21. <!-- 用户名 -->
  22. <div class="chat-message-content__name">
  23. {{ message.name }}
  24. <!-- <span v-if="message.author !== 'sender'" class="tag">AI助手</span>-->
  25. </div>
  26. <!-- 消息主内容 -->
  27. <div class="chat-message-content__message">
  28. <!-- 消息部分 -->
  29. <template v-if="message.body.component">
  30. <component :is="message.body.component" v-bind="message" />
  31. </template>
  32. <div v-else class="message-text" v-html="message.body.text"></div>
  33. </div>
  34. </div>
  35. </div>
  36. </div>
  37. </div>
  38. <!-- 聊天框下方操作部分 -->
  39. <ChatBottom @handleSend="handleOutboundMessage" />
  40. </div>
  41. </template>
  42. <script lang="ts" setup>
  43. import { dateFormatter } from '../utils'
  44. import ManAvatar from '../img/chat/man-avatar.png'
  45. import AiAvatar from '../img/chat/ai-avatar-base.png'
  46. import ChatBottom from './ChatBottom.vue'
  47. import Thinking from './Thinking.vue'
  48. import { marked } from 'marked'
  49. import { ref, watch, onUnmounted, nextTick } from 'vue'
  50. const props = defineProps({
  51. isOpen: {
  52. type: Boolean,
  53. default: false
  54. }
  55. })
  56. const emit = defineEmits(['handleSend'])
  57. const aiName = 'AI机器人'
  58. const isInit = ref(false) // 判断是否已经初始化 否则不监听滚动
  59. watch(
  60. () => props.isOpen,
  61. (val) => {
  62. // 打开弹窗时 有历史记录 则需要自动滚动到最下面
  63. if (val) {
  64. init()
  65. setTimeout(() => {
  66. isInit.value = false
  67. }, 500)
  68. } else reset()
  69. }
  70. )
  71. // 销毁(按需)
  72. onUnmounted(() => {
  73. document.querySelector('.chat-message')?.removeEventListener('scroll', () => {})
  74. })
  75. const isFull = ref(false) // 消息是否充满一页 用于首次加载滚动
  76. const showMore = ref(false) // 点击可以查看更多
  77. const messageList = ref<Recordable[]>([]) // 消息列表
  78. const historyList = ref<Recordable[]>([]) // 历史消息列表
  79. // 整理、移除历史记录 仅记录7天内
  80. const trimHistory = () => {
  81. const historyChat =
  82. localStorage.getItem('chat') && JSON.parse(localStorage.getItem('chat') as string)
  83. if (historyChat && historyChat.length) {
  84. const findIndex = historyChat.findIndex((i) => {
  85. const time = i.date
  86. const now = new Date().getTime()
  87. const day = 24 * 60 * 60 * 1000 * 7
  88. return now - time > day
  89. })
  90. if (findIndex !== -1) {
  91. const list = historyChat.slice(0, findIndex)
  92. localStorage.setItem('chat', JSON.stringify(list))
  93. return list
  94. } else return historyChat
  95. } else return []
  96. }
  97. const init = () => {
  98. historyList.value = trimHistory()
  99. // 有历史记录,默认展示historyLimit条
  100. if (historyList.value.length) {
  101. showMore.value = true
  102. isFull.value = true
  103. }
  104. // 最新的一条记录(欢迎语), 所以记录这个时间
  105. const newRecordTime = Date.now()
  106. // 新增欢迎语 每次初始化都来一次(但不计入历史记录中)
  107. const record = {
  108. body: {
  109. text: 'Hi~我是AI机器人,我可以帮你什么?'
  110. },
  111. date: newRecordTime,
  112. showTime: newRecordTime,
  113. author: 'replyer',
  114. name: aiName,
  115. ignore: true
  116. }
  117. messageList.value.push(record)
  118. setTimeout(() => {
  119. messageScroll()
  120. })
  121. // 监听滚动事件 到顶部自动加载历史记录
  122. document.querySelector('.chat-message')?.addEventListener('scroll', (e) => {
  123. handleScroll(e, newRecordTime)
  124. })
  125. }
  126. // 消息内容发出
  127. const handleOutboundMessage = (message) => {
  128. if (!message) {
  129. return
  130. }
  131. let body = {}
  132. if (typeof message === 'string') {
  133. body = {
  134. text: message
  135. }
  136. } else if (Object.prototype.toString.call(message) === '[object Object]') {
  137. body = message
  138. }
  139. handleMessageReceived({
  140. body,
  141. date: Date.now(),
  142. author: 'sender'
  143. })
  144. }
  145. const chatArea = ref()
  146. // 实时滚动
  147. const messageScroll = () => {
  148. chatArea.value.scrollTop = chatArea.value.scrollHeight
  149. }
  150. // 模拟思考
  151. const setThinking = (bol: boolean = true) => {
  152. if (bol) {
  153. messageList.value.push({
  154. body: { component: Thinking },
  155. author: 'replyer',
  156. name: aiName
  157. })
  158. } else messageList.value.pop()
  159. }
  160. const sessionId = ref('')
  161. // 发送消息
  162. const handleMessageReceived = async (message) => {
  163. // 展示用户问题
  164. await addMessage({ ...message, name: '用户' })
  165. setTimeout(() => {
  166. messageScroll()
  167. })
  168. // 及时来一个loading 模拟思考
  169. setThinking()
  170. emit('handleSend', message)
  171. // 移除loading
  172. // setThinking(false)
  173. // handleMessageResponse({ text })
  174. // else { // demo部分
  175. // // 无答案话术
  176. // this.handleMessageResponse({
  177. // text: '很抱歉,您问的问题暂未找到答案,请尝试其他问题'
  178. // })
  179. // }
  180. // setTimeout(() => {
  181. // messageScroll()
  182. // })
  183. }
  184. // 回答
  185. const handleMessageResponse = async (message) => {
  186. console.log(message)
  187. if (Object.prototype.toString.call(message) !== '[object Object]') {
  188. return new Error('得是object格式')
  189. }
  190. // 移除loading
  191. setThinking(false)
  192. const record = {
  193. body: { ...message },
  194. date: new Date().getTime(),
  195. author: 'replyer',
  196. name: aiName
  197. }
  198. await addMessage(record)
  199. setTimeout(() => {
  200. messageScroll()
  201. })
  202. }
  203. // 开启新对话
  204. const newChat = () => {
  205. sessionId.value = ''
  206. messageList.value.push({
  207. body: { text: '已开启新对话~' },
  208. author: 'replyer',
  209. name: aiName,
  210. ignore: true
  211. })
  212. }
  213. const timer: any = ref(null) // 文字处理定时器
  214. const preRecord: any = ref(null) // 上一次的记录
  215. // 记录消息
  216. const addMessage = (record) => {
  217. return new Promise((resolve) => {
  218. // 第一条消息 自动加上时间
  219. // 两分钟以内连续发的消息 不显示时间 由 showTime 来判断显示与否
  220. const curList = messageList.value.filter((item) => !item.ignore)
  221. if (!curList.length || record.date - curList.slice(-1)[0].date > 2 * 60 * 1000) {
  222. record.showTime = record.date
  223. }
  224. // 消息来自用户 或者 回复内容包含组件 直接给出 message 内容
  225. // 否则纯文本类型的走 GPT动效
  226. if (record.author === 'sender' || record.body.component) {
  227. // 继续提问时 有正在进行的输出 提前结束回答
  228. if (preRecord.value) {
  229. clearInterval(timer.value)
  230. timer.value = null
  231. saveHistory(preRecord.value)
  232. }
  233. messageList.value.push(record)
  234. saveHistory(record)
  235. resolve(true)
  236. return
  237. }
  238. preRecord.value = { ...record }
  239. // **** ai的回答 纯文字的要做 GPT 文字效果 ****
  240. // 用tempText 先存一下字段
  241. const body = preRecord.value.body
  242. const { text, messageProps } = body
  243. if (record.author === 'replyer') {
  244. if (text) {
  245. body.tempText = text
  246. body.text = ''
  247. }
  248. if (messageProps?.text) {
  249. messageProps.tempText = messageProps.text
  250. messageProps.text = ''
  251. }
  252. }
  253. // 先 消息列表增加
  254. messageList.value.push(preRecord.value)
  255. // 再 处理消息效果
  256. if (preRecord.value.author === 'replyer' && (body.tempText || messageProps?.tempText)) {
  257. // 记录本次的记录 用于防止在文字演进效果时 没存入记录时 被上一条记录替换掉
  258. const tempText = body.tempText || messageProps.tempText
  259. const len = tempText.length
  260. let num = 0
  261. let string = ''
  262. timer.value = setInterval(() => {
  263. if (num >= len) {
  264. clearInterval(timer.value)
  265. timer.value = null
  266. saveHistory(preRecord.value)
  267. resolve(true)
  268. return
  269. }
  270. // 持续保持滚动最底
  271. if (num % 10 === 0) {
  272. setTimeout(() => {
  273. messageScroll()
  274. })
  275. }
  276. string = `${string}${tempText[num]}`
  277. if (body.tempText) {
  278. body.text = marked(string)
  279. } else {
  280. body.messageProps.text = marked(string)
  281. }
  282. num++
  283. }, 20)
  284. }
  285. })
  286. }
  287. // 将对话存入缓存
  288. const saveHistory = (record) => {
  289. if (!record) return
  290. // GTP对话 将对话内容还原
  291. const body = record.body
  292. const { messageProps } = body
  293. if (body.tempText) {
  294. delete body.tempText
  295. } else if (messageProps?.tempText) {
  296. delete messageProps.tempText
  297. }
  298. setTimeout(() => {
  299. messageScroll()
  300. })
  301. // 增加历史记录
  302. const historyChat = localStorage.getItem('chat')
  303. if (historyChat) {
  304. const list = JSON.parse(historyChat)
  305. list.push(record)
  306. localStorage.setItem('chat', JSON.stringify(list))
  307. } else {
  308. localStorage.setItem('chat', JSON.stringify([record]))
  309. }
  310. // 清除记录
  311. if (preRecord.value) preRecord.value = null
  312. }
  313. const historyPage = ref(1) // 分页
  314. const historyLimit = ref(10) // 每页数量
  315. // 查看历史记录
  316. const handleMoreHistory = () => {
  317. const lastPageList = historyList.value.splice(
  318. -(historyLimit.value * historyPage.value),
  319. historyLimit.value
  320. )
  321. messageList.value = [...lastPageList, ...messageList.value]
  322. historyPage.value++
  323. // 看完了
  324. if (!historyList.value.length) {
  325. showMore.value = false
  326. }
  327. nextTick(() => {
  328. // 获取查看历史记录后的信息列表
  329. const messageList = document.querySelectorAll('.chat-message-box') as NodeListOf<HTMLElement>
  330. // 获取这一批次历史记录最后一个距离文档顶部的高度
  331. const lastOffsetTop = messageList[lastPageList.length - 1]?.offsetTop || 0
  332. // 获取这一批次历史记录最后一个的高度
  333. const lastH = messageList[lastPageList.length - 1]?.clientHeight || 0
  334. // 滚动位置
  335. chatArea.value.scrollTop = lastOffsetTop + lastH
  336. })
  337. }
  338. // 滚动事件 自动加载
  339. const handleScroll = (e, time) => {
  340. if (isInit.value) return
  341. if (Date.now() - time > 1000 && isFull.value) {
  342. isFull.value = false
  343. }
  344. const step = e.target.scrollTop
  345. if (step <= 30 && showMore.value) {
  346. handleMoreHistory()
  347. }
  348. }
  349. const reset = () => {
  350. isInit.value = true
  351. messageList.value = []
  352. historyPage.value = 1
  353. historyLimit.value = 10
  354. preRecord.value = null
  355. }
  356. defineExpose({ newChat, handleMessageResponse })
  357. </script>
  358. <style lang="less">
  359. @import '../styles/variables.less';
  360. .chat-content-ai {
  361. display: flex;
  362. flex-direction: column;
  363. .is-expend & {
  364. background: transparent;
  365. }
  366. .more {
  367. text-align: center;
  368. color: @color-primary;
  369. padding: 8px 0;
  370. cursor: pointer;
  371. }
  372. .chat-message {
  373. flex: 1;
  374. overflow-y: auto;
  375. overflow-x: hidden;
  376. padding: 0 12px;
  377. margin-top: 10px;
  378. &-scroll {
  379. &.is-full {
  380. min-height: 100%;
  381. }
  382. }
  383. &-box {
  384. display: flex;
  385. position: relative;
  386. &:has(.other) {
  387. padding-top: 30px;
  388. }
  389. .other {
  390. position: absolute;
  391. top: 0;
  392. left: 0;
  393. width: 100%;
  394. font-size: 12px;
  395. text-align: center;
  396. &.time {
  397. color: #999;
  398. }
  399. }
  400. .divider {
  401. border-bottom: 1px solid #ddd;
  402. span {
  403. display: inline-block;
  404. position: relative;
  405. padding: 0 8px;
  406. top: 8px;
  407. background-color: #f4f9fd;
  408. }
  409. }
  410. .chat-message-avatar {
  411. img {
  412. width: 40px;
  413. }
  414. }
  415. .chat-message-content {
  416. width: 100%;
  417. margin-left: 4px;
  418. &__name {
  419. font-size: 14px;
  420. font-weight: 400;
  421. color: #7c838e;
  422. line-height: 20px;
  423. margin-bottom: 4px;
  424. margin-left: 3px;
  425. .tag {
  426. font-size: 11px;
  427. color: #0482ff;
  428. line-height: 17px;
  429. padding: 0 4px;
  430. background: linear-gradient(270deg, #8afffa, #a5ffec);
  431. border-radius: 2px;
  432. box-shadow: 0px 1px 4px 0px rgba(255, 255, 255, 0.2) inset;
  433. & + .tag {
  434. margin-left: 12px;
  435. }
  436. }
  437. }
  438. &__message {
  439. display: inline-block;
  440. max-width: 85%;
  441. width: auto;
  442. min-width: 20px;
  443. border-radius: 8px;
  444. font-weight: 400;
  445. line-height: 22px;
  446. padding: 12px;
  447. margin-bottom: 20px;
  448. position: relative;
  449. word-break: break-all;
  450. .message-text {
  451. > *:first-child {
  452. margin-top: 0;
  453. }
  454. > *:last-child {
  455. margin-bottom: 0;
  456. }
  457. }
  458. }
  459. }
  460. }
  461. .message-sender {
  462. justify-content: flex-end;
  463. .chat-message-avatar {
  464. order: 2;
  465. }
  466. .chat-message-content {
  467. order: 1;
  468. text-align: right;
  469. margin-right: 4px;
  470. &__name {
  471. margin-right: 3px;
  472. }
  473. }
  474. .chat-message-content__message {
  475. background: @color-primary;
  476. color: #ffffff;
  477. text-align: left;
  478. // 发送文件类型时 白底
  479. &:has(.white-bg) {
  480. background-color: #fff;
  481. color: #333;
  482. }
  483. }
  484. }
  485. .message-replyer {
  486. color: #333;
  487. text-align: left;
  488. .chat-message-content__message {
  489. background: #fff;
  490. color: #333;
  491. width: 96%;
  492. max-width: 96%;
  493. }
  494. }
  495. }
  496. }
  497. </style>