getSelectionRangeForNode method

({String endFrag, int endOff, String startFrag, int startOff})? getSelectionRangeForNode(
  1. String nodeId, {
  2. Map<String, int>? positionIndex,
})

For a given node, returns the selection limits in terms of fragment/offset Returns: (startFragmentId, startOffset, endFragmentId, endOffset) or null if not selected

Implementation

({String startFrag, int startOff, String endFrag, int endOff})? getSelectionRangeForNode(
  String nodeId, {
  Map<String, int>? positionIndex,
}) {
  if (!hasSelection) return null;
  if (!isNodeSelected(nodeId, positionIndex: positionIndex)) return null;

  final base = _isAnchorBeforeFocus(positionIndex) ? anchor! : focus!;
  final extent = _isAnchorBeforeFocus(positionIndex) ? focus! : anchor!;

  final nodeIsBase = base.nodeId == nodeId;
  final nodeIsExtent = extent.nodeId == nodeId;

  if (nodeIsBase && nodeIsExtent) {
    // Selection entirely within this node
    return (
      startFrag: base.fragmentId,
      startOff: base.offset,
      endFrag: extent.fragmentId,
      endOff: extent.offset,
    );
  } else if (nodeIsBase) {
    // Selection starts here and continues in other nodes
    // Select from base to the end of the node
    return (
      startFrag: base.fragmentId,
      startOff: base.offset,
      endFrag: '',  // "" = end of node
      endOff: -1,
    );
  } else if (nodeIsExtent) {
    // Selection ends here, started in other nodes
    // Select from the beginning of the node to extent
    return (
      startFrag: '',  // "" = start of node
      startOff: 0,
      endFrag: extent.fragmentId,
      endOff: extent.offset,
    );
  } else {
    // Node completely selected (in the middle)
    return (
      startFrag: '',  // start
      startOff: 0,
      endFrag: '',    // end
      endOff: -1,
    );
  }
}