uni-im-editor.vue 20.2 KB
Newer Older
1
<template>
2 3 4 5 6 7 8 9 10 11 12 13 14 15
  <view class="uni-im-editor-box">
    
    <!-- #ifdef MP -->
      <textarea class="uni-im-editor-mp" v-model="textareaValue" @input="oninput" auto-height :maxlength="maxlength"
        :show-confirm-bar="false" :adjust-position="false" @blur="lastCursor = $event.detail.cursor"
      ></textarea>
    <!-- #endif -->
    
    <!-- #ifndef MP -->
      <div class="uni-im-editor" contenteditable="true" ></div>
      <!-- 与rmd通讯专用 -->
      <view :change:prop="rdm.$callMethod" :prop="callRmdParam"></view>
    <!-- #endif -->
    
16 17 18 19 20 21
  </view>
</template>

<script>
  import uniIm from '@/uni_modules/uni-im/sdk/index.js';
  export default {
22
    emits: ["input", "confirm", "change"],
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
23 24
    data() {
      return {
25 26 27 28 29
        callRmdParam: [],
        // #ifdef MP
        "textareaValue":this.modelValue,
        lastCursor:this.modelValue.length
        // #endif
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
      }
    },
    props: {
      modelValue: {
        type: [String, Object],
        default: ""
      },
      placeholder: {
        type: String,
        default: ""
      },
      maxlength: {
        type: Number,
        default: 140
      }
45 46 47 48 49 50 51 52 53 54
    },
    // #ifdef MP
    watch: {
      textareaValue(val){
        this.$emit("change",{
          value:val
        })
      }
    },
    // #endif
55 56
    mounted() {
      // 与rmd通讯专用
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
      this.callRmd = async (funcName, ...params) => {
        // #ifdef MP
        switch (funcName){
          case '$setContent':
            this.textareaValue = params[0]
            break;
          case '$addHtmlToCursor':
            // 在第lastCursor位置添加内容
            setTimeout(()=>{
              this.textareaValue = this.textareaValue.slice(0,this.lastCursor) + params[0] + this.textareaValue.slice(this.lastCursor)
            },300)
            break;
          default:
            console.error('小程序暂不支持与rmd通讯',funcName,params)
            break;
        }
        return
        // #endif
75 76 77 78 79 80 81 82 83 84 85
        this.callRmdParam = []
        this.$nextTick(() => {
          return new Promise((resolve, reject) => {
            this.callRmdParam = [funcName, ...params,param=>{
              resolve(param)
            }]
          })
        })
      }
      
      // #ifndef H5
86 87 88 89 90 91 92
      // uni.onKeyboardHeightChange((res) => {
      //   console.log('键盘高度变化22222', res.height);
      //   if(res.height === 0){
      //     // console.error('@##键盘被收起,可以失去焦点')
      //     // this.callRmd('$blur')
      //   }
      // });
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
      // #endif
      
      // #ifdef H5
      const uniImEditor = document.querySelector('.uni-im-editor')
      uniIm.utils.appEvent.onAppActivate(() => {
        // 主窗口激活时设置输入焦点到这里的文本编辑框
        uniImEditor.focus()
      })
      let shiftIsDown = false;
      window.addEventListener('keydown', (e) => {
        if (e.key == 'Shift') {
          shiftIsDown = true
        }
      })
      window.addEventListener('keyup', (e) => {
        if (e.key == 'Shift') {
          shiftIsDown = false
        }
      })

      let isComposing = false;
      // 输入法开始输入
      uniImEditor.addEventListener('compositionstart', () => {
        isComposing = true
        uniImEditor.isComposing = isComposing;
      });
      // 输入法结束输入
      uniImEditor.addEventListener('compositionend', () => {
        isComposing = false
        uniImEditor.isComposing = isComposing;
      });

      uniImEditor.addEventListener('keydown', (event) => {
        if (event.key === 'Enter') {
          if (isComposing) {
            console.log('输入法正在输入中,此时回车不发送消息')
            event.preventDefault();
          } else {
            if (shiftIsDown) {
              console.log('shift键处于按下状态,为换行不是confirm发送')
            } else {
              this.$emit('confirm');
              // 防止,回车执行发送的同时执行换行
              event.preventDefault();
            }
          }
        }
      });

DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
      uniImEditor.addEventListener('paste', async event => {
        // 阻止默认行为
        event.preventDefault();
        
        // 删除选中的文本
        const selection = window.getSelection();
        if (!selection.isCollapsed) {  // console.log('选中文本', selection.toString());
          const range = selection.getRangeAt(0);
          range.deleteContents();
          selection.removeAllRanges();
        }
        
        //某些chrome版本使用的是event.originalEvent
        const clipboardData = event.clipboardData || event.originalEvent?.clipboardData;
        let htmlString = clipboardData.getData('text/html');
        console.log('paste',{htmlString});
        if (htmlString) {
          // 获取html字符串
          htmlString = await filterHTML(htmlString);
          console.log('htmlString222', htmlString);
          const tmpDom = document.createElement('div');
          tmpDom.innerHTML = htmlString;
          if (tmpDom.innerText.length > 50000) {
            uni.showModal({
              content: '你粘贴的文本长度超过50000,将被截断。',
              complete: e => {
                if (e.confirm) {
                  this.$addHtmlToCursor(htmlString.substring(0, 50000))
                }
              }
            });
          } else {
            this.$addHtmlToCursor(htmlString)
          }
          // 检查图片加载失败,删除图片
          const imgs = uniImEditor.querySelectorAll('img');
          for (const img of imgs) {
            img.onerror = () => {
              img.remove();
            }
          }
        } else {
          // 获取文件
          let items = clipboardData.items;
          for (const item of items) {
            if (item.type.indexOf("image") !== -1) {
188 189 190 191
              const file = item.getAsFile();
              const blobUrl = URL.createObjectURL(file)
              console.log('blobUrl',blobUrl)
              this.$addHtmlToCursor(`<img src="${blobUrl}" />`)
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
192 193 194 195 196 197 198 199
            }
          }
          // 获取文本
          const clipboardDataText = clipboardData.getData('text');
          if (clipboardDataText) {
            this.$addHtmlToCursor(clipboardDataText)
          }
        }
200 201 202 203 204
      })

      async function filterHTML(htmlString) {
        // 过滤html字符串,只保留:文字,图片,链接
        // html字符串转dom对象,并深度遍历
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
205 206
        let tmpDiv = document.createElement('div');
        tmpDiv.innerHTML = htmlString;
207
        let arr = [];
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
        await deepTr(tmpDiv);
        // 销毁tmpDiv
        tmpDiv = null;
        return arr.join('');
        async function deepTr(node) {
          // console.log('node', node);
          if (node.nodeType === 1) {
            const action = {
              async IMG(){
                // 只保留src属性
                // 处理图片跨域问题
                if (node.src.indexOf('blob:http') != 0 && !node.src.includes('https://im-res.dcloud.net.cn')) {
                  const uniImCo = uniCloud.importObject("uni-im-co", {
                    loadingOptions: { // loading相关配置
                      title: '处理跨域图片...',
                      mask: true
                    }
                  })
                  let res = await uniImCo.getImgBase64(node.src)
                  function base64ToBlob(base64) {
                    // 将Base64字符串分割为数据和应用信息
                    const byteChars = atob(base64.split(',')[1]);
                    // 创建一个长度为byteChars长度的数组
                    const byteArrays = new Array(byteChars.length);
                    // 将二进制字符串转换为Uint8Array
                    for (let i = 0; i < byteChars.length; i++) {
                      byteArrays[i] = byteChars.charCodeAt(i);
                    }
                    // 返回一个Blob对象
                    return new Blob([new Uint8Array(byteArrays)], {type: 'image/png'});
238
                  }
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
239
                  node.src = URL.createObjectURL( base64ToBlob(res.data) )
240
                }
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
                arr.push(`<img src="${node.src}" />`);
              },
              A(){
                // 只保留href属性
                arr.push(`<a href="${node.href}">${node.innerText}</a>`);
              }
            }
            await action[node.tagName]?.();
            for (let i = 0; i < node.childNodes.length; i++) {
              await deepTr(node.childNodes[i]);
            }
          } else if (node.nodeType === 3) {
            // 排除非内容的文本节点
            const tagNameList = ['A','IMG','STYLE','SCRIPT'];
            if (!tagNameList.includes(node.parentNode.tagName)) {
              // 把node中的<>&转义
              node.nodeValue = node.nodeValue.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
              arr.push(node.nodeValue.trim());
              // 如果父节点是需要换行的标签,且当前节点是最后一个节点,则添加换行
              const tagNameList2 = ['P','DIV','FONT','H1','H2','H3','H4','H5','H6','LI','UL','OL','BR'];
              if (tagNameList2.includes(node.parentNode.tagName) && node.parentNode.lastChild === node) {
                arr.push('\n');
              }
            }else{
              // console.log('非内容文本节点', node.parentNode.tagName,node);
            }
          }else{
            // console.log('其他节点', node);
          }
270 271 272 273 274
        }
      }
      // #endif
    },
    methods: {
275 276 277 278 279 280 281 282 283 284 285 286 287
      oninput(e) {
        // #ifdef MP
        let oldValue = this.oninput.oldValue || '';
        // 当前输入框的值
        const value = e.detail.value 
        // 本次输入的数据
        const data = value.replace(oldValue, '') 
        this.oninput.oldValue = value
        e = {
          data,
          value
        }
        // #endif
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
288
        // console.error('input',e)
289 290 291 292 293
        this.$emit('input', e)
      }
    }
  }
