all files / model/ Editing.js

98.66% Statements 517/524
91.88% Branches 283/308
100% Functions 21/21
98.65% Lines 513/520
23 statements, 36 branches Ignored     
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 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080                                                      41× 41×         39×     39× 37× 37×       37× 37× 37× 37× 37×             37×         37×     31×     31×       19× 19× 19× 19× 19×       19×       14× 14×   13× 13×                     12×     11× 11×                                                                                                         14× 14× 14× 14× 14× 14× 14× 14×     14×                 11× 11× 11× 11×     11×                   11× 14× 14× 14×       11×                   11×             10×             23× 23× 23× 23× 23× 23× 23×                   23×       12×   12× 12×       12×                                                                                             10×       121×       121×     118×   118×   117×           76×   74× 71× 71×                                                                                                                                                                                                                                             117× 117×   117×   117× 117× 117× 117× 117×   117×     117×   117× 117× 14× 14×       14×                                                           117× 117×                     37×   37× 31×           31× 31× 31× 31×       31×                         30× 30× 30×   30×   30×   30×   29×   29×     30×   30×                                                                                                                 19×                       18× 18× 14× 13×         17× 17× 17×   13×       10× 10× 10× 10×                                                                                                    
import { isArrayEqual, isString, last, uuid } from '../util'
import annotationHelpers from './annotationHelpers'
import documentHelpers from './documentHelpers'
import { setCursor, isEntirelySelected, selectNode } from './selectionHelpers'
import paste from './paste'
 
/**
  Core editing implementation, that controls meta behavior
  such as deleting a selection, merging nodes, etc.
 
  Some of the implementation are then delegated to specific editing behaviors,
  such as manipulating content of a text-property, merging or breaking text nodes
 
  Note: this is pretty much the same what we did with transforms before.
        We decided to move this here, to switch to a stateful editor implementation (aka turtle-graphics-style)
 */
class Editing {
 
  // create an annotation for the current selection using the given data
  annotate(tx, annotation) {
    let sel = tx.selection
    let schema = tx.getSchema()
    let AnnotationClass = schema.getNodeClass(annotation.type)
    if (!AnnotationClass) throw new Error('Unknown annotation type', annotation)
    let start = sel.start
    let end = sel.end
    let containerId = sel.containerId
    let nodeData = { start, end, containerId }
    /* istanbul ignore else  */
    Eif (sel.isPropertySelection()) {
      if (!AnnotationClass.prototype._isAnnotation) {
        throw new Error('Annotation can not be created for a selection.')
      }
    } else if (sel.isContainerSelection()) {
      if (AnnotationClass.prototype._isPropertyAnnotation) {
        console.warn('NOT SUPPORTED YET: creating property annotations for a non collapsed container selection.')
      }
    }
    Object.assign(nodeData, annotation)
    return tx.create(nodeData)
  }
 
  break(tx) {
    let sel = tx.selection
    if (sel.isNodeSelection()) {
      let containerId = sel.containerId
      let container = tx.get(containerId)
      let nodeId = sel.getNodeId()
      let nodePos = container.getPosition(nodeId, 'strict')
      let textNode = tx.createDefaultTextNode()
      if (sel.isBefore()) {
        tx.update(container.getContentPath(), { type: 'insert', pos: nodePos, value: textNode.id })
        // leave selection as is
      } else {
        tx.update(container.getContentPath(), { type: 'insert', pos: nodePos+1, value: textNode.id })
        setCursor(tx, textNode, containerId, 'before')
      }
    }
    else Iif (sel.isCustomSelection()) {
      // TODO: what to do with custom selections?
    }
    else if (sel.isCollapsed() || sel.isPropertySelection()) {
      let containerId = sel.containerId
      if (!sel.isCollapsed()) {
        // delete the selection
        this._deletePropertySelection(tx, sel)
        tx.setSelection(sel.collapse('left'))
      }
      // then break the node
      Eif (containerId) {
        let container = tx.get(containerId)
        let nodeId = sel.start.path[0]
        let node = tx.get(nodeId)
        this._breakNode(tx, node, sel.start, container)
      }
    }
    else Eif (sel.isContainerSelection()) {
      let start = sel.start
      let containerId = sel.containerId
      let container = tx.get(containerId)
      let startNodeId = start.path[0]
      let nodePos = container.getPosition(startNodeId, 'strict')
      this._deleteContainerSelection(tx, sel, {noMerge: true })
      setCursor(tx, container.getNodeAt(nodePos+1), containerId, 'before')
    }
  }
 
