All files / src/pwk/content branch_node.js

90.66% Statements 447/493
84.72% Branches 233/275
75% Functions 48/64
90.86% Lines 418/460

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389                                                      1x   1x 1x 1x 1x 1x 1x                     574x             574x             574x             574x             574x     574x               465x 465x 465x                   465x   465x   465x 1395x   1395x 753x       465x                 574x 2672x                     833x 2104x                     467x 467x 467x   467x                   117x                   15728x 15728x 95555x     15728x                                                   3175x 3175x   3175x 1476x 1476x 1476x 1476x   1699x 1699x     3175x   3175x                 28x     28x   30x 30x 25x     3x                               6x   6x 6x   6x 14x 14x   10x 10x 10x 10x 10x 10x     10x 7x 7x   7x     10x                                                                 2x   2x 2x 2x   2x 5x 5x 5x 5x 5x   5x 31x 31x 31x   31x 16x 16x 16x   16x       5x 5x                             8122x 8122x 8122x 8122x 8122x     8122x 50637x 50637x 50637x 50637x 50637x   50637x 50556x 50556x 50556x   50556x 42434x 127302x 1x   127301x       8122x 8122x       50637x     8122x               7120x                                           15x 15x 37x       15x       15x                       58x   58x 192x 192x     58x                                                                                                           14x   14x 14x   14x 33x   33x 33x   33x 14x 14x     19x                         114x     114x 114x 114x             114x 341x   341x 341x 341x 341x 341x   341x 267x 267x 267x 267x   267x 114x 114x                     341x     114x 114x 114x         114x             169x 48x 48x 48x   48x 134x     48x                 80x               9x   9x                   1x 1x   1x   1x 1x 1x     1x                   7x     7x 4x 4x   3x 3x     7x 7x 7x   7x 14x 14x 14x 14x 14x   14x 12x     14x                       203x 203x 203x 203x 203x 203x 203x 203x 203x 203x 203x   203x 1101x 1101x 1101x 1101x 1101x   1101x 1100x     1101x     203x                   28x 28x     28x     50x 48x   48x 34x     48x   2x       28x                       237x 237x   237x 236x 236x   236x 505x   505x 505x   505x 236x 236x 236x       236x 236x     269x       237x                     2x 2x   2x 2x 2x   2x 3x   3x 3x   3x 2x 2x     1x         2x 2x 2x 2x     2x                                                                                                   1x 1x 1x                   1x 1x 1x                   1x   1x 2x     1x                     1x 1x         1x 2x     2x 1x       1x 1x     1x 1x       1x 1x         1x                         1x 1x 1x       1x   2x 1x     1x 1x     1x 1x 1x       1x 1x 1x           1x                 28x 28x           28x                             7x 7x 7x 7x 7x       7x 7x 13x   13x 13x   13x 7x 3x     3x 3x         3x     3x   4x   7x     6x 6x           7x 2x       7x 5x     7x                           7x 7x 7x 7x 7x       7x 7x 11x   11x 11x   11x 7x 3x     3x 3x         3x     3x   4x   7x     4x 4x           7x 2x       7x 4x     7x                           5x 5x 5x 5x   5x 5x 7x   7x 7x       7x 2x 2x         5x           5x 3x   3x     2x         5x 4x     5x                       5x 5x 5x 5x 5x         5x 8x 8x 8x   8x   5x 3x 1x   2x       5x     5x 5x     5x                   53352x                                                                 7x   7x 12x 4x   8x       7x                                                                                                                                           123x 123x 123x   123x 435x 435x 435x 435x 435x 435x     435x 379x 379x 379x     435x                 1x 1x                   1x  
/**
 * @fileoverview A node with at least one child. The main different to leaf node
 * that branch node does not contain content and have different rule for
 * offsets calculation.
 *
 * Offset calculated by the following rule:
 *  - offsets related to the first (index: 0) node remaining unmodified
 *  - offsets starts from the second node calculated by following formula:
 *    {sum of all lengths of children} + {count of children nodes} - 1;
 * This is necessary for the correct way to distinguish between the end and
 * the beginning of the child nodes.
 * @author Dmytro Antonenko <dmitry.antonenko@pubwebkit.com>
 */
import {APPLICABLE_AREA, BaseNodeStyle} from '../style/node/base_node_style.js';
import {BranchNodeModel, NodeStylesModel} from '../typedefs.js';
import {ContentRenderingReadyEvent} from './content_rendering_ready_event.js';
import {Content} from './content.js';
import {DEFAULT_WIDTH_VALUE} from '../style/node/width_node_style.js';
import {DIRECTIONS, GRANULARITY} from '../base.js';
import {NodeOffsetInfo} from '../range/node_offset_info.js';
import {NodeRange} from '../range/node_range.js';
import {Node} from './node.js';
import {RangeOffset} from '../range/range_offset.js';
import {Range} from '../range/range.js';
import {RuntimeTextStylesConfiguration} from '../text/runtime_text_styles_configuration.js';
import {env} from '../env.js';
 
goog.declareModuleId('pwk.content.BranchNode');
 
const GRange = goog.require('goog.math.Range');
const object = goog.require('goog.object');
const style = goog.require('goog.style');
const {NodeStyle} = goog.requireType('pwk.style.node.NodeStyle');
const {TextStyle} = goog.requireType('pwk.style.text.TextStyle');
const {OffsetWordInfo} = goog.requireType('pwk.content.types.OffsetWordInfo');
 
/**
 * @extends {Node}
 */
export class BranchNode extends Node {
  /**
   * @param {!Array<!BranchNode|!Node>=} opt_nodes Inner nodes.
   * @param {?NodeStylesModel=} opt_nodeStyles Optional branch node level styles.
   */
  constructor(opt_nodes, opt_nodeStyles) {
    super();
 
    /**
     * Inner nodes.
     * @const {!Array<!Node>}
     * @private
     */
    this.nodes_ = opt_nodes || [];
 
    /**
     * Node level styles.
     * @type {?NodeStylesModel|undefined}
     * @private
     */
    this.nodeStyles_ = opt_nodeStyles;
 
    /**
     * Node selection range information.
     * @type {?NodeRange}
     * @private
     */
    this.selectionRange_ = null;
 
    /**
     * Runtime text styles configuration.
     * @const {!RuntimeTextStylesConfiguration}
     * @private
     */
    this.runtimeTextStylesConfiguration_ = RuntimeTextStylesConfiguration.getInstance();
 
    // Perform initial component initialization.
    this.initialize_();
  }
 
