all files / src/js/base/module/ Editor.js

70.78% Statements 281/397
43.43% Branches 76/175
64.29% Functions 54/84
71.43% Lines 280/392
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 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 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 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862           78× 77×   77× 77× 77× 77× 77×   77× 77×   77× 77× 77× 77× 77×   77× 77× 77× 77× 77× 77× 77× 77× 77× 77× 77× 77×     77×           77× 1001× 1001× 14× 14× 14×     1001×     77×       77×     77× 462× 462×       462×     77×     77×     77×     77×     77×               77×               77×             77×                 77×                 77×               77×                     77×                                                                           77×                 77×               77×             77×                             77×                     77×                 78×   77×                       23×                   77×   77× 13×     77× 20×       77× 77×     77×     77×     77×         77×                                               12×   12×             12×               13× 13×                                                           58×                       215× 215× 38×   215×                                                 49×   49×             49× 49× 49× 35×                                                               1541× 1540× 33× 33× 33×                                                                                                                                                                                                                                                                                                                                                                                                             115×               62× 62×                                   49×    
import $ from 'jquery';
import env from '../core/env';
import key from '../core/key';
import func from '../core/func';
import lists from '../core/lists';
import dom from '../core/dom';
import range from '../core/range';
import { readFileAsDataURL, createImage } from '../core/async';
import History from '../editing/History';
import Style from '../editing/Style';
import Typing from '../editing/Typing';
import Table from '../editing/Table';
import Bullet from '../editing/Bullet';
 
const KEY_BOGUS = 'bogus';
 
/**
 * @class Editor
 */
