Fix the accessible name lookup for a form control
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, askey=valuepairs 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 withhtmlFor, 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
attrsby 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, andtext, which is the control's own text content. Every other key is ignored, includingplaceholderandtitle. - First, a non-empty
aria-labelis 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'sid. Its text is trimmed before use. - Otherwise, a non-empty
textis the name. - Otherwise, return
"".
Examples
accessible_name(attrs: str, labels: list[str]) -> strExample 1
Input
accessible_name("id=q;type=text;placeholder=Search", ["for=q|Search"])Output
"Search"Example 2
Input
accessible_name("id=q;type=text;placeholder=Search", [])Output
""Example 3
Input
accessible_name("id=submit;aria-label=Submit search", [])Output
"Submit search"