  delete(tx, direction) {
    let sel = tx.selection
    // special implementation for node selections:
    // either delete the node (replacing with an empty text node)
    // or just move the cursor
    /* istanbul ignore else  */
    if (sel.isNodeSelection()) {
      this._deleteNodeSelection(tx, sel, direction)
    }
    // TODO: what to do with custom selections?
    else Iif (sel.isCustomSelection()) {}
    // if the selection is collapsed this is the classical one-character deletion
    // either backwards (backspace) or forward (delete)
    else if (sel.isCollapsed()) {
      // Deletion of a single character leads to a merge
      // if cursor is at a text boundary (TextNode, ListItem)
      // and direction is towards that boundary
      let path = sel.start.path
      let node = tx.get(path[0])
      let text = tx.get(path)
      let offset = sel.start.offset
      let needsMerge = (sel.containerId && (
        (offset === 0 && direction === 'left') ||
        (offset === text.length && direction === 'right')
      ))
      if (needsMerge) {
        // ATTENTION: deviation from standard implementation
        // for list items: Word and GDoc toggle a list item
        // when doing a BACKSPACE at the first position
        let root = node.getRoot()
        if (root.isList() && offset === 0 && direction === 'left') {
          return this.toggleList(tx)
        } else {
          let container = tx.get(sel.containerId)
          this._merge(tx, root, sel.start, direction, container)
        }
      } else {
        let startOffset = (direction === 'left') ? offset-1 : offset
        let endOffset = startOffset+1
        let start = { path: path, offset: startOffset }
        let end = { path: path, offset: endOffset }
        documentHelpers.deleteTextRange(tx, start, end)
        tx.setSelection({
          type: 'property',
          path: path,
          startOffset: startOffset,
          containerId: sel.containerId
        })
      }
    }
    // deleting a range of characters within a text property
    else if (sel.isPropertySelection()) {
      documentHelpers.deleteTextRange(tx, sel.start, sel.end)
      tx.setSelection(sel.collapse('left'))
    }
    // deleting a range within a container (across multiple nodes)
    else Eif (sel.isContainerSelection()) {
      this._deleteContainerSelection(tx, sel)
    }
    else {
      console.warn('Unsupported case: tx.delete(%)', direction, sel)
    }
  }
 
  _deleteNodeSelection(tx, sel, direction) {
    let nodeId = sel.getNodeId()
    let container = tx.get(sel.containerId)
    let nodePos = container.getPosition(nodeId, 'strict')
    if (sel.isFull() ||
        sel.isBefore() && direction === 'right' ||
        sel.isAfter() && direction === 'left' ) {
      // replace the node with default text node
      let contentPath = container.getContentPath()
      tx.update(contentPath, { type: 'delete', pos: nodePos })
      documentHelpers.deleteNode(tx, tx.get(nodeId))
      let newNode = tx.createDefaultTextNode()
      tx.update(contentPath, { type: 'insert', pos: nodePos, value: newNode.id })
      tx.setSelection({
        type: 'property',
        path: newNode.getTextPath(),
        startOffset: 0,
        containerId: container.id,
      })
    } else {
      /* istanbul ignore else  */
      if (sel.isBefore() && direction === 'left') {
        Eif (nodePos > 0) {
          let previous = container.getNodeAt(nodePos-1)
          if (previous.isText()) {
            tx.setSelection({
              type: 'property',
              path: previous.getTextPath(),
              startOffset: previous.getLength()
            })
            this.delete(tx, direction)
          } else {
            tx.setSelection({
              type: 'node',
              nodeId: previous.id,
              containerId: container.id
            })
          }
        } else {
          // nothing to do
        }
      } else Eif (sel.isAfter() && direction === 'right') {
        Eif (nodePos < container.getLength()-1) {
          let next = container.getNodeAt(nodePos+1)
          if (next.isText()) {
            tx.setSelection({
              type: 'property',
              path: next.getTextPath(),
              startOffset: 0
            })
            this.delete(tx, direction)
          } else {
            tx.setSelection({
              type: 'node',
              nodeId: next.id,
              containerId: container.id
            })
          }
        } else {
          // nothing to do
        }
      } else {
        console.warn('Unsupported case: delete(%s)', direction, sel)
      }
    }
  }
 
  _deletePropertySelection(tx, sel) {
    let path = sel.start.path
    let start = sel.start.offset
    let end = sel.end.offset
    tx.update(path, { type: 'delete', start: start, end: end })
    annotationHelpers.deletedText(tx, path, start, end)
  }
 
