calculateBoundedFloatingCursorOffset method Null safety

Offset calculateBoundedFloatingCursorOffset(
  1. Offset rawCursorOffset
)

Returns the position within the text field closest to the raw cursor offset.

Implementation

Offset calculateBoundedFloatingCursorOffset(Offset rawCursorOffset) {
  Offset deltaPosition = Offset.zero;
  final double topBound = -floatingCursorAddedMargin.top;
  final double bottomBound = _textPainter.height - preferredLineHeight + floatingCursorAddedMargin.bottom;
  final double leftBound = -floatingCursorAddedMargin.left;
  final double rightBound = _textPainter.width + floatingCursorAddedMargin.right;

  if (_previousOffset != null) {
    deltaPosition = rawCursorOffset - _previousOffset!;
  }

  // If the raw cursor offset has gone off an edge, we want to reset the relative
  // origin of the dragging when the user drags back into the field.
  if (_resetOriginOnLeft && deltaPosition.dx > 0) {
    _relativeOrigin = Offset(rawCursorOffset.dx - leftBound, _relativeOrigin.dy);
    _resetOriginOnLeft = false;
  } else if (_resetOriginOnRight && deltaPosition.dx < 0) {
    _relativeOrigin = Offset(rawCursorOffset.dx - rightBound, _relativeOrigin.dy);
    _resetOriginOnRight = false;
  }
  if (_resetOriginOnTop && deltaPosition.dy > 0) {
    _relativeOrigin = Offset(_relativeOrigin.dx, rawCursorOffset.dy - topBound);
    _resetOriginOnTop = false;
  } else if (_resetOriginOnBottom && deltaPosition.dy < 0) {
    _relativeOrigin = Offset(_relativeOrigin.dx, rawCursorOffset.dy - bottomBound);
    _resetOriginOnBottom = false;
  }

  final double currentX = rawCursorOffset.dx - _relativeOrigin.dx;
  final double currentY = rawCursorOffset.dy - _relativeOrigin.dy;
  final double adjustedX = math.min(math.max(currentX, leftBound), rightBound);
  final double adjustedY = math.min(math.max(currentY, topBound), bottomBound);
  final Offset adjustedOffset = Offset(adjustedX, adjustedY);

  if (currentX < leftBound && deltaPosition.dx < 0) {
    _resetOriginOnLeft = true;
  } else if (currentX > rightBound && deltaPosition.dx > 0) {
    _resetOriginOnRight = true;
  }
  if (currentY < topBound && deltaPosition.dy < 0) {
    _resetOriginOnTop = true;
  } else if (currentY > bottomBound && deltaPosition.dy > 0) {
    _resetOriginOnBottom = true;
  }

  _previousOffset = rawCursorOffset;

  return adjustedOffset;
}