  /** @override */
  enterDocument() {
    // Initialize and apply node styles to component element. We need to initialize node styles here,
    // because sometimes we need parent component information, check List.proto.initializeNodeStyles_(nodeStyles)
    // implementation as example
    this.nodeStyles_ = this.initializeNodeStyles_(this.nodeStyles_);
    this.applyNodeStyles_();
    super.enterDocument();
  }
 
  /**
   * Initializes node styles model. Sets default configuration for styles without configurations.
   * @param {?NodeStylesModel|?Object|undefined} model
   * @return {!NodeStylesModel}
   * @protected
   */
  initializeNodeStyles_(model) {
    model = model || {};
    /** @type {!Object<string, !BaseNodeStyle>} */
    const nodeStyles = env['nodeStyles'];
 
    for (let nodeStyle in nodeStyles) {
      const area = APPLICABLE_AREA.BRANCH_NODE;
 
      if (!model.hasOwnProperty(nodeStyle) && nodeStyles[nodeStyle].applicableFor().has(area)) {
        model[nodeStyle] = nodeStyles[nodeStyle].getDefaultConfiguration(area, this.getNodeType());
      }
    }
 
    return /** @type {!NodeStylesModel} */ (model);
  }
 
  /**
   * Initialize branch node component.
   * @private
   */
  initialize_() {
    // Add all nodes as child.
    this.nodes_.forEach(node => {
      this.addChild(node, true);
    });
  }
 
  /**
   * (Re-)Render child nodes. Call if you have updated a branch node and need to update child components to match the
   * updated element.
   * @protected
   * @override
   */
  renderContent() {
    this.forEachChild((child) => {
      child.renderContent();
    });
  }
 
  /**
   * Sets leaf and parent branch nodes styles
   * @param {!Element=} opt_element Optional element to apply styles
   * @protected
   */
  applyNodeStyles_(opt_element) {
    // TODO: Add check if styles already set, then avoid update
    const element = opt_element || this.getElement();
    if (element) {
      const nodeStyles = BaseNodeStyle.getStylesheetsMapFor(
          env['nodeStyles'], this.getBranchNodeStyles(), APPLICABLE_AREA.BRANCH_NODE, this.getNodeType());
      style.setStyle(element, nodeStyles);
    }
  }
 
  /**
   * Gets component default css class.
   * @return {string} Base CSS class for this component.
   * @override
   */
  getCssClass() {
    return BranchNode.CSS_CLASS;
  }
 
  /**
   * Gets node content length. The length calculation follows the offset rules
   * for branch nodes.
   * @return {number}
   * @override
   */
  getLength() {
    let length = 0;
    this.forEachChild((child) => {
      length += child.getLength();
    });
 
    return length + Math.max(this.getChildCount() - 1, 0);
  }
 
  /**
   * Gets content height.
   * @return {number}
   * @override
   */
  getHeight() {
    let height = 0;
 
    this.forEachChild((child) => {
      height += child.getHeight();
    });
 
    // TODO: Add branch styles check, which node affect height
 
    return height;
  }
 
  /**
   * Gets component width in pixels.
   * @return {number}
   * @override
   */
  getWidth() {
    let width = 0;
    const parent = /** @type {!BranchNode|null} */(this.getParent());
 
    if (parent instanceof BranchNode) {
      const parentWidth = parent.getBranchNodeStyles().width;
      const parentIndent = parent.getBranchNodeStyles().indent ?? 0;
      width += parentWidth !== DEFAULT_WIDTH_VALUE ? /** @type {number} */(parentWidth) : parent.getWidth();
      width -= parentIndent;
    } else {
      const documentSettings = this.runtimeTextStylesConfiguration_.getDocumentSettings();
      width += documentSettings?.getPageWidthPixel() ?? 0;
    }
 
    width -= this.getNodeStyles().indent ?? 0;
 
    return width;
  }
 
  /**
   * Indicates whether any content in this node.
   * @return {boolean}
   * @override
   */
  hasContent() {
    const length = this.getChildCount();
    let loopChild;
 
    for (let i = 0; i < length; i++) {
 
      loopChild = this.getChildNodeAt(i);
      if (loopChild.hasContent()) {
        return true;
      }
    }
    return false;
  }
 
  /**
   * Apply text style for content in offset and re-render node content.
   * @param {!TextStyle} textStyle Text style name.
   * @param {!Object<string, !Object>} configuration Configuration object.
   * @param {number=} opt_startOffset Optional zero-based offset where to apply
   *    text formatting. If opt_startOffset is omitted, the style will be
   *    applied from the start of the node content.
   * @param {number=} opt_endOffset Optional zero-based offset where to apply
   *    text formatting. If opt_endOffset is omitted, the style will be applied
   *    to the end of the node content.
   * @override
   */
  applyTextStyle(textStyle, configuration, opt_startOffset = 0, opt_endOffset = this.getLength()) {
    Iif (opt_startOffset === opt_endOffset) { return; }
 
    let loopOffset = 0;
    let childCount = this.getChildCount();
 
    for (let i = 0; i < childCount; i++) {
      if (i > 0) { loopOffset++; }
      if (loopOffset > opt_endOffset) { break; }
 
      let loopNode = this.getChildNodeAt(i);
      let loopNodeLength = loopNode.getLength();
      let endLoopOffset = loopOffset + loopNodeLength;
      let isStartOffsetInRange = opt_startOffset >= loopOffset && opt_startOffset < endLoopOffset;
      let isEndOffsetInRange = opt_endOffset > loopOffset && opt_endOffset <= endLoopOffset;
      let isInRange = opt_startOffset < loopOffset && opt_endOffset > endLoopOffset;
 
      // If the offsets are in the range of the current node
      if (isStartOffsetInRange || isEndOffsetInRange || isInRange) {
        let startOffset = isStartOffsetInRange ? opt_startOffset - loopOffset : 0;
        let endOffset = isEndOffsetInRange ? opt_endOffset - loopOffset : loopNodeLength;
 
        loopNode.applyTextStyle(textStyle, configuration, startOffset, endOffset);
      }
 
      loopOffset += loopNodeLength;
    }
  }
 
  /**
   * Clears text styles in the specific offset.
   * @param {!TextStyle} textStyle Text style name.
   * @param {number=} opt_startOffset Optional zero-based offset where to apply
   *    text formatting. If opt_startOffset is omitted, the style will be
   *    applied from the start of the node content.
   * @param {number=} opt_endOffset Optional zero-based offset where to apply
   *    text formatting. If opt_endOffset is omitted, the style will be applied
   *    to the end of the node content.
   * @override
   */
  clearTextStyles(textStyle, opt_startOffset, opt_endOffset) {
    this.forEachChildInOffset((child, start, end) => {
      child.clearTextStyles(textStyle, start, end);
    }, true, opt_startOffset, opt_endOffset);
  }
 
