index.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. <template>
  2. <div
  3. class="container"
  4. :style="{ height: `calc(100% - ${currentBottomHeight}px)` }"
  5. >
  6. <div class="chat-bg"></div>
  7. <!-- 顶部导航 -->
  8. <div class="header-chat">
  9. <svg-icon class="page-icon" name="lf-arrow" @click="goBack" />
  10. <div class="header-title">群聊2({{ wsStore.messages.length }})</div>
  11. <svg-icon class="page-icon" name="more" @click="goDetail" />
  12. </div>
  13. <!-- 聊天消息区域 -->
  14. <div class="chat-list" ref="chatListRef">
  15. <div v-for="(item, index) in wsStore.messages" :key="index">
  16. <div class="chat-time">
  17. {{ formatTime(item.timestamp || Date.now()) }}
  18. </div>
  19. <div class="box">
  20. <div
  21. class="list-item"
  22. :class="
  23. isSender(item.toUsername) ? '' : 'flex-reverse'
  24. "
  25. >
  26. <!-- 头像 -->
  27. <van-image
  28. class="list-img"
  29. :class="isSender(item.toUsername) ? 'mr12' : 'ml12'"
  30. round
  31. :src="item.avatar"
  32. @click="router.push('personal')"
  33. />
  34. <!-- 内容 -->
  35. <div class="list-cont">
  36. <div>{{ item.fromUsername || "匿名用户" }}</div>
  37. <!-- 文本消息 -->
  38. <div class="content" v-if="item.contentType === MSG_TYPE.TEXT">
  39. {{ item.content }}
  40. </div>
  41. <!-- 图片消息 -->
  42. <div class="content" v-else-if="item.contentType === MSG_TYPE.IMAGE">
  43. <van-image
  44. :src="item?.localUrl || IM_PATH + item.url"
  45. alt="图片"
  46. style="max-width: 120px; border-radius: 8px"
  47. />
  48. </div>
  49. <!-- 名片消息 -->
  50. <div
  51. class="content card-message"
  52. v-else-if="item.contentType === 3"
  53. >
  54. <div class="card-title">名片</div>
  55. <div class="card-name">{{ item.content }}</div>
  56. </div>
  57. <!-- 录音消息 -->
  58. <div
  59. class="audio-message"
  60. v-else-if="item.contentType === MSG_TYPE.AUDIO"
  61. >
  62. <!-- <audio
  63. v-if="item.localUrl"
  64. :src="item.localUrl"
  65. controls
  66. style="width: 200px"
  67. />
  68. <audio
  69. v-else
  70. :src="IM_PATH + item.url"
  71. controls
  72. style="width: 200px"
  73. /> -->
  74. <messageAudio :src="item?.localUrl || IM_PATH + item.url" :isSender="isSender(item.toUsername)"/>
  75. </div>
  76. <!-- 其他未知类型 -->
  77. <div class="content" v-else>[未知消息类型]</div>
  78. </div>
  79. </div>
  80. </div>
  81. </div>
  82. </div>
  83. <!-- 输入框 -->
  84. <div class="page-foot">
  85. <div class="flex-box">
  86. <svg-icon
  87. type="button"
  88. class="page-icon"
  89. name="voice"
  90. @mousedown="startAudio"
  91. @touchstart="startAudio"
  92. @mouseup="sendAudioMessage"
  93. @touchend="sendAudioMessage"
  94. />
  95. <van-field
  96. rows="1"
  97. type="textarea"
  98. :border="false"
  99. autosize
  100. class="input"
  101. v-model="text"
  102. @focus="onFocus"
  103. placeholder="输入文本"
  104. @keyup.enter="sendMessage"
  105. />
  106. <svg-icon
  107. class="page-icon mr12 emoji-toggle"
  108. name="emoji"
  109. @click="toggleAppBox(1)"
  110. />
  111. <svg-icon
  112. class="page-icon tools-toggle"
  113. name="add2"
  114. @click="toggleAppBox(2)"
  115. />
  116. </div>
  117. <!-- 表情面板 -->
  118. <div
  119. class="app-box"
  120. v-show="showEmoji"
  121. :style="{ height: `${appBoxHeight}px` }"
  122. ref="emojiRef"
  123. >
  124. 😀 😃 😄 😁 😆 😅 😂 🤣 😊 😇 🙂 🙃 😉 😌 😍
  125. </div>
  126. <!-- 工具栏面板 -->
  127. <div
  128. class="app-box"
  129. v-show="showTools"
  130. :style="{ height: `${appBoxHeight}px` }"
  131. ref="toolsRef"
  132. >
  133. <div class="tool-btn">
  134. <van-uploader :after-read="afterRead">
  135. <svg-icon class="tool-icon" name="tp" />
  136. </van-uploader>
  137. <div>图片</div>
  138. </div>
  139. <div class="tool-btn">
  140. <svg-icon class="tool-icon" name="ps" />
  141. <div>拍摄</div>
  142. </div>
  143. <div class="tool-btn" @click="startAudioOnline">
  144. <svg-icon class="tool-icon" name="yyth" />
  145. <div>语音通话</div>
  146. </div>
  147. <div class="tool-btn">
  148. <svg-icon class="tool-icon" name="spth" />
  149. <div>视频通话</div>
  150. </div>
  151. <div class="tool-btn">
  152. <svg-icon class="tool-icon" name="mp" />
  153. <div>名片</div>
  154. </div>
  155. </div>
  156. </div>
  157. </div>
  158. </template>
  159. <script setup>
  160. import { ref, computed, onMounted, onUnmounted, onBeforeUnmount } from "vue";
  161. import { useRouter, useRoute } from "vue-router";
  162. import { useWebSocketStore } from "@/stores/modules/webSocketStore.js";
  163. import { useWalletStore } from "@/stores/modules/walletStore.js";
  164. import { Keyboard } from "@capacitor/keyboard";
  165. import { Capacitor } from "@capacitor/core";
  166. import { MSG_TYPE, MESSAGE_TYPE_USER } from "@/common/constant/msgType";
  167. import messageAudio from "@/views/im/components/messageAudio/index.vue";
  168. import {useWebRTCStore} from "@/stores/modules/webrtcStore";
  169. const IM_PATH = import.meta.env.VITE_IM_PATH_FIlE;
  170. // 路由 & store
  171. const router = useRouter();
  172. const route = useRoute();
  173. const wsStore = useWebSocketStore();
  174. const walletStore = useWalletStore();
  175. const webRTCStore = useWebRTCStore()
  176. // 输入框文本
  177. const text = ref("");
  178. // 状态管理
  179. const keyboardHeight = ref(0);
  180. const showEmoji = ref(false);
  181. const showTools = ref(false);
  182. const appBoxHeight = ref(210);
  183. const chatListRef = ref(null);
  184. const emojiRef = ref(null);
  185. const toolsRef = ref(null);
  186. const isSender = (toUsername) => {
  187. return walletStore.account === toUsername;
  188. };
  189. // 滚动到底部
  190. const scrollToBottom = () => {
  191. nextTick(() => {
  192. if (chatListRef.value) {
  193. const el = chatListRef.value;
  194. el.scrollTop = el.scrollHeight;
  195. }
  196. });
  197. };
  198. watch(
  199. () => wsStore.messages.length,
  200. () => {
  201. scrollToBottom();
  202. }
  203. );
  204. // 平台判断
  205. const isMobile = Capacitor.getPlatform() !== "web";
  206. // 语音
  207. const isTouchDevice = ref(false);
  208. const mediaRecorder = ref(null); // 录音对象
  209. const audioChunks = ref([]); // 录音数据
  210. // 计算当前底部总高度
  211. const currentBottomHeight = computed(() => {
  212. if (keyboardHeight.value > 0) return keyboardHeight.value;
  213. if (showEmoji.value || showTools.value) return appBoxHeight.value;
  214. return 0;
  215. });
  216. // 切换表情/工具面板
  217. const toggleAppBox = async (type) => {
  218. if (isMobile) await Keyboard.hide();
  219. keyboardHeight.value = 0;
  220. if (type === 1) {
  221. showEmoji.value = !showEmoji.value;
  222. showTools.value = false;
  223. } else {
  224. showTools.value = !showTools.value;
  225. showEmoji.value = false;
  226. }
  227. scrollToBottom();
  228. };
  229. const onFocus = () => {
  230. // 隐藏所有面板
  231. showEmoji.value = false;
  232. showTools.value = false;
  233. if (isMobile) setupKeyboardListeners();
  234. scrollToBottom();
  235. };
  236. // 键盘监听
  237. const setupKeyboardListeners = async () => {
  238. Keyboard.addListener("keyboardWillShow", (info) => {
  239. keyboardHeight.value = info.keyboardHeight;
  240. });
  241. Keyboard.addListener("keyboardWillHide", () => {
  242. keyboardHeight.value = 0;
  243. });
  244. };
  245. // 录音
  246. const startAudio = async (event) => {
  247. if (event.type === "touchstart") {
  248. isTouchDevice.value = true;
  249. }
  250. // 如果是触摸设备且事件是鼠标事件,则忽略
  251. if (isTouchDevice.value && event.type === "mousedown") {
  252. return;
  253. }
  254. try {
  255. // 请求麦克风权限
  256. const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
  257. // 创建 MediaRecorder 实例
  258. mediaRecorder.value = new MediaRecorder(stream, {
  259. mimeType: "audio/webm; codecs=opus",
  260. });
  261. // 收集音频数据
  262. mediaRecorder.value.ondataavailable = (e) => {
  263. audioChunks.value.push(e.data);
  264. };
  265. mediaRecorder.value.start(1000); // 每1秒收集一次数据
  266. console.log("Recording started");
  267. } catch (error) {
  268. console.error("Error accessing microphone:", error);
  269. }
  270. };
  271. // 停止录音
  272. const stopRecording = async () => {
  273. return new Promise(async (resolve) => {
  274. if (!mediaRecorder.value) {
  275. resolve(new Uint8Array());
  276. return;
  277. }
  278. // 停止录音
  279. mediaRecorder.value.stop();
  280. mediaRecorder.value.stream.getTracks().forEach((track) => track.stop());
  281. // 等待最后的数据可用
  282. mediaRecorder.value.onstop = async () => {
  283. // 合并所有音频片段
  284. const audioBlob = new Blob(audioChunks.value, { type: "audio/webm" });
  285. // 转换为 Uint8Array
  286. const arrayBuffer = await audioBlob.arrayBuffer();
  287. const audioData = new Uint8Array(arrayBuffer);
  288. resolve(audioData);
  289. };
  290. });
  291. };
  292. // 发送音频消息
  293. const sendAudioMessage = async (event) => {
  294. if (isTouchDevice.value && event.type === "mouseup") {
  295. return;
  296. }
  297. console.log("发送音频消息");
  298. try {
  299. // 1. 停止录音并获取音频数据
  300. const audioData = await stopRecording();
  301. // 2. 准备消息体
  302. const message = {
  303. content: text.value, // 如果有文本内容
  304. contentType: MSG_TYPE.AUDIO, // 音频消息类型
  305. messageType: MESSAGE_TYPE_USER, // 单聊消息
  306. to: route.query.uuid, // 接收方ID
  307. fileSuffix: "wav", // 使用webm后缀更准确
  308. file: audioData, // 将Uint8Array转为普通数组
  309. };
  310. // 3. 通过WebSocket发送
  311. wsStore.sendMessage(message);
  312. // 4. 重置状态
  313. mediaRecorder.value = null;
  314. audioChunks.value = [];
  315. } catch (error) {
  316. console.error("Error sending audio message:", error);
  317. }
  318. };
  319. // 发送消息
  320. const sendMessage = () => {
  321. if (!text.value.trim()) return;
  322. const message = {
  323. content: text.value,
  324. contentType: MSG_TYPE.TEXT, // 1: 文本消息
  325. messageType: MESSAGE_TYPE_USER, // 1: 单聊天
  326. to: route.query.uuid,
  327. };
  328. wsStore.sendMessage(message);
  329. text.value = "";
  330. scrollToBottom();
  331. };
  332. // 发送图片消息
  333. const afterRead = async (file) => {
  334. const arrayBuffer = await file.file.arrayBuffer();
  335. const message = {
  336. content: text.value, // 如果有文本内容
  337. contentType: MSG_TYPE.IMAGE, // 音频消息类型
  338. messageType: MESSAGE_TYPE_USER, // 单聊消息
  339. to: route.query.uuid, // 接收方ID
  340. fileSuffix: file.type, // 使用webm后缀更准确
  341. file: new Uint8Array(arrayBuffer), // 将Uint8Array转为普通数组
  342. };
  343. wsStore.sendMessage(message);
  344. };
  345. // 开启语音电话
  346. const startAudioOnline = () => {
  347. webRTCStore.initConnection(
  348. MESSAGE_TYPE_USER,
  349. {
  350. fromUsername: walletStore.username,
  351. from: walletStore.account,
  352. to: route.query.uuid,
  353. }
  354. )
  355. };
  356. // 时间格式化
  357. const formatTime = (timestamp) => {
  358. const date = new Date(timestamp);
  359. const h = date.getHours().toString().padStart(2, "0");
  360. const m = date.getMinutes().toString().padStart(2, "0");
  361. return `${h}:${m}`;
  362. };
  363. // 页面生命周期
  364. onMounted(() => {
  365. wsStore.getMessages({
  366. uuid: walletStore.account,
  367. messageType: 1,
  368. friendUsername: route.query.uuid,
  369. });
  370. scrollToBottom();
  371. document.addEventListener("click", handleClickOutside);
  372. });
  373. onUnmounted(() => {
  374. if (isMobile) Keyboard.removeAllListeners();
  375. });
  376. onBeforeUnmount(() => {
  377. document.removeEventListener("click", handleClickOutside);
  378. });
  379. // 判断是否点击在元素外
  380. const handleClickOutside = (event) => {
  381. const emojiEl = emojiRef.value;
  382. const toolsEl = toolsRef.value;
  383. const target = event.target;
  384. if (
  385. showEmoji.value &&
  386. emojiEl &&
  387. !emojiEl.contains(target) &&
  388. !target.closest(".emoji-toggle")
  389. ) {
  390. showEmoji.value = false;
  391. }
  392. if (
  393. showTools.value &&
  394. toolsEl &&
  395. !toolsEl.contains(target) &&
  396. !target.closest(".tools-toggle")
  397. ) {
  398. showTools.value = false;
  399. }
  400. };
  401. // 页面跳转
  402. const goBack = () => router.push("im");
  403. const goDetail = () => router.push("detail");
  404. </script>
  405. <style lang="less" scoped>
  406. .mr12 {
  407. margin-right: 12px;
  408. }
  409. .ml12 {
  410. margin-left: 12px;
  411. }
  412. .text-right {
  413. text-align: right;
  414. }
  415. .page-icon {
  416. width: 24px;
  417. height: 24px;
  418. flex-shrink: 0;
  419. }
  420. .container {
  421. display: flex;
  422. flex-direction: column;
  423. .chat-bg {
  424. height: 126px;
  425. background: linear-gradient(90deg, @theme-color1 0%, #40a4fb 100%);
  426. position: absolute;
  427. left: 0;
  428. right: 0;
  429. z-index: -1;
  430. }
  431. .header-chat {
  432. padding-top: 56px;
  433. margin: 0 16px;
  434. display: flex;
  435. align-items: center;
  436. color: @theme-color1;
  437. .header-title {
  438. flex: 1;
  439. font-family:
  440. PingFang SC,
  441. PingFang SC;
  442. font-weight: 500;
  443. font-size: 19px;
  444. color: #ffffff;
  445. text-align: center;
  446. }
  447. }
  448. .chat-list {
  449. background: #f7f8fa;
  450. border-radius: 30px 30px 0 0;
  451. flex: 1;
  452. overflow: auto;
  453. margin-top: 20px;
  454. padding: 0 16px 24px;
  455. .chat-time {
  456. font-family:
  457. PingFang SC,
  458. PingFang SC;
  459. font-weight: 400;
  460. font-size: 12px;
  461. color: #8d8d8d;
  462. text-align: center;
  463. margin: 20px 0;
  464. }
  465. .box {
  466. .list-item {
  467. display: flex;
  468. margin-bottom: 24px;
  469. .list-img {
  470. width: 44px;
  471. height: 44px;
  472. flex-shrink: 0;
  473. }
  474. .list-cont {
  475. font-family:
  476. PingFang SC,
  477. PingFang SC;
  478. font-weight: 400;
  479. font-size: 12px;
  480. color: #8d8d8d;
  481. max-width: 70%;
  482. display: flex;
  483. flex-direction: column;
  484. align-items: flex-start;
  485. .business-card {
  486. width: 199px;
  487. height: 93px;
  488. background: #ffffff;
  489. border-radius: 10px;
  490. margin-top: 8px;
  491. padding: 10px;
  492. box-sizing: border-box;
  493. .business-card-cont {
  494. display: flex;
  495. align-items: center;
  496. font-family:
  497. PingFang SC,
  498. PingFang SC;
  499. font-weight: 400;
  500. font-size: 15px;
  501. color: #000000;
  502. }
  503. .line {
  504. height: 1px;
  505. background: #f2f2f2;
  506. margin: 10px 0 6px;
  507. }
  508. .business-card-text {
  509. font-family:
  510. PingFang SC,
  511. PingFang SC;
  512. font-weight: 400;
  513. font-size: 10px;
  514. color: #8d8d8d;
  515. }
  516. }
  517. .content {
  518. background: #ffffff; // 对方消息背景白色
  519. color: #000;
  520. border-radius: 10px;
  521. margin-top: 8px;
  522. padding: 8px 17px;
  523. word-break: break-word;
  524. white-space: pre-wrap;
  525. max-width: 100%;
  526. font-family:
  527. PingFang SC,
  528. PingFang SC;
  529. font-weight: 400;
  530. font-size: 15px;
  531. }
  532. }
  533. }
  534. .withdrawal {
  535. display: flex;
  536. justify-content: center;
  537. margin-bottom: 24px;
  538. .withdrawal-text {
  539. width: 142px;
  540. height: 29px;
  541. line-height: 29px;
  542. box-sizing: border-box;
  543. background: #f2f2f2;
  544. border-radius: 4px;
  545. font-family:
  546. PingFang SC,
  547. PingFang SC;
  548. font-weight: 400;
  549. font-size: 12px;
  550. color: #8d8d8d;
  551. text-align: center;
  552. }
  553. }
  554. .flex-reverse {
  555. flex-direction: row-reverse;
  556. }
  557. .flex-reverse .list-cont {
  558. align-items: flex-end;
  559. .content {
  560. background: #4d71ff; // 自己的消息是蓝色
  561. color: #ffffff; // 白字
  562. }
  563. }
  564. }
  565. }
  566. .chat-list::-webkit-scrollbar {
  567. width: 0;
  568. }
  569. .page-foot {
  570. position: relative;
  571. background-color: #fff;
  572. .flex-box {
  573. padding: 8px 16px;
  574. display: flex;
  575. align-items: center;
  576. box-sizing: border-box;
  577. .input {
  578. flex: 1;
  579. background: #f2f2f2;
  580. border-radius: 17px;
  581. border: 1px solid #d8d8d8;
  582. padding: 6px 16px;
  583. font-weight: 500;
  584. font-size: 15px;
  585. margin: 0 12px;
  586. overflow-y: auto;
  587. }
  588. }
  589. }
  590. }
  591. .app-box {
  592. position: fixed;
  593. bottom: 210px;
  594. left: 0;
  595. right: 0;
  596. background: white;
  597. transition: transform 0.3s ease;
  598. transform: translateY(100%);
  599. display: flex;
  600. flex-wrap: wrap;
  601. padding: 10px 0 0 32px;
  602. &.visible {
  603. transform: translateY(0);
  604. }
  605. .tool-btn {
  606. margin-right: 32px;
  607. display: flex;
  608. flex-direction: column;
  609. align-items: center;
  610. font-family:
  611. PingFang SC,
  612. PingFang SC;
  613. font-weight: 400;
  614. font-size: 12px;
  615. color: #000000;
  616. .tool-icon {
  617. width: 56px;
  618. height: 56px;
  619. margin-bottom: 4px;
  620. }
  621. }
  622. }
  623. .page-foot {
  624. position: relative;
  625. z-index: 10; /* 确保输入框在上层 */
  626. }
  627. </style>