nearest<T extends TransformNode> method

T? nearest<T extends TransformNode>([
  1. Node? within
])

The nearest T to this node among within's descendants, or null if there is none.

Defaults to searching this node's whole tree. Never returns this node.

Implementation

T? nearest<T extends TransformNode>([Node? within]) {
  var root = within;

  if (root == null) {
    root = this;

    while (root!.parent != null) {
      root = root.parent;
    }
  }

  final absolute = absolutePosition;
  T? closest;
  var closestDistance2 = double.infinity;

  for (final descendant in root.descendants) {
    if (descendant is! T || identical(descendant, this)) continue;

    final distance2 = descendant.absolutePosition.distance2(absolute);

    if (distance2 < closestDistance2) {
      closest = descendant;
      closestDistance2 = distance2;
    }
  }

  return closest;
}