  // deletes all inner nodes and 'truncates' start and end node
  _deleteContainerSelection(tx, sel, options = {}) {
    let containerId = sel.containerId
    let container = tx.get(containerId)
    let start = sel.start
    let end = sel.end
    let startId = start.getNodeId()
    let endId = end.getNodeId()
    let startPos = container.getPosition(startId, 'strict')
    let endPos = container.getPosition(endId, 'strict')
 
    // special case: selection within one node
    if (startPos === endPos) {
      // ATTENTION: we need the root node here e.g. the list, not the list-item
      let node = tx.get(startId).getRoot()
      /* istanbul ignore else  */
      if (node.isText()) {
        documentHelpers.deleteTextRange(tx, start, end)
      } else Eif (node.isList()) {
        documentHelpers.deleteListRange(tx, node, start, end)
      } else {
        throw new Error('Not supported yet.')
      }
      tx.setSelection(sel.collapse('left'))
      return
    }
 
    // TODO: document the algorithm
 
    let firstNode = tx.get(start.getNodeId())
    let lastNode = tx.get(end.getNodeId())
    let firstEntirelySelected = isEntirelySelected(tx, firstNode, start, null)
    let lastEntirelySelected = isEntirelySelected(tx, lastNode, null, end)
 
    // delete or truncate last node
    if (lastEntirelySelected) {
      tx.update([container.id, 'nodes'], { type: 'delete', pos: endPos })
      documentHelpers.deleteNode(tx, lastNode)
    } else {
      // ATTENTION: we need the root node here e.g. the list, not the list-item
      let node = lastNode.getRoot()
      /* istanbul ignore else  */
      if (node.isText()) {
        documentHelpers.deleteTextRange(tx, null, end)
      } else Eif (node.isList()) {
        documentHelpers.deleteListRange(tx, node, null, end)
      } else {
        // IsolatedNodes can not be selected partially
      }
    }
 
    // delete inner nodes
    for (let i = endPos-1; i > startPos; i--) {
      let nodeId = container.nodes[i]
      tx.update([container.id, 'nodes'], { type: 'delete', pos: i })
      documentHelpers.deleteNode(tx, tx.get(nodeId))
    }
 
    // delete or truncate the first node
    if (firstEntirelySelected) {
      tx.update([container.id, 'nodes'], { type: 'delete', pos: startPos })
      documentHelpers.deleteNode(tx, firstNode)
    } else {
      // ATTENTION: we need the root node here e.g. the list, not the list-item
      let node = firstNode.getRoot()
      /* istanbul ignore else  */
      if (node.isText()) {
        documentHelpers.deleteTextRange(tx, start, null)
      } else Eif (node.isList()) {
        documentHelpers.deleteListRange(tx, node, start, null)
      } else {
        // IsolatedNodes can not be selected partially
      }
    }
 
    // insert a new TextNode if all has been deleted
    if (firstEntirelySelected && lastEntirelySelected) {
      // insert a new paragraph
      let textNode = tx.createDefaultTextNode()
      tx.update([container.id, 'nodes'], { type: 'insert', pos: startPos, value: textNode.id })
      tx.setSelection({
        type: 'property',
        path: textNode.getTextPath(),
        startOffset: 0,
        containerId: containerId
      })
    } else if (!firstEntirelySelected && !lastEntirelySelected) {
      if (!options.noMerge) {
        this._merge(tx, firstNode, sel.start, 'right', container)
      }
      tx.setSelection(sel.collapse('left'))
    } else if (firstEntirelySelected) {
      setCursor(tx, lastNode, container.id, 'before')
    } else {
      setCursor(tx, firstNode, container.id, 'after')
    }
  }
 
  insertInlineNode(tx, nodeData) {
    let sel = tx.selection
    let text = "\uFEFF"
    this.insertText(tx, text)
    sel = tx.selection
    let endOffset = tx.selection.end.offset
    let startOffset = endOffset - text.length
    nodeData = Object.assign({}, nodeData, {
      start: {
        path: sel.path,
        offset: startOffset
      },
      end: {
        path: sel.path,
        offset: endOffset
      }
    })
    return tx.create(nodeData)
  }
 
