chat-box.vue 30 KB

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