tag-textarea.vue 13.8 KB
1 2 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 28 29 30 31 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 166 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 193 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 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 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 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 329 330 331 332 333 334 335 336 337 338 339 340 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 384 385 386 387 388 389 390 391 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 433 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
<template>
  <div class="w-textarea" ref="wTextarea">
    <div contenteditable="true" class="w-textarea_input" ref="wTextareaContent" :id="contentId" @click="inputClick($event)" @focus="onFocus" @blur="onBlur" @keydown="textareaKeydown($event)" @input="handleInput($event.target)"></div>
    <!-- <div class="w-textarea_tools" v-if="tools.length > 0 || maxlength">
      <button
        class="w-textarea_tools__item"
        v-for="item in tools"
        :key="item.type"
        @click="openTagDialog(item.type)"
      >{{item.text}}</button>
      <span
        :class="['w-textarea_tools__text',
        count.num < 0 ? '__danger' : '']"
        v-if="maxlength"
      >{{count.text}}</span>
    </div>-->
    <!-- <div class="w-textarea_dialog">
      <slot></slot>
    </div>-->
  </div>
</template>

<script>
import emoji from '@/utils/emo'
export default {
  name: 'wTextarea',
  data() {
    return {
      // 记录currentText以计算长度
      currentText: this.value,
      // 为input区域生成随机id,当在页面上有多个组件时,用于监听光标的变化
      contentId: `content${this.getGuid()}`,
      // 输入的时候锁定,禁止更新innerHTML
      isLocked: false,
      isInsert: false,
      // 记录当前选中tag的ID
      currentTagId: null,
      // 当前光标位置
      savedRange: {}
    }
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    tag: {
      // 自定义模版标签的标签名
      type: String,
      // 默认使用wise作为标签名,并添加了默认样式
      // 当使用其他标签名的时候,需要另写标签样式
      default: 'wise'
    },
    tools: {
      // 自定义扩展功能:超链接'link',模版标签'tag'
      type: Array,
      default() {
        return [
          { type: 'link', text: '添加超链接' },
          { type: 'tag', text: '添加模版标签' }
        ]
      }
    },
    maxlength: {
      // 最大输入长度
      type: [String, Number],
      default: ''
    }
  },
  computed: {
    count() {
      // 字符长度记数
      let num = this.maxlength - this.currentText.length
      let text = num < 0 ? `已超出${Math.abs(num)}个字符` : `还可以输入${num}个字符`
      return { num, text }
    }
  },
  mounted() {
    // 初始化数据
    this.currentText && (this.$refs.wTextareaContent.innerHTML = this.currentText)
    // 创建模版标签的style
    this.createStyle()
    // 每次光标变化的时候,保存 range
    document.addEventListener('selectionchange', this.selectHandler)
  },
  beforeDestroy() {
    // 卸载事件
    document.removeEventListener('selectionchange', this.selectHandler)
  },
  methods: {
    updateData(text) {
      this.$emit('input', text)
    },
    createStyle() {
      // 为自定义的模版标签添加样式,使之不可编辑
      let style = document.createElement('style')
      style.innerHTML = `.w-textarea ${this.tag} {
        cursor: default;
        -webkit-user-modify: read-only !important;
      }`
      this.$refs.wTextarea.appendChild(style)
    },
    closeModal() {
      this.form.text = ''
      this.showModal = false
    },
    openTagDialog(type) {
      // if (addLink)
      // 将事件抛给父组件处理
      // 处理后需要调用 addTag() 或者 addLink() 将内容传回来
      this.$emit('add', type)
    },
    textareaKeydown(event) {
      if (event.keyCode == 13) {
        this.insertHtml('<br>')
        let nn = document.createElement('br')
        document.querySelector('.w-textarea_input').appendChild(nn)
        return false
      }
    },
    /*换行*/
    insertHtml(html) {
      var sel, range
      if (window.getSelection) {
        // IE9 或 非IE浏览器
        sel = window.getSelection()
        if (sel.getRangeAt && sel.rangeCount) {
          range = sel.getRangeAt(0)
          range.deleteContents()
          // Range.createContextualFragment() would be useful here but is
          // non-standard and not supported in all browsers (IE9, for one)
          var el = document.createElement('div')
          el.innerHTML = html
          var frag = document.createDocumentFragment(),
            node,
            lastNode
          while ((node = el.firstChild)) {
            lastNode = frag.appendChild(node)
          }
          range.insertNode(frag)
          // Preserve the selection
          if (lastNode) {
            range = range.cloneRange()
            range.setStartAfter(lastNode)
            range.collapse(true)
            sel.removeAllRanges()
            sel.addRange(range)
          }
        }
      } else if (document.selection && document.selection.type != 'Control') {
        // IE < 9
        document.selection.createRange().pasteHTML(html)
      }
      this.currentText = document.querySelector('.w-textarea_input').innerHTML
      this.$emit('updateText', this.currentText)
    },
    addTag(text) {
      // 创建模版标签
      let node = document.createElement(this.tag)
      if (navigator.userAgent.indexOf('Firefox') > 0) {
        node.setAttribute('contenteditable', 'false')
      }
      node.innerText = text
      // 添加id便于删除
      node.id = this.getGuid()
      this.insertNode(node)
    },
    addNode() {
      let target = this.$refs.wTextareaContent
      this.updateData(target.innerHTML)
    },
    promiseAdd(item, num) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          document.querySelector('.w-textarea_input').innerHTML += item
          document.querySelector('.w-textarea_input').focus()
          resolve()
        }, num * 100)
      })
    },
    promiseAddNode(item, num) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          document.querySelector('.w-textarea_input').innerHTML += item
          document.querySelector('.w-textarea_input').focus()
          resolve()
        }, num * 100)
      })
    },
    addContent(attContent) {
      attContent.forEach(async (item, index) => {
        await this.promiseAdd(item, index)
        this.addTag('@昵称')
        // await this.promiseAddNode(item, index)
        // this.addNode()

        // t2(item)
      })
      //       for (let i = 0; i < attContent.length; i++) {
      //         if (attContent[i] || (i == 0 && !attContent[i])) {
      //           document.querySelector('.w-textarea_input').innerHTML += attContent[i]

      //  document.querySelector('.w-textarea_input').focus()
      //           document.querySelector('.w-textarea_input').click()
      //           this.$nextTick(()=>{
      //           this.addTag('@昵称')
      //           })

      //         }
      //         // 代码格式
      //         // (function(a) {})(b)
      //       }
    },
    addLink(text, url) {
      // 创建a标签
      let node = document.createElement('a')
      node.innerText = text
      node.href = url
      node.target = 'blank'
      this.insertNode(node)
    },
    addImg(url) {
      // 创建a标签
      let node = document.createElement('img')
      node.src = url
      // node.setAttribute('ondragstart', 'return false;')
      this.insertNode(node)
    },
    onFocus() {
      this.isLocked = true
      this.isInsert = true
    },
    onBlur() {
      this.isLocked = false
    },
    insertNode(node) {
      // 在内容中插入标签
      // 删掉选中的内容(如有)
      if (this.savedRange.startContainer) {
        this.insertNodeFirst(node)
      } else {
        document.querySelector('.w-textarea_input').focus()
        setTimeout(() => {
          this.insertNodeFirst(node)
          document.querySelector('.w-textarea_input').blur()
        }, 100)
      }
    },
    insertNodeFirst(node) {
      this.savedRange.deleteContents()
      // 插入链接
      if (this.isInsert) {
        this.savedRange.insertNode(node)
      } else {
        document.querySelector('.w-textarea_input').appendChild(node)
      }
      this.isInsert = false
      // 更新双向绑定数据
      let target = this.$refs.wTextareaContent
      if (navigator.userAgent.indexOf('Firefox') > 0 || navigator.userAgent.indexOf('QQBrowser') > 0) {
        this.updateData(target.innerHTML + '&nbsp;')
      } else {
        this.updateData(target.innerHTML)
      }
      let htm = target.innerHTML
      const list = emoji.flat(Infinity)
      const cutImg = htm.replaceAll('<img src="https://img01.glsx.com.cn/weapp/resource/saas/scrm/emoji/', '').replaceAll('<wise id="1">@昵称</wise>', '@昵称').replaceAll('<br>', '\n')
      const replaceImg = cutImg.replace(/(\d){3}.png">/g, function (str) {
        let s = list[parseInt(str.split('.')[0]) - 1]
        return `[${s}]`
      })
      let Textnode = document.createElement('div')
      Textnode.innerHTML = replaceImg
      this.currentText = replaceImg.substring(0, 600)
      console.log(this.currentText)
      this.$emit('updateText', this.currentText)
    },
    placeCaretAtEnd(el) {
      //传入光标要去的jq节点对象
      el.focus()
      if (typeof window.getSelection != 'undefined' && typeof document.createRange != 'undefined') {
        var range = document.createRange()
        range.selectNodeContents(el)
        range.collapse(false)
        var sel = window.getSelection()
        sel.removeAllRanges()
        sel.addRange(range)
      } else if (typeof document.body.createTextRange != 'undefined') {
        var textRange = document.body.createTextRange()
        textRange.moveToElementText(el)
        textRange.collapse(false)
        textRange.select()
      }
    },
    handleInput(target) {
      // 即时更新数据
      this.updateData(target.innerHTML)
      let htm = target.innerHTML
      console.log(htm)
      const list = emoji.flat(Infinity)
      const cutImg = htm.replaceAll('<img src="https://img01.glsx.com.cn/weapp/resource/saas/scrm/emoji/', '').replaceAll('<wise id="1">@昵称</wise>', '@昵称').replaceAll('<br>', '\n')
      const replaceImg = cutImg.replace(/(\d){3}.png">/g, function (str) {
        let s = list[parseInt(str.split('.')[0]) - 1]
        return `[${s}]`
      })
      let Textnode = document.createElement('div')
      Textnode.innerHTML = replaceImg
      this.currentText = replaceImg.substring(0, 600)
      console.log(this.currentText)
      this.$emit('updateText', this.currentText)
    },
    handleDelete(e) {
      // 监听“删除”事件
      if (this.currentTagId) {
        // 若已选中模版标签,直接删除dom节点
        let t = document.getElementById(this.currentTagId)
        this.$refs.wTextareaContent.removeChild(t)
        this.currentTagId = null
        // 阻止浏览器默认的删除事件,并手动更新数据
        e.preventDefault()
        this.handleInput(e.target)
      }
    },
    inputClick(e) {
      console.log(this.tag.toUpperCase(), e.target.nodeName, e)
      // 监听点击事件
      this.isLocked = true
      const TAG_NAME = e.target.nodeName
      if (TAG_NAME === this.tag.toUpperCase()) {
        // 点击模版标签时,记录id
        this.currentTagId = e.target.id
        e.target.className = 'active'
      } else if (this.currentTagId) {
        // 清空active样式
        let target = document.getElementById(this.currentTagId)
        target.className = ''
        this.currentTagId = null
      } else {
        this.currentTagId = null
      }
    },
    getGuid() {
      return 1
      // 生成随机ID
      // return `r${new Date().getTime()}d${Math.ceil(Math.random() * 1000)}`
    },
    selectHandler() {
      // 监听选定文本的变动
      let sel = window.getSelection()
      let range = sel.rangeCount > 0 ? sel.getRangeAt(0) : null
      if (range && range.commonAncestorContainer.ownerDocument.activeElement.id === this.contentId) {
        this.savedRange = range
      }
    }
  },
  watch: {
    value(val) {
      // 非锁定状态下,实时更新innerHTML
      if (!this.isLocked) {
        this.$refs.wTextareaContent.innerHTML = val
      }
    }
  }
}
</script>