  /**
   * Apply text styles for content in given offsets and re-render node content.
   * The styles will be applied in the order provided in the array.
   * @param {!Array<{
   *          textStyle: !TextStyle,
   *          configuration: !Object<string, !Object>,
   *          startOffset: number,
   *          endOffset: number
   *        }>} styles
   * @override
   */
  applyTextStyles(styles) {
    const stylesLength = styles.length;
 
    if (stylesLength > 0) {
      let loopStartOffset = 0;
      let childCount = this.getChildCount();
 
      for (let i = 0; i < childCount; i++) {
        if (i > 0) { loopStartOffset++; }
        let child = this.getChildNodeAt(i);
        let loopEndOffset = loopStartOffset + child.getLength();
        let loopRange = new GRange(loopStartOffset, loopEndOffset);
        let loopStyles = [];
 
        for (let i = 0; i < stylesLength; i++) {
          let style = styles[i];
          let styleRange = new GRange(style.startOffset, style.endOffset);
          let intersection = GRange.intersection(styleRange, loopRange);
 
          if (intersection != null && intersection.start !== intersection.end) {
            let styleCopy = object.unsafeClone(style);
            styleCopy.startOffset = intersection.start - loopStartOffset;
            styleCopy.endOffset = intersection.end - loopStartOffset;
 
            loopStyles.push(styleCopy);
          }
        }
 
        child.applyTextStyles(loopStyles);
        loopStartOffset = loopEndOffset;
      }
    }
  }
 
  /**
   * Gets node styles in offset. This method returns the same information as
   * {@link Content#getNodeStyles}, but required to get aggregated node styles for complex nodes
   * like {@link BranchNode}
   * @param {number=} opt_startOffset Optional zero-based offset at which to begin extraction.
   * @param {number=} opt_endOffset Optional zero-based offset before which to end extraction.
   * @return {!NodeStylesModel}
   * @override
   */
  getNodeStyles(opt_startOffset = 0, opt_endOffset = this.getLength()) {
    const childCount = this.getChildCount();
    const extractionRange = new GRange(opt_startOffset, opt_endOffset);
    let loopStartOffset = 0;
    let /** !NodeStylesModel|!Object */ nodeStyles = new NodeStylesModel();
    let initialized = false;
    let loopStyles;
 
    for (let i = 0; i < childCount && loopStartOffset <= opt_endOffset; i++) {
      if (i > 0) { loopStartOffset++; }
      let child = this.getChildNodeAt(i);
      let loopEndOffset = loopStartOffset + child.getLength();
      let loopRange = new GRange(loopStartOffset, loopEndOffset);
      let intersection = GRange.intersection(extractionRange, loopRange);
 
      if (intersection != null) {
        const start = intersection.start - loopStartOffset;
        const end = intersection.end - loopStartOffset;
        loopStyles = /** @type {!Object} */ (child.getNodeStyles(start, end));
 
        if (initialized) {
          for (let key in nodeStyles) {
            if (nodeStyles[key] !== loopStyles[key]) {
              nodeStyles[key] = null;
            } else {
              nodeStyles[key] = object.unsafeClone(loopStyles[key]);
            }
          }
        } else {
          Object.assign(nodeStyles, object.unsafeClone(loopStyles));
          initialized = true;
        }
      }
 
      loopStartOffset = loopEndOffset;
    }
 
    return /** @type {!NodeStylesModel} */(nodeStyles);
  }
 
  /**
   * Gets branch node styles.
   * @return {!NodeStylesModel}
   */
  getBranchNodeStyles() {
    return /** @type {!NodeStylesModel} */(this.nodeStyles_ || {});
  }
 
  /**
   * Sets node style by key.
   * @param {!NodeStyle} nodeStyle
   * @param {?Object|string|number} configuration
   */
  setBranchNodeStyle(nodeStyle, configuration) {
    const model = /** @type {!Object<string, ?Object|string|number>} */ (this.nodeStyles_);
    model[nodeStyle] = configuration;
 
    this.applyNodeStyles_();
    this.dispatchEvent(new ContentRenderingReadyEvent(this));
  }
 
  /**
   * Gets node content.
   * @return {!Content}
   * @override
   */
  getContent() {
    const content = new Content('', {});
    this.forEachChild((child) => {
      content.appendText(child.getContent());
    });
 
    // If content empty, required to define default text style configuration
    Iif (content.getLength() === 0) {
      content.setDefaultStyles(this.getChildNodeAt(0).getContent().getDefaultStyles());
    }
 
    return content;
  }
 
  /**
   * Extracts a section of a node content. The start and end offsets follow the
   * offset rules for branch nodes.
   * @param {number} startOffset The zero-based offset at which to begin extraction.
   * @param {number=} opt_endOffset Optional zero-based offset before which to end extraction.
   * @return {!Content}
   * @override
   */
  getContentAt(startOffset, opt_endOffset = this.getLength()) {
    let content = new Content('', {});
 
    this.forEachChildInOffset((child, start, end) => {
      let loopContent = child.getContentAt(start, end);
      content.appendText(loopContent);
    }, false, startOffset, opt_endOffset);
 
    return content;
  }
 
  /**
   * Modifies text styles in the offset using given function.
   * @param {number} startOffset The zero-based offset at which to begin
   *    extraction. If negative, it is treated as nodeContentLength + startOffset
   *    where nodeContentLength is the length of the node content (for example,
   *    if startOffset is -3 it is treated as nodeContentLength - 3). If
   *    startOffset is greater than or equal to the length of the node content,
   *    getContentAt() returns empty result.
   * @param {number|undefined} endOffset Optional zero-based offset before which to
   *    end extraction. The character at this offset will not be included. If
   *    opt_endOffset is omitted, getContentAt() extracts to the end of the
   *    string. If negative, it is treated as nodeContentLength + opt_endOffset
   *    where nodeContentLength is the length of the node content (for example, if
   *    opt_endOffset is -3 it is treated as nodeContentLength - 3).
   * @param {!TextStyle} textStyle Text style name.
   * @param {!Object<string, !Object>} configuration Configuration object.
   * @param {function(
   *          !Object<string, !Object>,
   *          !Object<string, !*>,
   *          !Content,
   *          !Object=):!Object<string, !Object>=} stylePreprocessor
   *    Optional preprocessor function to apply for each text style for each
   *    node content. Should return new configuration object which will be
   *    applied to content rage.
   *    - 1st argument: passed configuration;
   *    - 2nd argument: inline style configuration for selected range in the
   *      current node;
   *    - 3rg argument: current content metadata instance;
   *    - 4th argument: optional data object;
   * @param {!Object=} opt_data Optional data object to pass to
   *    opt_stylePreprocessor function.
   * @param {!Object=} opt_thisArg Object that should be used by default for
   *    opt_stylePreprocessor function calls. Current metadata instance will
   *    used by default.
   * @override
   */
  modifyTextStylesAndUpdate(startOffset, endOffset, textStyle, configuration, stylePreprocessor,
      opt_data, opt_thisArg) {
    this.forEachChildInOffset((child, start, end) => {
      child.modifyTextStylesAndUpdate(start, end, textStyle, configuration, stylePreprocessor, opt_data, opt_thisArg);
    }, false, startOffset, endOffset);
  }
 
