insertNewLine method

Future<void> insertNewLine({
  1. Position? position,
  2. Node nodeBuilder(
    1. Node node
    )?,
})

Inserts a new line at the given position.

If the Position is not passed in, use the current selection. If there is no position, or if the selection is not collapsed, do nothing.

Then it inserts a new paragraph node. After that, it sets the selection to be at the beginning of the new paragraph.

Implementation

Future<void> insertNewLine({
  Position? position,
  Node Function(Node node)? nodeBuilder,
}) async {
  // If the position is not passed in, use the current selection.
  position ??= selection?.start;

  // If there is no position, or if the selection is not collapsed, do nothing.
  if (position == null || !(selection?.isCollapsed ?? false)) {
    return;
  }

  final node = getNodeAtPath(position.path);

  if (node == null) {
    return;
  }

  // Get the transaction and the path of the next node.
  final transaction = this.transaction;
  final next = position.path.next;
  final children = node.children;
  final delta = node.delta;

  if (delta != null) {
    // Delete the text after the cursor in the current node.
    transaction.deleteText(
      node,
      position.offset,
      delta.length - position.offset,
    );
  }

  // Delete the current node's children if it is not empty.
  if (children.isNotEmpty) {
    transaction.deleteNodes(children);
  }

  final slicedDelta = delta == null ? Delta() : delta.slice(position.offset);
  final Map<String, dynamic> attributes = {
    'delta': slicedDelta.toJson(),
  };

  // Copy the text direction from the current node.
  final textDirection =
      node.attributes[blockComponentTextDirection] as String?;
  if (textDirection != null) {
    attributes[blockComponentTextDirection] = textDirection;
  }

  final insertedNode = paragraphNode(
    attributes: attributes,
    children: children,
  );
  nodeBuilder ??= (node) => node.copyWith();

  // Insert a new paragraph node.
  transaction.insertNode(
    next,
    nodeBuilder(insertedNode),
    deepCopy: true,
  );

  // Set the selection to be at the beginning of the new paragraph.
  transaction.afterSelection = Selection.collapsed(
    Position(
      path: next,
      offset: 0,
    ),
  );

  // Apply the transaction.
  return apply(transaction);
}