chat-box.vue 30 KB

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