  /**
   * Inserts text at the given position. The offset follow the offsets rule for branch nodes.
   * @param {!Content} content The content to insert.
   * @param {number} offset The offset to insert text. Can't be negative. Represents symbol position
   *    in the text.
   * @override
   */
  insertContentAt(content, offset) {
    Iif (content.getLength() === 0) { return; }
 
    let childCount = this.getChildCount();
    let loopOffset = 0;
 
    for (let i = 0; i < childCount && loopOffset <= offset; i++) {
      if (i > 0) { loopOffset++; }
 
      let child = this.getChildNodeAt(i);
      let childLength = child.getLength();
 
      if (offset >= loopOffset && offset <= loopOffset + childLength) {
        child.insertContentAt(content, offset - loopOffset);
        break;
      }
 
      loopOffset += childLength;
    }
  }
 
  /**
   * @param {number=} opt_startOffset Optional selection start offset.
   * @param {number=} opt_endOffset Optional selection end offset.
   * @param {boolean=} opt_addExtraSpace Indicates if required to add extra space in the end of the node.
   * @param {boolean=} opt_isDocumentSelectionCollapsed Indicates if document selection is collapsed.
   * @override
   */
  select(opt_startOffset = 0, opt_endOffset = this.getLength(), opt_addExtraSpace, opt_isDocumentSelectionCollapsed) {
    // TODO: Unselect nodes outside of current selection range only
    this.unselect();
 
    // Update branch node component selection
    let loopStartOffset = 0;
    let childCount = this.getChildCount();
    let rangeToSelect = new GRange(opt_startOffset, opt_endOffset);
    let startNodeOffsetInfo;
    let endNodeOffsetInfo;
    let loopOffsetInfo;
    let child;
    let endChildInSelection;
 
    for (let i = 0; i < childCount && (loopStartOffset < opt_endOffset || loopStartOffset === 0); i++) {
      if (i > 0) { loopStartOffset++; }
 
      child = this.getChildNodeAt(i);
      let childLength = child.getLength();
      let loopEndOffset = loopStartOffset + childLength;
      let loopRange = new GRange(loopStartOffset, loopEndOffset);
      let intersection = GRange.intersection(rangeToSelect, loopRange);
 
      if (intersection) {
        let startSelection = intersection.start - loopStartOffset;
        let endSelection = intersection.end - loopStartOffset;
        child.select(startSelection, endSelection, opt_addExtraSpace || loopEndOffset < opt_endOffset, opt_isDocumentSelectionCollapsed);
        endChildInSelection = child;
 
        if (startNodeOffsetInfo === undefined) {
          loopOffsetInfo = child.getSelectionRange().getStartOffset();
          startNodeOffsetInfo =
              new NodeOffsetInfo(loopOffsetInfo.getNode(),
                  loopOffsetInfo.getLine(),
                  loopOffsetInfo.getLineIndex(),
                  loopOffsetInfo.getLineOffset(),
                  loopOffsetInfo.getNodeOffset(),
                  this,
                  opt_startOffset);
        }
      }
 
      loopStartOffset = loopEndOffset;
    }
 
    if (endChildInSelection && startNodeOffsetInfo) {
      loopOffsetInfo = endChildInSelection.getSelectionRange().getEndOffset();
      endNodeOffsetInfo =
          new NodeOffsetInfo(loopOffsetInfo.getNode(), loopOffsetInfo.getLine(),
              loopOffsetInfo.getLineIndex(), loopOffsetInfo.getLineOffset(),
              loopOffsetInfo.getNodeOffset(), this, opt_endOffset);
 
      this.selectionRange_ =
          new NodeRange(startNodeOffsetInfo, endNodeOffsetInfo);
    }
  }
 
  /** @override */
  unselect() {
    if (this.selectionRange_) {
      let selectionRange = this.selectionRange_;
      let startOffset = /** @type {number} */ (selectionRange.getStartOffset().getBranchNodeOffset());
      let endOffset = /** @type {number} */  (selectionRange.getEndOffset().getBranchNodeOffset());
 
      this.forEachChildInOffset((child) => {
        child.unselect();
      }, true, startOffset, endOffset);
 
      this.selectionRange_ = null;
    }
  }
 
  /**
   * @return {?NodeRange}
   * @override
   */
  getSelectionRange() {
    return this.selectionRange_;
  }
 
  /**
   * @return {boolean}
   * @override
   */
  isSelectedEntirely() {
    const selectionRange = this.selectionRange_;
 
    return selectionRange != null &&
        selectionRange.getStartOffset().getBranchNodeOffset() === 0 &&
        selectionRange.getEndOffset().getBranchNodeOffset() === this.getLength();
  }
 
  /**
   * @return {?Content}
   * @override
   */
  getSelectedContent() {
    let selectedContent = null;
    const selectionRange = this.selectionRange_;
 
    if (selectionRange != null) {
      const startOffset =
          /** @type {number} */(selectionRange.getStartOffset().getBranchNodeOffset());
      const endOffset = /** @type {number} */(selectionRange.getEndOffset().getBranchNodeOffset());
      selectedContent = this.getContentAt(startOffset, endOffset);
    }
 
    return selectedContent;
  }
 
  /**
   * Apply node styles for selected nodes only and re-render node content.
   * @param {!NodeStyle} nodeStyle Node style.
   * @param {?Object|string|number} configuration Configuration object.
   * @override
   */
  applyNodeStyle(nodeStyle, configuration) {
    const selectionRange = this.selectionRange_;
    let startOffset, endOffset;
 
    if (selectionRange) {
      startOffset = /** @type {number} */ (selectionRange.getStartOffset().getBranchNodeOffset());
      endOffset = /** @type {number} */ (selectionRange.getEndOffset().getBranchNodeOffset());
    } else {
      startOffset = 0;
      endOffset = this.getLength();
    }
 
    const childCount = this.getChildCount();
    const contentRange = new GRange(startOffset, endOffset);
    let loopStartOffset = 0;
 
    for (let i = 0; i < childCount && loopStartOffset <= endOffset; i++) {
      if (i > 0) { loopStartOffset++; }
      let child = this.getChildNodeAt(i);
      let loopEndOffset = loopStartOffset + child.getLength();
      let loopContentRange = new GRange(loopStartOffset, loopEndOffset);
      let intersection = GRange.intersection(contentRange, loopContentRange);
 
      if (intersection) {
        child.applyNodeStyle(nodeStyle, configuration);
      }
 
      loopStartOffset = loopEndOffset;
    }
  }
 
