chat-box.vue 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  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. this.sendMessageRequest(msgInfo).then((m) => {
  310. m.selfSend = true;
  311. this.chatStore.insertMessage(m, this.chat);
  312. // 会话置顶
  313. this.moveChatToTop();
  314. }).finally(() => {
  315. // 滚动到底部
  316. this.scrollToBottom();
  317. });
  318. }
  319. })
  320. },
  321. createAtText() {
  322. let atText = "";
  323. this.atUserIds.forEach((id) => {
  324. if (id == -1) {
  325. atText += ` @全体成员`;
  326. } else {
  327. let member = this.groupMembers.find((m) => m.userId == id);
  328. if (member) {
  329. atText += ` @${member.showNickName}`;
  330. }
  331. }
  332. })
  333. return atText;
  334. },
  335. fillTargetId(msgInfo, targetId) {
  336. if (this.chat.type == "GROUP") {
  337. msgInfo.groupId = targetId;
  338. } else {
  339. msgInfo.recvId = targetId;
  340. }
  341. },
  342. scrollToBottom() {
  343. let size = this.messageSize;
  344. if (size > 0) {
  345. this.scrollToMsgIdx(size - 1);
  346. }
  347. },
  348. scrollToMsgIdx(idx) {
  349. // 如果scrollMsgIdx值没变化,滚动条不会移动
  350. if (idx == this.scrollMsgIdx && idx > 0) {
  351. this.$nextTick(() => {
  352. // 先滚动到上一条
  353. this.scrollMsgIdx = idx - 1;
  354. // 再滚动目标位置
  355. this.scrollToMsgIdx(idx);
  356. });
  357. return;
  358. }
  359. this.$nextTick(() => {
  360. this.scrollMsgIdx = idx;
  361. });
  362. },
  363. onShowEmoChatTab() {
  364. this.showRecord = false;
  365. this.switchChatTabBox('emo')
  366. },
  367. onShowToolsChatTab() {
  368. this.showRecord = false;
  369. this.switchChatTabBox('tools')
  370. },
  371. switchChatTabBox(chatTabBox) {
  372. this.chatTabBox = chatTabBox;
  373. this.reCalChatMainHeight();
  374. if (chatTabBox != 'tools' && this.$refs.fileUpload) {
  375. this.$refs.fileUpload.hide()
  376. }
  377. },
  378. selectEmoji(emoText) {
  379. let path = this.$emo.textToPath(emoText)
  380. // 先把键盘禁用了,否则会重新弹出键盘
  381. this.isReadOnly = true;
  382. this.isEmpty = false;
  383. this.$nextTick(() => {
  384. this.editorCtx.insertImage({
  385. src: path,
  386. alt: emoText,
  387. extClass: 'emoji-small',
  388. nowrap: true,
  389. complete: () => {
  390. this.isReadOnly = false;
  391. this.editorCtx.blur();
  392. }
  393. });
  394. })
  395. },
  396. onUploadImageBefore(file) {
  397. // 检查是否被封禁
  398. if (this.isBanned) {
  399. this.showBannedTip();
  400. return;
  401. }
  402. let data = {
  403. originUrl: file.path,
  404. thumbUrl: file.path
  405. }
  406. let msgInfo = {
  407. id: 0,
  408. tmpId: this.generateId(),
  409. fileId: file.uid,
  410. sendId: this.mine.id,
  411. content: JSON.stringify(data),
  412. sendTime: new Date().getTime(),
  413. selfSend: true,
  414. type: this.$enums.MESSAGE_TYPE.IMAGE,
  415. readedCount: 0,
  416. loadStatus: "loading",
  417. status: this.$enums.MESSAGE_STATUS.UNSEND
  418. }
  419. // 填充对方id
  420. this.fillTargetId(msgInfo, this.chat.targetId);
  421. // 插入消息
  422. this.chatStore.insertMessage(msgInfo, this.chat);
  423. // 会话置顶
  424. this.moveChatToTop();
  425. // 借助file对象保存
  426. file.msgInfo = msgInfo;
  427. file.chat = this.chat;
  428. // 滚到最低部
  429. this.scrollToBottom();
  430. return true;
  431. },
  432. onUploadImageSuccess(file, res) {
  433. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  434. msgInfo.content = JSON.stringify(res.data);
  435. msgInfo.receipt = this.isReceipt
  436. this.sendMessageRequest(msgInfo).then((m) => {
  437. msgInfo.loadStatus = 'ok';
  438. msgInfo.id = m.id;
  439. this.isReceipt = false;
  440. this.chatStore.insertMessage(msgInfo, file.chat);
  441. })
  442. },
  443. onUploadImageFail(file, err) {
  444. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  445. msgInfo.loadStatus = 'fail';
  446. this.chatStore.insertMessage(msgInfo, file.chat);
  447. },
  448. onUploadFileBefore(file) {
  449. // 检查是否被封禁
  450. if (this.isBanned) {
  451. this.showBannedTip();
  452. return;
  453. }
  454. let data = {
  455. name: file.name,
  456. size: file.size,
  457. url: file.path
  458. }
  459. let msgInfo = {
  460. id: 0,
  461. tmpId: this.generateId(),
  462. sendId: this.mine.id,
  463. content: JSON.stringify(data),
  464. sendTime: new Date().getTime(),
  465. selfSend: true,
  466. type: this.$enums.MESSAGE_TYPE.FILE,
  467. readedCount: 0,
  468. loadStatus: "loading",
  469. status: this.$enums.MESSAGE_STATUS.UNSEND
  470. }
  471. // 填充对方id
  472. this.fillTargetId(msgInfo, this.chat.targetId);
  473. // 插入消息
  474. this.chatStore.insertMessage(msgInfo, this.chat);
  475. // 会话置顶
  476. this.moveChatToTop();
  477. // 借助file对象保存
  478. file.msgInfo = msgInfo;
  479. file.chat = this.chat;
  480. // 滚到最低部
  481. this.scrollToBottom();
  482. return true;
  483. },
  484. onUploadFileSuccess(file, res) {
  485. let data = {
  486. name: file.name,
  487. size: file.size,
  488. url: res.data
  489. }
  490. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  491. msgInfo.content = JSON.stringify(data);
  492. msgInfo.receipt = this.isReceipt
  493. this.sendMessageRequest(msgInfo).then((m) => {
  494. msgInfo.loadStatus = 'ok';
  495. msgInfo.id = m.id;
  496. this.isReceipt = false;
  497. this.chatStore.insertMessage(msgInfo, file.chat);
  498. })
  499. },
  500. onUploadFileFail(file, res) {
  501. let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  502. msgInfo.loadStatus = 'fail';
  503. this.chatStore.insertMessage(msgInfo, file.chat);
  504. },
  505. onDeleteMessage(msgInfo) {
  506. uni.showModal({
  507. title: '删除消息',
  508. content: '确认删除消息?',
  509. success: (res) => {
  510. if (!res.cancel) {
  511. this.chatStore.deleteMessage(msgInfo, this.chat);
  512. uni.showToast({
  513. title: "删除成功",
  514. icon: "none"
  515. })
  516. }
  517. }
  518. })
  519. },
  520. onRecallMessage(msgInfo) {
  521. uni.showModal({
  522. title: '撤回消息',
  523. content: '确认撤回消息?',
  524. success: (res) => {
  525. if (!res.cancel) {
  526. let url = `/message/${this.chat.type.toLowerCase()}/recall/${msgInfo.id}`
  527. this.$http({
  528. url: url,
  529. method: 'DELETE'
  530. }).then((m) => {
  531. m.selfSend = true;
  532. this.chatStore.recallMessage(m, this.chat);
  533. })
  534. }
  535. }
  536. })
  537. },
  538. onCopyMessage(msgInfo) {
  539. uni.setClipboardData({
  540. data: msgInfo.content,
  541. success: () => {
  542. uni.showToast({ title: '复制成功' });
  543. },
  544. fail: () => {
  545. uni.showToast({ title: '复制失败', icon: 'none' });
  546. }
  547. });
  548. },
  549. onDownloadFile(msgInfo) {
  550. let url = JSON.parse(msgInfo.content).url;
  551. uni.downloadFile({
  552. url: url,
  553. success(res) {
  554. if (res.statusCode === 200) {
  555. var filePath = encodeURI(res.tempFilePath);
  556. uni.openDocument({
  557. filePath: filePath,
  558. showMenu: true
  559. });
  560. }
  561. },
  562. fail(e) {
  563. uni.showToast({
  564. title: "文件下载失败",
  565. icon: "none"
  566. })
  567. }
  568. });
  569. },
  570. onClickToBottom() {
  571. this.scrollToBottom();
  572. // 有些设备滚到底部时会莫名触发滚动到顶部的事件
  573. // 所以这里延迟100s保证能准确设置底部标志
  574. setTimeout(() => {
  575. this.isInBottom = true;
  576. this.newMessageSize = 0;
  577. }, 100)
  578. },
  579. onScroll(e) {
  580. // 记录当前滚动条高度
  581. this.scrollViewHeight = e.detail.scrollHeight;
  582. },
  583. onScrollToTop() {
  584. if (this.showMinIdx > 0) {
  585. // #ifndef H5
  586. // 防止滚动条定格在顶部,不能一直往上滚,app和小程序采用scroll-into-view定位
  587. this.scrollToMsgIdx(this.showMinIdx);
  588. // #endif
  589. // #ifdef H5
  590. // 防止滚动条定格在顶部,不能一直往上滚,h5采用scroll-top定位
  591. this.holdingScrollBar(this.scrollViewHeight);
  592. // #endif
  593. // 多展示20条信息
  594. this.showMinIdx = this.showMinIdx > 20 ? this.showMinIdx - 20 : 0;
  595. }
  596. // 清除底部标识
  597. this.isInBottom = false;
  598. },
  599. onScrollToBottom(e) {
  600. // 设置底部标识
  601. this.isInBottom = true;
  602. this.newMessageSize = 0;
  603. },
  604. holdingScrollBar(scrollViewHeight) {
  605. // 内容高度
  606. const query = uni.createSelectorQuery().in(this);
  607. setTimeout(() => {
  608. query.select('.chat-wrap').boundingClientRect();
  609. query.exec(data => {
  610. this.scrollTop = data[0].height - scrollViewHeight;
  611. if (this.scrollTop < 10) {
  612. // 未渲染完成,重试一次
  613. this.holdingScrollBar();
  614. }
  615. });
  616. }, 50)
  617. },
  618. onShowMore() {
  619. if (this.chat.type == "GROUP") {
  620. uni.navigateTo({
  621. url: "/pages/group/group-info?id=" + this.group.id
  622. })
  623. } else {
  624. uni.navigateTo({
  625. url: "/pages/common/user-info?id=" + this.userInfo.id
  626. })
  627. }
  628. },
  629. onTextInput(e) {
  630. this.isEmpty = e.detail.html == '<p><br></p>'
  631. },
  632. onEditorReady() {
  633. this.$nextTick(() => {
  634. const query = uni.createSelectorQuery().in(this);
  635. query.select('#editor').context((res) => {
  636. this.editorCtx = res.context
  637. }).exec()
  638. })
  639. },
  640. onEditorFocus(e) {
  641. this.isFocus = true;
  642. this.scrollToBottom()
  643. this.switchChatTabBox('none')
  644. },
  645. onEditorBlur(e) {
  646. this.isFocus = false;
  647. },
  648. onAudioStateChange(state, msgInfo) {
  649. const playingAudio = this.$refs['message' + msgInfo.id][0]
  650. if (state == 'PLAYING' && playingAudio != this.playingAudio) {
  651. // 停止之前的录音
  652. this.playingAudio && this.playingAudio.stopPlayAudio();
  653. // 记录当前正在播放的消息
  654. this.playingAudio = playingAudio;
  655. }
  656. },
  657. loadReaded(fid) {
  658. this.$http({
  659. url: `/message/private/maxReadedId?friendId=${fid}`,
  660. method: 'get'
  661. }).then((id) => {
  662. this.chatStore.readedMessage({
  663. friendId: fid,
  664. maxId: id
  665. });
  666. });
  667. },
  668. readedMessage() {
  669. if (this.unreadCount > 0) {
  670. let url = ""
  671. if (this.chat.type == "GROUP") {
  672. url = `/message/group/readed?groupId=${this.chat.targetId}`
  673. } else {
  674. url = `/message/private/readed?friendId=${this.chat.targetId}`
  675. }
  676. this.$http({
  677. url: url,
  678. method: 'PUT'
  679. }).then(() => {})
  680. }
  681. this.chatStore.resetUnreadCount(this.chat)
  682. },
  683. loadGroup(groupId) {
  684. this.$http({
  685. url: `/group/find/${groupId}`,
  686. method: 'GET'
  687. }).then((group) => {
  688. this.group = group;
  689. this.chatStore.updateChatFromGroup(group);
  690. this.groupStore.updateGroup(group);
  691. });
  692. this.$http({
  693. url: `/group/members/${groupId}`,
  694. method: 'GET'
  695. }).then((groupMembers) => {
  696. this.groupMembers = groupMembers;
  697. });
  698. },
  699. updateFriendInfo() {
  700. if (this.isFriend) {
  701. // store的数据不能直接修改,深拷贝一份store的数据
  702. let friend = JSON.parse(JSON.stringify(this.friend));
  703. friend.headImage = this.userInfo.headImageThumb;
  704. friend.nickName = this.userInfo.nickName;
  705. friend.showNickName = friend.remarkNickName ? friend.remarkNickName : friend.nickName;
  706. // 更新好友列表中的昵称和头像
  707. this.friendStore.updateFriend(friend);
  708. // 更新会话中的头像和昵称
  709. this.chatStore.updateChatFromFriend(friend);
  710. } else {
  711. this.chatStore.updateChatFromUser(this.userInfo);
  712. }
  713. },
  714. loadFriend(friendId) {
  715. // 获取好友用户信息
  716. this.$http({
  717. url: `/user/find/${friendId}`,
  718. method: 'GET'
  719. }).then((userInfo) => {
  720. this.userInfo = userInfo;
  721. this.updateFriendInfo();
  722. })
  723. },
  724. rpxTopx(rpx) {
  725. // rpx转换成px
  726. let info = uni.getSystemInfoSync()
  727. let px = info.windowWidth * rpx / 750;
  728. return Math.floor(rpx);
  729. },
  730. html2Escape(strHtml) {
  731. return strHtml.replace(/[<>&"]/g, function(c) {
  732. return {
  733. '<': '&lt;',
  734. '>': '&gt;',
  735. '&': '&amp;',
  736. '"': '&quot;'
  737. } [c];
  738. });
  739. },
  740. sendMessageRequest(msgInfo) {
  741. return new Promise((resolve, reject) => {
  742. // 请求入队列,防止请求"后发先至",导致消息错序
  743. this.reqQueue.push({ msgInfo, resolve, reject });
  744. this.processReqQueue();
  745. })
  746. },
  747. processReqQueue() {
  748. if (this.reqQueue.length && !this.isSending) {
  749. this.isSending = true;
  750. const reqData = this.reqQueue.shift();
  751. this.$http({
  752. url: this.messageAction,
  753. method: 'post',
  754. data: reqData.msgInfo
  755. }).then((res) => {
  756. reqData.resolve(res)
  757. }).catch((e) => {
  758. reqData.reject(e)
  759. }).finally(() => {
  760. this.isSending = false;
  761. // 发送下一条请求
  762. this.processReqQueue();
  763. })
  764. }
  765. },
  766. reCalChatMainHeight() {
  767. setTimeout(() => {
  768. let h = this.windowHeight;
  769. // 减去标题栏高度
  770. h -= 50;
  771. // 减去键盘高度
  772. if (this.isShowKeyBoard || this.chatTabBox != 'none') {
  773. h -= this.keyboardHeight;
  774. this.scrollToBottom();
  775. }
  776. // #ifndef H5
  777. // h5需要减去状态栏高度
  778. h -= uni.getSystemInfoSync().statusBarHeight;
  779. // #endif
  780. this.chatMainHeight = h;
  781. if (this.isShowKeyBoard || this.chatTabBox != 'none') {
  782. this.scrollToBottom();
  783. }
  784. // ios浏览器键盘把页面顶起后,页面长度不会变化,这里把页面拉到顶部适配一下
  785. // #ifdef H5
  786. if (uni.getSystemInfoSync().platform == 'ios') {
  787. // 不同手机需要的延时时间不一致,采用分段延时的方式处理
  788. const delays = [50, 100, 500];
  789. delays.forEach((delay) => {
  790. setTimeout(() => {
  791. uni.pageScrollTo({
  792. scrollTop: 0,
  793. duration: 10
  794. });
  795. }, delay);
  796. })
  797. }
  798. // #endif
  799. }, 30)
  800. },
  801. listenKeyBoard() {
  802. // #ifdef H5
  803. if (navigator.platform == "Win32") {
  804. // 电脑端不需要弹出键盘
  805. console.log("navigator.platform:", navigator.platform)
  806. return;
  807. }
  808. if (uni.getSystemInfoSync().platform == 'ios') {
  809. // ios h5实现键盘监听
  810. window.addEventListener('focusin', this.focusInListener);
  811. window.addEventListener('focusout', this.focusOutListener);
  812. // 监听键盘高度,ios13以上开始支持
  813. if (window.visualViewport) {
  814. window.visualViewport.addEventListener('resize', this.resizeListener);
  815. }
  816. } else {
  817. // 安卓h5实现键盘监听
  818. window.addEventListener('resize', this.resizeListener);
  819. }
  820. // #endif
  821. // #ifndef H5
  822. // app实现键盘监听
  823. uni.onKeyboardHeightChange(this.keyBoardListener);
  824. // #endif
  825. },
  826. unListenKeyboard() {
  827. // #ifdef H5
  828. window.removeEventListener('resize', this.resizeListener);
  829. window.removeEventListener('focusin', this.focusInListener);
  830. window.removeEventListener('focusout', this.focusOutListener);
  831. // #endif
  832. // #ifndef H5
  833. uni.offKeyboardHeightChange(this.keyBoardListener);
  834. // #endif
  835. },
  836. keyBoardListener(res) {
  837. this.isShowKeyBoard = res.height > 0;
  838. if (this.isShowKeyBoard) {
  839. this.keyboardHeight = res.height; // 获取并保存键盘高度
  840. }
  841. this.reCalChatMainHeight();
  842. },
  843. resizeListener() {
  844. let keyboardHeight = this.initHeight - window.innerHeight;
  845. // 兼容部分ios浏览器
  846. if (window.visualViewport && uni.getSystemInfoSync().platform == 'ios') {
  847. keyboardHeight = this.initHeight - window.visualViewport.height;
  848. }
  849. console.log("resizeListener:", window.visualViewport.height)
  850. this.isShowKeyBoard = keyboardHeight > 150;
  851. if (this.isShowKeyBoard) {
  852. this.keyboardHeight = keyboardHeight;
  853. }
  854. this.reCalChatMainHeight();
  855. },
  856. focusInListener() {
  857. this.isShowKeyBoard = true;
  858. this.reCalChatMainHeight();
  859. },
  860. focusOutListener() {
  861. this.isShowKeyBoard = false;
  862. this.reCalChatMainHeight();
  863. },
  864. showBannedTip() {
  865. let msgInfo = {
  866. tmpId: this.generateId(),
  867. sendId: this.mine.id,
  868. sendTime: new Date().getTime(),
  869. type: this.$enums.MESSAGE_TYPE.TIP_TEXT
  870. }
  871. if (this.chat.type == "PRIVATE") {
  872. msgInfo.recvId = this.mine.id
  873. msgInfo.content = "该用户已被管理员封禁,原因:" + this.userInfo.reason
  874. } else {
  875. msgInfo.groupId = this.group.id;
  876. msgInfo.content = "本群聊已被管理员封禁,原因:" + this.group.reason
  877. }
  878. this.chatStore.insertMessage(msgInfo, this.chat);
  879. },
  880. generateId() {
  881. // 生成临时id
  882. return String(new Date().getTime()) + String(Math.floor(Math.random() * 1000));
  883. }
  884. },
  885. computed: {
  886. mine() {
  887. return this.userStore.userInfo;
  888. },
  889. friend() {
  890. return this.friendStore.findFriend(this.userInfo.id);
  891. },
  892. title() {
  893. if (!this.chat) {
  894. return "";
  895. }
  896. let title = this.chat.showName;
  897. if (this.chat.type == "GROUP") {
  898. let size = this.groupMembers.filter(m => !m.quit).length;
  899. title += `(${size})`;
  900. }
  901. return title;
  902. },
  903. messageAction() {
  904. return `/message/${this.chat.type.toLowerCase()}/send`;
  905. },
  906. messageSize() {
  907. if (!this.chat || !this.chat.messages) {
  908. return 0;
  909. }
  910. return this.chat.messages.length;
  911. },
  912. unreadCount() {
  913. if (!this.chat || !this.chat.unreadCount) {
  914. return 0;
  915. }
  916. return this.chat.unreadCount;
  917. },
  918. isBanned() {
  919. return (this.chat.type == "PRIVATE" && this.userInfo.isBanned) ||
  920. (this.chat.type == "GROUP" && this.group.isBanned)
  921. },
  922. atUserItems() {
  923. let atUsers = [];
  924. this.atUserIds.forEach((id) => {
  925. if (id == -1) {
  926. atUsers.push({
  927. id: -1,
  928. showNickName: "全体成员"
  929. })
  930. return;
  931. }
  932. let member = this.groupMembers.find((m) => m.userId == id);
  933. if (member) {
  934. atUsers.push(member);
  935. }
  936. })
  937. return atUsers;
  938. },
  939. memberSize() {
  940. return this.groupMembers.filter(m => !m.quit).length;
  941. }
  942. },
  943. watch: {
  944. messageSize: function(newSize, oldSize) {
  945. // 接收到新消息
  946. if (newSize > oldSize && oldSize > 0) {
  947. let lastMessage = this.chat.messages[newSize - 1];
  948. if (this.$msgType.isNormal(lastMessage.type)) {
  949. if (this.isInBottom) {
  950. // 收到消息,则滚动至底部
  951. this.scrollToBottom();
  952. } else {
  953. // 若滚动条不在底部,说明用户正在翻历史消息,此时滚动条不能动,同时增加新消息提示
  954. this.newMessageSize++;
  955. }
  956. }
  957. }
  958. },
  959. unreadCount: {
  960. handler(newCount, oldCount) {
  961. if (newCount > 0) {
  962. // 消息已读
  963. this.readedMessage()
  964. }
  965. }
  966. }
  967. },
  968. onLoad(options) {
  969. // 聊天数据
  970. this.chat = this.chatStore.chats[options.chatIdx];
  971. // 初始状态只显示20条消息
  972. let size = this.messageSize;
  973. this.showMinIdx = size > 20 ? size - 20 : 0;
  974. // 消息已读
  975. this.readedMessage()
  976. // 加载好友或群聊信息
  977. if (this.chat.type == "GROUP") {
  978. this.loadGroup(this.chat.targetId);
  979. } else {
  980. this.loadFriend(this.chat.targetId);
  981. this.loadReaded(this.chat.targetId)
  982. }
  983. // 激活当前会话
  984. this.chatStore.activeChat(options.chatIdx);
  985. // 复位回执消息
  986. this.isReceipt = false;
  987. // 清空底部标志
  988. this.isInBottom = true;
  989. this.newMessageSize = 0;
  990. // 监听键盘高度
  991. this.listenKeyBoard();
  992. // 计算聊天窗口高度
  993. this.$nextTick(() => {
  994. this.windowHeight = uni.getSystemInfoSync().windowHeight;
  995. this.reCalChatMainHeight();
  996. this.scrollToBottom();
  997. // #ifdef H5
  998. this.initHeight = window.innerHeight;
  999. // 兼容ios的h5:禁止页面滚动
  1000. const chatBox = document.getElementById('chatBox')
  1001. chatBox.addEventListener('touchmove', e => {
  1002. e.preventDefault()
  1003. }, { passive: false });
  1004. // #endif
  1005. });
  1006. },
  1007. onUnload() {
  1008. this.unListenKeyboard();
  1009. }
  1010. }
  1011. </script>
  1012. <style lang="scss">
  1013. .chat-box {
  1014. $icon-color: rgba(0, 0, 0, 0.88);
  1015. position: relative;
  1016. background-color: #fafafa;
  1017. .header {
  1018. display: flex;
  1019. justify-content: center;
  1020. align-items: center;
  1021. height: 60rpx;
  1022. padding: 5px;
  1023. background-color: #fafafa;
  1024. line-height: 50px;
  1025. font-size: $im-font-size-large;
  1026. box-shadow: $im-box-shadow-lighter;
  1027. z-index: 1;
  1028. .btn-side {
  1029. position: absolute;
  1030. line-height: 60rpx;
  1031. cursor: pointer;
  1032. &.right {
  1033. right: 30rpx;
  1034. }
  1035. }
  1036. }
  1037. .chat-main-box {
  1038. // #ifdef H5
  1039. top: $im-nav-bar-height;
  1040. // #endif
  1041. // #ifndef H5
  1042. top: calc($im-nav-bar-height + var(--status-bar-height));
  1043. // #endif
  1044. position: fixed;
  1045. width: 100%;
  1046. display: flex;
  1047. flex-direction: column;
  1048. z-index: 2;
  1049. .chat-message {
  1050. flex: 1;
  1051. padding: 0;
  1052. overflow: hidden;
  1053. position: relative;
  1054. background-color: white;
  1055. .scroll-box {
  1056. height: 100%;
  1057. }
  1058. .scroll-to-bottom {
  1059. position: absolute;
  1060. right: 30rpx;
  1061. bottom: 30rpx;
  1062. font-size: $im-font-size;
  1063. color: $im-color-primary;
  1064. font-weight: 600;
  1065. background: white;
  1066. padding: 10rpx 30rpx;
  1067. border-radius: 25rpx;
  1068. box-shadow: $im-box-shadow-dark;
  1069. }
  1070. }
  1071. .chat-at-bar {
  1072. display: flex;
  1073. align-items: center;
  1074. padding: 0 10rpx;
  1075. .icon-at {
  1076. font-size: $im-font-size-larger;
  1077. color: $im-color-primary;
  1078. font-weight: bold;
  1079. }
  1080. .chat-at-scroll-box {
  1081. flex: 1;
  1082. width: 80%;
  1083. .chat-at-items {
  1084. display: flex;
  1085. align-items: center;
  1086. height: 70rpx;
  1087. .chat-at-item {
  1088. padding: 0 3rpx;
  1089. }
  1090. }
  1091. }
  1092. }
  1093. .send-bar {
  1094. display: flex;
  1095. align-items: center;
  1096. padding: 10rpx;
  1097. border-top: $im-border solid 1px;
  1098. background-color: $im-bg;
  1099. min-height: 80rpx;
  1100. margin-bottom: 14rpx;
  1101. .iconfont {
  1102. font-size: 60rpx;
  1103. margin: 0 10rpx;
  1104. color: $icon-color;
  1105. }
  1106. .chat-record {
  1107. flex: 1;
  1108. }
  1109. .send-text {
  1110. flex: 1;
  1111. overflow: auto;
  1112. padding: 14rpx 20rpx;
  1113. background-color: #fff;
  1114. border-radius: 8rpx;
  1115. font-size: $im-font-size;
  1116. box-sizing: border-box;
  1117. margin: 0 10rpx;
  1118. position: relative;
  1119. .send-text-area {
  1120. width: 100%;
  1121. height: 100%;
  1122. min-height: 40rpx;
  1123. max-height: 200rpx;
  1124. font-size: 30rpx;
  1125. }
  1126. }
  1127. .btn-send {
  1128. margin: 5rpx;
  1129. }
  1130. }
  1131. }
  1132. .chat-tab-bar {
  1133. position: fixed;
  1134. bottom: 0;
  1135. background-color: $im-bg;
  1136. .chat-tools {
  1137. display: flex;
  1138. flex-wrap: wrap;
  1139. align-items: top;
  1140. height: 310px;
  1141. padding: 40rpx;
  1142. box-sizing: border-box;
  1143. .chat-tools-item {
  1144. width: 25%;
  1145. padding: 16rpx;
  1146. box-sizing: border-box;
  1147. display: flex;
  1148. flex-direction: column;
  1149. align-items: center;
  1150. .tool-icon {
  1151. padding: 26rpx;
  1152. font-size: 54rpx;
  1153. border-radius: 20%;
  1154. background-color: white;
  1155. color: $icon-color;
  1156. &:active {
  1157. background-color: $im-bg-active;
  1158. }
  1159. }
  1160. .tool-name {
  1161. height: 60rpx;
  1162. line-height: 60rpx;
  1163. font-size: 28rpx;
  1164. }
  1165. }
  1166. }
  1167. .chat-emotion {
  1168. height: 310px;
  1169. padding: 20rpx;
  1170. box-sizing: border-box;
  1171. .emotion-item-list {
  1172. display: flex;
  1173. flex-wrap: wrap;
  1174. justify-content: space-between;
  1175. align-content: center;
  1176. .emotion-item {
  1177. text-align: center;
  1178. cursor: pointer;
  1179. padding: 5px;
  1180. }
  1181. }
  1182. }
  1183. }
  1184. }
  1185. </style>