  insertBlockNode(tx, nodeData) {
    let sel = tx.selection
    // don't create the node if it already exists
    let blockNode
    if (!nodeData._isNode || !tx.get(nodeData.id)) {
      blockNode = tx.create(nodeData)
    } else {
      blockNode = tx.get(nodeData.id)
    }
    /* istanbul ignore else  */
    if (sel.isNodeSelection()) {
      let containerId = sel.containerId
      let container = tx.get(containerId)
      let nodeId = sel.getNodeId()
      let nodePos = container.getPosition(nodeId, 'strict')
      // insert before
      if (sel.isBefore()) {
        tx.update(container.getContentPath(), { type: 'insert', pos: nodePos, value: blockNode.id })
      }
      // insert after
      else if (sel.isAfter()) {
        tx.update(container.getContentPath(), { type: 'insert', pos: nodePos+1, value: blockNode.id })
        tx.setSelection({
          type: 'node',
          containerId: containerId,
          nodeId: blockNode.id,
          mode: 'after'
        })
      } else {
        tx.update(container.getContentPath(), { type: 'delete', pos: nodePos })
        documentHelpers.deleteNode(tx, tx.get(nodeId))
        tx.update([container.id, 'nodes'], { type: 'insert', pos: nodePos, value: blockNode.id })
        tx.setSelection({
          type: 'node',
          containerId: containerId,
          nodeId: blockNode.id,
          mode: 'after'
        })
      }
    } else if (sel.isPropertySelection()) {
      /* istanbul ignore next */
      Iif (!sel.containerId) throw new Error('insertBlockNode can only be used within a container.')
      let container = tx.get(sel.containerId)
      if (!sel.isCollapsed()) {
        this._deletePropertySelection(tx, sel)
        tx.setSelection(sel.collapse('left'))
      }
      let node = tx.get(sel.path[0])
      /* istanbul ignore next */
      Iif (!node) throw new Error('Invalid selection.')
      let nodePos = container.getPosition(node.id, 'strict')
      /* istanbul ignore else  */
      Eif (node.isText()) {
        let text = node.getText()
        // replace node
        if (text.length === 0) {
          tx.update(container.getContentPath(), { type: 'delete', pos: nodePos })
          documentHelpers.deleteNode(tx, node)
          tx.update([container.id, 'nodes'], { type: 'insert', pos: nodePos, value: blockNode.id })
          setCursor(tx, blockNode, container.id, 'after')
        }
        // insert before
        else if (sel.start.offset === 0) {
          tx.update(container.getContentPath(), { type: 'insert', pos: nodePos, value: blockNode.id })
        }
        // insert after
        else if (sel.start.offset === text.length) {
          tx.update(container.getContentPath(), { type: 'insert', pos: nodePos+1, value: blockNode.id })
          setCursor(tx, blockNode, container.id, 'before')
        }
        // break
        else {
          this.break(tx)
          tx.update(container.getContentPath(), { type: 'insert', pos: nodePos+1, value: blockNode.id })
          setCursor(tx, blockNode, container.id, 'after')
        }
      } else {
        console.error('Not supported: insertBlockNode() on a custom node')
      }
    } else Eif (sel.isContainerSelection()) {
      if (sel.isCollapsed()) {
        let start = sel.start
        /* istanbul ignore else  */
        Eif (start.isPropertyCoordinate()) {
          tx.setSelection({
            type: 'property',
            path: start.path,
            startOffset: start.offset,
            containerId: sel.containerId,
          })
        } else if (start.isNodeCoordinate()) {
          tx.setSelection({
            type: 'node',
            containerId: sel.containerId,
            nodeId: start.path[0],
            mode: start.offset === 0 ? 'before' : 'after',
          })
        } else {
          throw new Error('Unsupported selection for insertBlockNode')
        }
        return this.insertBlockNode(tx, blockNode)
      } else {
        this.break(tx)
        return this.insertBlockNode(tx, blockNode)
      }
    }
    return blockNode
  }
 
  insertText(tx, text) {
    let sel = tx.selection
    // type over a selected node or insert a paragraph before
    // or after
    /* istanbul ignore else  */
    if (sel.isNodeSelection()) {
      let containerId = sel.containerId
      let container = tx.get(containerId)
      let nodeId = sel.getNodeId()
      let nodePos = container.getPosition(nodeId, 'strict')
      let textNode = tx.createDefaultTextNode(text)
      if (sel.isBefore()) {
        container.show(textNode, nodePos)
      } else if (sel.isAfter()) {
        container.show(textNode, nodePos+1)
      } else {
        container.hide(nodeId)
        documentHelpers.deleteNode(tx, tx.get(nodeId))
        container.show(textNode, nodePos)
      }
      setCursor(tx, textNode, sel.containerId, 'after')
    } else Iif (sel.isCustomSelection()) {
      // TODO: what to do with custom selections?
    } else if (sel.isCollapsed() || sel.isPropertySelection()) {
      // console.log('#### before', sel.toString())
      this._insertText(tx, sel, text)
      // console.log('### setting selection after typing: ', tx.selection.toString())
    } else Eif (sel.isContainerSelection()) {
      this._deleteContainerSelection(tx, sel)
      this.insertText(tx, text)
    }
  }
 
  paste(tx, content) {
    if (!content) return
    /* istanbul ignore else  */
    if (isString(content)) {
      paste(tx, {text: content})
    } else Eif (content._isDocument) {
      paste(tx, {doc: content})
    } else {
      throw new Error('Illegal content for paste.')
    }
  }
 