  /**
   * Gets model object.
   * @param {boolean=} selectedContentOnly If true, returns model object for selected content only. If node not
   *    selected, returns whole model for whole node content.
   * @return {!BranchNodeModel}
   * @override
   */
  toModel(selectedContentOnly) {
    const selectionRange = this.selectionRange_;
    const startNodeOffset = selectionRange?.getStartOffset().getBranchNodeOffset();
    const endNodeOffset = selectionRange?.getEndOffset().getBranchNodeOffset();
    const startOffset = /** @type {number} */ (selectedContentOnly && startNodeOffset ? startNodeOffset : 0);
    const endOffset = /** @type {number} */ (selectedContentOnly && endNodeOffset ? endNodeOffset : this.getLength());
    const childCount = this.getChildCount();
    const contentRange = new GRange(startOffset, endOffset);
    const model = new BranchNodeModel();
    model.nodeType = this.getNodeType();
    model.childNodes = [];
    model.nodeStyles = BaseNodeStyle.getModifiedNodeStyles(env['nodeStyles'], this.getBranchNodeStyles());
 
    for (let i = 0, loopStartOffset = 0; i < childCount && loopStartOffset <= endOffset; i++) {
      if (i > 0) { loopStartOffset++; }
      let child = this.getChildNodeAt(i);
      let loopEndOffset = loopStartOffset + child.getLength();
      let loopContentRange = new GRange(loopStartOffset, loopEndOffset);
      let intersection = GRange.intersection(contentRange, loopContentRange);
 
      if (intersection) {
        model.childNodes.push(child.toModel(selectedContentOnly));
      }
 
      loopStartOffset = loopEndOffset;
    }
 
    return model;
  }
 
  /**
   * Gets offset by child node offset info.
   * @param {!NodeOffsetInfo} offsetInfo Child node offset info
   * @return {number} branch node offset. Returns -1 if no offset found for
   * passed node info.
   */
  getOffsetForInnerNode(offsetInfo) {
    let child = offsetInfo.getNode();
    let offset = offsetInfo.getNodeOffset();
    let parent;
 
    while(parent = /** @type {!Node} */(child.getParent())) {
      // TODO: Refactor this, remove indexOfChild and use more efficient way
      //  to get index of child node. (ex. introduce hash map like [id:index])
      if (parent instanceof BranchNode) {
        let childIndex = parent.indexOfChild(child);
 
        for (let i = childIndex - 1; i >= 0; i--) {
          offset += parent.getChildNodeAt(i).getLength() + 1;
        }
 
        child = parent;
      } else {
        break;
      }
    }
 
    return offset;
  }
 
  /**
   * Gets detailed range offset information for specific offset.
   * @param {number} offset 0-based node offset.
   * @param {boolean=} opt_considerEndOfLineOffset Consider end of line offset
   *    as valid result.
   * @return {?RangeOffset}
   * @override
   */
  getRangeOffsetForOffset(offset, opt_considerEndOfLineOffset) {
    let length = this.getLength();
    let rangeOffset = null;
 
    if (offset >= 0 && offset <= length) {
      let childCount = this.getChildCount();
      let loopOffset = 0;
 
      for (let i = 0; i < childCount && loopOffset <= offset; i++) {
        if (i > 0) { loopOffset++; }
 
        let child = this.getChildNodeAt(i);
        let childLength = child.getLength();
 
        if (offset >= loopOffset && offset <= loopOffset + childLength) {
          let loopRangeOffset = child.getRangeOffsetForOffset(offset - loopOffset, opt_considerEndOfLineOffset);
          let loopOffsetInfo = loopRangeOffset.getNodeOffsetInfo();
          let nodeOffsetInfo = new NodeOffsetInfo(
              loopOffsetInfo.getNode(), loopOffsetInfo.getLine(),
              loopOffsetInfo.getLineIndex(), loopOffsetInfo.getLineOffset(),
              loopOffsetInfo.getNodeOffset(), this, offset);
          rangeOffset = new RangeOffset(loopRangeOffset.getNode(), nodeOffsetInfo, loopRangeOffset.getNodeBounds());
          break;
        }
 
        loopOffset += childLength;
      }
    }
 
    return rangeOffset;
  }
 
  /**
   * Gets range of the word in the specified x coordinate and the specified y
   * coordinate.
   * @param {number} offset 0-based node offset.
   * @return {?Range}
   * @override
   */
  getWordRangeOffsetFromOffset(offset) {
    let length = this.getLength();
    let range = null;
 
    if (offset >= 0 && offset < length) {
      let childCount = this.getChildCount();
      let loopOffset = 0;
 
      for (let i = 0; i < childCount && loopOffset <= offset; i++) {
        if (i > 0) { loopOffset++; }
 
        let child = this.getChildNodeAt(i);
        let childLength = child.getLength();
 
        if (offset >= loopOffset && offset <= loopOffset + childLength) {
          range = child.getWordRangeOffsetFromOffset(offset - loopOffset);
          break;
        }
 
        loopOffset += childLength;
      }
    }
 
    // Add branch offset information
    if (range) {
      let startRangeOffset = this.getRangeOffsetForChildRangeOffset(range.getStartRangeOffset());
      let endRangeOffset = this.getRangeOffsetForChildRangeOffset(range.getEndRangeOffset());
      range = new Range(startRangeOffset, endRangeOffset);
    }
 
    return range;
  }
 
  /**
   * Get words around offset.
   * @param {number} offset 0-based node offset
   * @return {?OffsetWordInfo}
   * @override
   */
  getWordsInformationAroundOffset(offset) {
    const length = this.getLength();
    let wordInfo = null;
 
    if (offset >= 0 && offset < length) {
      let childCount = this.getChildCount();
      let loopOffset = 0;
 
      for (let i = 0; i < childCount && loopOffset <= offset; i++) {
        if (i > 0) { loopOffset++; }
 
        let child = this.getChildNodeAt(i);
        let childLength = child.getLength();
 
        if (offset >= loopOffset && offset <= loopOffset + childLength) {
          wordInfo = child.getWordsInformationAroundOffset(offset - loopOffset);
          break;
        }
 
        loopOffset += childLength;
      }
    }
 
    // Update branch range information
    if (wordInfo != null) {
      let range = wordInfo.range;
      let startRangeOffset = this.getRangeOffsetForChildRangeOffset(range.getStartRangeOffset());
      let endRangeOffset = this.getRangeOffsetForChildRangeOffset(range.getEndRangeOffset());
      wordInfo.range = new Range(startRangeOffset, endRangeOffset);
    }
 
    return wordInfo;
  }
 
