absorbFormFieldLabels function
Fold nearby standalone label Text into form controls and drop duplicates.
Implementation
List<({Element element, UiElement ui})> absorbFormFieldLabels(
List<({Element element, UiElement ui})> kept,
) {
return RunnerBenchmark.sync('observer', 'absorbFormFieldLabels', () {
const formTypes = {'textInput', 'switch', 'toggle', 'checkbox', 'dropdown'};
final claimed = <int>{};
final updated = List<({Element element, UiElement ui})>.of(kept);
for (var i = 0; i < kept.length; i++) {
final control = kept[i].ui;
if (!formTypes.contains(control.type)) continue;
// Explicit labels from InputDecoration / semantics are more reliable than
// nearby layout text. Only infer a sibling label when the control has no
// authored label, otherwise a heading above the field can replace it.
if (control.label?.trim().isNotEmpty == true) continue;
final controlBounds = control.bounds;
if (controlBounds == null) continue;
int? bestTextIndex;
var bestScore = double.infinity;
for (var j = 0; j < kept.length; j++) {
if (i == j || claimed.contains(j)) continue;
final textUi = kept[j].ui;
if (textUi.type != 'text') continue;
if (textUi.testId != null && textUi.testId!.isNotEmpty) continue;
final textBounds = textUi.bounds;
if (textBounds == null) continue;
// A full-width heading above a compact checkbox is section copy, not
// the checkbox label. Input labels above full-width fields remain
// eligible for association.
if (control.type == 'checkbox' &&
textBounds.width > controlBounds.width * 2) {
continue;
}
final label = (textUi.text ?? textUi.label)?.trim();
if (label == null || label.isEmpty) continue;
final score = labelAssociationScore(textBounds, controlBounds);
if (score != null && score < bestScore) {
bestScore = score;
bestTextIndex = j;
}
}
if (bestTextIndex == null) continue;
claimed.add(bestTextIndex);
final labelText =
(kept[bestTextIndex].ui.text ?? kept[bestTextIndex].ui.label)!.trim();
updated[i] = (
element: kept[i].element,
ui: refreshObserveActions(control.copyWith(label: labelText)),
);
}
return [
for (var i = 0; i < updated.length; i++)
if (!claimed.contains(i)) updated[i],
];
});
}