mergeAtJunction function

void mergeAtJunction(
  1. FluentDocument document,
  2. InlineContainerNode targetContainer,
  3. Fragment? junctionFrag,
  4. int childrenBeforeCount,
)

Merges children at the junction point after moving children from one container to another. Handles fragment merging, cursor positioning, list index recalculation, and content update.

targetContainer is the container that received the moved children. junctionFrag is the last fragment of the target container before the move (captured by the caller). childrenBeforeCount is the number of children targetContainer had before the move.

Implementation

void mergeAtJunction(
  FluentDocument document,
  InlineContainerNode targetContainer,
  Fragment? junctionFrag,
  int childrenBeforeCount,
) {
  final root = document.content;
  final cursor = document.cursor;

  final children = targetContainer.getChildren();
  final firstMoved = children.length > childrenBeforeCount
      ? children[childrenBeforeCount]
      : null;

  if (junctionFrag != null &&
      firstMoved != null &&
      firstMoved is Fragment &&
      firstMoved is! InlineContainerNode) {
    final newCursorOffset = junctionFrag.text.length;
    FragmentOperations.mergeFragments(junctionFrag, firstMoved);
    removeNode(root, firstMoved);
    cursor.moveTo(junctionFrag.id, newCursorOffset);
  } else if (junctionFrag != null) {
    cursor.moveTo(junctionFrag.id, junctionFrag.text.length);
  } else if (children.isNotEmpty) {
    moveCursorToFirstFragment(cursor, targetContainer);
  }

  recalculateAndUpdate(document);
}