chat-box.vue 32 KB

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