uni-im-msg.vue 14.3 KB
Newer Older
DCloud_JSON's avatar
DCloud_JSON 已提交
1
<template>
2
  <view v-if="!msg.is_delete" class="uni-im-msg" :class="{self}">
DCloud_JSON's avatar
DCloud_JSON 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
    <msg-system v-if="msg.type === 'system'" class="system-msg-box" :msg="msg" />
    <template v-else>
      <view v-if="!noTime" class="friendlyTime">
        <text class="format-time-text" :class="{'dup-format-time-text':equalPrevTime}">
          {{ friendlyTime }}
        </text>
      </view>
      <view class="msg-box">
        <view v-if="msg.is_revoke" class="revoke-text-box">
          <text class="revoke-text">
            已被撤回
          </text>
          <text v-if="msg.before_revoke_body && ['text','rich-text'].includes(msg.type) " class="re-edit" @click="putChatInputContent">
            重新编辑
          </text>
        </view>
        <view v-else-if="msg.revoke_ing" class="revoke-text-box">
          <text class="revoke-text">
            消息撤回中...
          </text>
        </view>
        <template v-else>
          <cloud-image ref="avatar" width="40px" height="40px" border-radius="5px"
            :src="avatarUrl||'/uni_modules/uni-im/static/avatarUrl.png'" mode="widthFix"
            :class="{'pointer':canPrivateChat}"
28
            @click.stop="toChat" @longpress.stop="longpressMsgAvatar" />
DCloud_JSON's avatar
DCloud_JSON 已提交
29 30
          <view class="msg-main">
            <view v-if="!self" class="nickname-box">
31
              <text :selectable="true" class="nickname" @click="longpressMsgAvatar">{{ msg.nickname || users.nickname }}</text>
DCloud_JSON's avatar
DCloud_JSON 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
              <text class="isFromAdmin" v-if="isFromAdmin">管理员</text>
            </view>
            
            <view v-if="msg.about_msg_id" class="cite-box">
              <template v-if="aboutMsg.body">
                <text v-if="aboutMsg.is_revoke" class="cite-box-text">
                  回复的消息已被撤回
                </text>
                <text v-else class="cite-box-text" :class="{'pointer':!noJump}" @click="showAboutMsg">
                  {{ getNicknameByUid(aboutMsg.from_uid) }}{{ aboutMsg.body }}
                </text>
              </template>
              <text v-else class="cite-box-text">
                [加载中]
              </text>
            </view>
            <view class="msg-content-box" @longpress="showControl">
              <uni-icons v-if="self && msg.state != 100 && msgStateIcon" :color="msg.state===0?'#999':'#d22'"
                :type="msgStateIcon" class="msgStateIcon" @click="retriesSendMsg" />
              <component :is="'msg-'+msg.type" :class="'msg-'+msg.type" class="msg-content" ref="msg-content" :msg="msg"
                @viewMsg="$emit('viewMsg',$event)"
                cementing="MsgByType"
              ></component>
            </view>
          </view>
        </template>
      </view>
      <slot />
    </template>

    <template
      v-for="extra in extraComponents"
      :key="extra.component.name"
    >
      <component
        :is="extra.component"
        v-bind="extra.props"
        ref="extras"
        cementing="MsgExtra"
      />
    </template>
  </view>
</template>

<script>
  import {
    store as uniIdStore,
  } from '@/uni_modules/uni-id-pages/common/store'
  import uniIm from '@/uni_modules/uni-im/sdk/index.js';
  // 导入各类型的消息组件
  import msgSystem from './types/system.vue'
  import msgUserinfoCard from './types/userinfo-card.vue'
  import msgVideo from './types/video.vue'
  import msgFile from './types/file.vue'
  import msgHistory from './types/history.vue'
  import msgRichText from './types/rich-text.vue'
  import msgCode from './types/code.vue'
  import msgText from './types/text.vue'
  import msgSound from './types/sound.vue'
  import msgImage from './types/image.vue'

  import { markRaw } from 'vue'

