executeHandleReplaceSelection function

void executeHandleReplaceSelection(
  1. String character,
  2. FluentDocument document
)

Implementation

void executeHandleReplaceSelection(String character, FluentDocument document) {
  final sel = resolveSelection(
    document.content,
    document.cursor.anchorId,
    document.cursor.anchorOffset,
    document.cursor.focusId,
    document.cursor.focusOffset,
    cachedStops: document.caretStops,
    cachedLines: document.logicalLines,
  );

  if (sel == null) return;

  final root = document.content;

  final cursorTarget = sel.isSingleNode
      ? _replaceSingleNode(sel, character, root)
      : _replaceMultiNode(sel, character, root);

  // The cursor should be positioned immediately after the inserted character
  document.cursor.moveTo(
    cursorTarget.fragId,
    cursorTarget.offset,
  );

  // Collapse the global selection to remove the highlight
  document.selectionManager.collapse();

  // Notify comment system of the text mutation (single-fragment case for simplicity).
  if (sel.isSingleNode && sel.base.fragment.id == sel.extent.fragment.id) {
    final paragraphId = (sel.base.container as FNode).id;
    final globalOffset = document.getGlobalOffsetInParagraph(
      paragraphId,
      sel.base.fragment.id,
      sel.base.offset,
    );
    if (globalOffset != null) {
      final delta = character.length - (sel.extent.offset - sel.base.offset);
      document.notifyTextMutation(paragraphId, globalOffset, delta);
    }
  }

  document.updateContent();
}