  /**
    Switch text type for a given node. E.g. from `paragraph` to `heading`.
 
    @param {Object} args object with `selection`, `containerId` and `data` with new node data
    @return {Object} object with updated `selection`
 
    @example
 
    ```js
    switchTextType(tx, {
      selection: bodyEditor.getSelection(),
      containerId: bodyEditor.getContainerId(),
      data: {
        type: 'heading',
        level: 2
      }
    })
    ```
  */
  switchTextType(tx, data) {
    let sel = tx.selection
    /* istanbul ignore next */
    Iif (!sel.isPropertySelection()) {
      throw new Error("Selection must be a PropertySelection.")
    }
    let containerId = sel.containerId
    /* istanbul ignore next */
    Iif (!containerId) {
      throw new Error("Selection must be within a container.")
    }
    let path = sel.path
    let nodeId = path[0]
    let node = tx.get(nodeId)
    /* istanbul ignore next */
    Iif (!(node.isInstanceOf('text'))) {
      throw new Error('Trying to use switchTextType on a non text node.')
    }
    // create a new node and transfer annotations
    let newNode = Object.assign({
      id: uuid(data.type),
      type: data.type,
      content: node.content,
      direction: node.direction
    }, data)
    let newPath = [newNode.id, 'content']
    newNode = tx.create(newNode)
    annotationHelpers.transferAnnotations(tx, path, 0, newPath, 0)
 
    // hide and delete the old one, show the new node
    let container = tx.get(sel.containerId)
    let pos = container.getPosition(nodeId, 'strict')
    container.hide(nodeId)
    documentHelpers.deleteNode(tx, node)
    container.show(newNode.id, pos)
 
    tx.setSelection({
      type: 'property',
      path: newPath,
      startOffset: sel.start.offset,
      endOffset: sel.end.offset,
      containerId: containerId
    })
 
    return newNode
  }
 
  toggleList(tx, params) {
    let sel = tx.selection
    let container = tx.get(sel.containerId)
    /* istanbul ignore next */
    Iif (!container) {
      throw new Error("Selection must be within a container.")
    }
    Eif (sel.isPropertySelection()) {
      let nodeId = sel.start.path[0]
      // ATTENTION: we need the root node here e.g. the list, not the list-item
      let node = tx.get(nodeId).getRoot()
      let nodePos = container.getPosition(node.id, 'strict')
      /* istanbul ignore else  */
      if (node.isText()) {
        tx.update([container.id, 'nodes'], { type: 'delete', pos: nodePos })
        // TODO: what if this should create a different list-item type?
        let newItem = tx.create({
          type: 'list-item',
          content: node.getText(),
        })
        annotationHelpers.transferAnnotations(tx, node.getTextPath(), 0, newItem.getTextPath(), 0)
        let newList = tx.create(Object.assign({
          type: 'list',
          items: [newItem.id]
        }, params))
        documentHelpers.deleteNode(tx, node)
        tx.update([container.id, 'nodes'], { type: 'insert', pos: nodePos, value: newList.id })
        tx.setSelection({
          type: 'property',
          path: newItem.getTextPath(),
          startOffset: sel.start.offset,
          containerId: sel.containerId
        })
      } else Eif (node.isList()) {
        let itemId = sel.start.path[0]
        let itemPos = node.getItemPosition(itemId)
        let item = node.getItemAt(itemPos)
        let newTextNode = tx.createDefaultTextNode(item.getText())
        annotationHelpers.transferAnnotations(tx, item.getTextPath(), 0, newTextNode.getTextPath(), 0)
        // take the item out of the list
        node.removeItemAt(itemPos)
        if (node.isEmpty()) {
          tx.update([container.id, 'nodes'], { type: 'delete', pos: nodePos })
          documentHelpers.deleteNode(tx, node)
          tx.update([container.id, 'nodes'], { type: 'insert', pos: nodePos, value: newTextNode.id })
        } else if (itemPos === 0) {
          tx.update([container.id, 'nodes'], { type: 'insert', pos: nodePos, value: newTextNode.id })
        } else if (node.getLength() <= itemPos){
          tx.update([container.id, 'nodes'], { type: 'insert', pos: nodePos+1, value: newTextNode.id })
        } else {
          //split the
          let tail = []
          const items = node.items.slice()
          const L = items.length
          for (let i = L-1; i >= itemPos; i--) {
            tail.unshift(items[i])
            node.removeItemAt(i)
          }
          let newList = tx.create({
            type: 'list',
            items: tail,
            ordered: node.ordered
          })
          tx.update([container.id, 'nodes'], { type: 'insert', pos: nodePos+1, value: newTextNode.id })
          tx.update([container.id, 'nodes'], { type: 'insert', pos: nodePos+2, value: newList.id })
        }
        tx.setSelection({
          type: 'property',
          path: newTextNode.getTextPath(),
          startOffset: sel.start.offset,
          containerId: sel.containerId
        })
      } else {
        // unsupported node type
      }
    } else if (sel.isContainerSelection()) {
      console.error('TODO: support toggleList with ContainerSelection')
    }
  }
 