  /**
   * Gets bottommost offset in the node by X axis.
   * @param {number} x X axis position to align.
   * @return {!RangeOffset} New offset below.
   * @override
   */
  getBottommostOffsetByX(x) {
    const lastNode = this.getChildNodeAt(this.getChildCount() - 1);
    const lastNodeBottommostOffsetByX = lastNode.getBottommostOffsetByX(x);
    return this.getRangeOffsetForChildRangeOffset(lastNodeBottommostOffsetByX);
  }
 
  /**
   * Gets topmost offset in the node by X axis.
   * @param {number} x X axis position to align.
   * @return {!RangeOffset} New offset below.
   * @override
   */
  getTopmostOffsetByX(x) {
    const firstNode = this.getChildNodeAt(0);
    const firstNodeTopmostOffsetByX = firstNode.getTopmostOffsetByX(x);
    return this.getRangeOffsetForChildRangeOffset(firstNodeTopmostOffsetByX);
  }
 
  /**
   * Gets the bottommost leaf node in the tree. Returns offset always equals to
   * the first position of the node above. Expected that branch node have always
   * at least one leaf node.
   * @return {!RangeOffset}
   */
  getBottommostLeafNodeOffset() {
    let bottomNode = this.getChildNodeAt(this.getChildCount() - 1);
 
    while (bottomNode instanceof BranchNode) {
      bottomNode = bottomNode.getChildNodeAt(bottomNode.getChildCount() - 1);
    }
 
    return this.getRangeOffsetForChildRangeOffset(
        /** @type {!RangeOffset} */(bottomNode.getRangeOffsetForOffset(0)));
  }
 
  /**
   * Gets range offset of the inner node above node in the offset. Returns
   * offset always equals to the first position of the node above.
   * @param {!RangeOffset} offset
   * @return {!RangeOffset|undefined}
   */
  getInnerNodeAboveNodeInOffset(offset) {
    let currentNode = offset.getNode();
    let parent = /** @type {!Node} */(currentNode.getParent());
    let currentNodeIndex;
    let nodeAbove;
    let rangeOffset;
 
    while (parent instanceof BranchNode && !nodeAbove) {
      currentNodeIndex = parent.indexOfChild(currentNode);
 
      // If current node index > 0, get the node above
      if (currentNodeIndex > 0) {
        nodeAbove = parent.getChildNodeAt(currentNodeIndex - 1);
 
        // If nodeAbove is BranchNode, traverse below by tree, to find the lowest
        // LeafNode
        while(nodeAbove instanceof BranchNode) {
          nodeAbove = nodeAbove.getChildNodeAt(nodeAbove.getChildCount() - 1);
        }
      } else {
        currentNode = parent;
        parent = /** @type {!Node} */(currentNode.getParent());
      }
    }
 
    if (nodeAbove) {
      rangeOffset =
          this.getRangeOffsetForChildRangeOffset(
              /** @type {!RangeOffset} */(nodeAbove.getRangeOffsetForOffset(0)));
    }
 
    return rangeOffset;
  }
 
  /**
   * Gets range offset of the inner node below node in the offset. Returns
   * offset always equals to the first position of the node below, except if
   * opt_endNodeOffset set to true.
   * @param {!RangeOffset} offset
   * @param {boolean=} opt_endNodeOffset If true, returns the last position of
   *    the node below.
   * @return {!RangeOffset|undefined}
   */
  getInnerNodeBelowNodeInOffset(offset, opt_endNodeOffset = false) {
    let currentNode = offset.getNode();
    let parent = /** @type {!Node} */(currentNode.getParent());
    let currentNodeIndex = parent.indexOfChild(currentNode);
    let nodeBelow;
    let rangeOffset;
 
    while (!nodeBelow && parent instanceof BranchNode) {
      // Get node below in the same branch node
      if (currentNodeIndex < parent.getChildCount() - 1) {
        nodeBelow = parent.getChildNodeAt(currentNodeIndex + 1);
 
        // Get topmost leaf node below if node is branch node
        while (nodeBelow instanceof BranchNode) {
          nodeBelow = nodeBelow.getChildNodeAt(0);
        }
      } else {
        currentNode = parent;
        parent = parent.getParent();
        currentNodeIndex = parent.indexOfChild(currentNode);
      }
    }
 
    if (nodeBelow) {
      let nodeBelowOffset = opt_endNodeOffset ? nodeBelow.getLength() : 0;
      rangeOffset =
          this.getRangeOffsetForChildRangeOffset(
              /** @type {!RangeOffset} */
              (nodeBelow.getRangeOffsetForOffset(nodeBelowOffset)));
    }
 
    return rangeOffset;
  }
 
  /**
   * Gets current branch node range offset by child's range offset.
   * @param {!RangeOffset} childRangeOffset
   * @return {!RangeOffset}
   */
  getRangeOffsetForChildRangeOffset(childRangeOffset) {
    const firstNodeOffsetInfo = childRangeOffset.getNodeOffsetInfo();
    const nodeOffsetInfo = new NodeOffsetInfo(
        firstNodeOffsetInfo.getNode(), firstNodeOffsetInfo.getLine(),
        firstNodeOffsetInfo.getLineIndex(), firstNodeOffsetInfo.getLineOffset(),
        firstNodeOffsetInfo.getNodeOffset(), this,
        this.getOffsetForInnerNode(childRangeOffset.getNodeOffsetInfo()));
 
    return new RangeOffset(childRangeOffset.getNode(), nodeOffsetInfo,
        childRangeOffset.getNodeBounds());
  }
 
