chat-box.vue 32 KB

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