calculateBoundedFloatingCursorOffset method

Offset calculateBoundedFloatingCursorOffset(
  1. Offset rawCursorOffset, {
  2. bool? shouldResetOrigin,
})

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

See also:

Implementation

Offset calculateBoundedFloatingCursorOffset(Offset rawCursorOffset, {bool? shouldResetOrigin}) {
  Offset deltaPosition = Offset.zero;
  final double topBound = -floatingCursorAddedMargin.top;
  final double bottomBound = math.min(size.height, _textPainter.height) - preferredLineHeight + floatingCursorAddedMargin.bottom;
  final double leftBound = -floatingCursorAddedMargin.left;
  final double rightBound = math.min(size.width, _textPainter.width) + floatingCursorAddedMargin.right;
  final Rect boundingRects = Rect.fromLTRB(leftBound, topBound, rightBound, bottomBound);

  if (shouldResetOrigin != null) {
    _shouldResetOrigin = shouldResetOrigin;
  }

  if (!_shouldResetOrigin) {
    return _calculateAdjustedCursorOffset(rawCursorOffset, boundingRects);
  }

  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 - boundingRects.left, _relativeOrigin.dy);
    _resetOriginOnLeft = false;
  } else if (_resetOriginOnRight && deltaPosition.dx < 0) {
    _relativeOrigin = Offset(rawCursorOffset.dx - boundingRects.right, _relativeOrigin.dy);
    _resetOriginOnRight = false;
  }
  if (_resetOriginOnTop && deltaPosition.dy > 0) {
    _relativeOrigin = Offset(_relativeOrigin.dx, rawCursorOffset.dy - boundingRects.top);
    _resetOriginOnTop = false;
  } else if (_resetOriginOnBottom && deltaPosition.dy < 0) {
    _relativeOrigin = Offset(_relativeOrigin.dx, rawCursorOffset.dy - boundingRects.bottom);
    _resetOriginOnBottom = false;
  }

  final double currentX = rawCursorOffset.dx - _relativeOrigin.dx;
  final double currentY = rawCursorOffset.dy - _relativeOrigin.dy;
  final Offset adjustedOffset = _calculateAdjustedCursorOffset(Offset(currentX, currentY), boundingRects);

  if (currentX < boundingRects.left && deltaPosition.dx < 0) {
    _resetOriginOnLeft = true;
  } else if (currentX > boundingRects.right && deltaPosition.dx > 0) {
    _resetOriginOnRight = true;
  }
  if (currentY < boundingRects.top && deltaPosition.dy < 0) {
    _resetOriginOnTop = true;
  } else if (currentY > boundingRects.bottom && deltaPosition.dy > 0) {
    _resetOriginOnBottom = true;
  }

  _previousOffset = rawCursorOffset;

  return adjustedOffset;
}