  indent(tx) {
    let sel = tx.selection
    Eif (sel.isPropertySelection()) {
      let nodeId = sel.start.getNodeId()
      // ATTENTION: we need the root node here, e.g. the list, not the list items
      let node = tx.get(nodeId).getRoot()
      Eif (node.isList()) {
        let itemId = sel.start.path[0]
        let item = tx.get(itemId)
        // Note: allowing only 3 levels
        Eif (item && item.level<3) {
          tx.set([itemId, 'level'], item.level+1)
        }
      }
    } else if (sel.isContainerSelection()) {
      console.error('TODO: support toggleList with ContainerSelection')
    }
  }
 
  dedent(tx) {
    let sel = tx.selection
    Eif (sel.isPropertySelection()) {
      let nodeId = sel.start.getNodeId()
      // ATTENTION: we need the root node here, e.g. the list, not the list items
      let node = tx.get(nodeId).getRoot()
      Eif (node.isList()) {
        let itemId = sel.start.path[0]
        let item = tx.get(itemId)
        Eif (item && item.level>1) {
          tx.set([itemId, 'level'], item.level-1)
        }
      }
    } else if (sel.isContainerSelection()) {
      console.error('TODO: support toggleList with ContainerSelection')
    }
  }
 
  /*
    <-->: anno
    |--|: area of change
    I: <--> |--|     :   nothing
    II: |--| <-->    :   move both by total span+L
    III: |-<-->-|    :   delete anno
    IV: |-<-|->      :   move start by diff to start+L, and end by total span+L
    V: <-|->-|       :   move end by diff to start+L
    VI: <-->|--|     :   noting if !anno.autoExpandRight
    VII: <-|--|->    :   move end by total span+L
  */
  _insertText(tx, sel, text) {
    let start = sel.start
    let end = sel.end
    /* istanbul ignore next  */
    Iif (!isArrayEqual(start.path, end.path)) {
      throw new Error('Unsupported state: range should be on one property')
    }
    let path = start.path
    let startOffset = start.offset
    let endOffset = end.offset
    let typeover = !sel.isCollapsed()
    let L = text.length
    // delete selected text
    if (typeover) {
      tx.update(path, { type: 'delete', start: startOffset, end: endOffset })
    }
    // insert new text
    tx.update(path, { type: 'insert', start: startOffset, text: text })
    // update annotations
    let annos = tx.getAnnotations(path)
    annos.forEach(function(anno) {
      let annoStart = anno.start.offset
      let annoEnd = anno.end.offset
 
      /* istanbul ignore else  */
      // I anno is before
      if (annoEnd<startOffset) {
        return
      }
      // II anno is after
      else if (annoStart>=endOffset) {
        tx.update([anno.id, 'start'], { type: 'shift', value: startOffset-endOffset+L })
        tx.update([anno.id, 'end'], { type: 'shift', value: startOffset-endOffset+L })
      }
      // III anno is deleted
      // NOTE: InlineNodes only have a length of one character
      // so they are always 'covered', and as they can not expand
      // they are deleted
      else if (
        (annoStart>=startOffset && annoEnd<endOffset) ||
        (anno._isInlineNode && annoStart>=startOffset && annoEnd<=endOffset)
      ) {
        tx.delete(anno.id)
      }
      // IV anno.start between and anno.end after
      else if (annoStart>=startOffset && annoEnd>=endOffset) {
        // do not move start if typing over
        Iif (annoStart>startOffset || !typeover) {
          tx.update([anno.id, 'start'], { type: 'shift', value: startOffset-annoStart+L })
        }
        tx.update([anno.id, 'end'], { type: 'shift', value: startOffset-endOffset+L })
      }
      // V anno.start before and anno.end between
      else Iif (annoStart<startOffset && annoEnd<endOffset) {
        // NOTE: here the anno gets expanded (that's the common way)
        tx.update([anno.id, 'end'], { type: 'shift', value: startOffset-annoEnd+L })
      }
      // VI
      else Iif (annoEnd === startOffset && !anno.constructor.autoExpandRight) {
          // skip
      }
      // VII anno.start before and anno.end after
      else Eif (annoStart<startOffset && annoEnd>=endOffset) {
        if (anno._isInlineNode) {
          // skip
        } else {
          tx.update([anno.id, 'end'], { type: 'shift', value: startOffset-endOffset+L })
        }
      }
      else {
        console.warn('TODO: handle annotation update case.')
      }
    })
    let offset = startOffset + text.length
    tx.setSelection({
      type: 'property',
      path: start.path,
      startOffset: offset,
      containerId: sel.containerId,
      surfaceId: sel.surfaceId
    })
  }
 
