# all files / src/js/base/module/ AutoLink.js

59.46% Statements 22/37
17.65% Branches 3/17
88.89% Functions 8/9
59.46% Lines 22/37

    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
    651×
    1×
    1×

    1×
    1×

    1×
    97×
    96×
    96×

    1×
    1×

    1×

    1×
    96×

    1×
    2×

    1×

    1×
    1×

    1×
    1×

    1×
     import $ from 'jquery';
    import lists from '../core/lists';
    import key from '../core/key';

    const defaultScheme = 'http://';
    const linkPattern = /^([A-Za-z][A-Za-z0-9+-.]*\:[\/]{2}|mailto:[A-Z0-9._%+-]+@)?(www\.)?(.+)$/i;

    export default class AutoLink {
      constructor(context) {
        this.context = context;
        this.events = {
          'summernote.keyup': (we, e) => {
            Eif (!e.isDefaultPrevented()) {
              this.handleKeyup(e);
            }
          },
          'summernote.keydown': (we, e) => {
            this.handleKeydown(e);
          },
        };
      }

      initialize() {
        this.lastWordRange = null;
      }

      destroy() {
        this.lastWordRange = null;
      }

      replace() {
        if (!this.lastWordRange) {
          return;
        }

        const keyword = this.lastWordRange.toString();
        const match = keyword.match(linkPattern);

        if (match && (match[1] || match[2])) {
          const link = match[1] ? keyword : defaultScheme + keyword;
          const node = $('<a />').html(keyword).attr('href', link)[0];
          if (this.context.options.linkTargetBlank) {
            $(node).attr('target', '_blank');
          }

          this.lastWordRange.insertNode(node);
          this.lastWordRange = null;
          this.context.invoke('editor.focus');
        }
      }

      handleKeydown(e) {
        Iif (lists.contains([key.code.ENTER, key.code.SPACE], e.keyCode)) {
          const wordRange = this.context.invoke('editor.createRange').getWordRange();
          this.lastWordRange = wordRange;
        }
      }

      handleKeyup(e) {
        Iif (lists.contains([key.code.ENTER, key.code.SPACE], e.keyCode)) {
          this.replace();
        }
      }
    }