chat-box.vue 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  1. <template>
  2. <view class="page chat-box" id="chatBox">
  3. <nav-bar back more @more="onShowMore">{{ title }}</nav-bar>
  4. <view class="chat-main-box" :style="{height: chatMainHeight+'px'}">
  5. <view class="chat-message" @click="switchChatTabBox('none')">
  6. <scroll-view class="scroll-box" scroll-y="true" upper-threshold="200" @scrolltoupper="onScrollToTop"
  7. @scroll="onScroll" :scroll-into-view="'chat-item-' + scrollMsgIdx" :scroll-top="scrollTop">
  8. <view v-if="chat" class="chat-wrap">
  9. <view v-for="(msgInfo, idx) in chat.messages" :key="idx">
  10. <chat-message-item :ref="'message'+msgInfo.id" v-if="idx >= showMinIdx"
  11. :headImage="headImage(msgInfo)" @call="onRtCall(msgInfo)" :showName="showName(msgInfo)"
  12. @recall="onRecallMessage" @delete="onDeleteMessage" @copy="onCopyMessage"
  13. @longPressHead="onLongPressHead(msgInfo)" @download="onDownloadFile"
  14. @audioStateChange="onAudioStateChange" :id="'chat-item-' + idx" :msgInfo="msgInfo"
  15. :groupMembers="groupMembers">
  16. </chat-message-item>
  17. </view>
  18. </view>
  19. </scroll-view>
  20. <view v-if="!isInBottom" class="scroll-to-bottom" @click="onClickToBottom">
  21. {{ newMessageSize > 0 ? newMessageSize+'条新消息' :'回到底部'}}
  22. </view>
  23. </view>
  24. <view v-if="atUserIds.length > 0" class="chat-at-bar" @click="openAtBox()">
  25. <view class="iconfont icon-at">&nbsp;</view>
  26. <scroll-view v-if="atUserIds.length > 0" class="chat-at-scroll-box" scroll-x="true" scroll-left="120">
  27. <view class="chat-at-items">
  28. <view v-for="m in atUserItems" class="chat-at-item" :key="m.userId">
  29. <head-image :name="m.showNickName" :url="m.headImage" size="minier"></head-image>
  30. </view>
  31. </view>
  32. </scroll-view>
  33. </view>
  34. <view class="send-bar">
  35. <view v-if="!showRecord" class="iconfont icon-voice-circle" @click="onRecorderInput()"></view>
  36. <view v-else class="iconfont icon-keyboard" @click="onKeyboardInput()"></view>
  37. <chat-record v-if="showRecord" class="chat-record" @send="onSendRecord"></chat-record>
  38. <view v-else class="send-text">
  39. <editor id="editor" class="send-text-area" :placeholder="isReceipt ? '[回执消息]' : ''"
  40. :read-only="isReadOnly" @focus="onEditorFocus" @blur="onEditorBlur" @ready="onEditorReady"
  41. @input="onTextInput">
  42. </editor>
  43. </view>
  44. <view v-if="chat && chat.type == 'GROUP'" class="iconfont icon-at" @click="openAtBox()"></view>
  45. <view class="iconfont icon-icon_emoji" @click="onShowEmoChatTab()"></view>
  46. <view v-if="isEmpty" class="iconfont icon-add" @click="onShowToolsChatTab()">
  47. </view>
  48. <button v-if="!isEmpty || atUserIds.length" class="btn-send" type="primary"
  49. @touchend.prevent="sendTextMessage()" size="mini">发送</button>
  50. </view>
  51. </view>
  52. <view class="chat-tab-bar">
  53. <view v-if="chatTabBox == 'tools'" class="chat-tools" :style="{height: keyboardHeight+'px'}">
  54. <view class="chat-tools-item">
  55. <file-upload ref="fileUpload" :onBefore="onUploadFileBefore" :onSuccess="onUploadFileSuccess"
  56. :onError="onUploadFileFail">
  57. <view class="tool-icon iconfont icon-folder"></view>
  58. </file-upload>
  59. <view class="tool-name">文件</view>
  60. </view>
  61. <view class="chat-tools-item">
  62. <image-upload :maxCount="9" sourceType="album" :onBefore="onUploadImageBefore"
  63. :onSuccess="onUploadImageSuccess" :onError="onUploadImageFail">
  64. <view class="tool-icon iconfont icon-picture"></view>
  65. </image-upload>
  66. <view class="tool-name">相册</view>
  67. </view>
  68. <view class="chat-tools-item">
  69. <image-upload sourceType="camera" :onBefore="onUploadImageBefore" :onSuccess="onUploadImageSuccess"
  70. :onError="onUploadImageFail">
  71. <view class="tool-icon iconfont icon-camera"></view>
  72. </image-upload>
  73. <view class="tool-name">拍摄</view>
  74. </view>
  75. <view class="chat-tools-item" @click="onRecorderInput()">
  76. <view class="tool-icon iconfont icon-microphone"></view>
  77. <view class="tool-name">语音消息</view>
  78. </view>
  79. <view v-if="chat.type == 'GROUP' && memberSize<=500" class="chat-tools-item" @click="switchReceipt()">
  80. <view class="tool-icon iconfont icon-receipt" :class="isReceipt ? 'active' : ''"></view>
  81. <view class="tool-name">回执消息</view>
  82. </view>
  83. <!-- #ifndef MP-WEIXIN -->
  84. <!-- 音视频不支持小程序 -->
  85. <view v-if="chat.type == 'PRIVATE'" class="chat-tools-item" @click="onPriviteVideo()">
  86. <view class="tool-icon iconfont icon-video"></view>
  87. <view class="tool-name">视频通话</view>
  88. </view>
  89. <view v-if="chat.type == 'PRIVATE'" class="chat-tools-item" @click="onPriviteVoice()">
  90. <view class="tool-icon iconfont icon-call"></view>
  91. <view class="tool-name">语音通话</view>
  92. </view>
  93. <view v-if="chat.type == 'GROUP'" class="chat-tools-item" @click="onGroupVideo()">
  94. <view class="tool-icon iconfont icon-call"></view>
  95. <view class="tool-name">语音通话</view>
  96. </view>
  97. <!-- #endif -->
  98. </view>
  99. <scroll-view v-if="chatTabBox === 'emo'" class="chat-emotion" scroll-y="true"
  100. :style="{height: keyboardHeight+'px'}">
  101. <view class="emotion-item-list">
  102. <image class="emotion-item emoji-large" :title="emoText" :src="$emo.textToPath(emoText)"
  103. v-for="(emoText, i) in $emo.emoTextList" :key="i" @click="selectEmoji(emoText)" mode="aspectFit"
  104. lazy-load="true"></image>
  105. </view>
  106. </scroll-view>
  107. </view>
  108. <!-- @用户时选择成员 -->
  109. <chat-at-box ref="atBox" :ownerId="group.ownerId" :members="groupMembers"
  110. @complete="onAtComplete"></chat-at-box>
  111. <!-- 群语音通话时选择成员 -->
  112. <!-- #ifndef MP-WEIXIN -->
  113. <group-member-selector ref="selBox" :members="groupMembers" :maxSize="configStore.webrtc.maxChannel"
  114. @complete="onInviteOk"></group-member-selector>
  115. <group-rtc-join ref="rtcJoin" :groupId="group.id"></group-rtc-join>
  116. <!-- #endif -->
  117. </view>
  118. </template>
  119. <script>
  120. import UNI_APP from '@/.env.js';
  121. export default {
  122. data() {
  123. return {
  124. chat: {},
  125. userInfo: {},
  126. group: {},
  127. groupMembers: [],
  128. isReceipt: false, // 是否回执消息
  129. scrollMsgIdx: 0, // 滚动条定位为到哪条消息
  130. chatTabBox: 'none',
  131. showRecord: false,
  132. chatMainHeight: 800, // 聊天窗口高度
  133. keyboardHeight: 290, // 键盘高度
  134. windowHeight: 1000, // 窗口高度
  135. initHeight: 1000, // h5初始高度
  136. atUserIds: [],
  137. showMinIdx: 0, // 下标小于showMinIdx的消息不显示,否则可能很卡
  138. reqQueue: [], // 请求队列
  139. isSending: false, // 是否正在发送请求
  140. isShowKeyBoard: false, // 键盘是否正在弹起
  141. editorCtx: null, // 编辑器上下文
  142. isEmpty: true, // 编辑器是否为空
  143. isFocus: false, // 编辑器是否焦点
  144. isReadOnly: false, // 编辑器是否只读
  145. playingAudio: null, // 当前正在播放的录音消息
  146. isInBottom: true, // 滚动条是否在底部
  147. newMessageSize: 0, // 滚动条不在底部时新的消息数量
  148. scrollTop: 0, // 用于ios h5定位滚动条
  149. scrollViewHeight: 0 // 滚动条总长度
  150. }
  151. },
  152. methods: {
  153. onRecorderInput() {
  154. this.showRecord = true;
  155. this.switchChatTabBox('none');
  156. },
  157. onKeyboardInput() {
  158. this.showRecord = false;
  159. this.switchChatTabBox('none');
  160. },
  161. onSendRecord(data) {
  162. // 检查是否被封禁
  163. if (this.isBanned) {
  164. this.showBannedTip();
  165. return;
  166. }
  167. let msgInfo = {
  168. content: JSON.stringify(data),
  169. type: this.$enums.MESSAGE_TYPE.AUDIO,
  170. receipt: this.isReceipt
  171. }
  172. // 填充对方id
  173. this.fillTargetId(msgInfo, this.chat.targetId);
  174. this.sendMessageRequest(msgInfo).then((m) => {
  175. m.selfSend = true;
  176. this.chatStore.insertMessage(m, this.chat);
  177. // 会话置顶
  178. this.moveChatToTop();
  179. // 滚动到底部
  180. this.scrollToBottom();
  181. this.isReceipt = false;
  182. })
  183. },
  184. onRtCall(msgInfo) {
  185. if (msgInfo.type == this.$enums.MESSAGE_TYPE.ACT_RT_VOICE) {
  186. this.onPriviteVoice();
  187. } else if (msgInfo.type == this.$enums.MESSAGE_TYPE.ACT_RT_VIDEO) {
  188. this.onPriviteVideo();
  189. }
  190. },
  191. onPriviteVideo() {
  192. const friendInfo = encodeURIComponent(JSON.stringify(this.friend));
  193. uni.navigateTo({
  194. url: `/pages/chat/chat-private-video?mode=video&friend=${friendInfo}&isHost=true`
  195. })
  196. },
  197. onPriviteVoice() {
  198. const friendInfo = encodeURIComponent(JSON.stringify(this.friend));
  199. uni.navigateTo({
  200. url: `/pages/chat/chat-private-video?mode=voice&friend=${friendInfo}&isHost=true`
  201. })
  202. },
  203. onGroupVideo() {
  204. // 邀请成员发起通话
  205. let ids = [this.mine.id];
  206. this.$refs.selBox.init(ids, ids, []);
  207. this.$refs.selBox.open();
  208. },
  209. onInviteOk(ids) {
  210. if (ids.length < 2) {
  211. return;
  212. }
  213. let users = [];
  214. ids.forEach(id => {
  215. let m = this.groupMembers.find(m => m.userId == id);
  216. // 只取部分字段,压缩url长度
  217. users.push({
  218. id: m.userId,
  219. nickName: m.showNickName,
  220. headImage: m.headImage,
  221. isCamera: false,
  222. isMicroPhone: true
  223. })
  224. })
  225. const groupId = this.group.id;
  226. const inviterId = this.mine.id;
  227. const userInfos = encodeURIComponent(JSON.stringify(users));
  228. uni.navigateTo({
  229. url: `/pages/chat/chat-group-video?groupId=${groupId}&isHost=true
  230. &inviterId=${inviterId}&userInfos=${userInfos}`
  231. })
  232. },
  233. moveChatToTop() {
  234. let chatIdx = this.chatStore.findChatIdx(this.chat);
  235. this.chatStore.moveTop(chatIdx);
  236. },
  237. switchReceipt() {
  238. this.isReceipt = !this.isReceipt;
  239. },
  240. openAtBox() {
  241. this.$refs.atBox.init(this.atUserIds);
  242. this.$refs.atBox.open();
  243. },
  244. onAtComplete(atUserIds) {
  245. this.atUserIds = atUserIds;
  246. },
  247. onLongPressHead(msgInfo) {
  248. if (!msgInfo.selfSend && this.chat.type == "GROUP" && this.atUserIds.indexOf(msgInfo.sendId) < 0) {
  249. this.atUserIds.push(msgInfo.sendId);
  250. }
  251. },
  252. headImage(msgInfo) {
  253. if (this.chat.type == 'GROUP') {
  254. let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
  255. return member ? member.headImage : "";
  256. } else {
  257. return msgInfo.selfSend ? this.mine.headImageThumb : this.chat.headImage
  258. }
  259. },
  260. showName(msgInfo) {
  261. if (this.chat.type == 'GROUP') {
  262. let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
  263. return member ? member.showNickName : "";
  264. } else {
  265. return msgInfo.selfSend ? this.mine.nickName : this.chat.showName
  266. }
  267. },
  268. sendTextMessage() {
  269. this.editorCtx.getContents({
  270. success: (e) => {
  271. // 清空编辑框数据
  272. this.editorCtx.clear();
  273. // 检查是否被封禁
  274. if (this.isBanned) {
  275. this.showBannedTip();
  276. return;
  277. }
  278. let sendText = "";
  279. e.delta.ops.forEach((op) => {
  280. if (op.insert.image) {
  281. // emo表情
  282. sendText += `#${op.attributes.alt};`
  283. } else(
  284. // 文字
  285. sendText += op.insert
  286. )
  287. })
  288. // 去除最后的换行符
  289. sendText = sendText.trim();
  290. if (!sendText && this.atUserIds.length == 0) {
  291. return uni.showToast({
  292. title: "不能发送空白信息",
  293. icon: "none"
  294. });
  295. }
  296. let receiptText = this.isReceipt ? "【回执消息】" : "";
  297. let atText = this.createAtText();
  298. let msgInfo = {
  299. content: receiptText + this.html2Escape(sendText) + atText,
  300. atUserIds: this.atUserIds,
  301. receipt: this.isReceipt,
  302. type: 0
  303. }
  304. // 清空@成员和回执标记
  305. this.atUserIds = [];
  306. this.isReceipt = false;
  307. // 填充对方id
  308. this.fillTargetId(msgInfo, this.chat.targetId);
  309. // 防止发送期间用户切换会话导致串扰
  310. const chat = this.chat;
  311. this.sendMessageRequest(msgInfo).then((m) => {
  312. m.selfSend = true;
  313. this.chatStore.insertMessage(m, chat);
  314. // 会话置顶
  315. this.moveChatToTop();
  316. }).finally(() => {
  317. // 滚动到底部
  318. this.scrollToBottom();
  319. });
  320. }
  321. })
  322. },
  323. createAtText() {
  324. let atText = "";
  325. this.atUserIds.forEach((id) => {
  326. if (id == -1) {
  327. atText += ` @全体成员`;
  328. } else {
  329. let member = this.groupMembers.find((m) => m.userId == id);
  330. if (member) {
  331. atText += ` @${member.showNickName}`;
  332. }
  333. }
  334. })
  335. return atText;
  336. },
  337. fillTargetId(msgInfo, targetId) {
  338. if (this.chat.type == "GROUP") {
  339. msgInfo.groupId = targetId;
  340. } else {
  341. msgInfo.recvId = targetId;
  342. }
  343. },
  344. scrollToBottom() {
  345. let size = this.messageSize;
  346. if (size > 0) {
  347. this.scrollToMsgIdx(size - 1);
  348. }
  349. },
  350. scrollToMsgIdx(idx) {
  351. // 如果scrollMsgIdx值没变化,滚动条不会移动
  352. if (idx == this.scrollMsgIdx && idx > 0) {
  353. this.$nextTick(() => {
  354. // 先滚动到上一条
  355. this.scrollMsgIdx = idx - 1;
  356. // 再滚动目标位置
  357. this.scrollToMsgIdx(idx);
  358. });
  359. return;
  360. }
  361. this.$nextTick(() => {
  362. this.scrollMsgIdx = idx;
  363. });
  364. },
  365. onShowEmoChatTab() {
  366. this.showRecord = false;
  367. this.switchChatTabBox('emo')
  368. },
  369. onShowToolsChatTab() {
  370. this.showRecord = false;
  371. this.switchChatTabBox('tools')
  372. },
  373. switchChatTabBox(chatTabBox) {
  374. this.chatTabBox = chatTabBox;
  375. this.reCalChatMainHeight();
  376. if (chatTabBox != 'tools' && this.$refs.fileUpload) {
  377. this.$refs.fileUpload.hide()
  378. }
  379. },
  380. selectEmoji(emoText) {
  381. let path = this.$emo.textToPath(emoText)
  382. // 先把键盘禁用了,否则会重新弹出键盘
  383. this.isReadOnly = true;
  384. this.isEmpty = false;
  385. this.$nextTick(() => {
  386. this.editorCtx.insertImage({
  387. src: path,
  388. alt: emoText,
  389. extClass: 'emoji-small',
  390. nowrap: true,
  391. complete: () => {
  392. this.isReadOnly = false;
  393. this.editorCtx.blur();
  394. }
  395. });
  396. })
  397. },
  398. onUploadImageBefore(file) {
  399. // 检查是否被封禁
  400. if (this.isBanned) {
  401. this.showBannedTip();
  402. return;
  403. }
  404. let data = {
  405. originUrl: file.path,
  406. thumbUrl: file.path
  407. }
  408. let msgInfo = {
  409. id: 0,
  410. tmpId: this.generateId(),
  411. fileId: file.uid,
  412. sendId: this.mine.id,
  413. content: JSON.stringify(data),
  414. sendTime: new Date().getTime(),
  415. selfSend: true,
  416. type: this.$enums.MESSAGE_TYPE.IMAGE,
  417. readedCount: 0,
  418. loadStatus: "loading",
  419. status: this.$enums.MESSAGE_STATUS.UNSEND
  420. }
  421. // 填充对方id
  422. this.fillTargetId(msgInfo, this.chat.targetId);
  423. // 插入消息
  424. this.chatStore.insertMessage(msgInfo, this.chat);
  425. // 会话置顶
  426. this.moveChatToTop();
  427. // 借助file对象保存
  428. file.msgInfo = msgInfo;
  429. file.chat = this.chat;
  430. // 滚到最低部
  431. this.scrollToBottom();
  432. return true;
  433. },
  434. onUploadImageSuccess(file, res) {
  435. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  436. msgInfo.content = JSON.stringify(res.data);
  437. msgInfo.receipt = this.isReceipt
  438. this.sendMessageRequest(msgInfo).then((m) => {
  439. msgInfo.loadStatus = 'ok';
  440. msgInfo.id = m.id;
  441. this.isReceipt = false;
  442. this.chatStore.insertMessage(msgInfo, file.chat);
  443. })
  444. },
  445. onUploadImageFail(file, err) {
  446. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  447. msgInfo.loadStatus = 'fail';
  448. this.chatStore.insertMessage(msgInfo, file.chat);
  449. },
  450. onUploadFileBefore(file) {
  451. // 检查是否被封禁
  452. if (this.isBanned) {
  453. this.showBannedTip();
  454. return;
  455. }
  456. let data = {
  457. name: file.name,
  458. size: file.size,
  459. url: file.path
  460. }
  461. let msgInfo = {
  462. id: 0,
  463. tmpId: this.generateId(),
  464. sendId: this.mine.id,
  465. content: JSON.stringify(data),
  466. sendTime: new Date().getTime(),
  467. selfSend: true,
  468. type: this.$enums.MESSAGE_TYPE.FILE,
  469. readedCount: 0,
  470. loadStatus: "loading",
  471. status: this.$enums.MESSAGE_STATUS.UNSEND
  472. }
  473. // 填充对方id
  474. this.fillTargetId(msgInfo, this.chat.targetId);
  475. // 插入消息
  476. this.chatStore.insertMessage(msgInfo, this.chat);
  477. // 会话置顶
  478. this.moveChatToTop();
  479. // 借助file对象保存
  480. file.msgInfo = msgInfo;
  481. file.chat = this.chat;
  482. // 滚到最低部
  483. this.scrollToBottom();
  484. return true;
  485. },
  486. onUploadFileSuccess(file, res) {
  487. let data = {
  488. name: file.name,
  489. size: file.size,
  490. url: res.data
  491. }
  492. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  493. msgInfo.content = JSON.stringify(data);
  494. msgInfo.receipt = this.isReceipt
  495. this.sendMessageRequest(msgInfo).then((m) => {
  496. msgInfo.loadStatus = 'ok';
  497. msgInfo.id = m.id;
  498. this.isReceipt = false;
  499. this.chatStore.insertMessage(msgInfo, file.chat);
  500. })
  501. },
  502. onUploadFileFail(file, res) {
  503. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  504. msgInfo.loadStatus = 'fail';
  505. this.chatStore.insertMessage(msgInfo, file.chat);
  506. },
  507. onDeleteMessage(msgInfo) {
  508. uni.showModal({
  509. title: '删除消息',
  510. content: '确认删除消息?',
  511. success: (res) => {
  512. if (!res.cancel) {
  513. this.chatStore.deleteMessage(msgInfo, this.chat);
  514. uni.showToast({
  515. title: "删除成功",
  516. icon: "none"
  517. })
  518. }
  519. }
  520. })
  521. },
  522. onRecallMessage(msgInfo) {
  523. uni.showModal({
  524. title: '撤回消息',
  525. content: '确认撤回消息?',
  526. success: (res) => {
  527. if (!res.cancel) {
  528. let url = `/message/${this.chat.type.toLowerCase()}/recall/${msgInfo.id}`
  529. this.$http({
  530. url: url,
  531. method: 'DELETE'
  532. }).then((m) => {
  533. m.selfSend = true;
  534. this.chatStore.recallMessage(m, this.chat);
  535. })
  536. }
  537. }
  538. })
  539. },
  540. onCopyMessage(msgInfo) {
  541. uni.setClipboardData({
  542. data: msgInfo.content,
  543. success: () => {
  544. uni.showToast({ title: '复制成功' });
  545. },
  546. fail: () => {
  547. uni.showToast({ title: '复制失败', icon: 'none' });
  548. }
  549. });
  550. },
  551. onDownloadFile(msgInfo) {
  552. let url = JSON.parse(msgInfo.content).url;
  553. uni.downloadFile({
  554. url: url,
  555. success(res) {
  556. if (res.statusCode === 200) {
  557. var filePath = encodeURI(res.tempFilePath);
  558. uni.openDocument({
  559. filePath: filePath,
  560. showMenu: true
  561. });
  562. }
  563. },
  564. fail(e) {
  565. uni.showToast({
  566. title: "文件下载失败",
  567. icon: "none"
  568. })
  569. }
  570. });
  571. },
  572. onClickToBottom() {
  573. this.scrollToBottom();
  574. // 有些设备滚到底部时会莫名触发滚动到顶部的事件
  575. // 所以这里延迟100s保证能准确设置底部标志
  576. setTimeout(() => {
  577. this.isInBottom = true;
  578. this.newMessageSize = 0;
  579. }, 100)
  580. },
  581. onScroll(e) {
  582. // 记录当前滚动条高度
  583. this.scrollViewHeight = e.detail.scrollHeight;
  584. },
  585. onScrollToTop() {
  586. if (this.showMinIdx > 0) {
  587. // #ifndef H5
  588. // 防止滚动条定格在顶部,不能一直往上滚,app和小程序采用scroll-into-view定位
  589. this.scrollToMsgIdx(this.showMinIdx);
  590. // #endif
  591. // #ifdef H5
  592. // 防止滚动条定格在顶部,不能一直往上滚,h5采用scroll-top定位
  593. this.holdingScrollBar(this.scrollViewHeight);
  594. // #endif
  595. // 多展示20条信息
  596. this.showMinIdx = this.showMinIdx > 20 ? this.showMinIdx - 20 : 0;
  597. }
  598. // 清除底部标识
  599. this.isInBottom = false;
  600. },
  601. onScrollToBottom(e) {
  602. // 设置底部标识
  603. this.isInBottom = true;
  604. this.newMessageSize = 0;
  605. },
  606. holdingScrollBar(scrollViewHeight) {
  607. // 内容高度
  608. const query = uni.createSelectorQuery().in(this);
  609. setTimeout(() => {
  610. query.select('.chat-wrap').boundingClientRect();
  611. query.exec(data => {
  612. this.scrollTop = data[0].height - scrollViewHeight;
  613. if (this.scrollTop < 10) {
  614. // 未渲染完成,重试一次
  615. this.holdingScrollBar();
  616. }
  617. });
  618. }, 50)
  619. },
  620. onShowMore() {
  621. if (this.chat.type == "GROUP") {
  622. uni.navigateTo({
  623. url: "/pages/group/group-info?id=" + this.group.id
  624. })
  625. } else {
  626. uni.navigateTo({
  627. url: "/pages/common/user-info?id=" + this.userInfo.id
  628. })
  629. }
  630. },
  631. onTextInput(e) {
  632. this.isEmpty = e.detail.html == '<p><br></p>'
  633. },
  634. onEditorReady() {
  635. this.$nextTick(() => {
  636. const query = uni.createSelectorQuery().in(this);
  637. query.select('#editor').context((res) => {
  638. this.editorCtx = res.context
  639. }).exec()
  640. })
  641. },
  642. onEditorFocus(e) {
  643. this.isFocus = true;
  644. this.scrollToBottom()
  645. this.switchChatTabBox('none')
  646. },
  647. onEditorBlur(e) {
  648. this.isFocus = false;
  649. },
  650. onAudioStateChange(state, msgInfo) {
  651. const playingAudio = this.$refs['message' + msgInfo.id][0]
  652. if (state == 'PLAYING' && playingAudio != this.playingAudio) {
  653. // 停止之前的录音
  654. this.playingAudio && this.playingAudio.stopPlayAudio();
  655. // 记录当前正在播放的消息
  656. this.playingAudio = playingAudio;
  657. }
  658. },
  659. loadReaded(fid) {
  660. this.$http({
  661. url: `/message/private/maxReadedId?friendId=${fid}`,
  662. method: 'get'
  663. }).then((id) => {
  664. this.chatStore.readedMessage({
  665. friendId: fid,
  666. maxId: id
  667. });
  668. });
  669. },
  670. readedMessage() {
  671. if (this.unreadCount > 0) {
  672. let url = ""
  673. if (this.chat.type == "GROUP") {
  674. url = `/message/group/readed?groupId=${this.chat.targetId}`
  675. } else {
  676. url = `/message/private/readed?friendId=${this.chat.targetId}`
  677. }
  678. this.$http({
  679. url: url,
  680. method: 'PUT'
  681. }).then(() => {})
  682. }
  683. this.chatStore.resetUnreadCount(this.chat)
  684. },
  685. loadGroup(groupId) {
  686. this.$http({
  687. url: `/group/find/${groupId}`,
  688. method: 'GET'
  689. }).then((group) => {
  690. this.group = group;
  691. this.chatStore.updateChatFromGroup(group);
  692. this.groupStore.updateGroup(group);
  693. });
  694. this.$http({
  695. url: `/group/members/${groupId}`,
  696. method: 'GET'
  697. }).then((groupMembers) => {
  698. this.groupMembers = groupMembers;
  699. });
  700. },
  701. updateFriendInfo() {
  702. if (this.isFriend) {
  703. // store的数据不能直接修改,深拷贝一份store的数据
  704. let friend = JSON.parse(JSON.stringify(this.friend));
  705. friend.headImage = this.userInfo.headImageThumb;
  706. friend.nickName = this.userInfo.nickName;
  707. friend.showNickName = friend.remarkNickName ? friend.remarkNickName : friend.nickName;
  708. // 更新好友列表中的昵称和头像
  709. this.friendStore.updateFriend(friend);
  710. // 更新会话中的头像和昵称
  711. this.chatStore.updateChatFromFriend(friend);
  712. } else {
  713. this.chatStore.updateChatFromUser(this.userInfo);
  714. }
  715. },
  716. loadFriend(friendId) {
  717. // 获取好友用户信息
  718. this.$http({
  719. url: `/user/find/${friendId}`,
  720. method: 'GET'
  721. }).then((userInfo) => {
  722. this.userInfo = userInfo;
  723. this.updateFriendInfo();
  724. })
  725. },
  726. rpxTopx(rpx) {
  727. // rpx转换成px
  728. let info = uni.getSystemInfoSync()
  729. let px = info.windowWidth * rpx / 750;
  730. return Math.floor(rpx);
  731. },
  732. html2Escape(strHtml) {
  733. return strHtml.replace(/[<>&"]/g, function(c) {
  734. return {
  735. '<': '&lt;',
  736. '>': '&gt;',
  737. '&': '&amp;',
  738. '"': '&quot;'
  739. } [c];
  740. });
  741. },
  742. sendMessageRequest(msgInfo) {
  743. return new Promise((resolve, reject) => {
  744. // 请求入队列,防止请求"后发先至",导致消息错序
  745. this.reqQueue.push({ msgInfo, resolve, reject });
  746. this.processReqQueue();
  747. })
  748. },
  749. processReqQueue() {
  750. if (this.reqQueue.length && !this.isSending) {
  751. this.isSending = true;
  752. const reqData = this.reqQueue.shift();
  753. this.$http({
  754. url: this.messageAction,
  755. method: 'post',
  756. data: reqData.msgInfo
  757. }).then((res) => {
  758. reqData.resolve(res)
  759. }).catch((e) => {
  760. reqData.reject(e)
  761. }).finally(() => {
  762. this.isSending = false;
  763. // 发送下一条请求
  764. this.processReqQueue();
  765. })
  766. }
  767. },
  768. reCalChatMainHeight() {
  769. setTimeout(() => {
  770. let h = this.windowHeight;
  771. // 减去标题栏高度
  772. h -= 50;
  773. // 减去键盘高度
  774. if (this.isShowKeyBoard || this.chatTabBox != 'none') {
  775. h -= this.keyboardHeight;
  776. this.scrollToBottom();
  777. }
  778. // #ifndef H5
  779. // h5需要减去状态栏高度
  780. h -= uni.getSystemInfoSync().statusBarHeight;
  781. // #endif
  782. this.chatMainHeight = h;
  783. if (this.isShowKeyBoard || this.chatTabBox != 'none') {
  784. this.scrollToBottom();
  785. }
  786. // ios浏览器键盘把页面顶起后,页面长度不会变化,这里把页面拉到顶部适配一下
  787. // #ifdef H5
  788. if (uni.getSystemInfoSync().platform == 'ios') {
  789. // 不同手机需要的延时时间不一致,采用分段延时的方式处理
  790. const delays = [50, 100, 500];
  791. delays.forEach((delay) => {
  792. setTimeout(() => {
  793. uni.pageScrollTo({
  794. scrollTop: 0,
  795. duration: 10
  796. });
  797. }, delay);
  798. })
  799. }
  800. // #endif
  801. }, 30)
  802. },
  803. listenKeyBoard() {
  804. // #ifdef H5
  805. if (navigator.platform == "Win32") {
  806. // 电脑端不需要弹出键盘
  807. console.log("navigator.platform:", navigator.platform)
  808. return;
  809. }
  810. if (uni.getSystemInfoSync().platform == 'ios') {
  811. // ios h5实现键盘监听
  812. window.addEventListener('focusin', this.focusInListener);
  813. window.addEventListener('focusout', this.focusOutListener);
  814. // 监听键盘高度,ios13以上开始支持
  815. if (window.visualViewport) {
  816. window.visualViewport.addEventListener('resize', this.resizeListener);
  817. }
  818. } else {
  819. // 安卓h5实现键盘监听
  820. window.addEventListener('resize', this.resizeListener);
  821. }
  822. // #endif
  823. // #ifndef H5
  824. // app实现键盘监听
  825. uni.onKeyboardHeightChange(this.keyBoardListener);
  826. // #endif
  827. },
  828. unListenKeyboard() {
  829. // #ifdef H5
  830. window.removeEventListener('resize', this.resizeListener);
  831. window.removeEventListener('focusin', this.focusInListener);
  832. window.removeEventListener('focusout', this.focusOutListener);
  833. // #endif
  834. // #ifndef H5
  835. uni.offKeyboardHeightChange(this.keyBoardListener);
  836. // #endif
  837. },
  838. keyBoardListener(res) {
  839. this.isShowKeyBoard = res.height > 0;
  840. if (this.isShowKeyBoard) {
  841. this.keyboardHeight = res.height; // 获取并保存键盘高度
  842. }
  843. this.reCalChatMainHeight();
  844. },
  845. resizeListener() {
  846. let keyboardHeight = this.initHeight - window.innerHeight;
  847. // 兼容部分ios浏览器
  848. if (window.visualViewport && uni.getSystemInfoSync().platform == 'ios') {
  849. keyboardHeight = this.initHeight - window.visualViewport.height;
  850. }
  851. console.log("resizeListener:", window.visualViewport.height)
  852. this.isShowKeyBoard = keyboardHeight > 150;
  853. if (this.isShowKeyBoard) {
  854. this.keyboardHeight = keyboardHeight;
  855. }
  856. this.reCalChatMainHeight();
  857. },
  858. focusInListener() {
  859. this.isShowKeyBoard = true;
  860. this.reCalChatMainHeight();
  861. },
  862. focusOutListener() {
  863. this.isShowKeyBoard = false;
  864. this.reCalChatMainHeight();
  865. },
  866. showBannedTip() {
  867. let msgInfo = {
  868. tmpId: this.generateId(),
  869. sendId: this.mine.id,
  870. sendTime: new Date().getTime(),
  871. type: this.$enums.MESSAGE_TYPE.TIP_TEXT
  872. }
  873. if (this.chat.type == "PRIVATE") {
  874. msgInfo.recvId = this.mine.id
  875. msgInfo.content = "该用户已被管理员封禁,原因:" + this.userInfo.reason
  876. } else {
  877. msgInfo.groupId = this.group.id;
  878. msgInfo.content = "本群聊已被管理员封禁,原因:" + this.group.reason
  879. }
  880. this.chatStore.insertMessage(msgInfo, this.chat);
  881. },
  882. generateId() {
  883. // 生成临时id
  884. return String(new Date().getTime()) + String(Math.floor(Math.random() * 1000));
  885. }
  886. },
  887. computed: {
  888. mine() {
  889. return this.userStore.userInfo;
  890. },
  891. friend() {
  892. return this.friendStore.findFriend(this.userInfo.id);
  893. },
  894. title() {
  895. if (!this.chat) {
  896. return "";
  897. }
  898. let title = this.chat.showName;
  899. if (this.chat.type == "GROUP") {
  900. let size = this.groupMembers.filter(m => !m.quit).length;
  901. title += `(${size})`;
  902. }
  903. return title;
  904. },
  905. messageAction() {
  906. return `/message/${this.chat.type.toLowerCase()}/send`;
  907. },
  908. messageSize() {
  909. if (!this.chat || !this.chat.messages) {
  910. return 0;
  911. }
  912. return this.chat.messages.length;
  913. },
  914. unreadCount() {
  915. if (!this.chat || !this.chat.unreadCount) {
  916. return 0;
  917. }
  918. return this.chat.unreadCount;
  919. },
  920. isBanned() {
  921. return (this.chat.type == "PRIVATE" && this.userInfo.isBanned) ||
  922. (this.chat.type == "GROUP" && this.group.isBanned)
  923. },
  924. atUserItems() {
  925. let atUsers = [];
  926. this.atUserIds.forEach((id) => {
  927. if (id == -1) {
  928. atUsers.push({
  929. id: -1,
  930. showNickName: "全体成员"
  931. })
  932. return;
  933. }
  934. let member = this.groupMembers.find((m) => m.userId == id);
  935. if (member) {
  936. atUsers.push(member);
  937. }
  938. })
  939. return atUsers;
  940. },
  941. memberSize() {
  942. return this.groupMembers.filter(m => !m.quit).length;
  943. }
  944. },
  945. watch: {
  946. messageSize: function(newSize, oldSize) {
  947. // 接收到新消息
  948. if (newSize > oldSize && oldSize > 0) {
  949. let lastMessage = this.chat.messages[newSize - 1];
  950. if (this.$msgType.isNormal(lastMessage.type)) {
  951. if (this.isInBottom) {
  952. // 收到消息,则滚动至底部
  953. this.scrollToBottom();
  954. } else {
  955. // 若滚动条不在底部,说明用户正在翻历史消息,此时滚动条不能动,同时增加新消息提示
  956. this.newMessageSize++;
  957. }
  958. }
  959. }
  960. },
  961. unreadCount: {
  962. handler(newCount, oldCount) {
  963. if (newCount > 0) {
  964. // 消息已读
  965. this.readedMessage()
  966. }
  967. }
  968. }
  969. },
  970. onLoad(options) {
  971. // 聊天数据
  972. this.chat = this.chatStore.chats[options.chatIdx];
  973. // 初始状态只显示20条消息
  974. let size = this.messageSize;
  975. this.showMinIdx = size > 20 ? size - 20 : 0;
  976. // 消息已读
  977. this.readedMessage()
  978. // 加载好友或群聊信息
  979. if (this.chat.type == "GROUP") {
  980. this.loadGroup(this.chat.targetId);
  981. } else {
  982. this.loadFriend(this.chat.targetId);
  983. this.loadReaded(this.chat.targetId)
  984. }
  985. // 激活当前会话
  986. this.chatStore.activeChat(options.chatIdx);
  987. // 复位回执消息
  988. this.isReceipt = false;
  989. // 清空底部标志
  990. this.isInBottom = true;
  991. this.newMessageSize = 0;
  992. // 监听键盘高度
  993. this.listenKeyBoard();
  994. // 计算聊天窗口高度
  995. this.$nextTick(() => {
  996. this.windowHeight = uni.getSystemInfoSync().windowHeight;
  997. this.reCalChatMainHeight();
  998. this.scrollToBottom();
  999. // #ifdef H5
  1000. this.initHeight = window.innerHeight;
  1001. // 兼容ios的h5:禁止页面滚动
  1002. const chatBox = document.getElementById('chatBox')
  1003. chatBox.addEventListener('touchmove', e => {
  1004. e.preventDefault()
  1005. }, { passive: false });
  1006. // #endif
  1007. });
  1008. },
  1009. onUnload() {
  1010. this.unListenKeyboard();
  1011. }
  1012. }
  1013. </script>
  1014. <style lang="scss">
  1015. .chat-box {
  1016. $icon-color: rgba(0, 0, 0, 0.88);
  1017. position: relative;
  1018. background-color: #fafafa;
  1019. .header {
  1020. display: flex;
  1021. justify-content: center;
  1022. align-items: center;
  1023. height: 60rpx;
  1024. padding: 5px;
  1025. background-color: #fafafa;
  1026. line-height: 50px;
  1027. font-size: $im-font-size-large;
  1028. box-shadow: $im-box-shadow-lighter;
  1029. z-index: 1;
  1030. .btn-side {
  1031. position: absolute;
  1032. line-height: 60rpx;
  1033. cursor: pointer;
  1034. &.right {
  1035. right: 30rpx;
  1036. }
  1037. }
  1038. }
  1039. .chat-main-box {
  1040. // #ifdef H5
  1041. top: $im-nav-bar-height;
  1042. // #endif
  1043. // #ifndef H5
  1044. top: calc($im-nav-bar-height + var(--status-bar-height));
  1045. // #endif
  1046. position: fixed;
  1047. width: 100%;
  1048. display: flex;
  1049. flex-direction: column;
  1050. z-index: 2;
  1051. .chat-message {
  1052. flex: 1;
  1053. padding: 0;
  1054. overflow: hidden;
  1055. position: relative;
  1056. background-color: white;
  1057. .scroll-box {
  1058. height: 100%;
  1059. }
  1060. .scroll-to-bottom {
  1061. position: absolute;
  1062. right: 30rpx;
  1063. bottom: 30rpx;
  1064. font-size: $im-font-size;
  1065. color: $im-color-primary;
  1066. font-weight: 600;
  1067. background: white;
  1068. padding: 10rpx 30rpx;
  1069. border-radius: 25rpx;
  1070. box-shadow: $im-box-shadow-dark;
  1071. }
  1072. }
  1073. .chat-at-bar {
  1074. display: flex;
  1075. align-items: center;
  1076. padding: 0 10rpx;
  1077. .icon-at {
  1078. font-size: $im-font-size-larger;
  1079. color: $im-color-primary;
  1080. font-weight: bold;
  1081. }
  1082. .chat-at-scroll-box {
  1083. flex: 1;
  1084. width: 80%;
  1085. .chat-at-items {
  1086. display: flex;
  1087. align-items: center;
  1088. height: 70rpx;
  1089. .chat-at-item {
  1090. padding: 0 3rpx;
  1091. }
  1092. }
  1093. }
  1094. }
  1095. .send-bar {
  1096. display: flex;
  1097. align-items: center;
  1098. padding: 10rpx;
  1099. border-top: $im-border solid 1px;
  1100. background-color: $im-bg;
  1101. min-height: 80rpx;
  1102. margin-bottom: 14rpx;
  1103. .iconfont {
  1104. font-size: 60rpx;
  1105. margin: 0 10rpx;
  1106. color: $icon-color;
  1107. }
  1108. .chat-record {
  1109. flex: 1;
  1110. }
  1111. .send-text {
  1112. flex: 1;
  1113. overflow: auto;
  1114. padding: 14rpx 20rpx;
  1115. background-color: #fff;
  1116. border-radius: 8rpx;
  1117. font-size: $im-font-size;
  1118. box-sizing: border-box;
  1119. margin: 0 10rpx;
  1120. position: relative;
  1121. .send-text-area {
  1122. width: 100%;
  1123. height: 100%;
  1124. min-height: 40rpx;
  1125. max-height: 200rpx;
  1126. font-size: 30rpx;
  1127. }
  1128. }
  1129. .btn-send {
  1130. margin: 5rpx;
  1131. }
  1132. }
  1133. }
  1134. .chat-tab-bar {
  1135. position: fixed;
  1136. bottom: 0;
  1137. background-color: $im-bg;
  1138. .chat-tools {
  1139. display: flex;
  1140. flex-wrap: wrap;
  1141. align-items: top;
  1142. height: 310px;
  1143. padding: 40rpx;
  1144. box-sizing: border-box;
  1145. .chat-tools-item {
  1146. width: 25%;
  1147. padding: 16rpx;
  1148. box-sizing: border-box;
  1149. display: flex;
  1150. flex-direction: column;
  1151. align-items: center;
  1152. .tool-icon {
  1153. padding: 26rpx;
  1154. font-size: 54rpx;
  1155. border-radius: 20%;
  1156. background-color: white;
  1157. color: $icon-color;
  1158. &:active {
  1159. background-color: $im-bg-active;
  1160. }
  1161. }
  1162. .tool-name {
  1163. height: 60rpx;
  1164. line-height: 60rpx;
  1165. font-size: 28rpx;
  1166. }
  1167. }
  1168. }
  1169. .chat-emotion {
  1170. height: 310px;
  1171. padding: 20rpx;
  1172. box-sizing: border-box;
  1173. .emotion-item-list {
  1174. display: flex;
  1175. flex-wrap: wrap;
  1176. justify-content: space-between;
  1177. align-content: center;
  1178. .emotion-item {
  1179. text-align: center;
  1180. cursor: pointer;
  1181. padding: 5px;
  1182. }
  1183. }
  1184. }
  1185. }
  1186. }
  1187. </style>