  /**
   * Gets position below of given offset. If given position is bottom of the
   * node, return `undefined`.
   * @param {!RangeOffset} startOffset Origin offset to search.
   * @param {number} x X axis position to align.
   * @return {!RangeOffset|undefined} New offset below or undefined.
   * @override
   */
  getOffsetBelow(startOffset, x) {
    const offset =
        /** @type {number} */
        (startOffset.getNodeOffsetInfo().getBranchNodeOffset());
    let childCount = this.getChildCount();
    let length = this.getLength();
    let loopOffset = 0;
    let i = 0;
    let rangeOffset;
 
    // Find the child node for offset and call getOffsetBelow for it
    if (offset >= 0 && offset <= length) {
      while(i < childCount && loopOffset <= offset) {
        if (i > 0) { loopOffset++; }
 
        let child = this.getChildNodeAt(i);
        let childLength = child.getLength();
 
        if (offset >= loopOffset && offset <= loopOffset + childLength) {
          if (child instanceof BranchNode) {
            let currentOffsetInfo = startOffset.getNodeOffsetInfo();
            let startOffsetBranchNodeOffset =
                /** @type {number} */
                (startOffset.getNodeOffsetInfo().getBranchNodeOffset());
            let nodeOffsetInfo = new NodeOffsetInfo(
                currentOffsetInfo.getNode(), currentOffsetInfo.getLine(),
                currentOffsetInfo.getLineIndex(), currentOffsetInfo.getLineOffset(),
                currentOffsetInfo.getNodeOffset(), child,
                startOffsetBranchNodeOffset - loopOffset);
            let newStartOffset = new RangeOffset(startOffset.getNode(),
                nodeOffsetInfo, startOffset.getNodeBounds());
 
            rangeOffset = child.getOffsetBelow(newStartOffset, x);
          } else {
            rangeOffset = child.getOffsetBelow(startOffset, x);
          }
          break;
        }
 
        loopOffset += childLength;
        i++;
      }
    }
 
    // If range offset is still undefined and this is not the last child node,
    // call .getTopmostOffsetByX() for node below and return result
    if (!rangeOffset && i + 1 < childCount) {
      rangeOffset = this.getChildNodeAt(i + 1).getTopmostOffsetByX(x);
    }
 
    // Add branch offset information
    if (rangeOffset) {
      rangeOffset = this.getRangeOffsetForChildRangeOffset(rangeOffset);
    }
 
    return rangeOffset;
  }
 
  /**
   * Gets position above of given offset. If given position is top of the node,
   * return `undefined`.
   * @param {!RangeOffset} startOffset Origin offset to search.
   * @param {number} x X axis position to align.
   * @return {!RangeOffset|undefined} New offset above or undefined.
   * @override
   */
  getOffsetAbove(startOffset, x) {
    const offset =
        /** @type {number} */
        (startOffset.getNodeOffsetInfo().getBranchNodeOffset());
    let childCount = this.getChildCount();
    let length = this.getLength();
    let loopOffset = 0;
    let i = 0;
    let rangeOffset;
 
    // Find the child node for offset and call getOffsetAbove for it
    if (offset >= 0 && offset <= length) {
      while(i < childCount && loopOffset <= offset) {
        if (i > 0) { loopOffset++; }
 
        let child = this.getChildNodeAt(i);
        let childLength = child.getLength();
 
        if (offset >= loopOffset && offset <= loopOffset + childLength) {
          if (child instanceof BranchNode) {
            let currentOffsetInfo = startOffset.getNodeOffsetInfo();
            let startBranchNodeOffset =
                /** @type {number} */
                (startOffset.getNodeOffsetInfo().getBranchNodeOffset());
            let nodeOffsetInfo = new NodeOffsetInfo(
                currentOffsetInfo.getNode(), currentOffsetInfo.getLine(),
                currentOffsetInfo.getLineIndex(), currentOffsetInfo.getLineOffset(),
                currentOffsetInfo.getNodeOffset(), child,
                startBranchNodeOffset - loopOffset);
            let newStartOffset = new RangeOffset(startOffset.getNode(),
                nodeOffsetInfo, startOffset.getNodeBounds());
 
            rangeOffset = child.getOffsetAbove(newStartOffset, x);
          } else {
            rangeOffset = child.getOffsetAbove(startOffset, x);
          }
          break;
        }
 
        loopOffset += childLength;
        i++;
      }
    }
 
    // If range offset is still undefined and this is not the first child node,
    // call .getBottommostOffsetByX() for node above and return result
    if (!rangeOffset && i - 1 >= 0) {
      rangeOffset = this.getChildNodeAt(i - 1).getBottommostOffsetByX(x);
    }
 
    // Add branch offset information
    if (rangeOffset) {
      rangeOffset = this.getRangeOffsetForChildRangeOffset(rangeOffset);
    }
 
    return rangeOffset;
  }
 
  /**
   * Gets range offset around given offset in the specified direction and
   * distance.
   * @param {number} offset 0-based node offset.
   * @param {!DIRECTIONS} direction The direction in which to adjust the offset.
   * @param {!GRANULARITY} granularity The distance to adjust the offset. Only
   *    pwk.GRANULARITY.CHAR an pwk.GRANULARITY.WORD accepted.
   * @return {?RangeOffset}
   * @override
   */
  getRangeOffsetAround(offset, direction, granularity) {
    let childCount = this.getChildCount();
    let length = this.getLength();
    let loopOffset = 0;
    let rangeOffset = null;
 
    if (offset >= 0 && offset <= length) {
      for (let i = 0; i < childCount && loopOffset <= offset; i++) {
        if (i > 0) { loopOffset++; }
 
        let child = this.getChildNodeAt(i);
        let childLength = child.getLength();
 
        // If offset is first position of the node for backward direction, get
        // the last position of the node above
        if (offset === loopOffset && direction === DIRECTIONS.BACKWARD) {
          rangeOffset = this.getRangeOffsetForOffset(offset - 1);
          break;
        }
 
        // If offset is last position of the node for forward direction, get
        // the first position of the node below
        Iif (offset === loopOffset + childLength &&
            direction === DIRECTIONS.FORWARD) {
          rangeOffset = this.getRangeOffsetForOffset(offset + 1);
          break;
        }
 
        if (offset >= loopOffset && offset <= loopOffset + childLength) {
          rangeOffset = child.getRangeOffsetAround(
              offset - loopOffset, direction, granularity);
          break;
        }
 
        loopOffset += childLength;
      }
    }
 
    // Add branch offset information
    if (rangeOffset) {
      rangeOffset = this.getRangeOffsetForChildRangeOffset(rangeOffset);
    }
 
    return rangeOffset;
  }
 