</script>
294
<!-- #ifndef MP -->
295
<script module="rdm" lang="renderjs">
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
296
  let lastFocusNode,lastCursor;
297 298 299 300 301 302 303 304 305 306 307 308 309 310
  // #ifdef APP
  function setSoftinputTemporary() {
      console.log('setSoftinputTemporary')
      // 设置当前窗口键盘弹出后不做变化
      const currentWebview = plus.webview.currentWebview();
      currentWebview.setSoftinputTemporary({
        mode:'nothing',
        position:{top: 0,height: 0}
      });
  }
  // #endif
  export default {
    name: 'uni-im-editor',
    data() {
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
311 312 313 314
      return {
        uniImEditor: null,
      }
    },
315
    mounted() {
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
316 317
      this.uniImEditor = document.querySelector('.uni-im-editor')
      this.uniImEditor.addEventListener('input', e => {
318 319
        setTimeout(()=>this.$oninput(e.data),0);
      });
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
320
      this.uniImEditor.addEventListener('click', e => {
321 322 323 324
        // console.log('click', e);
        // #ifdef APP
        setSoftinputTemporary()
        // #endif
325
        setTimeout(this.$refreshLastCursor, 0);
326
      });
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
327
      this.uniImEditor.addEventListener('blur', e => {
328 329 330
        // console.error('###blur', e);
      });
      // 键盘敲左右
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
331
      this.uniImEditor.addEventListener('keydown', e => {
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
        setTimeout(this.$refreshLastCursor, 0);
      });
      
      // 监听nickname后面的空格被删除(提醒此空格在margin-right: -3px;内,用于解决办法浏览器非文本节点后的光标定位不正确的问题)
      const observer = new MutationObserver(function(mutations) {
        mutations.forEach(mutation=> {
          // 判断是否为删除节点的操作
          const [removedNode] = mutation.removedNodes
          if(removedNode){
            if(removedNode && mutation?.previousSibling?.className === "nickname"){
              mutation.previousSibling.remove()
            }
          }
        });
      })
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
347
      .observe(this.uniImEditor, {
348 349 350 351 352 353 354 355
        childList: true, // 监听子节点的变化
      });
    },
    watch: {
      modelValue(modelValue, oldModelValue) {
        this.$nextTick(() => {
          // console.log('modelValue', modelValue);
          if (modelValue.length === 0) {
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
356
            this.uniImEditor.innerHTML = ''
357
          } else if (typeof modelValue === 'string' && modelValue != this.$inputText()) {
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
358 359 360
            this.uniImEditor.innerHTML = modelValue
          } else if (typeof modelValue === 'object' && modelValue.html != this.uniImEditor.innerHTML) {
            this.uniImEditor.innerHTML = modelValue.html
361 362 363
          }
        });
      },
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
364
    },
365 366 367 368 369
    methods: {
      // 刷新光标信息
      $refreshLastCursor() {
        lastCursor = this.$getCursor();
        lastFocusNode = window.getSelection().focusNode;
370 371 372 373
        // console.log('刷新光标信息',{
        //   lastCursor,
        //   lastFocusNode
        // });
374 375 376 377 378 379 380
      },
      $oninput(data){
        this.$refreshLastCursor()
        // 耗时计算
        let start = new Date().getTime();
        
        let param = '';
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
381
        let val = this.uniImEditor.innerHTML;
382
        
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
383 384 385
        const hasImg = this.uniImEditor.querySelector('img');
        const hasNickname = this.uniImEditor.querySelector('.nickname');
        const hasA = this.uniImEditor.querySelector('a');
386 387 388 389
        if (hasImg || hasNickname || hasA) {
          param = {
            // "rich-text": //uniIm.utils.parseHtml( 执行比较消耗内存,改为chat页面 confirm时执行,
            "html": val,
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
390 391
            "text": this.uniImEditor.innerText,
            "aboutUserIds": Array.from(this.uniImEditor.querySelectorAll('.nickname')).map(i=>i.getAttribute('user_id'))
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
          }
        } else {
          param = this.$inputText()
        }
        
        // 打印耗时
        const spendTime = new Date().getTime() - start
        if(spendTime > 10){
          console.log('耗时', );
        }
        
        this.$ownerInstance.callMethod('oninput',{
          data,// 本次输入的数据
          value: param // 当前输入框的值
        })
      },
      $callMethod([funcName, ...params]) {
        // console.log('$callMethod funcName', funcName)
        // console.log('$callMethod funcName', funcName === null)
        // console.log('$callMethod params', params)
        // console.log('$callMethod typeof funcName', typeof funcName)
        try {
          if(typeof funcName == 'string'){
            const res = this[funcName](...params)
            // console.log('res', res)
          }
        } catch (e) {
          console.error("调用renderjs模块的方法失败", e,funcName,params)
        }
      },
      $getCursor() {
        const selection = window.getSelection();
        return selection.focusOffset;
      },
      // 恢复光标位置
      $restoreCursor(focus = true) {
        this.$focus();
        // 获取焦点时所在的子元素
        try{
          const range = document.createRange();
          const sel = window.getSelection(); 
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
433
          range.setStart(lastFocusNode || this.uniImEditor, lastCursor);
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
          range.collapse(true); 
          sel.removeAllRanges(); 
          sel.addRange(range);
        }catch(e){
          console.error('恢复光标位置失败',e)
          //TODO handle the exception
        }
      },
      $deleteLeftChar(n = 1) {
        this.$restoreCursor(true);
        const selection = window.getSelection();
        if (!selection.isCollapsed){
          console.error('不要删除已选中的内容')
          return;
        }
        const range = selection.getRangeAt(0).cloneRange();
        if (range.startOffset > 0) {
          range.setStart(range.startContainer, range.startOffset - n);
          range.deleteContents();
          selection.removeAllRanges();
          selection.addRange(range);
        } else if (range.startContainer.previousSibling) {
          const container = range.startContainer;
          const sibling = container.previousSibling;
          range.setStart(sibling, sibling.length - n);
          range.setEnd(sibling, sibling.length);
          range.deleteContents();
          selection.removeAllRanges();
          selection.addRange(range);
        }
        lastCursor = this.$getCursor();
        this.$oninput();
      },
      $addHtmlToCursor(html,focus = true) {
        this.$restoreCursor(focus);
        const selection = window.getSelection();
        if (selection.getRangeAt && selection.rangeCount) {
          let range = selection.getRangeAt(0);
          range.deleteContents();
          var ele = document.createElement("div");
          ele.innerHTML = html;
          var frag = document.createDocumentFragment(),
            node, lastNode;
          while ((node = ele.firstChild)) {
            lastNode = frag.appendChild(node);
          }
          range.insertNode(frag);
          // 设置光标到插入内容之后的位置
          if (lastNode) {
            range = range.cloneRange();
            range.setStartAfter(lastNode);
            range.collapse(true);
            selection.removeAllRanges(); // 清除现有的选择区域
            selection.addRange(range); // 将更新后的范围添加回选择区域
          }
        }else{
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
490
          this.uniImEditor.innerHTML += html;
491 492 493
        }
        this.$oninput(html);
      },
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
494 495
      $inputText() {
        return this.uniImEditor.innerText.trim();
496 497 498 499 500 501 502 503 504
      },
      $focus() {
        if(document.activeElement.className === 'uni-im-editor'){
          document.activeElement.blur();
        }
        // #ifdef APP
        setSoftinputTemporary()
        // #endif
        // console.error('获取焦点',document.activeElement.className);
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
505
        this.uniImEditor.focus();
506 507 508 509
        // console.error('获取焦点',document.activeElement.className);
      },
      $blur(){
        // console.error('失去焦点1',document.activeElement.className);
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
510
        this.uniImEditor.blur();
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
        // console.error('失去焦点2',document.activeElement.className);
        setTimeout(()=>{
          // console.error('失去焦点3',document.activeElement.className);
        },1000)
      },
      $onBlur() {
        // this.$emit('update:focus', false);
        // console.log('blur');
        this.$emit('blur');
      },
      $onFocus() {
        // console.log('$onFocus');
        this.$emit('focus');
        // this.$emit('update:focus', true);
      },
      $setContent(data) {
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
527 528 529 530 531
        if (typeof data === 'string') {
          // 为兼容旧版- s &gt; 转换为 > $lt; 转换为 < &amp; 转换为 &
          data = data.replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&');
          // 为兼容旧版- e
          this.uniImEditor.innerText = data;
532
          this.$oninput(data);
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
533 534 535
        } else if (typeof data === 'object') {
          this.uniImEditor.innerHTML = data.html || this.$arrDomJsonToHtml(data);
          this.$oninput(this.uniImEditor.innerHTML);
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
        }
      },
      $arrDomJsonToHtml(arr) {
        function parseItem(item) {
          if (item.type === "text") {
            return item.text;
          }
          let html = `<${item.name}`;
          if (item.attrs) {
            for (const key in item.attrs) {
              html += ` ${key}="${item.attrs[key]}"`;
            }
          }
          if (item.children) {
            html += ">";
            for (const child of item.children) {
              html += parseItem(child);
            }
            html += `</${item.name}>`;
          } else {
            html += " />";
          }
          return html;
        }

        let result = "";
        for (const item of arr) {
          result += parseItem(item);
        }
        return result;
DCloud_JSON's avatar
3.4.31  
DCloud_JSON 已提交
566
      }
567 568
    }
  }
569 570
</script>
<!-- #endif -->
571

572 573
<style lang="scss">
.uni-im-editor-box {
574 575 576 577
  /* #ifdef MP */
  .uni-im-editor-mp {
    width: 100%;
    height: auto;
578
    max-height: 110px;
579
  }
580 581 582 583 584 585
  /* #endif */
  
  /* #ifndef MP */
  .uni-im-editor {
    min-height: 26px;
    max-height: 110px;
586 587 588 589 590 591 592 593
    overflow: auto;
    // 解决ios下不能编辑的问题
    -webkit-user-modify: read-write-plaintext-only;
    /* #ifdef APP */
    &,* {
      -webkit-user-select:text;
    }
    /* #endif */
594 595
    &:focus {
      outline: none;
596 597 598
    }
    & ::v-deep {
      img {
DCloud_JSON's avatar
DCloud_JSON 已提交
599
        max-width: 50%;
600 601 602 603 604 605 606 607 608 609 610 611
        display: block;
      }
      .nickname {
         color: #0b65ff !important;
         user-select: text;
         margin-right: -3px;
         /* #ifdef H5 */
         cursor: pointer;
         /* #endif */
       }
    }
  }
612 613
  /* #endif */
}
614
</style>