export default class Editor {
  constructor(context) {
    this.context = context;
 
    this.$note = context.layoutInfo.note;
    this.$editor = context.layoutInfo.editor;
    this.$editable = context.layoutInfo.editable;
    this.options = context.options;
    this.lang = this.options.langInfo;
 
    this.editable = this.$editable[0];
    this.lastRange = null;
 
    this.style = new Style();
    this.table = new Table();
    this.typing = new Typing();
    this.bullet = new Bullet();
    this.history = new History(this.$editable);
 
    this.context.memo('help.undo', this.lang.help.undo);
    this.context.memo('help.redo', this.lang.help.redo);
    this.context.memo('help.tab', this.lang.help.tab);
    this.context.memo('help.untab', this.lang.help.untab);
    this.context.memo('help.insertParagraph', this.lang.help.insertParagraph);
    this.context.memo('help.insertOrderedList', this.lang.help.insertOrderedList);
    this.context.memo('help.insertUnorderedList', this.lang.help.insertUnorderedList);
    this.context.memo('help.indent', this.lang.help.indent);
    this.context.memo('help.outdent', this.lang.help.outdent);
    this.context.memo('help.formatPara', this.lang.help.formatPara);
    this.context.memo('help.insertHorizontalRule', this.lang.help.insertHorizontalRule);
    this.context.memo('help.fontName', this.lang.help.fontName);
 
    // native commands(with execCommand), generate function for execCommand
    const commands = [
      'bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript',
      'justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull',
      'formatBlock', 'removeFormat', 'backColor'
    ];
 
    for (let idx = 0, len = commands.length; idx < len; idx++) {
      this[commands[idx]] = ((sCmd) => {
        return (value) => {
          this.beforeCommand();
          document.execCommand(sCmd, false, value);
          this.afterCommand(true);
        };
      })(commands[idx]);
      this.context.memo('help.' + commands[idx], this.lang.help[commands[idx]]);
    }
 
    this.fontName = this.wrapCommand((value) => {
      return this.fontStyling('font-family', "\'" + value + "\'");
    });
 
    this.fontSize = this.wrapCommand((value) => {
      return this.fontStyling('font-size', value + 'px');
    });
 
    for (let idx = 1; idx <= 6; idx++) {
      this['formatH' + idx] = ((idx) => {
        return () => {
          this.formatBlock('H' + idx);
        };
      })(idx);
      this.context.memo('help.formatH' + idx, this.lang.help['formatH' + idx]);
    };
 
    this.insertParagraph = this.wrapCommand(() => {
      this.typing.insertParagraph(this.editable);
    });
 
    this.insertOrderedList = this.wrapCommand(() => {
      this.bullet.insertOrderedList(this.editable);
    });
 
    this.insertUnorderedList = this.wrapCommand(() => {
      this.bullet.insertUnorderedList(this.editable);
    });
 
    this.indent = this.wrapCommand(() => {
      this.bullet.indent(this.editable);
    });
 
    this.outdent = this.wrapCommand(() => {
      this.bullet.outdent(this.editable);
    });
 
    /**
     * insertNode
     * insert node
     * @param {Node} node
     */
    this.insertNode = this.wrapCommand((node) => {
      if (this.isLimited($(node).text().length)) {
        return;
      }
      const rng = this.createRange();
      rng.insertNode(node);
      range.createFromNodeAfter(node).select();
    });
 
    /**
     * insert text
     * @param {String} text
     */
    this.insertText = this.wrapCommand((text) => {
      if (this.isLimited(text.length)) {
        return;
      }
      const rng = this.createRange();
      const textNode = rng.insertNode(dom.createText(text));
      range.create(textNode, dom.nodeLength(textNode)).select();
    });
    /**
     * paste HTML
     * @param {String} markup
     */
    this.pasteHTML = this.wrapCommand((markup) => {
      if (this.isLimited(markup.length)) {
        return;
      }
      const contents = this.createRange().pasteHTML(markup);
      range.createFromNodeAfter(lists.last(contents)).select();
    });
 
    /**
     * formatBlock
     *
     * @param {String} tagName
     */
    this.formatBlock = this.wrapCommand((tagName, $target) => {
      const onApplyCustomStyle = this.options.callbacks.onApplyCustomStyle;
      Iif (onApplyCustomStyle) {
        onApplyCustomStyle.call(this, $target, this.context, this.onFormatBlock);
      } else {
        this.onFormatBlock(tagName, $target);
      }
    });
 
    /**
     * insert horizontal rule
     */
    this.insertHorizontalRule = this.wrapCommand(() => {
      const hrNode = this.createRange().insertNode(dom.create('HR'));
      Eif (hrNode.nextSibling) {
        range.create(hrNode.nextSibling, 0).normalize().select();
      }
    });
 
    /**
     * lineHeight
     * @param {String} value
     */
    this.lineHeight = this.wrapCommand((value) => {
      this.style.stylePara(this.createRange(), {
        lineHeight: value
      });
    });
 
    /**
     * create link (command)
     *
     * @param {Object} linkInfo
     */
    this.createLink = this.wrapCommand((linkInfo) => {
      let linkUrl = linkInfo.url;
      const linkText = linkInfo.text;
      const isNewWindow = linkInfo.isNewWindow;
      let rng = linkInfo.range || this.createRange();
      const isTextChanged = rng.toString() !== linkText;
 
      // handle spaced urls from input
      Eif (typeof linkUrl === 'string') {
        linkUrl = linkUrl.trim();
      }
 
      Iif (this.options.onCreateLink) {
        linkUrl = this.options.onCreateLink(linkUrl);
      } else {
        // if url doesn't match an URL schema, set http:// as default
        linkUrl = /^[A-Za-z][A-Za-z0-9+-.]*\:[\/\/]?/.test(linkUrl)
          ? linkUrl : 'http://' + linkUrl;
      }
 
      let anchors = [];
      Eif (isTextChanged) {
        rng = rng.deleteContents();
        const anchor = rng.insertNode($('<A>' + linkText + '</A>')[0]);
        anchors.push(anchor);
      } else {
        anchors = this.style.styleNodes(rng, {
          nodeName: 'A',
          expandClosestSibling: true,
          onlyPartialContains: true
        });
      }
 
      $.each(anchors, (idx, anchor) => {
        $(anchor).attr('href', linkUrl);
        if (isNewWindow) {
          $(anchor).attr('target', '_blank');
        } else {
          $(anchor).removeAttr('target');
        }
      });
 
      const startRange = range.createFromNodeBefore(lists.head(anchors));
      const startPoint = startRange.getStartPoint();
      const endRange = range.createFromNodeAfter(lists.last(anchors));
      const endPoint = endRange.getEndPoint();
 
      range.create(
        startPoint.node,
        startPoint.offset,
        endPoint.node,
        endPoint.offset
      ).select();
    });
 
    /**
     * setting color
     *
     * @param {Object} sObjColor  color code
     * @param {String} sObjColor.foreColor foreground color
     * @param {String} sObjColor.backColor background color
     */
    this.color = this.wrapCommand((colorInfo) => {
      const foreColor = colorInfo.foreColor;
      const backColor = colorInfo.backColor;
 
      Iif (foreColor) { document.execCommand('foreColor', false, foreColor); }
      Eif (backColor) { document.execCommand('backColor', false, backColor); }
    });
 
    /**
     * Set foreground color
     *
     * @param {String} colorCode foreground color code
     */
    this.foreColor = this.wrapCommand((colorInfo) => {
      document.execCommand('styleWithCSS', false, true);
      document.execCommand('foreColor', false, colorInfo);
    });
 
    /**
     * insert Table
     *
     * @param {String} dimension of table (ex : "5x5")
     */
    this.insertTable = this.wrapCommand((dim) => {
      const dimension = dim.split('x');
 
      const rng = this.createRange().deleteContents();
      rng.insertNode(this.table.createTable(dimension[0], dimension[1], this.options));
    });
 
    /**
     * remove media object and Figure Elements if media object is img with Figure.
     */
    this.removeMedia = this.wrapCommand(() => {
      let $target = $(this.restoreTarget()).parent();
      if ($target.parent('figure').length) {
        $target.parent('figure').remove();
      } else {
        $target = $(this.restoreTarget()).detach();
      }
      this.context.triggerEvent('media.delete', $target, this.$editable);
    });
 
    /**
     * float me
     *
     * @param {String} value
     */
    this.floatMe = this.wrapCommand((value) => {
      const $target = $(this.restoreTarget());
      $target.toggleClass('note-float-left', value === 'left');
      $target.toggleClass('note-float-right', value === 'right');
      $target.css('float', value);
    });
 
    /**
     * resize overlay element
     * @param {String} value
     */
    this.resize = this.wrapCommand((value) => {
      const $target = $(this.restoreTarget());
      $target.css({
        width: value * 100 + '%',
        height: ''
      });
    });
  }
 
