chat-box.vue 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  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)"
  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)
  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((m) => {
  519. m.selfSend = true;
  520. this.chatStore.recallMessage(m, this.chat);
  521. })
  522. }
  523. }
  524. })
  525. },
  526. onCopyMessage(msgInfo) {
  527. uni.setClipboardData({
  528. data: msgInfo.content,
  529. success: () => {
  530. uni.showToast({ title: '复制成功' });
  531. },
  532. fail: () => {
  533. uni.showToast({ title: '复制失败', icon: 'none' });
  534. }
  535. });
  536. },
  537. onDownloadFile(msgInfo) {
  538. let url = JSON.parse(msgInfo.content).url;
  539. uni.downloadFile({
  540. url: url,
  541. success(res) {
  542. if (res.statusCode === 200) {
  543. var filePath = encodeURI(res.tempFilePath);
  544. uni.openDocument({
  545. filePath: filePath,
  546. showMenu: true
  547. });
  548. }
  549. },
  550. fail(e) {
  551. uni.showToast({
  552. title: "文件下载失败",
  553. icon: "none"
  554. })
  555. }
  556. });
  557. },
  558. onScrollToTop() {
  559. if (this.showMinIdx == 0) {
  560. console.log("消息已滚动到顶部")
  561. return;
  562. }
  563. // #ifndef H5
  564. // 防止滚动条定格在顶部,不能一直往上滚
  565. this.scrollToMsgIdx(this.showMinIdx);
  566. // #endif
  567. // 多展示20条信息
  568. this.showMinIdx = this.showMinIdx > 20 ? this.showMinIdx - 20 : 0;
  569. },
  570. onShowMore() {
  571. if (this.chat.type == "GROUP") {
  572. uni.navigateTo({
  573. url: "/pages/group/group-info?id=" + this.group.id
  574. })
  575. } else {
  576. uni.navigateTo({
  577. url: "/pages/common/user-info?id=" + this.friend.id
  578. })
  579. }
  580. },
  581. onTextInput(e) {
  582. this.isEmpty = e.detail.html == '<p><br></p>'
  583. },
  584. onEditorReady() {
  585. this.$nextTick(() => {
  586. const query = uni.createSelectorQuery().in(this);
  587. query.select('#editor').context((res) => {
  588. this.editorCtx = res.context
  589. }).exec()
  590. })
  591. },
  592. onEditorFocus(e) {
  593. this.isFocus = true;
  594. this.scrollToBottom()
  595. this.switchChatTabBox('none')
  596. },
  597. onEditorBlur(e) {
  598. this.isFocus = false;
  599. },
  600. onAudioStateChange(state, msgInfo) {
  601. const playingAudio = this.$refs['message' + msgInfo.id][0]
  602. if (state == 'PLAYING' && playingAudio != this.playingAudio) {
  603. // 停止之前的录音
  604. this.playingAudio && this.playingAudio.stopPlayAudio();
  605. // 记录当前正在播放的消息
  606. this.playingAudio = playingAudio;
  607. }
  608. },
  609. loadReaded(fid) {
  610. this.$http({
  611. url: `/message/private/maxReadedId?friendId=${fid}`,
  612. method: 'get'
  613. }).then((id) => {
  614. this.chatStore.readedMessage({
  615. friendId: fid,
  616. maxId: id
  617. });
  618. });
  619. },
  620. readedMessage() {
  621. if (this.unreadCount == 0) {
  622. return;
  623. }
  624. let url = ""
  625. if (this.chat.type == "GROUP") {
  626. url = `/message/group/readed?groupId=${this.chat.targetId}`
  627. } else {
  628. url = `/message/private/readed?friendId=${this.chat.targetId}`
  629. }
  630. this.$http({
  631. url: url,
  632. method: 'PUT'
  633. }).then(() => {
  634. this.chatStore.resetUnreadCount(this.chat)
  635. this.scrollToBottom();
  636. })
  637. },
  638. loadGroup(groupId) {
  639. this.$http({
  640. url: `/group/find/${groupId}`,
  641. method: 'GET'
  642. }).then((group) => {
  643. this.group = group;
  644. this.chatStore.updateChatFromGroup(group);
  645. this.groupStore.updateGroup(group);
  646. });
  647. this.$http({
  648. url: `/group/members/${groupId}`,
  649. method: 'GET'
  650. }).then((groupMembers) => {
  651. this.groupMembers = groupMembers;
  652. });
  653. },
  654. loadFriend(friendId) {
  655. // 获取对方最新信息
  656. this.$http({
  657. url: `/user/find/${friendId}`,
  658. method: 'GET'
  659. }).then((friend) => {
  660. this.friend = friend;
  661. this.chatStore.updateChatFromFriend(friend);
  662. this.friendStore.updateFriend(friend);
  663. })
  664. },
  665. rpxTopx(rpx) {
  666. // rpx转换成px
  667. let info = uni.getSystemInfoSync()
  668. let px = info.windowWidth * rpx / 750;
  669. return Math.floor(rpx);
  670. },
  671. sendMessageRequest(msgInfo) {
  672. return new Promise((resolve, reject) => {
  673. // 请求入队列,防止请求"后发先至",导致消息错序
  674. this.reqQueue.push({ msgInfo, resolve, reject });
  675. this.processReqQueue();
  676. })
  677. },
  678. processReqQueue() {
  679. if (this.reqQueue.length && !this.isSending) {
  680. this.isSending = true;
  681. const reqData = this.reqQueue.shift();
  682. this.$http({
  683. url: this.messageAction,
  684. method: 'post',
  685. data: reqData.msgInfo
  686. }).then((res) => {
  687. reqData.resolve(res)
  688. }).catch((e) => {
  689. reqData.reject(e)
  690. }).finally(() => {
  691. this.isSending = false;
  692. // 发送下一条请求
  693. this.processReqQueue();
  694. })
  695. }
  696. },
  697. reCalChatMainHeight() {
  698. setTimeout(() => {
  699. let h = this.windowHeight;
  700. // 减去标题栏高度
  701. h -= 50;
  702. // 减去键盘高度
  703. if (this.isShowKeyBoard || this.chatTabBox != 'none') {
  704. console.log("减去键盘高度:", this.keyboardHeight)
  705. h -= this.keyboardHeight;
  706. this.scrollToBottom();
  707. }
  708. // #ifndef H5
  709. // h5需要减去状态栏高度
  710. h -= uni.getSystemInfoSync().statusBarHeight;
  711. // #endif
  712. this.chatMainHeight = h;
  713. console.log("窗口高度:", this.chatMainHeight)
  714. if (this.isShowKeyBoard || this.chatTabBox != 'none') {
  715. this.scrollToBottom();
  716. }
  717. // ios浏览器键盘把页面顶起后,页面长度不会变化,这里把页面拉到顶部适配一下
  718. // #ifdef H5
  719. if (uni.getSystemInfoSync().platform == 'ios') {
  720. // 不同手机需要的延时时间不一致,采用分段延时的方式处理
  721. const delays = [50, 100, 500];
  722. delays.forEach((delay) => {
  723. setTimeout(() => {
  724. uni.pageScrollTo({
  725. scrollTop: 0,
  726. duration: 10
  727. });
  728. }, delay);
  729. })
  730. }
  731. // #endif
  732. }, 30)
  733. },
  734. listenKeyBoard() {
  735. // #ifdef H5
  736. if (navigator.platform == "Win32" || navigator.platform == "MacIntel") {
  737. // 电脑端不需要弹出键盘
  738. console.log("navigator.platform:", navigator.platform)
  739. return;
  740. }
  741. if (uni.getSystemInfoSync().platform == 'ios') {
  742. // ios h5实现键盘监听
  743. window.addEventListener('focusin', this.focusInListener);
  744. window.addEventListener('focusout', this.focusOutListener);
  745. // 监听键盘高度,ios13以上开始支持
  746. if (window.visualViewport) {
  747. window.visualViewport.addEventListener('resize', this.resizeListener);
  748. }
  749. } else {
  750. // 安卓h5实现键盘监听
  751. window.addEventListener('resize', this.resizeListener);
  752. }
  753. // #endif
  754. // #ifndef H5
  755. // app实现键盘监听
  756. uni.onKeyboardHeightChange(this.keyBoardListener);
  757. // #endif
  758. },
  759. unListenKeyboard() {
  760. // #ifdef H5
  761. window.removeEventListener('resize', this.resizeListener);
  762. window.removeEventListener('focusin', this.focusInListener);
  763. window.removeEventListener('focusout', this.focusOutListener);
  764. // #endif
  765. // #ifndef H5
  766. uni.offKeyboardHeightChange(this.keyBoardListener);
  767. // #endif
  768. },
  769. keyBoardListener(res) {
  770. this.isShowKeyBoard = res.height > 0;
  771. if (this.isShowKeyBoard) {
  772. this.keyboardHeight = res.height; // 获取并保存键盘高度
  773. }
  774. this.reCalChatMainHeight();
  775. },
  776. resizeListener() {
  777. console.log("resize")
  778. let keyboardHeight = this.initHeight - window.innerHeight;
  779. this.isShowKeyBoard = keyboardHeight > 150;
  780. if (this.isShowKeyBoard) {
  781. this.keyboardHeight = keyboardHeight;
  782. }
  783. this.reCalChatMainHeight();
  784. },
  785. focusInListener() {
  786. console.log("focusInListener")
  787. this.isShowKeyBoard = true;
  788. this.reCalChatMainHeight();
  789. },
  790. focusOutListener() {
  791. console.log("focusOutListener")
  792. this.isShowKeyBoard = false;
  793. this.reCalChatMainHeight();
  794. },
  795. showBannedTip() {
  796. let msgInfo = {
  797. tmpId: this.generateId(),
  798. sendId: this.mine.id,
  799. sendTime: new Date().getTime(),
  800. type: this.$enums.MESSAGE_TYPE.TIP_TEXT
  801. }
  802. if (this.chat.type == "PRIVATE") {
  803. msgInfo.recvId = this.mine.id
  804. msgInfo.content = "该用户已被管理员封禁,原因:" + this.friend.reason
  805. } else {
  806. msgInfo.groupId = this.group.id;
  807. msgInfo.content = "本群聊已被管理员封禁,原因:" + this.group.reason
  808. }
  809. this.chatStore.insertMessage(msgInfo, this.chat);
  810. },
  811. generateId() {
  812. // 生成临时id
  813. return String(new Date().getTime()) + String(Math.floor(Math.random() * 1000));
  814. }
  815. },
  816. computed: {
  817. mine() {
  818. return this.userStore.userInfo;
  819. },
  820. title() {
  821. if (!this.chat) {
  822. return "";
  823. }
  824. let title = this.chat.showName;
  825. if (this.chat.type == "GROUP") {
  826. let size = this.groupMembers.filter(m => !m.quit).length;
  827. title += `(${size})`;
  828. }
  829. return title;
  830. },
  831. messageAction() {
  832. return `/message/${this.chat.type.toLowerCase()}/send`;
  833. },
  834. messageSize() {
  835. if (!this.chat || !this.chat.messages) {
  836. return 0;
  837. }
  838. return this.chat.messages.length;
  839. },
  840. unreadCount() {
  841. if (!this.chat || !this.chat.unreadCount) {
  842. return 0;
  843. }
  844. return this.chat.unreadCount;
  845. },
  846. isBanned() {
  847. return (this.chat.type == "PRIVATE" && this.friend.isBanned) ||
  848. (this.chat.type == "GROUP" && this.group.isBanned)
  849. },
  850. atUserItems() {
  851. let atUsers = [];
  852. this.atUserIds.forEach((id) => {
  853. if (id == -1) {
  854. atUsers.push({
  855. id: -1,
  856. showNickName: "全体成员"
  857. })
  858. return;
  859. }
  860. let member = this.groupMembers.find((m) => m.userId == id);
  861. if (member) {
  862. atUsers.push(member);
  863. }
  864. })
  865. return atUsers;
  866. }
  867. },
  868. watch: {
  869. messageSize: function(newSize, oldSize) {
  870. // 接收到消息时滚动到底部
  871. if (newSize > oldSize) {
  872. let pages = getCurrentPages();
  873. let curPage = pages[pages.length - 1].route;
  874. if (curPage == "pages/chat/chat-box") {
  875. this.scrollToBottom();
  876. } else {
  877. this.needScrollToBottom = true;
  878. }
  879. }
  880. },
  881. unreadCount: {
  882. handler(newCount, oldCount) {
  883. if (newCount > 0) {
  884. // 消息已读
  885. this.readedMessage()
  886. }
  887. }
  888. }
  889. },
  890. onLoad(options) {
  891. // 聊天数据
  892. this.chat = this.chatStore.chats[options.chatIdx];
  893. // 初始状态只显示20条消息
  894. let size = this.messageSize;
  895. this.showMinIdx = size > 20 ? size - 20 : 0;
  896. // 消息已读
  897. this.readedMessage()
  898. // 加载好友或群聊信息
  899. if (this.chat.type == "GROUP") {
  900. this.loadGroup(this.chat.targetId);
  901. } else {
  902. this.loadFriend(this.chat.targetId);
  903. this.loadReaded(this.chat.targetId)
  904. }
  905. // 激活当前会话
  906. this.chatStore.activeChat(options.chatIdx);
  907. // 复位回执消息
  908. this.isReceipt = false;
  909. // 监听键盘高度
  910. this.listenKeyBoard();
  911. // 计算聊天窗口高度
  912. this.$nextTick(() => {
  913. this.windowHeight = uni.getSystemInfoSync().windowHeight;
  914. this.reCalChatMainHeight()
  915. // 兼容ios h5:禁止页面滚动
  916. // #ifdef H5
  917. this.initHeight = window.innerHeight;
  918. document.body.addEventListener('touchmove', function(e) {
  919. e.preventDefault();
  920. }, { passive: false });
  921. // #endif
  922. });
  923. },
  924. onUnload() {
  925. this.unListenKeyboard();
  926. },
  927. onShow() {
  928. if (this.needScrollToBottom) {
  929. // 页面滚到底部
  930. this.scrollToBottom();
  931. this.needScrollToBottom = false;
  932. }
  933. }
  934. }
  935. </script>
  936. <style lang="scss">
  937. .chat-box {
  938. $icon-color: rgba(0, 0, 0, 0.88);
  939. position: relative;
  940. background-color: #fafafa;
  941. .header {
  942. display: flex;
  943. justify-content: center;
  944. align-items: center;
  945. height: 60rpx;
  946. padding: 5px;
  947. background-color: #fafafa;
  948. line-height: 50px;
  949. font-size: $im-font-size-large;
  950. box-shadow: $im-box-shadow-lighter;
  951. z-index: 1;
  952. .btn-side {
  953. position: absolute;
  954. line-height: 60rpx;
  955. cursor: pointer;
  956. &.right {
  957. right: 30rpx;
  958. }
  959. }
  960. }
  961. .chat-main-box {
  962. // #ifdef H5
  963. top: $im-nav-bar-height;
  964. // #endif
  965. // #ifndef H5
  966. top: calc($im-nav-bar-height + var(--status-bar-height));
  967. // #endif
  968. position: fixed;
  969. width: 100%;
  970. display: flex;
  971. flex-direction: column;
  972. z-index: 2;
  973. .chat-msg {
  974. flex: 1;
  975. padding: 0;
  976. overflow: hidden;
  977. position: relative;
  978. background-color: white;
  979. .scroll-box {
  980. height: 100%;
  981. }
  982. }
  983. .chat-at-bar {
  984. display: flex;
  985. align-items: center;
  986. padding: 0 10rpx;
  987. .icon-at {
  988. font-size: $im-font-size-larger;
  989. color: $im-color-primary;
  990. font-weight: bold;
  991. }
  992. .chat-at-scroll-box {
  993. flex: 1;
  994. width: 80%;
  995. .chat-at-items {
  996. display: flex;
  997. align-items: center;
  998. height: 70rpx;
  999. .chat-at-item {
  1000. padding: 0 3rpx;
  1001. }
  1002. }
  1003. }
  1004. }
  1005. .send-bar {
  1006. display: flex;
  1007. align-items: center;
  1008. padding: 10rpx;
  1009. border-top: $im-border solid 1px;
  1010. background-color: $im-bg;
  1011. min-height: 80rpx;
  1012. margin-bottom: 14rpx;
  1013. .iconfont {
  1014. font-size: 60rpx;
  1015. margin: 0 10rpx;
  1016. color: $icon-color;
  1017. }
  1018. .chat-record {
  1019. flex: 1;
  1020. }
  1021. .send-text {
  1022. flex: 1;
  1023. overflow: auto;
  1024. padding: 14rpx 20rpx;
  1025. background-color: #fff;
  1026. border-radius: 8rpx;
  1027. font-size: $im-font-size;
  1028. box-sizing: border-box;
  1029. margin: 0 10rpx;
  1030. position: relative;
  1031. .send-text-area {
  1032. width: 100%;
  1033. height: 100%;
  1034. min-height: 40rpx;
  1035. max-height: 200rpx;
  1036. font-size: 30rpx;
  1037. }
  1038. }
  1039. .btn-send {
  1040. margin: 5rpx;
  1041. }
  1042. }
  1043. }
  1044. .chat-tab-bar {
  1045. position: fixed;
  1046. bottom: 0;
  1047. background-color: $im-bg;
  1048. .chat-tools {
  1049. display: flex;
  1050. flex-wrap: wrap;
  1051. align-items: top;
  1052. height: 310px;
  1053. padding: 40rpx;
  1054. box-sizing: border-box;
  1055. .chat-tools-item {
  1056. width: 25%;
  1057. padding: 16rpx;
  1058. box-sizing: border-box;
  1059. display: flex;
  1060. flex-direction: column;
  1061. align-items: center;
  1062. .tool-icon {
  1063. padding: 26rpx;
  1064. font-size: 54rpx;
  1065. border-radius: 20%;
  1066. background-color: white;
  1067. color: $icon-color;
  1068. &:active {
  1069. background-color: $im-bg-active;
  1070. }
  1071. }
  1072. .tool-name {
  1073. height: 60rpx;
  1074. line-height: 60rpx;
  1075. font-size: 28rpx;
  1076. }
  1077. }
  1078. }
  1079. .chat-emotion {
  1080. height: 310px;
  1081. padding: 20rpx;
  1082. box-sizing: border-box;
  1083. .emotion-item-list {
  1084. display: flex;
  1085. flex-wrap: wrap;
  1086. justify-content: space-between;
  1087. align-content: center;
  1088. .emotion-item {
  1089. text-align: center;
  1090. cursor: pointer;
  1091. padding: 5px;
  1092. }
  1093. }
  1094. }
  1095. }
  1096. }
  1097. </style>