  /**
   * Gets detailed range offset information to the specified x coordinate and
   * the specified y coordinate.
   * @param {number} x Horizontal coordinate within the application client area.
   * @param {number} y Vertical coordinate within the application client area.
   * @return {?RangeOffset}
   * @override
   */
  getRangeOffsetFromPoint(x, y) {
    const nodeBounds = style.getBounds(this.getElement());
    const innerY = Math.min(Math.max(y - nodeBounds.top, 0), nodeBounds.height);
    const searchYCoordinate = nodeBounds.top + innerY;
    let startChildIndex = 0;
    let endChildIndex = this.getChildCount() - 1;
    let loopIndex;
    let loopChild;
    let loopBounds;
 
    while (startChildIndex <= endChildIndex) {
      loopIndex = Math.floor((startChildIndex + endChildIndex) / 2);
      loopChild = /** @type {!Node} */(this.getChildNodeAt(loopIndex));
      loopBounds = style.getBounds(loopChild.getElement());
 
      if (searchYCoordinate >= loopBounds.top &&
          searchYCoordinate <= loopBounds.top + loopBounds.height) {
        break;
      } else if (loopBounds.top < searchYCoordinate) {
        startChildIndex = loopIndex + 1;
      } else {
        endChildIndex = loopIndex - 1;
      }
    }
 
    let rangeOffset = loopChild.getRangeOffsetFromPoint(x, y);
 
    // Add branch offset information
    if (rangeOffset) {
      rangeOffset = this.getRangeOffsetForChildRangeOffset(rangeOffset);
    }
 
    return rangeOffset;
  }
 
  /**
   * Returns the child node at the given index, or null if the index is out of
   * bounds.
   * @param {number} index 0-based index.
   * @return {?Node} The node at the given index; null if none.
   */
  getChildNodeAt(index) {
    return /** @type {!Node} */ (this.getChildAt(index));
  }
 
  /**
   * Gets html representation of the node content in the offset. Use
   * Node.getContent().toHtmlString() if you need to obtain the HTML representation of the content
   * without considering node HTML structure. Should be overridden by derived class.
   * @param {number} startOffset The zero-based offset at which to begin extraction.
   * @param {number=} opt_endOffset Optional zero-based offset before which to end extraction.
   * @return {string} HTML string
   * @override
   */
  getOuterHtml(startOffset, opt_endOffset) {
    throw new Error('getOuterHtml method not implemented');
  }
 
  /**
   * Appends text. Not intended to be implemented for BranchNode successor.
   * @param {!Content} content The content to append.
   * @override
   */
  appendText(content) {
    throw new Error('Please use insertContentAt method to insert new content or implement appendText logic');
  }
 
  /**
   * Converts current node content to plain text.
   * @param {number=} opt_startOffset Optional zero-based offset at which to begin extraction.
   * @param {number=} opt_endOffset Optional zero-based offset before which to end extraction.
   * @return {string}
   * @override
   */
  toPlainText(opt_startOffset = 0, opt_endOffset = this.getLength()) {
    const textArray = [];
 
    this.forEachChildInOffset((child, start, end) => {
      if (child instanceof BranchNode) {
        textArray.push(child.toPlainText(start, end));
      } else {
        textArray.push(child.getContentAt(start, end).getText());
      }
    }, false, opt_startOffset, opt_endOffset);
 
    return textArray.join('\n');
  }
 
  /**
   * @param {number} startOffset Zero-based offset at which to begin removing.
   * @param {number=} opt_endOffset Optional zero-based offset before which to end removing.
   * @param {?Range=} opt_currentSelectionRange Optional current selection range.
   * @override
   */
  removeAt(startOffset, opt_endOffset = this.getLength(), opt_currentSelectionRange) {
    throw new Error('removeAt method not implemented');
  }
 
  /**
   * @override
   * Should be overridden by derived class.
   */
  getNodeType() {
    throw new Error('getNodeType method not implemented');
  }
 
  /**
   * Splits node. Returns second part of node as a result.
   * @param {!NodeOffsetInfo} nodeOffsetInfo
   * @return {!Node} Node to render below current node.
   * @override
   * Should be overridden by derived class.
   */
  split(nodeOffsetInfo) {
    throw new Error('split method not implemented');
  }
 
  /**
   * Inserts node at the given branch node position. The offset follow the offsets rule for branch nodes.
   * @param {!Node} node The node to insert.
   * @param {number} offset The offset to insert node.
   * @return {?RangeOffset} Range offset for end position of the inserted node
   */
  insertNodeAt(node, offset) {
    throw new Error('insertNodeAt method not implemented');
  }
 
  /**
   * Handles new line logic inside branch node.
   * Should be overridden by derived class.
   * @param {!NodeOffsetInfo} nodeOffsetInfo
   * @return {?RangeOffset} Range offset for the `new line` position
   */
  newLine(nodeOffsetInfo) {
    throw new Error('newLine method not implemented');
  }
 
  /**
   * Returns true if branch node contains only one child node with content.
   * Should be overridden by derived class.
   * @return {boolean}
   */
  isSingleChildNode() {
    throw new Error('isSingleChildNode method not implemented');
  }
 
  /**
   * Calls the given function on each of this branch node children in order.
   * @param {function(!Node, number, number): void} callback The function to call for every child
   *    node; should take 3 arguments (the child node, start and end offset).
   * @param {boolean=} ignoreCollapsedIntersection Ignore start/end intersection.
   * @param {number=} opt_startOffset Optional zero-based offset at which to begin extraction.
   * @param {number=} opt_endOffset Optional zero-based offset before which to end extraction.
   */
  forEachChildInOffset(callback, ignoreCollapsedIntersection = false, opt_startOffset = 0, opt_endOffset = this.getLength()) {
    let loopStartOffset = 0;
    let childCount = this.getChildCount();
    let contentRange = new GRange(opt_startOffset, opt_endOffset);
 
    for (let i = 0; i < childCount && (loopStartOffset < opt_endOffset || loopStartOffset === 0); i++) {
      if (i > 0) { loopStartOffset++; }
      let child = this.getChildNodeAt(i);
      let loopEndOffset = loopStartOffset + child.getLength();
      let loopRange = new GRange(loopStartOffset, loopEndOffset);
      let intersection = GRange.intersection(contentRange, loopRange);
      let startEndIntersection = ignoreCollapsedIntersection ||
          intersection != null && intersection.start !== intersection.end;
 
      if (intersection != null && startEndIntersection) {
        const start = intersection.start - loopStartOffset;
        const end = intersection.end - loopStartOffset;
        callback(/** @type {!Node} */(child), start, end);
      }
 
      loopStartOffset = loopEndOffset;
    }
  }
 
  /**
   * Merges nodes. Removes content from fromNode.
   * @param {!BranchNode} fromNode
   */
  merge(fromNode) {
    while (fromNode.getChildCount() !== 0) {
      this.addChild(fromNode.removeChild(fromNode.getChildNodeAt(0), true), true);
    }
  }
}
 
/**
 * Component default css class
 * @type {string}
 * @override
 */
BranchNode.CSS_CLASS = 'pwk-branch-node';