getSelectionRangeForNode method

({String endFrag, int endOff, String startFrag, int startOff})? getSelectionRangeForNode(
  1. String nodeId
)

Implementation

({String startFrag, int startOff, String endFrag, int endOff})? getSelectionRangeForNode(String nodeId) {
  if (!_selectionManager.hasSelection) return null;
  if (!isNodeSelected(nodeId)) return null;

  final state = _selectionManager.state;
  final anchor = state.anchor!;
  final focus = state.focus!;

  // O(1) document-order position lookups instead of O(n) getNodePath.
  final nodePos = nodePosition(nodeId);
  final anchorPos = nodePosition(anchor.nodeId);
  final focusPos = nodePosition(focus.nodeId);

  if (nodePos == null || anchorPos == null || focusPos == null) return null;

  final base = anchorPos <= focusPos ? anchor : focus;
  final extent = anchorPos <= focusPos ? focus : anchor;
  final basePos = anchorPos <= focusPos ? anchorPos : focusPos;
  final extentPos = anchorPos <= focusPos ? focusPos : anchorPos;

  final isBaseNode = nodePos == basePos;
  final isExtentNode = nodePos == extentPos;

  if (isBaseNode && isExtentNode) {
    return (
      startFrag: base.fragmentId,
      startOff: base.offset,
      endFrag: extent.fragmentId,
      endOff: extent.offset,
    );
  } else if (isBaseNode) {
    return (
      startFrag: base.fragmentId,
      startOff: base.offset,
      endFrag: '',
      endOff: -1,
    );
  } else if (isExtentNode) {
    return (
      startFrag: '',
      startOff: 0,
      endFrag: extent.fragmentId,
      endOff: extent.offset,
    );
  } else {
    return (
      startFrag: '',
      startOff: 0,
      endFrag: '',
      endOff: -1,
    );
  }
}