execute method

  1. @override
void execute(
  1. EditContext context,
  2. CommandExecutor executor
)
override

Executes this command and logs all changes with the executor.

Implementation

@override
void execute(EditContext context, CommandExecutor executor) {
  final document = context.document;
  final composer = context.find<MutableDocumentComposer>(Editor.composerKey);

  final node = document.getNodeById(nodeId);
  final listItemNode = node as ListItemNode;
  final text = listItemNode.text;
  final startText = text.copyText(0, splitPosition.offset);
  final endText = splitPosition.offset < text.length ? text.copyText(splitPosition.offset) : AttributedText();
  _log.log('SplitListItemCommand', 'Splitting list item:');
  _log.log('SplitListItemCommand', ' - start text: "$startText"');
  _log.log('SplitListItemCommand', ' - end text: "$endText"');

  // Change the current node's content to just the text before the caret.
  _log.log('SplitListItemCommand', ' - changing the original list item text due to split');
  final updatedListItemNode = listItemNode.copyListItemWith(text: startText);
  document.replaceNodeById(
    listItemNode.id,
    updatedListItemNode,
  );

  // Create a new node that will follow the current node. Set its text
  // to the text that was removed from the current node.
  final newNode = listItemNode.type == ListItemType.ordered
      ? ListItemNode.ordered(
          id: newNodeId,
          text: endText,
          indent: listItemNode.indent,
        )
      : ListItemNode.unordered(
          id: newNodeId,
          text: endText,
          indent: listItemNode.indent,
        );

  // Insert the new node after the current node.
  _log.log('SplitListItemCommand', ' - inserting new node in document');
  document.insertNodeAfter(
    existingNodeId: updatedListItemNode.id,
    newNode: newNode,
  );

  // Clear the composing region to avoid keeping a region pointing to the
  // node that was split.
  composer.setComposingRegion(null);

  _log.log('SplitListItemCommand', ' - inserted new node: ${newNode.id} after old one: ${node.id}');

  executor.logChanges([
    SplitListItemIntention.start(),
    DocumentEdit(
      NodeChangeEvent(nodeId),
    ),
    DocumentEdit(
      NodeInsertedEvent(newNodeId, document.getNodeIndexById(newNodeId)),
    ),
    SplitListItemIntention.end(),
  ]);
}