hitTest method

bool hitTest({
  1. required Connection connection,
  2. required Node sourceNode,
  3. required Node targetNode,
  4. required Offset testPoint,
  5. double? tolerance,
})

Test if a point hits a connection path Returns true if the point is within the hit tolerance of the connection

Implementation

bool hitTest({
  required Connection connection,
  required Node sourceNode,
  required Node targetNode,
  required Offset testPoint,
  double? tolerance,
}) {
  final hitTolerance = tolerance ?? defaultHitTolerance;
  final connectionStyle = theme.connectionTheme.style;

  // Get cached path
  final cachedPath = _getCachedPath(connection.id);
  final currentSourcePos = sourceNode.position.value;
  final currentTargetPos = targetNode.position.value;

  // Check if cache is valid (positions match)
  final cacheValid =
      cachedPath != null &&
      cachedPath.sourcePosition == currentSourcePos &&
      cachedPath.targetPosition == currentTargetPos;

  if (cacheValid) {
    // Use the pre-computed hit test path (already expanded for tolerance)
    // Only recompute if tolerance differs significantly from default
    if ((hitTolerance - defaultHitTolerance).abs() > 1.0) {
      // Custom tolerance - recompute hit test with new tolerance
      // Note: We'd need the segments to do this properly, but for now
      // we can use the cached path bounds with adjusted tolerance
      // This is a simplification - for full accuracy we'd cache segments too
      return cachedPath.hitTestPath.contains(testPoint);
    }

    // Use cached hit test path (most common case)
    return cachedPath.hitTestPath.contains(testPoint);
  }

  // Cache is stale or missing - compute path on-demand for hit testing
  // This ensures hit testing works even before the next paint cycle
  final newCachedPath = _createAndCachePath(
    connection: connection,
    sourceNode: sourceNode,
    targetNode: targetNode,
    sourcePosition: currentSourcePos,
    targetPosition: currentTargetPos,
    connectionStyle: connectionStyle,
    startGap: connection.startGap ?? theme.connectionTheme.startGap,
    endGap: connection.endGap ?? theme.connectionTheme.endGap,
  );

  if (newCachedPath == null) {
    return false; // Could not create path (missing ports, etc.)
  }

  // Use the newly created hit test path
  // Note: Custom tolerance handling simplified - use default tolerance
  return newCachedPath.hitTestPath.contains(testPoint);
}