<style lang="scss">
// 给标签默认样式,不可scoped
.w-textarea {
  wise {
    border-radius: 2px;
    background-color: #fff;
    font-size: 14px;
    color: #5850ff;
    line-height: 20px;
    padding: 2px;
    margin: 0 5px;
    color: #26a2ff;
    // padding: 0 1px;
    white-space: nowrap;
    cursor: default;
    -webkit-user-modify: read-only !important;
  }
  img {
    width: 24px;
    height: 24px;
    -webkit-user-select: none;
    cursor: default;
    pointer-events: none;
  }
  .active {
    background: #dcdfe6;
  }
}
</style>

<style lang="scss" scoped>
$borderColor: #dcdfe6;
$bgColor: #f5f7fa;
$textColor: #666;
.w-textarea {
  width: 100%;
  box-sizing: border-box;
  //   border-radius: 4px;
  border: 1px solid $borderColor;
  overflow: hidden;
  min-height: 200px;
  //   margin-bottom: 15px;
  overflow: hidden;
  position: relative;
  &_input {
    width: 100%;
    min-height: 100px;
    box-sizing: border-box;
    padding: 10px;
    line-height: 1.5;
    word-break: break-word;
    // 允许编辑,禁止富文本
    -webkit-user-modify: read-write-plaintext-only !important;
    &:focus {
      outline: none;
    }
  }
  &_tools {
    padding: 0 10px;
    height: 40px;
    line-height: 40px;
    border-top: 1px solid $borderColor;
    background-color: $bgColor;
    color: $textColor;
    font-size: 12px;
    &__item {
      display: inline-block;
      line-height: 1;
      padding: 5px 8px;
      margin-right: 8px;
      color: $textColor;
      cursor: pointer;
      border: 1px solid $borderColor;
      border-radius: 4px;
      background: #fff;
      transition: all 0.3s;
      &:hover {
        background: $bgColor;
        opacity: 0.7;
      }
      &:focus {
        outline: none;
      }
    }
    &__text {
      display: inline-block;
      line-height: 40px;
      padding: 0 8px;
      float: right;
      color: $textColor;
      cursor: default;
      transition: all 0.3s;
      &:hover {
        opacity: 1;
      }
      &.__danger {
        color: red;
      }
    }
  }
}
</style>