private void onChildAdd()

in cell/src/main/java/jetbrains/jetpad/cell/indent/updater/IndentUpdater.java [115:177]


  private void onChildAdd(Cell child) {
    if (!isVisible(child)) return;

    if (isAttached(child)) {
      throw new IllegalStateException("child " + child + " is already attached");
    }

    setAttached(child, true);

    Position insertAt = new Position(this, child);
    Position prevNewLinePos = prevNewLine(insertAt.prev());

    if (isCell(child)) {
      CellWrapper<TargetT> wrapper = myIndentUpdaterTarget.wrap(child);
      myWrappers.put(child, wrapper);

      if (prevNewLinePos == null) {
        Position first = new Position(this, firstLeaf(myRoot));
        children(children(myTarget).get(0)).add(first.deltaTo(insertAt), wrapper.item());
      } else {
        TargetT targetLine = myNewLineToLine.get(prevNewLinePos.get());
        int indentDelta = indent(prevNewLinePos.get()) > 0 ? 1 : 0;
        children(targetLine).add(prevNewLinePos.deltaTo(insertAt) - 1 + indentDelta, wrapper.item());
      }
    } else if (child instanceof NewLineCell) {
      Position nextNewLinePos = nextNewLine(insertAt.next());

      TargetT newLine = myIndentUpdaterTarget.newLine();
      int indent = indent(child);

      if (indent > 0) {
        TargetT indentItem = myIndentUpdaterTarget.newIndent(indent);
        children(newLine).add(indentItem);
      }

      myNewLineToLine.put(child, newLine);

      if (prevNewLinePos == null) {
        children(myTarget).add(1, newLine);
      } else {
        TargetT prevLine = myNewLineToLine.get(prevNewLinePos.get());

        //this is optimization for the initalization case
        int prevLineIndex = children(myTarget).lastIndexOf(prevLine);
        children(myTarget).add(prevLineIndex + 1, newLine);
      }

      Iterator<Position> positions = nextNewLinePos == null ? toEnd(insertAt.next()) : range(insertAt.next(), nextNewLinePos);
      while (positions.hasNext()) {
        Cell part = positions.next().get();
        if (!isCell(part)) continue;
        CellWrapper<TargetT> wrapper = myWrappers.get(part);
        TargetT item = wrapper.item();

        if (myIndentUpdaterTarget.parent(item) == null) {
          throw new IllegalStateException();
        }

        removeFromParent(item);
        children(newLine).add(item);
      }
    }
  }