observedIdHighlightRect function

Rect? observedIdHighlightRect({
  1. required TestStep step,
  2. required UiObservation observation,
})

Bounds fallback for a step target when its live finder cannot provide a render object (for example, a keyed host wrapper around a text field). Use only a unique, visible observer match so this never invents a target.

Implementation

Rect? observedIdHighlightRect({
  required TestStep step,
  required UiObservation observation,
}) {
  String? id = step.args['id']?.toString();
  if (id == null || id.isEmpty) {
    final target = step.args['target'];
    if (target is Map) {
      id = target['id']?.toString();
    }
  }
  if (id == null || id.isEmpty) return null;

  final matches = <UiElement>[];
  void visit(List<UiElement> elements) {
    for (final element in elements) {
      if (element.testId == id &&
          element.state.visible == true &&
          element.state.offscreen != true &&
          element.bounds != null) {
        matches.add(element);
      }
      visit(element.children);
    }
  }

  visit(observation.elements);
  if (matches.length != 1) return null;
  final bounds = matches.single.bounds!;
  final rect = Rect.fromLTWH(
    bounds.left,
    bounds.top,
    bounds.width,
    bounds.height,
  );
  return rect.isFinite && !rect.isEmpty ? rect : null;
}