  initialize() {
    // bind custom events
    this.$editable.on('keydown', (event) => {
      Iif (event.keyCode === key.code.ENTER) {
        this.context.triggerEvent('enter', event);
      }
      this.context.triggerEvent('keydown', event);
 
      Eif (!event.isDefaultPrevented()) {
        Eif (this.options.shortcuts) {
          this.handleKeyMap(event);
        } else {
          this.preventDefaultEditableShortCuts(event);
        }
      }
      Iif (this.isLimited(1, event)) {
        return false;
      }
    }).on('keyup', (event) => {
      this.context.triggerEvent('keyup', event);
    }).on('focus', (event) => {
      this.context.triggerEvent('focus', event);
    }).on('blur', (event) => {
      this.context.triggerEvent('blur', event);
    }).on('mousedown', (event) => {
      this.context.triggerEvent('mousedown', event);
    }).on('mouseup', (event) => {
      this.context.triggerEvent('mouseup', event);
    }).on('scroll', (event) => {
      this.context.triggerEvent('scroll', event);
    }).on('paste', (event) => {
      this.context.triggerEvent('paste', event);
    });
 
    // init content before set event
    this.$editable.html(dom.html(this.$note) || dom.emptyPara);
 
    this.$editable.on(env.inputEventName, func.debounce(() => {
      this.context.triggerEvent('change', this.$editable.html());
    }, 100));
 
    this.$editor.on('focusin', (event) => {
      this.context.triggerEvent('focusin', event);
    }).on('focusout', (event) => {
      this.context.triggerEvent('focusout', event);
    });
 
    Eif (!this.options.airMode) {
      Iif (this.options.width) {
        this.$editor.outerWidth(this.options.width);
      }
      Iif (this.options.height) {
        this.$editable.outerHeight(this.options.height);
      }
      Iif (this.options.maxHeight) {
        this.$editable.css('max-height', this.options.maxHeight);
      }
      Iif (this.options.minHeight) {
        this.$editable.css('min-height', this.options.minHeight);
      }
    }
 
    this.history.recordUndo();
  }
 