/**
 * uni-im-msg 组件,渲染一条消息。
 * 
 * 支持多种消息类型:
 * 
 * - text
 * - rich-text
 * - code
 * - file
 * - image
 * - sound
 * - video
 * - userinfo-card
 * - history
 * 
 * @module
 */
  export default {
    components: {
      msgSystem,
      msgUserinfoCard,
      msgVideo,
      msgFile,
      msgHistory,
      msgRichText,
      msgCode,
      msgText,
      msgSound,
      msgImage
    },
    props: {
      msg: {
        type: Object,
        default () {
          return {
            body: ""
          }
        }
      },
      self: {
        type: Boolean,
        default () {
          return false
        }
      },
      avatar_file: {
        type: [Object, String, Boolean],
        default () {
          return {
            url: "/uni_modules/uni-im/static/avatarUrl.png"
          }
        }
      },
      index: {
        type: Number
      },
      equalPrevTime: {
        type: Boolean,
        default () {
          return false
        }
      },
      noTime: { // 不显示时间
        type: Boolean,
        default: false
      },
      noJump: { // 引用的消息不可点击跳转
        type: Boolean,
        default: false
      },
    },
166
    emits: ['viewMsg', 'showControl', 'showMsgById','loadMore','longpressMsgAvatar','putChatInputContent'],
DCloud_JSON's avatar
DCloud_JSON 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
    data() {
      let currentUser = {
        user_id: uniCloud.getCurrentUserInfo().uid,
        isInternalUser: this.uniIDHasRole('staff'),
      }
      // 调用扩展点,正在渲染一条消息,扩展程序可以返回扩展组件,为该消息增加一些显示元素。
      let extraComponents = uniIm.extensions.invokeExts('msg-extra', this.msg, currentUser)
        .filter(result => result && result.component)
        .map(result => {
          return {
            component: markRaw(result.component),
            props: result.props || {},
            handlers: result.handlers || {},
          }
        })

      return {
        nickname: "用户名",
        videoUrl: '',
        soundPlayState: 0,
        aboutMsg: {},
        extraComponents,
      };
    },
    computed: {
      currentConversation() {
193
        return uniIm.conversation.getCached(this.msg.conversation_id)
DCloud_JSON's avatar
DCloud_JSON 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
      },
      friendlyTime() {
        let time = this.msg.create_time || this.msg.client_create_time
        // 使得时间会随着心跳动态更新
        time = time + uniIm.heartbeat * 0
        return uniIm.utils.toFriendlyTime(time)
      },
      users() {
        return uniIm.users[this.msg.from_uid] || {}
      },
      msgStateIcon() {
        switch (this.msg.state) {
          case 0:
            // 发送中
            return 'spinner-cycle'
            break;
          case -100:
            // 发送失败
            return 'refresh-filled'
            break;
          case -200:
            // 禁止发送(内容不合法)
            return 'info-filled'
            break;
          default:
            return false
            break;
        }
      },
      isFromAdmin() {
DCloud_JSON's avatar
DCloud_JSON 已提交
224
        const conversation = uniIm.conversation.getCached(this.msg.conversation_id)
225
        return conversation?.group_id && conversation.group_member[this.msg.from_uid]?.role?.includes('admin')
DCloud_JSON's avatar
DCloud_JSON 已提交
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
      },
      mineId() {
        return uniCloud.getCurrentUserInfo().uid
      },
      avatarUrl() {
        if (this.self) {
          // console.error('uniIdStore.userInfo',uniIdStore.userInfo)
          return uniIdStore.userInfo.avatar_file?.url
        } else {
          return this.users.avatar_file?.url
        }
      },
      soundBoxWidth() {
        return uni.upx2px(750 / 60 * this.msg.body.time) + 50 + 'px'
      },
      canPrivateChat(){
242 243 244 245 246 247
        const conversation = uniIm.conversation.getCached(this.msg.conversation_id)
        const currentUserId = uniCloud.getCurrentUserInfo().uid;
        // 当前登录的账号是管理员,或者是群管理员,或者当前消息是群管理员发的
        return this.uniIDHasRole('staff') || 
               conversation.group_member?.[currentUserId]?.role?.includes('admin') || 
               this.isFromAdmin
DCloud_JSON's avatar
DCloud_JSON 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
      }
    },
    async mounted() {
      this.initAboutMsg()

      // #ifdef H5
      // web端限制不选中文字时出现系统右键菜单
      let msgContent = this.$refs['msg-content']
      if (msgContent && uniIm.isWidescreen) {
        msgContent.$el.addEventListener('contextmenu', (e) => {
          if (!document.getSelection().toString()) {
            this.showControl(e)
            e.preventDefault()
          }
        })
      }
      let avatarRef = this.$refs['avatar']
      if (avatarRef) {
        avatarRef.$el.addEventListener('contextmenu', (e) => {
          if (uniIm.isWidescreen) {
268
            this.longpressMsgAvatar()
DCloud_JSON's avatar
DCloud_JSON 已提交
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
          }
          e.preventDefault()
        })
      }
      // #endif
    },
    methods: {
      getNicknameByUid(uid) {
        let users = uniIm.users[uid]
        if (users) {
          return users.nickname
        } else {
          return ''
        }
      },
      showAboutMsg() {
        this.$emit('showMsgById', this.aboutMsg._id)
      },
      onAppear() {
        // console.log('msg ----msgAppear msg.body',this.msg.body)
        let index = this.currentConversation.call_list.findIndex(i => i == this.msg._id)
        if (index != -1) {
          console.log('已读,移除call_list对应数据')
          this.currentConversation.call_list.splice(index, 1)
        }
      },
      onDisappear() {},
      async showControl(e) {
        let msgContentDomInfo;
        const query = uni.createSelectorQuery().in(this);
        await new Promise(callback => {
          query.selectAll('.msg-content-box .msg-content').boundingClientRect(data => {
            msgContentDomInfo = data[0]
            // console.log('msgContentDomInfo data--------', data);
            callback(msgContentDomInfo)
          }).exec();
        })

        this.$emit('showControl', {
          msgId: this.msg._id,
          msgContentDomInfo,
          // #ifdef H5
          coordinate: {
            left: e.x,
            top: e.y
          }
          // #endif
        })
      },
      retriesSendMsg() {
        // if (this.msg.state == -200) {
        //   return uni.showToast({
        //     title: '内容不合法',
        //     icon: 'error'
        //   });
        // }
        this.$emit('retriesSendMsg', this.msg)
      },
      toChat() {
        if (this.canPrivateChat) {
329 330 331 332 333 334 335
          uniIm.toChat({
            user_id: this.msg.from_uid,
            source: {
              group_id: this.msg.group_id
            }
          })
        }
DCloud_JSON's avatar
DCloud_JSON 已提交
336
      },
337
      longpressMsgAvatar() {
DCloud_JSON's avatar
DCloud_JSON 已提交
338 339
        if (this.msg.group_id) {
          // console.log('~~~~this.msg.from_uid', this.msg.from_uid)
340
          this.$emit('longpressMsgAvatar', this.msg.from_uid)
DCloud_JSON's avatar
DCloud_JSON 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
        }
      },
      async initAboutMsg() {
        // 处理引用消息
        const {
          about_msg_id
        } = this.msg
        if (about_msg_id) {
          const _aboutMsg = this.currentConversation.msgList.find(i => i._id == about_msg_id) || false
          let aboutMsg = JSON.parse(JSON.stringify(_aboutMsg))
          // 本地不存在联网查找
          if (!aboutMsg) {
            const db = uniCloud.database();
            let {
              conversation_id,
              "about_msg_id": _id
            } = this.msg;
            let res = await db.collection('uni-im-msg')
              .where({
                conversation_id,
                _id
              })
              .limit(1)
              .get()
            aboutMsg = res.result.data[0]
            if (aboutMsg) {
              aboutMsg.isCloudMsg = true
            } else {
              console.error('疑似脏数据,云端也没有查到');
              delete this.msg.about_msg_id
              return
            }
          }
          aboutMsg.body = uniIm.utils.getMsgNote(aboutMsg)
          this.aboutMsg = aboutMsg
        }
      },
      putChatInputContent() {
        this.$emit('putChatInputContent', JSON.parse(JSON.stringify(this.msg.before_revoke_body)))
      }
    }
  }
