Fix the accessible name lookup for a form control

Review the AI's codeEasy12 min

Your task

A screen reader user tabs into your search form and hears "edit text, blank". The form has a <label>Search</label> next to the input, but nothing ties the label to it, and the placeholder does not count as a name. Your team wants a function that computes a control's accessible name: the name a screen reader announces for it.

An assistant wrote accessible_name(attrs, labels). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • attrs: the control's attributes, as key=value pairs joined by ";", such as "id=q;type=text;placeholder=Search". It can be empty.
  • labels: the form's label elements. Each is "for=<id>|<text>" for a label with htmlFor, or "wraps=<id>|<text>" for a label wrapped around the control.
  • Return the accessible name as a string, or "" when the control has none.

Rules the tests check:

  • Read attrs by splitting on ";", then splitting each pair at its first "=". Skip a pair with no "=" or an empty key. Keys are case sensitive. Trim whitespace from both ends of each value. If a key repeats, the last one wins.
  • Only three keys matter: id, aria-label, and text, which is the control's own text content. Every other key is ignored, including placeholder and title.
  • First, a non-empty aria-label is the name.
  • Otherwise, if the control has a non-empty id, use the first label that points at that control and has non-empty text.
  • To read a label, split it at its first "|" into a target and a text. Split the target at its first "=" into a kind and an id. Skip a label with no "|", no "=" in the target, or an empty kind.
  • A label points at the control when its kind is exactly "for" or "wraps" and its id, trimmed, equals the control's id. Its text is trimmed before use.
  • Otherwise, a non-empty text is the name.
  • Otherwise, return "".

Examples

accessible_name(attrs: str, labels: list[str]) -> str
Example 1
Inputaccessible_name("id=q;type=text;placeholder=Search", ["for=q|Search"])
Output"Search"
Example 2
Inputaccessible_name("id=q;type=text;placeholder=Search", [])
Output""
Example 3
Inputaccessible_name("id=submit;aria-label=Submit search", [])
Output"Submit search"