  destroy() {
    this.$editable.off();
  }
 
  handleKeyMap(event) {
    const keyMap = this.options.keyMap[env.isMac ? 'mac' : 'pc'];
    const keys = [];
 
    Iif (event.metaKey) { keys.push('CMD'); }
    Iif (event.ctrlKey && !event.altKey) { keys.push('CTRL'); }
    Iif (event.shiftKey) { keys.push('SHIFT'); }
 
    const keyName = key.nameFromCode[event.keyCode];
    Iif (keyName) {
      keys.push(keyName);
    }
 
    const eventName = keyMap[keys.join('+')];
    Iif (eventName) {
      if (this.context.invoke(eventName) !== false) {
        event.preventDefault();
      }
    } else Iif (key.isEdit(event.keyCode)) {
      this.afterCommand();
    }
  }
 
  preventDefaultEditableShortCuts(event) {
    // B(Bold, 66) / I(Italic, 73) / U(Underline, 85)
    if ((event.ctrlKey || event.metaKey) &&
      lists.contains([66, 73, 85], event.keyCode)) {
      event.preventDefault();
    }
  }
 
  isLimited(pad, event) {
    pad = pad || 0;
 
    if (typeof event !== 'undefined') {
      Iif (key.isMove(event.keyCode) ||
          (event.ctrlKey || event.metaKey) ||
          lists.contains([key.code.BACKSPACE, key.code.DELETE], event.keyCode)) {
        return false;
      }
    }
 
    if (this.options.maxTextLength > 0) {
      Eif ((this.$editable.text().length + pad) >= this.options.maxTextLength) {
        return true;
      }
    }
    return false;
  }
  /**
   * create range
   * @return {WrappedRange}
   */
  createRange() {
    this.focus();
    return range.create(this.editable);
  }
 
  /**
   * saveRange
   *
   * save current range
   *
   * @param {Boolean} [thenCollapse=false]
   */
  saveRange(thenCollapse) {
    this.lastRange = this.createRange();
    if (thenCollapse) {
      this.lastRange.collapse().select();
    }
  }
 
  /**
   * restoreRange
   *
   * restore lately range
   */
  restoreRange() {
    if (this.lastRange) {
      this.lastRange.select();
      this.focus();
    }
  }
 
  saveTarget(node) {
    this.$editable.data('target', node);
  }
 
  clearTarget() {
    this.$editable.removeData('target');
  }
 
  restoreTarget() {
    return this.$editable.data('target');
  }
 
  /**
   * currentStyle
   *
   * current style
   * @return {Object|Boolean} unfocus
   */
  currentStyle() {
    let rng = range.create();
    if (rng) {
      rng = rng.normalize();
    }
    return rng ? this.style.current(rng) : this.style.fromNode(this.$editable);
  }
 
  /**
   * style from node
   *
   * @param {jQuery} $node
   * @return {Object}
   */
  styleFromNode($node) {
    return this.style.fromNode($node);
  }
 
  /**
   * undo
   */
  undo() {
    this.context.triggerEvent('before.command', this.$editable.html());
    this.history.undo();
    this.context.triggerEvent('change', this.$editable.html());
  }
 
  /**
   * redo
   */
  redo() {
    this.context.triggerEvent('before.command', this.$editable.html());
    this.history.redo();
    this.context.triggerEvent('change', this.$editable.html());
  }
 
  /**
   * before command
   */
  beforeCommand() {
    this.context.triggerEvent('before.command', this.$editable.html());
    // keep focus on editable before command execution
    this.focus();
  }
 
  /**
   * after command
   * @param {Boolean} isPreventTrigger
   */
  afterCommand(isPreventTrigger) {
    this.normalizeContent();
    this.history.recordUndo();
    if (!isPreventTrigger) {
      this.context.triggerEvent('change', this.$editable.html());
    }
  }
 