</script>
384 385 386 387 388 389 390 391 392 393
<style lang="scss">
.uni-im-msg {
  position: relative;
  flex: 1;
  /* #ifdef H5 */
  width: 100%;
  /* #endif */
  /* #ifdef MP */
  width: 750rpx;
  /* #endif */
DCloud_JSON's avatar
DCloud_JSON 已提交
394 395 396 397 398 399
  .msg-box {
    flex-direction: row;
    justify-content: flex-start;
    padding: 0 8px;
    margin: 8px 0;
    position: relative;
400
    width: 100%;
DCloud_JSON's avatar
DCloud_JSON 已提交
401
  }
402
  
DCloud_JSON's avatar
DCloud_JSON 已提交
403 404 405 406 407 408 409 410 411 412 413 414
  /* #ifdef H5 */
  .msg-box,
  .msg-box * {
    cursor: default;
  }
  .file-msg-box,
  .cloud-image {
    cursor: pointer;
  }
  /* #endif */
  
  .msg-main {
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
    width: 80%;
    margin: 0 8px;
    // overflow: hidden;
  }
  /* 回复引用某条消息提示框 */
  .cite-box {
    margin:8px 0;
    margin-right: auto;
    background-color: #e3e3e3;
    color: #6a6a6a;
    border-radius: 5px;
    max-width: 100%;
    justify-content: center;
    padding: 5px 10px;
  }
  .self .cite-box {
    margin-right: 0;
    margin-left: auto;
  }
  
  .cite-box-text {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 14px;
DCloud_JSON's avatar
DCloud_JSON 已提交
440
  }
441
  
DCloud_JSON's avatar
DCloud_JSON 已提交
442 443 444
  .self .msg-main {
    align-items: flex-end;
  }
445
  
DCloud_JSON's avatar
DCloud_JSON 已提交
446 447 448 449 450 451 452 453 454 455 456 457 458
  .msg-content-box {
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
  }
  .self .msg-content-box {
    justify-content: flex-end;
  }
  
  .nickname-box {
    flex-direction: row;
    align-items: center;
  }
459
  
DCloud_JSON's avatar
DCloud_JSON 已提交
460 461 462
  .nickname {
    font-size: 13px;
    color: #666666;
DCloud_JSON's avatar
DCloud_JSON 已提交
463
    padding-left: 2px;
DCloud_JSON's avatar
DCloud_JSON 已提交
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
  }
  
  /* #ifdef H5 */
  .nickname-box .nickname:hover {
    color: #0b65ff;
    cursor: pointer;
  }
  .nickname-box .nickname:hover::after {
    content: '@';
    margin-left: 3px;
  }
  /* #endif */
  
  .isFromAdmin {
    font-size: 14px;
    color: #FFFFFF;
    background-color: #1ab94d;
    padding: 2px 3px;
    border-radius: 2px;
    transform: scale(0.7);
484
    margin-left: -4px;
DCloud_JSON's avatar
DCloud_JSON 已提交
485 486 487 488 489 490
  }
  
  .rich-text {
    background-color: transparent;
    width: 500rpx;
  }
491
  
DCloud_JSON's avatar
DCloud_JSON 已提交
492 493 494 495 496 497 498
  .link {
    // font-size: 16px;
    color: #007fff;
    /* #ifdef H5 */
    cursor: pointer;
    /* #endif */
  }
499
  
DCloud_JSON's avatar
DCloud_JSON 已提交
500 501 502
  .msgStateIcon {
    margin-right: 5px;
  }
503
  &.self .msg-box {
DCloud_JSON's avatar
DCloud_JSON 已提交
504 505
    flex-direction: row-reverse;
  }
506
  
DCloud_JSON's avatar
DCloud_JSON 已提交
507 508 509 510 511
  .revoke-text-box {
    flex-direction: row;
    flex: 1;
    justify-content: center;
  }
512
  
DCloud_JSON's avatar
DCloud_JSON 已提交
513 514 515 516
  .revoke-text-box .revoke-text {
    color: #999;
    font-size: 12px;
  }
517
  
DCloud_JSON's avatar
DCloud_JSON 已提交
518 519 520 521 522 523 524 525
  .revoke-text-box .re-edit {
    color: #0b65ff;
    font-size: 12px;
    margin-left: 10px;
    /* #ifdef H5 */
    cursor: pointer;
    /* #endif */
  }
526
  
DCloud_JSON's avatar
DCloud_JSON 已提交
527 528 529
  .friendlyTime {
    height: 22px;
  }
530
  
DCloud_JSON's avatar
DCloud_JSON 已提交
531 532 533 534 535 536
  .format-time-text {
    font-size: 12px;
    text-align: center;
    color: #999999;
    line-height: 22px;
  }
537
  
DCloud_JSON's avatar
DCloud_JSON 已提交
538 539 540 541
  /* #ifdef H5 */
  .dup-format-time-text {
    display: none;
  }
542
  &:hover .dup-format-time-text {
DCloud_JSON's avatar
DCloud_JSON 已提交
543 544 545 546 547 548
    display: unset;
  }
  .pointer {
    cursor: pointer;
  }
  /* #endif */
549
}
DCloud_JSON's avatar
DCloud_JSON 已提交
550
</style>