  _breakNode(tx, node, coor, container) {
    // ATTENTION: we need the root here, e.g. a list, not the list-item
    node = node.getRoot()
    /* istanbul ignore else  */
    if (node.isText()) {
      this._breakTextNode(tx, node, coor, container)
    } else Eif (node.isList()) {
      this._breakListNode(tx, node, coor, container)
    } else {
      throw new Error('Not supported')
    }
  }
 
  _breakTextNode(tx, node, coor, container) {
    let path = coor.path
    let offset = coor.offset
    let nodePos = container.getPosition(node.id, 'strict')
    let text = node.getText()
 
    // when breaking at the first position, a new node of the same
    // type will be inserted.
    if (offset === 0) {
      let newNode = tx.create({
        type: node.type,
        content: ""
      })
      // show the new node
      container.show(newNode.id, nodePos)
      tx.setSelection({
        type: 'property',
        path: path,
        startOffset: 0,
        containerId: container.id
      })
    }
    // otherwise split the text property and create a new paragraph node with trailing text and annotations transferred
    else {
      let newNode = node.toJSON()
      delete newNode.id
      newNode.content = text.substring(offset)
      // if at the end insert a default text node no matter in which text node we are
      if (offset === text.length) {
        newNode.type = tx.getSchema().getDefaultTextType()
      }
      newNode = tx.create(newNode)
      // Now we need to transfer annotations
      if (offset < text.length) {
        // transfer annotations which are after offset to the new node
        annotationHelpers.transferAnnotations(tx, path, offset, newNode.getTextPath(), 0)
        // truncate the original property
        tx.update(path, { type: 'delete', start: offset, end: text.length })
      }
      // show the new node
      container.show(newNode.id, nodePos+1)
      // update the selection
      tx.setSelection({
        type: 'property',
        path: newNode.getTextPath(),
        startOffset: 0,
        containerId: container.id
      })
    }
  }
 
  _breakListNode(tx, node, coor, container) {
    let path = coor.path
    let offset = coor.offset
    let listItem = tx.get(path[0])
 
    let L = node.length
    let itemPos = node.getItemPosition(listItem.id)
    let text = listItem.getText()
    let newItem = listItem.toJSON()
    delete newItem.id
    if (offset === 0) {
      // if breaking at an empty list item, then the list is split into two
      if (!text) {
        // if it is the first or last item, a default text node is inserted before or after, and the item is removed
        // if the list has only one element, it is removed
        let nodePos = container.getPosition(node.id, 'strict')
        let newTextNode = tx.createDefaultTextNode()
        // if the list is empty, replace it with a paragraph
        if (L < 2) {
          container.hide(node.id)
          documentHelpers.deleteNode(tx, node)
          container.show(newTextNode.id, nodePos)
        }
        // if at the first list item, remove the item
        else if (itemPos === 0) {
          node.remove(listItem.id)
          documentHelpers.deleteNode(tx, listItem)
          container.show(newTextNode.id, nodePos)
        }
        // if at the last list item, remove the item and append the paragraph
        else if (itemPos >= L-1) {
          node.remove(listItem.id)
          documentHelpers.deleteNode(tx, listItem)
          container.show(newTextNode.id, nodePos+1)
        }
        // otherwise create a new list
        else {
          let tail = []
          const items = node.items.slice()
          for (let i = L-1; i > itemPos; i--) {
            tail.unshift(items[i])
            node.remove(items[i])
          }
          node.remove(items[itemPos])
          let newList = tx.create({
            type: 'list',
            items: tail,
            ordered: node.ordered
          })
          container.show(newTextNode.id, nodePos+1)
          container.show(newList.id, nodePos+2)
        }
        tx.setSelection({
          type: 'property',
          path: newTextNode.getTextPath(),
          startOffset: 0
        })
      }
      // insert a new paragraph above the current one
      else {
        newItem.content = ""
        newItem = tx.create(newItem)
        node.insertItemAt(itemPos, newItem.id)
        tx.setSelection({
          type: 'property',
          path: listItem.getTextPath(),
          startOffset: 0
        })
      }
    }
    // otherwise split the text property and create a new paragraph node with trailing text and annotations transferred
    else {
      newItem.content = text.substring(offset)
      newItem = tx.create(newItem)
      // Now we need to transfer annotations
      Eif (offset < text.length) {
        // transfer annotations which are after offset to the new node
        annotationHelpers.transferAnnotations(tx, path, offset, [newItem.id,'content'], 0)
        // truncate the original property
        tx.update(path, { type: 'delete', start: offset, end: text.length })
      }
      node.insertItemAt(itemPos+1, newItem.id)
      tx.setSelection({
        type: 'property',
        path: newItem.getTextPath(),
        startOffset: 0
      })
    }
  }
 