  /**
   * handle tab key
   */
  tab() {
    const rng = this.createRange();
    Iif (rng.isCollapsed() && rng.isOnCell()) {
      this.table.tab(rng);
    } else {
      Iif (this.options.tabSize === 0) {
        return false;
      }
 
      Eif (!this.isLimited(this.options.tabSize)) {
        this.beforeCommand();
        this.typing.insertTab(rng, this.options.tabSize);
        this.afterCommand();
      }
    }
  }
 
  /**
   * handle shift+tab key
   */
  untab() {
    const rng = this.createRange();
    if (rng.isCollapsed() && rng.isOnCell()) {
      this.table.tab(rng, true);
    } else {
      if (this.options.tabSize === 0) {
        return false;
      }
    }
  }
 
  /**
   * run given function between beforeCommand and afterCommand
   */
  wrapCommand(fn) {
    return () => {
      this.beforeCommand();
      fn.apply(this, arguments);
      this.afterCommand();
    };
  }
 
  /**
   * insert image
   *
   * @param {String} src
   * @param {String|Function} param
   * @return {Promise}
   */
  insertImage(src, param) {
    return createImage(src, param).then(($image) => {
      this.beforeCommand();
 
      Iif (typeof param === 'function') {
        param($image);
      } else {
        Eif (typeof param === 'string') {
          $image.attr('data-filename', param);
        }
        $image.css('width', Math.min(this.$editable.width(), $image.width()));
      }
 
      $image.show();
      range.create(this.editable).insertNode($image[0]);
      range.createFromNodeAfter($image[0]).select();
      this.afterCommand();
    }).fail((e) => {
      this.context.triggerEvent('image.upload.error', e);
    });
  }
 
  /**
   * insertImages
   * @param {File[]} files
   */
  insertImages(files) {
    $.each(files, (idx, file) => {
      const filename = file.name;
      if (this.options.maximumImageFileSize && this.options.maximumImageFileSize < file.size) {
        this.context.triggerEvent('image.upload.error', this.lang.image.maximumFileSizeError);
      } else {
        readFileAsDataURL(file).then((dataURL) => {
          return this.insertImage(dataURL, filename);
        }).fail(() => {
          this.context.triggerEvent('image.upload.error');
        });
      }
    });
  }
 
  /**
   * insertImagesOrCallback
   * @param {File[]} files
   */
  insertImagesOrCallback(files) {
    const callbacks = this.options.callbacks;
 
    // If onImageUpload this.options setted
    if (callbacks.onImageUpload) {
      this.context.triggerEvent('image.upload', files);
      // else insert Image as dataURL
    } else {
      this.insertImages(files);
    }
  }
 
  /**
   * return selected plain text
   * @return {String} text
   */
  getSelectedText() {
    let rng = this.createRange();
 
    // if range on anchor, expand range with anchor
    if (rng.isOnAnchor()) {
      rng = range.createFromNode(dom.ancestor(rng.sc, dom.isAnchor));
    }
 
    return rng.toString();
  }
 
  onFormatBlock(tagName, $target) {
    // [workaround] for MSIE, IE need `<`
    tagName = env.isMSIE ? '<' + tagName + '>' : tagName;
    document.execCommand('FormatBlock', false, tagName);
 
    // support custom class
    if ($target && $target.length) {
      const className = $target[0].className || '';
      Eif (className) {
        const currentRange = this.createRange();
 
        const $parent = $([currentRange.sc, currentRange.ec]).closest(tagName);
        $parent.addClass(className);
      }
    }
  }
 
  formatPara() {
    this.formatBlock('P');
  }
 
  fontStyling(target, value) {
    const rng = this.createRange();
 
    Eif (rng) {
      const spans = this.style.styleNodes(rng);
      $(spans).css(target, value);
 
      // [workaround] added styled bogus span for style
      //  - also bogus character needed for cursor position
      Eif (rng.isCollapsed()) {
        const firstSpan = lists.head(spans);
        Eif (firstSpan && !dom.nodeLength(firstSpan)) {
          firstSpan.innerHTML = dom.ZERO_WIDTH_NBSP_CHAR;
          range.createFromNodeAfter(firstSpan.firstChild).select();
          this.$editable.data(KEY_BOGUS, firstSpan);
        }
      }
    }
  }
 
