chat-box.vue 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  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 + 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. sendMessageRequest(msgInfo) {
  733. return new Promise((resolve, reject) => {
  734. // 请求入队列,防止请求"后发先至",导致消息错序
  735. this.reqQueue.push({ msgInfo, resolve, reject });
  736. this.processReqQueue();
  737. })
  738. },
  739. processReqQueue() {
  740. if (this.reqQueue.length && !this.isSending) {
  741. this.isSending = true;
  742. const reqData = this.reqQueue.shift();
  743. this.$http({
  744. url: this.messageAction,
  745. method: 'post',
  746. data: reqData.msgInfo
  747. }).then((res) => {
  748. reqData.resolve(res)
  749. }).catch((e) => {
  750. reqData.reject(e)
  751. }).finally(() => {
  752. this.isSending = false;
  753. // 发送下一条请求
  754. this.processReqQueue();
  755. })
  756. }
  757. },
  758. reCalChatMainHeight() {
  759. setTimeout(() => {
  760. let h = this.windowHeight;
  761. // 减去标题栏高度
  762. h -= 50;
  763. // 减去键盘高度
  764. if (this.isShowKeyBoard || this.chatTabBox != 'none') {
  765. h -= this.keyboardHeight;
  766. this.scrollToBottom();
  767. }
  768. // #ifndef H5
  769. // h5需要减去状态栏高度
  770. h -= uni.getSystemInfoSync().statusBarHeight;
  771. // #endif
  772. this.chatMainHeight = h;
  773. if (this.isShowKeyBoard || this.chatTabBox != 'none') {
  774. this.scrollToBottom();
  775. }
  776. // ios浏览器键盘把页面顶起后,页面长度不会变化,这里把页面拉到顶部适配一下
  777. // #ifdef H5
  778. if (uni.getSystemInfoSync().platform == 'ios') {
  779. // 不同手机需要的延时时间不一致,采用分段延时的方式处理
  780. const delays = [50, 100, 500];
  781. delays.forEach((delay) => {
  782. setTimeout(() => {
  783. uni.pageScrollTo({
  784. scrollTop: 0,
  785. duration: 10
  786. });
  787. }, delay);
  788. })
  789. }
  790. // #endif
  791. }, 30)
  792. },
  793. listenKeyBoard() {
  794. // #ifdef H5
  795. if (navigator.platform == "Win32") {
  796. // 电脑端不需要弹出键盘
  797. console.log("navigator.platform:", navigator.platform)
  798. return;
  799. }
  800. if (uni.getSystemInfoSync().platform == 'ios') {
  801. // ios h5实现键盘监听
  802. window.addEventListener('focusin', this.focusInListener);
  803. window.addEventListener('focusout', this.focusOutListener);
  804. // 监听键盘高度,ios13以上开始支持
  805. if (window.visualViewport) {
  806. window.visualViewport.addEventListener('resize', this.resizeListener);
  807. }
  808. } else {
  809. // 安卓h5实现键盘监听
  810. window.addEventListener('resize', this.resizeListener);
  811. }
  812. // #endif
  813. // #ifndef H5
  814. // app实现键盘监听
  815. uni.onKeyboardHeightChange(this.keyBoardListener);
  816. // #endif
  817. },
  818. unListenKeyboard() {
  819. // #ifdef H5
  820. window.removeEventListener('resize', this.resizeListener);
  821. window.removeEventListener('focusin', this.focusInListener);
  822. window.removeEventListener('focusout', this.focusOutListener);
  823. // #endif
  824. // #ifndef H5
  825. uni.offKeyboardHeightChange(this.keyBoardListener);
  826. // #endif
  827. },
  828. keyBoardListener(res) {
  829. this.isShowKeyBoard = res.height > 0;
  830. if (this.isShowKeyBoard) {
  831. this.keyboardHeight = res.height; // 获取并保存键盘高度
  832. }
  833. this.reCalChatMainHeight();
  834. },
  835. resizeListener() {
  836. let keyboardHeight = this.initHeight - window.innerHeight;
  837. // 兼容部分ios浏览器
  838. if (window.visualViewport && uni.getSystemInfoSync().platform == 'ios') {
  839. keyboardHeight = this.initHeight - window.visualViewport.height;
  840. }
  841. console.log("resizeListener:", window.visualViewport.height)
  842. this.isShowKeyBoard = keyboardHeight > 150;
  843. if (this.isShowKeyBoard) {
  844. this.keyboardHeight = keyboardHeight;
  845. }
  846. this.reCalChatMainHeight();
  847. },
  848. focusInListener() {
  849. this.isShowKeyBoard = true;
  850. this.reCalChatMainHeight();
  851. },
  852. focusOutListener() {
  853. this.isShowKeyBoard = false;
  854. this.reCalChatMainHeight();
  855. },
  856. showBannedTip() {
  857. let msgInfo = {
  858. tmpId: this.generateId(),
  859. sendId: this.mine.id,
  860. sendTime: new Date().getTime(),
  861. type: this.$enums.MESSAGE_TYPE.TIP_TEXT
  862. }
  863. if (this.chat.type == "PRIVATE") {
  864. msgInfo.recvId = this.mine.id
  865. msgInfo.content = "该用户已被管理员封禁,原因:" + this.userInfo.reason
  866. } else {
  867. msgInfo.groupId = this.group.id;
  868. msgInfo.content = "本群聊已被管理员封禁,原因:" + this.group.reason
  869. }
  870. this.chatStore.insertMessage(msgInfo, this.chat);
  871. },
  872. generateId() {
  873. // 生成临时id
  874. return String(new Date().getTime()) + String(Math.floor(Math.random() * 1000));
  875. }
  876. },
  877. computed: {
  878. mine() {
  879. return this.userStore.userInfo;
  880. },
  881. friend() {
  882. return this.friendStore.findFriend(this.userInfo.id);
  883. },
  884. title() {
  885. if (!this.chat) {
  886. return "";
  887. }
  888. let title = this.chat.showName;
  889. if (this.chat.type == "GROUP") {
  890. let size = this.groupMembers.filter(m => !m.quit).length;
  891. title += `(${size})`;
  892. }
  893. return title;
  894. },
  895. messageAction() {
  896. return `/message/${this.chat.type.toLowerCase()}/send`;
  897. },
  898. messageSize() {
  899. if (!this.chat || !this.chat.messages) {
  900. return 0;
  901. }
  902. return this.chat.messages.length;
  903. },
  904. unreadCount() {
  905. if (!this.chat || !this.chat.unreadCount) {
  906. return 0;
  907. }
  908. return this.chat.unreadCount;
  909. },
  910. isBanned() {
  911. return (this.chat.type == "PRIVATE" && this.userInfo.isBanned) ||
  912. (this.chat.type == "GROUP" && this.group.isBanned)
  913. },
  914. atUserItems() {
  915. let atUsers = [];
  916. this.atUserIds.forEach((id) => {
  917. if (id == -1) {
  918. atUsers.push({
  919. id: -1,
  920. showNickName: "全体成员"
  921. })
  922. return;
  923. }
  924. let member = this.groupMembers.find((m) => m.userId == id);
  925. if (member) {
  926. atUsers.push(member);
  927. }
  928. })
  929. return atUsers;
  930. },
  931. memberSize() {
  932. return this.groupMembers.filter(m => !m.quit).length;
  933. }
  934. },
  935. watch: {
  936. messageSize: function(newSize, oldSize) {
  937. // 接收到新消息
  938. if (newSize > oldSize && oldSize > 0) {
  939. let lastMessage = this.chat.messages[newSize - 1];
  940. if (this.$msgType.isNormal(lastMessage.type)) {
  941. if (this.isInBottom) {
  942. // 收到消息,则滚动至底部
  943. this.scrollToBottom();
  944. } else {
  945. // 若滚动条不在底部,说明用户正在翻历史消息,此时滚动条不能动,同时增加新消息提示
  946. this.newMessageSize++;
  947. }
  948. }
  949. }
  950. },
  951. unreadCount: {
  952. handler(newCount, oldCount) {
  953. if (newCount > 0) {
  954. // 消息已读
  955. this.readedMessage()
  956. }
  957. }
  958. }
  959. },
  960. onLoad(options) {
  961. // 聊天数据
  962. this.chat = this.chatStore.chats[options.chatIdx];
  963. // 初始状态只显示20条消息
  964. let size = this.messageSize;
  965. this.showMinIdx = size > 20 ? size - 20 : 0;
  966. // 消息已读
  967. this.readedMessage()
  968. // 加载好友或群聊信息
  969. if (this.chat.type == "GROUP") {
  970. this.loadGroup(this.chat.targetId);
  971. } else {
  972. this.loadFriend(this.chat.targetId);
  973. this.loadReaded(this.chat.targetId)
  974. }
  975. // 激活当前会话
  976. this.chatStore.activeChat(options.chatIdx);
  977. // 复位回执消息
  978. this.isReceipt = false;
  979. // 清空底部标志
  980. this.isInBottom = true;
  981. this.newMessageSize = 0;
  982. // 监听键盘高度
  983. this.listenKeyBoard();
  984. // 计算聊天窗口高度
  985. this.$nextTick(() => {
  986. this.windowHeight = uni.getSystemInfoSync().windowHeight;
  987. this.reCalChatMainHeight();
  988. this.scrollToBottom();
  989. // #ifdef H5
  990. this.initHeight = window.innerHeight;
  991. // 兼容ios的h5:禁止页面滚动
  992. const chatBox = document.getElementById('chatBox')
  993. chatBox.addEventListener('touchmove', e => {
  994. e.preventDefault()
  995. }, { passive: false });
  996. // #endif
  997. });
  998. },
  999. onUnload() {
  1000. this.unListenKeyboard();
  1001. }
  1002. }
  1003. </script>
  1004. <style lang="scss">
  1005. .chat-box {
  1006. $icon-color: rgba(0, 0, 0, 0.88);
  1007. position: relative;
  1008. background-color: #fafafa;
  1009. .header {
  1010. display: flex;
  1011. justify-content: center;
  1012. align-items: center;
  1013. height: 60rpx;
  1014. padding: 5px;
  1015. background-color: #fafafa;
  1016. line-height: 50px;
  1017. font-size: $im-font-size-large;
  1018. box-shadow: $im-box-shadow-lighter;
  1019. z-index: 1;
  1020. .btn-side {
  1021. position: absolute;
  1022. line-height: 60rpx;
  1023. cursor: pointer;
  1024. &.right {
  1025. right: 30rpx;
  1026. }
  1027. }
  1028. }
  1029. .chat-main-box {
  1030. // #ifdef H5
  1031. top: $im-nav-bar-height;
  1032. // #endif
  1033. // #ifndef H5
  1034. top: calc($im-nav-bar-height + var(--status-bar-height));
  1035. // #endif
  1036. position: fixed;
  1037. width: 100%;
  1038. display: flex;
  1039. flex-direction: column;
  1040. z-index: 2;
  1041. .chat-message {
  1042. flex: 1;
  1043. padding: 0;
  1044. overflow: hidden;
  1045. position: relative;
  1046. background-color: white;
  1047. .scroll-box {
  1048. height: 100%;
  1049. }
  1050. .scroll-to-bottom {
  1051. position: absolute;
  1052. right: 30rpx;
  1053. bottom: 30rpx;
  1054. font-size: $im-font-size;
  1055. color: $im-color-primary;
  1056. font-weight: 600;
  1057. background: white;
  1058. padding: 10rpx 30rpx;
  1059. border-radius: 25rpx;
  1060. box-shadow: $im-box-shadow-dark;
  1061. }
  1062. }
  1063. .chat-at-bar {
  1064. display: flex;
  1065. align-items: center;
  1066. padding: 0 10rpx;
  1067. .icon-at {
  1068. font-size: $im-font-size-larger;
  1069. color: $im-color-primary;
  1070. font-weight: bold;
  1071. }
  1072. .chat-at-scroll-box {
  1073. flex: 1;
  1074. width: 80%;
  1075. .chat-at-items {
  1076. display: flex;
  1077. align-items: center;
  1078. height: 70rpx;
  1079. .chat-at-item {
  1080. padding: 0 3rpx;
  1081. }
  1082. }
  1083. }
  1084. }
  1085. .send-bar {
  1086. display: flex;
  1087. align-items: center;
  1088. padding: 10rpx;
  1089. border-top: $im-border solid 1px;
  1090. background-color: $im-bg;
  1091. min-height: 80rpx;
  1092. margin-bottom: 14rpx;
  1093. .iconfont {
  1094. font-size: 60rpx;
  1095. margin: 0 10rpx;
  1096. color: $icon-color;
  1097. }
  1098. .chat-record {
  1099. flex: 1;
  1100. }
  1101. .send-text {
  1102. flex: 1;
  1103. overflow: auto;
  1104. padding: 14rpx 20rpx;
  1105. background-color: #fff;
  1106. border-radius: 8rpx;
  1107. font-size: $im-font-size;
  1108. box-sizing: border-box;
  1109. margin: 0 10rpx;
  1110. position: relative;
  1111. .send-text-area {
  1112. width: 100%;
  1113. height: 100%;
  1114. min-height: 40rpx;
  1115. max-height: 200rpx;
  1116. font-size: 30rpx;
  1117. }
  1118. }
  1119. .btn-send {
  1120. margin: 5rpx;
  1121. }
  1122. }
  1123. }
  1124. .chat-tab-bar {
  1125. position: fixed;
  1126. bottom: 0;
  1127. background-color: $im-bg;
  1128. .chat-tools {
  1129. display: flex;
  1130. flex-wrap: wrap;
  1131. align-items: top;
  1132. height: 310px;
  1133. padding: 40rpx;
  1134. box-sizing: border-box;
  1135. .chat-tools-item {
  1136. width: 25%;
  1137. padding: 16rpx;
  1138. box-sizing: border-box;
  1139. display: flex;
  1140. flex-direction: column;
  1141. align-items: center;
  1142. .tool-icon {
  1143. padding: 26rpx;
  1144. font-size: 54rpx;
  1145. border-radius: 20%;
  1146. background-color: white;
  1147. color: $icon-color;
  1148. &:active {
  1149. background-color: $im-bg-active;
  1150. }
  1151. }
  1152. .tool-name {
  1153. height: 60rpx;
  1154. line-height: 60rpx;
  1155. font-size: 28rpx;
  1156. }
  1157. }
  1158. }
  1159. .chat-emotion {
  1160. height: 310px;
  1161. padding: 20rpx;
  1162. box-sizing: border-box;
  1163. .emotion-item-list {
  1164. display: flex;
  1165. flex-wrap: wrap;
  1166. justify-content: space-between;
  1167. align-content: center;
  1168. .emotion-item {
  1169. text-align: center;
  1170. cursor: pointer;
  1171. padding: 5px;
  1172. }
  1173. }
  1174. }
  1175. }
  1176. }
  1177. </style>