  _merge(tx, node, coor, direction, container) {
    // detect cases where list items get merged
    // within a single list node
    if (node.isList()) {
      let list = node
      let itemId = coor.path[0]
      let itemPos = list.getItemPosition(itemId)
      let withinListNode = (
        (direction === 'left' && itemPos > 0) ||
        (direction === 'right' && itemPos<list.items.length-1)
      )
      if (withinListNode) {
        itemPos = (direction === 'left') ? itemPos-1 : itemPos
        let target = list.getItemAt(itemPos)
        let targetLength = target.getLength()
        documentHelpers.mergeListItems(tx, list.id, itemPos)
        tx.setSelection({
          type: 'property',
          path: target.getTextPath(),
          startOffset: targetLength,
          containerId: container.id
        })
        return
      }
    }
    // in all other cases merge is done across node boundaries
    let nodePos = container.getPosition(node, 'strict')
    if (direction === 'left' && nodePos > 0) {
      this._mergeNodes(tx, container, nodePos-1, direction)
    } else if (direction === 'right' && nodePos<container.getLength()-1) {
      this._mergeNodes(tx, container, nodePos, direction)
    }
  }
 
  _mergeNodes(tx, container, pos, direction) {
    let first = container.getChildAt(pos)
    let second = container.getChildAt(pos+1)
    if (first.isText()) {
      // Simplification for empty nodes
      if (first.isEmpty()) {
        container.hide(first.id)
        documentHelpers.deleteNode(tx, first)
        // TODO: need to clear where to handle
        // selections ... probably better not to do it here
        setCursor(tx, second, container.id, 'before')
        return
      }
      let target = first
      let targetPath = target.getTextPath()
      let targetLength = target.getLength()
      if (second.isText()) {
        let source = second
        let sourcePath = source.getTextPath()
        container.hide(source.id)
        // append the text
        tx.update(targetPath, { type: 'insert', start: targetLength, text: source.getText() })
        // transfer annotations
        annotationHelpers.transferAnnotations(tx, sourcePath, 0, targetPath, targetLength)
        documentHelpers.deleteNode(tx, source)
        tx.setSelection({
          type: 'property',
          path: targetPath,
          startOffset: targetLength,
          containerId: container.id
        })
      } else if (second.isList()) {
        let list = second
        if (!second.isEmpty()) {
          let source = list.getFirstItem()
          let sourcePath = source.getTextPath()
          // remove merged item from list
          list.removeItemAt(0)
          // append the text
          tx.update(targetPath, { type: 'insert', start: targetLength, text: source.getText() })
          // transfer annotations
          annotationHelpers.transferAnnotations(tx, sourcePath, 0, targetPath, targetLength)
          // delete item and prune empty list
          documentHelpers.deleteNode(tx, source)
        }
        if (list.isEmpty()) {
          container.hide(list.id)
          documentHelpers.deleteNode(tx, list)
        }
        tx.setSelection({
          type: 'property',
          path: targetPath,
          startOffset: targetLength,
          containerId: container.id
        })
      } else {
        selectNode(tx, direction === 'left' ? first.id : second.id, container.id)
      }
    } else if (first.isList()) {
      if (second.isText()) {
        let source = second
        let sourcePath = source.getTextPath()
        let target = first.getLastItem()
        let targetPath = target.getTextPath()
        let targetLength = target.getLength()
        // hide source
        container.hide(source.id)
        // append the text
        tx.update(targetPath, { type: 'insert', start: targetLength, text: source.getText() })
        // transfer annotations
        annotationHelpers.transferAnnotations(tx, sourcePath, 0, targetPath, targetLength)
        documentHelpers.deleteNode(tx, source)
        tx.setSelection({
          type: 'property',
          path: target.getTextPath(),
          startOffset: targetLength,
          containerId: container.id
        })
      } else Eif (second.isList()) {
        /* istanbul ignore next */
        Iif (direction !== 'right') {
          // ATTENTION: merging two lists by using BACKSPACE is not possible,
          // as BACKSPACE will first turn the list into a paragraph
          throw new Error('Illegal state')
        }
        container.hide(second.id)
        let firstItems = first.items.slice()
        let secondItems = second.items.slice()
        for (let i=0; i<secondItems.length;i++) {
          second.removeItemAt(0)
          first.appendItem(secondItems[i])
        }
        documentHelpers.deleteNode(tx, second)
        let item = tx.get(last(firstItems))
        tx.setSelection({
          type: 'property',
          path: item.getTextPath(),
          startOffset: item.getLength(),
          containerId: container.id
        })
      } else {
        selectNode(tx, direction === 'left' ? first.id : second.id, container.id)
      }
    } else {
      if (second.isText() && second.isEmpty()) {
        container.hide(second.id)
        documentHelpers.deleteNode(tx, second)
        setCursor(tx, first, container.id, 'after')
      } else {
        selectNode(tx, direction === 'left' ? first.id : second.id, container.id)
      }
    }
  }
}
 
export default Editing