  /**
   * unlink
   *
   * @type command
   */
  unlink() {
    let rng = this.createRange();
    if (rng.isOnAnchor()) {
      const anchor = dom.ancestor(rng.sc, dom.isAnchor);
      rng = range.createFromNode(anchor);
      rng.select();
 
      this.beforeCommand();
      document.execCommand('unlink');
      this.afterCommand();
    }
  }
 
  /**
   * returns link info
   *
   * @return {Object}
   * @return {WrappedRange} return.range
   * @return {String} return.text
   * @return {Boolean} [return.isNewWindow=true]
   * @return {String} [return.url=""]
   */
  getLinkInfo() {
    const rng = this.createRange().expand(dom.isAnchor);
 
    // Get the first anchor on range(for edit).
    const $anchor = $(lists.head(rng.nodes(dom.isAnchor)));
    const linkInfo = {
      range: rng,
      text: rng.toString(),
      url: $anchor.length ? $anchor.attr('href') : ''
    };
 
    // Define isNewWindow when anchor exists.
    if ($anchor.length) {
      linkInfo.isNewWindow = $anchor.attr('target') === '_blank';
    }
 
    return linkInfo;
  }
 
  addRow(position) {
    const rng = this.createRange(this.$editable);
    if (rng.isCollapsed() && rng.isOnCell()) {
      this.beforeCommand();
      this.table.addRow(rng, position);
      this.afterCommand();
    }
  }
 
  addCol(position) {
    const rng = this.createRange(this.$editable);
    if (rng.isCollapsed() && rng.isOnCell()) {
      this.beforeCommand();
      this.table.addCol(rng, position);
      this.afterCommand();
    }
  }
 
  deleteRow() {
    const rng = this.createRange(this.$editable);
    if (rng.isCollapsed() && rng.isOnCell()) {
      this.beforeCommand();
      this.table.deleteRow(rng);
      this.afterCommand();
    }
  }
 
  deleteCol() {
    const rng = this.createRange(this.$editable);
    if (rng.isCollapsed() && rng.isOnCell()) {
      this.beforeCommand();
      this.table.deleteCol(rng);
      this.afterCommand();
    }
  }
 
  deleteTable() {
    const rng = this.createRange(this.$editable);
    if (rng.isCollapsed() && rng.isOnCell()) {
      this.beforeCommand();
      this.table.deleteTable(rng);
      this.afterCommand();
    }
  }
 
  /**
   * @param {Position} pos
   * @param {jQuery} $target - target element
   * @param {Boolean} [bKeepRatio] - keep ratio
   */
  resizeTo(pos, $target, bKeepRatio) {
    let imageSize;
    if (bKeepRatio) {
      const newRatio = pos.y / pos.x;
      const ratio = $target.data('ratio');
      imageSize = {
        width: ratio > newRatio ? pos.x : pos.y / ratio,
        height: ratio > newRatio ? pos.x * ratio : pos.y
      };
    } else {
      imageSize = {
        width: pos.x,
        height: pos.y
      };
    }
 
    $target.css(imageSize);
  }
 
  /**
   * returns whether editable area has focus or not.
   */
  hasFocus() {
    return this.$editable.is(':focus');
  }
 
  /**
   * set focus
   */
  focus() {
    // [workaround] Screen will move when page is scolled in IE.
    //  - do focus when not focused
    Eif (!this.hasFocus()) {
      this.$editable.focus();
    }
  }
 
  /**
   * returns whether contents is empty or not.
   * @return {Boolean}
   */
  isEmpty() {
    return dom.isEmpty(this.$editable[0]) || dom.emptyPara === this.$editable.html();
  }
 
  /**
   * Removes all contents and restores the editable instance to an _emptyPara_.
   */
  empty() {
    this.context.invoke('code', dom.emptyPara);
  }
 
  /**
   * normalize content
   */
  normalizeContent() {
    this.$editable[0].normalize();
  }
}