Skip to content

UI Guidelines sample: building a country combobox

Sample output. A spec and React code for a type-to-filter country picker with about 200 countries, for a fictional train-ticket startup, with the counts from 14 design systems, the WCAG 2.2 criteria and what still needs testing.

UI Guidelines sample: building a country combobox

This is one of three samples made with UI Guidelines, published here in full so you can see what the skill produces before you buy.

UI Guidelines sample: building a country combobox

Sample output, not a customer story. Produced in a test run of UI Guidelines v1.1 on 22 November 2026. The company and the request are fictional and the buyer's messages were scripted, including a few requests the skill should refuse. Code shown has not been tested with a screen reader. Shown in full so you can see what the skill produces before you buy.

What the buyer asked for

The front-end lead at Wayfarer Rail, a small train-ticket startup, needed a country picker for the passenger form: React 18 and TypeScript, about 200 countries, type to filter, working on phones. They had read that "18 of 20 design systems call this Autocomplete", and later asked for a line saying the picker is "fully WCAG 2.2 AA compliant".

How it was made
  • The naming question answered from the research: 14 systems, not 20, with the real counts for Combobox and Autocomplete.
  • A spec in the skill's layout: anatomy, props, states, a keyboard table on the W3C combobox pattern, roles and attributes, content rules and acceptance checks.
  • Every WCAG 2.2 criterion cited with its number, name and level. Mobile notes labelled as outside the research.
  • Full React and TypeScript code, reviewed for bugs before it was handed over.
  • The "fully compliant" line declined. A status sentence with blanks was offered instead, to fill in after testing.

The full run follows, including the complete code.

Try it live: run this country combobox in your browser. It is the code below, unchanged, with keyboard and mouse checks done. It has not been tested with a screen reader.


Buyer

I'm the front-end lead at Wayfarer Rail, a small train-ticket booking startup. React 18 with TypeScript, plain CSS modules, no design system yet. I need a country picker for the passenger details form: about 200 countries, type to filter, works on phones. Also, I read that 18 of 20 design systems call this Autocomplete, is that right?

Assistant

There are two parts here: a Build (a spec and React code for a type-to-filter country picker) and a quick fact check on the name. I'll do them in your order.

Context. I'm reading the platform as web, including phone browsers, since you're on React with CSS modules. You didn't give an accessibility target, so I'm assuming WCAG 2.2 AA (Web Content Accessibility Guidelines, level AA). Tell me if either is wrong.

Which component. "Type to filter" over a long fixed list is a combobox: a text input joined to a popup list that narrows as you type. In the research, 6 of 14 systems recommend a combobox when the list is long enough that typing helps (Material 3, Carbon, Atlassian, Spectrum, Fluent 2, Lightning). A native <select> is the fallback if you ever need the simplest possible build: it has no type-to-filter, but it needs no custom keyboard code.


Spec: CountryCombobox

1. Name. CountryCombobox. A field where the passenger types part of a country name and picks it from a filtered list. You have no design system, so every name below is new; it uses React's usual value / onChange shape.

2. When to use, when not to

  • Use for picking one country from about 200.
  • Do not use for a short list with no typing needed: use radio buttons or a select. Spectrum and Primer put the line at around 6 items.
  • The field must be finishable without tapping a suggestion: typing a full country name (or a known alias such as "UK") and leaving the field accepts it.

3. Anatomy

  • Label (visible, always)
  • Hint text under the label, replaced by the error when there is one
  • Text input with role="combobox"
  • Toggle button (chevron) that shows the list, for people who want to browse
  • Popup listbox of options; a tick on the current country
  • No-results message
  • Hidden status region that announces the result count
  • Hidden form input carrying the country code

4. Props

PropTypeDefaultWhat it does
labelstringrequiredVisible label text
countriesCountry[]required{ code, name, aliases? }; code is ISO 3166-1 alpha-2
value`string \null`requiredChosen country code
onChange`(code: string \null) => void`requiredCalled with a code, or null when cleared or not matched
namestringnoneForm field name for the hidden input
hintstringnoneHelp text under the label
errorstringnoneError from your form validation (for example "Enter your country of residence")
requiredbooleanfalseSets aria-required
disabledbooleanfalseTurns the field off

Left out on purpose:

  • Free entry (8 systems document it): a country must come from the list, so a typed value that matches nothing gets an error when the passenger leaves the field.
  • Multiple selection (7): one country per passenger.
  • Async options (5): 200 countries ship with the page.
  • Virtualised list (3): 200 options render fine without it.
  • Clear button (5): deleting the text works on every keyboard, and one trailing button keeps the field simpler on a phone. Escape twice also clears on a hardware keyboard.

5. States

StateLooksAnnounced
Default (empty)Label, hint, empty box, chevronLabel, hint, "combobox", collapsed
Focus2px blue outline outside the boxAs default
FilledCountry name in the boxLabel and value
OpenList below the box, scrolls insideExpanded; "12 countries available" after typing pauses
Highlighted optionBlue background, white textThe option name, via aria-activedescendant
No resultsText below the box: No countries match "xyz""No countries found"
ErrorRed border, error text replaces hintError text read with the field (aria-describedby), and announced when it appears
DisabledGreyed, not focusableSkipped in tab order

Hover styles appear only on devices that can hover; hover is never the only cue.

6. Keyboard (W3C APG Combobox pattern, editable list version; DOM focus never leaves the input)

KeyAction
TypingEdits the text, opens and filters the list
SpaceTypes a space (it does not select)
Down ArrowOpens the list and highlights the current country (or the first); in the list, next option (wraps)
Up ArrowOpens the list on the last option; in the list, previous option (wraps)
Alt+DownOpens the list without highlighting
Alt+UpCloses the list
EnterWith the list open: accepts the highlighted option (or an exact typed name), closes, puts the name in the box. With the list closed and typed text that is not yet confirmed: confirms it, or shows the no-match error (the form does not submit on Enter until the box holds a country or is empty). Otherwise: submits the form as normal
EscapeFirst press closes the list and keeps the text; a second press clears the text
Left / Right Arrow, Home / EndMove the caret in the box; the highlight goes back to the input
TabLeaves the field. It never picks the highlighted option; an exact typed name is accepted, anything else gets an error

7. Accessibility

  • Pattern: W3C ARIA Authoring Practices Guide (APG), Combobox pattern, with a Listbox popup; aria-autocomplete="list" (the list filters, the text is not auto-completed inline).
  • Input: role="combobox", aria-expanded, aria-controls pointing to the listbox (always set: the listbox stays in the page, hidden, when closed), aria-autocomplete="list", aria-activedescendant pointing to the highlighted option while the list is open, aria-describedby to the hint or error, aria-invalid on error, aria-required when required, autocomplete="country-name".
  • Listbox: role="listbox", named by the label (aria-labelledby). Options have role="option", and aria-selected="true" is on the highlighted option (the one aria-activedescendant points to), as in the APG examples. The current country gets a visual tick only, because its name is already in the box.
  • Toggle button: aria-label="Show countries", aria-expanded, aria-controls, out of the tab order (tabindex="-1") because Down Arrow does the same from the keyboard.
  • Focus: the input is the only Tab stop. Tapping an option or the chevron keeps focus in the input.
  • Announcements: result count, after typing pauses for half a second, so fast typing does not flood the screen reader; "No countries found"; errors as they appear. None of these moves focus.
  • WCAG 2.2 criteria:
    • 1.3.1 Info and Relationships (A): label, hint and error tied to the input in code
    • 1.3.5 Identify Input Purpose (AA): autocomplete="country-name"
    • 1.4.3 Contrast (Minimum) (AA): text at least 4.5:1
    • 1.4.10 Reflow (AA): works at 320 CSS pixels wide
    • 1.4.11 Non-text Contrast (AA): border, chevron and focus outline at least 3:1
    • 2.1.1 Keyboard (A): every action from the keyboard
    • 2.4.7 Focus Visible (AA) and 2.4.11 Focus Not Obscured (Minimum) (AA): the outline shows, and the open list or a sticky footer does not hide the input or the highlighted option
    • 2.5.3 Label in Name (A): accessible name is the visible label
    • 2.5.8 Target Size (Minimum) (AA): options and chevron are 44 by 44 CSS pixels, above the 24 minimum (44 is the AAA level, 2.5.5 Target Size (Enhanced) (AAA))
    • 3.2.2 On Input (A): highlighting an option changes nothing until it is accepted
    • 3.3.1 Error Identification (A) and 3.3.3 Error Suggestion (AA): error in text, saying how to fix it
    • 3.3.2 Labels or Instructions (A): visible label and hint
    • 4.1.2 Name, Role, Value (A): role, name, expanded state and highlighted option exposed
    • 4.1.3 Status Messages (AA): result count, no results and errors announced without moving focus

Colours (calculated with the WCAG relative luminance formula, not measured; change them to your brand, then recalculate)

PairL (foreground)L (background)RatioNeeds
Text #1a1a1a on #ffffff0.01031.0(1.0 + 0.05) / (0.0103 + 0.05) = 17.4:14.5:1
Hint #4a4a4a on #ffffff0.06851.01.05 / 0.1185 = 8.86:14.5:1
Border and chevron #6b6b6b on #ffffff0.1471.01.05 / 0.197 = 5.33:13:1
Focus outline and highlight #1d4ed8 on #ffffff (and white text on it)0.10671.01.05 / 0.1567 = 6.70:13:1 outline, 4.5:1 text
Error #b42318 on #ffffff0.10971.01.05 / 0.1597 = 6.57:14.5:1

Working, per channel: c = value/255; c/12.92 if c is 0.04045 or less, else ((c + 0.055)/1.055)^2.4; L = 0.2126 R + 0.7152 G + 0.0722 B; ratio = (lighter L + 0.05) / (darker L + 0.05). Example for #6b6b6b: 107/255 = 0.4196; ((0.4196 + 0.055)/1.055)^2.4 = 0.147 for each channel, so L = 0.147.

8. Content rules

  • Label: what to enter, short, sentence case, no colon: "Country of residence" (or "Nationality", whichever your ticketing needs; they are different questions).
  • Hint: "Start typing, then choose from the list".
  • Placeholder: none. It vanishes on typing and is not a label.
  • Error, nothing typed (from your form): "Enter your country of residence".
  • Error, no match (from the component): No country called "Frnace". Check the spelling, or choose a country from the list. It keeps what the passenger typed.
  • Matching ignores case and accents, so "cote" finds Côte d'Ivoire. Names that start with the text come first.
  • Add aliases people really type: UK, Britain, USA, America, Holland.

9. Acceptance checks

  • [ ] Input has role="combobox", aria-expanded, aria-controls (set even when closed) and aria-autocomplete="list"
  • [ ] Highlighted option is the target of aria-activedescendant and has aria-selected="true"; focus stays in the input
  • [ ] Every key in the table works; first Escape closes and keeps the text; Tab never picks the highlighted option
  • [ ] Result count, no results and errors announced without moving focus
  • [ ] Typing a full name or alias and leaving the field accepts it; anything else shows the no-match error on leaving, not while typing
  • [ ] Visible label tied to the input; no essential text in a placeholder
  • [ ] autocomplete="country-name" set; browser autofill fills the field and sets the value
  • [ ] Open list does not cover the input or the highlighted option, including with the phone keyboard up
  • [ ] Options and chevron at least 24 by 24 CSS pixels (built at 44)
  • [ ] Border, chevron and focus outline at least 3:1; text at least 4.5:1
  • [ ] Input text is at least 16px
  • [ ] Works at 320 CSS pixels wide and 200% zoom

10. Test it (see the full test list after the code)

11. Basis. The research covers 14 public design systems plus the W3C APG and WCAG 2.2, read on 20 November 2026. 8 of 14 systems have a combobox, 4 partly, 2 not at all. The keyboard, ARIA and focus rules follow the APG Combobox pattern. Where the systems disagree, the spec follows the research's recommendations: Space types (Carbon types, Fluent 2 selects after arrowing); the list opens on typing or Down Arrow, not on focus (Spectrum lets you choose, Lightning opens on click or focus); the first Escape closes and keeps the text (Carbon may clear typed text); Tab does not commit the highlight (Spectrum and Lightning commit on Tab), so a value is chosen only by Enter, a tap, or a complete typed name. The no-results message is documented by 5 systems, the disabled state by 8, the error state by 5. A visible label is asked for by 7 systems for the combobox and 9 for text inputs. Case-insensitive matching is documented by 3. Swapping the hint for the error follows 4 systems (Material 3, Spectrum, Carbon, Fluent 2). The hidden "Error:" before the message follows GOV.UK.


Code

Three files: the component, its CSS module, and an example of use with the country data.

// CountryCombobox.tsx
import { useEffect, useId, useMemo, useRef, useState } from 'react';
import type { KeyboardEvent as ReactKeyboardEvent, RefObject } from 'react';
import styles from './CountryCombobox.module.css';

export type Country = {
  /** ISO 3166-1 alpha-2 code, for example "FR" */
  code: string;
  /** Name shown in the list, for example "France" */
  name: string;
  /** Other names people type, for example ["UK", "Britain"] */
  aliases?: string[];
};

export type CountryComboboxProps = {
  label: string;
  countries: Country[];
  value: string | null;
  onChange: (code: string | null) => void;
  name?: string;
  hint?: string;
  error?: string;
  required?: boolean;
  disabled?: boolean;
};

// Lower case, accents removed and curly apostrophes made straight,
// so "cote d'ivoire" finds "Côte d’Ivoire".
function normalise(s: string): string {
  return s
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    .replace(/\u2019/g, "'")
    .toLowerCase()
    .trim();
}

// Names (or aliases) that start with the text come first, then names that contain it.
function filterCountries(countries: Country[], query: string): Country[] {
  const q = normalise(query);
  if (!q) return countries;
  const starts: Country[] = [];
  const contains: Country[] = [];
  for (const c of countries) {
    const n = normalise(c.name);
    const aliasStarts = (c.aliases ?? []).some((a) => normalise(a).startsWith(q));
    if (n.startsWith(q) || aliasStarts) starts.push(c);
    else if (n.includes(q)) contains.push(c);
  }
  return [...starts, ...contains];
}

// A country whose name or alias equals the typed text.
function findExact(countries: Country[], text: string): Country | undefined {
  const t = normalise(text);
  if (!t) return undefined;
  return countries.find(
    (c) => normalise(c.name) === t || (c.aliases ?? []).some((a) => normalise(a) === t),
  );
}

// Fit the list into the space between the field and the bottom of the visible
// area, which shrinks when the phone keyboard opens. Falls back to the CSS
// max-height where window.visualViewport is not available.
function useListMaxHeight(open: boolean, anchorRef: RefObject<HTMLElement>): number | undefined {
  const [maxHeight, setMaxHeight] = useState<number | undefined>(undefined);

  useEffect(() => {
    const vv = window.visualViewport;
    if (!open || !vv) return;
    const update = () => {
      const anchor = anchorRef.current;
      if (!anchor) return;
      const bottom = anchor.getBoundingClientRect().bottom;
      const space = vv.offsetTop + vv.height - bottom - 8;
      setMaxHeight(Math.max(132, Math.min(320, Math.floor(space))));
    };
    update();
    vv.addEventListener('resize', update);
    vv.addEventListener('scroll', update);
    window.addEventListener('scroll', update, { passive: true });
    return () => {
      vv.removeEventListener('resize', update);
      vv.removeEventListener('scroll', update);
      window.removeEventListener('scroll', update);
    };
  }, [open, anchorRef]);

  return maxHeight;
}

export function CountryCombobox({
  label,
  countries,
  value,
  onChange,
  name,
  hint,
  error,
  required = false,
  disabled = false,
}: CountryComboboxProps) {
  const baseId = useId();
  const inputId = `${baseId}-input`;
  const labelId = `${baseId}-label`;
  const listId = `${baseId}-list`;
  const hintId = `${baseId}-hint`;
  const errorId = `${baseId}-error`;
  const optionId = (code: string) => `${baseId}-opt-${code}`;

  const rootRef = useRef<HTMLDivElement>(null);
  const fieldRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  const selected = countries.find((c) => c.code === value);
  const selectedName = selected?.name;

  const [text, setText] = useState(selectedName ?? '');
  const [open, setOpen] = useState(false);
  const [activeIndex, setActiveIndex] = useState(-1);
  const [localError, setLocalError] = useState<string | null>(null);
  const [status, setStatus] = useState('');

  // Show the chosen country's name when the value is set from outside.
  // Depends on the name string, not the object, so a new countries array
  // on each parent render does not overwrite what the passenger is typing.
  useEffect(() => {
    if (selectedName !== undefined) setText(selectedName);
  }, [selectedName]);

  // While the box shows the chosen country, browse the full list;
  // otherwise filter by what is typed.
  const query = selectedName !== undefined && text === selectedName ? '' : text;
  const results = useMemo(() => filterCountries(countries, query), [countries, query]);
  const expanded = open && results.length > 0;
  const noResults = open && results.length === 0;
  const active = expanded && activeIndex >= 0 ? results[activeIndex] : undefined;
  const activeId = active ? optionId(active.code) : undefined;
  const shownError = error ?? localError ?? undefined;
  const describedBy = shownError ? errorId : hint ? hintId : undefined;

  const maxHeight = useListMaxHeight(open, fieldRef);

  // Result count for screen readers, sent after typing pauses for 500 ms.
  const announcement = !open
    ? ''
    : results.length === 0
      ? 'No countries found'
      : `${results.length} ${results.length === 1 ? 'country' : 'countries'} available`;
  useEffect(() => {
    const timer = window.setTimeout(() => setStatus(announcement), 500);
    return () => window.clearTimeout(timer);
  }, [announcement]);

  // Keep the highlighted option in view inside the list.
  useEffect(() => {
    if (activeId) document.getElementById(activeId)?.scrollIntoView({ block: 'nearest' });
  }, [activeId]);

  // Close on a tap or click outside, in case the input does not lose focus.
  useEffect(() => {
    if (!open) return;
    const onPointerDown = (e: PointerEvent) => {
      if (!rootRef.current?.contains(e.target as Node)) {
        setOpen(false);
        setActiveIndex(-1);
      }
    };
    document.addEventListener('pointerdown', onPointerDown);
    return () => document.removeEventListener('pointerdown', onPointerDown);
  }, [open]);

  function openList(highlight: number) {
    setOpen(true);
    setActiveIndex(highlight);
  }

  function closeList() {
    setOpen(false);
    setActiveIndex(-1);
  }

  function choose(country: Country) {
    setText(country.name);
    setLocalError(null);
    closeList();
    if (country.code !== value) onChange(country.code);
  }

  // True when the box holds text that has not been confirmed as a country.
  const unconfirmed = text.trim() !== '' && text !== selectedName;

  // On leaving the field: accept an exact name or alias, clear an empty box,
  // otherwise keep the text and explain. Never commits the highlighted option.
  function commitTypedText() {
    if (text.trim() === '') {
      setLocalError(null);
      if (value !== null) onChange(null);
      return;
    }
    if (!unconfirmed) return;
    const match = findExact(countries, text);
    if (match) {
      choose(match);
    } else {
      setLocalError(
        `No country called "${text.trim()}". Check the spelling, or choose a country from the list.`,
      );
      if (value !== null) onChange(null);
    }
  }

  function handleInputChange(next: string) {
    setText(next);
    // Browser autofill can fill this field while another field has focus:
    // accept an exact match instead of opening a list nobody is looking at.
    if (document.activeElement !== inputRef.current) {
      const match = findExact(countries, next);
      if (match) choose(match);
      return;
    }
    openList(-1);
  }

  function handleKeyDown(e: ReactKeyboardEvent<HTMLInputElement>) {
    // Ignore keys used to compose characters with an input method editor.
    if (e.nativeEvent.isComposing) return;
    const last = results.length - 1;

    switch (e.key) {
      case 'ArrowDown': {
        e.preventDefault();
        if (e.altKey) {
          setOpen(true);
          return;
        }
        if (!expanded) {
          const current = selected ? results.indexOf(selected) : -1;
          openList(current >= 0 ? current : 0);
        } else {
          setActiveIndex(activeIndex >= last ? 0 : activeIndex + 1);
        }
        return;
      }
      case 'ArrowUp': {
        e.preventDefault();
        if (e.altKey) {
          closeList();
          return;
        }
        if (!expanded) openList(last);
        else setActiveIndex(activeIndex <= 0 ? last : activeIndex - 1);
        return;
      }
      case 'Enter': {
        if (open) {
          e.preventDefault();
          if (active) {
            choose(active);
          } else {
            const match = findExact(countries, text);
            if (match) choose(match);
          }
          return;
        }
        // List closed: confirm typed text first; the next Enter submits the form.
        if (unconfirmed) {
          e.preventDefault();
          commitTypedText();
        }
        return;
      }
      case 'Escape': {
        if (open) {
          // First Escape: close the list, keep the text, and stop a parent dialog closing too.
          e.preventDefault();
          e.stopPropagation();
          closeList();
          return;
        }
        if (text !== '') {
          // Second Escape: clear the box.
          e.preventDefault();
          setText('');
          setLocalError(null);
          if (value !== null) onChange(null);
        }
        return;
      }
      case 'ArrowLeft':
      case 'ArrowRight':
      case 'Home':
      case 'End':
        // The browser moves the caret; the highlight goes back to the input.
        setActiveIndex(-1);
        return;
      default:
        // Tab and Space are left to the browser: Tab leaves, Space types.
        return;
    }
  }

  function handleToggleClick() {
    if (expanded) {
      closeList();
      return;
    }
    inputRef.current?.focus();
    const current = selected ? results.indexOf(selected) : -1;
    openList(current);
  }

  return (
    <div ref={rootRef} className={styles.root}>
      <label id={labelId} htmlFor={inputId} className={styles.label}>
        {label}
      </label>

      {hint && !shownError && (
        <p id={hintId} className={styles.hint}>
          {hint}
        </p>
      )}

      {/* Always in the page, so an error that appears is announced. */}
      <div aria-live="polite">
        {shownError && (
          <p id={errorId} className={styles.error}>
            <span className={styles.visuallyHidden}>Error: </span>
            {shownError}
          </p>
        )}
      </div>

      <div ref={fieldRef} className={styles.field}>
        <input
          ref={inputRef}
          id={inputId}
          type="text"
          role="combobox"
          className={styles.input}
          value={text}
          disabled={disabled}
          autoComplete="country-name"
          autoCorrect="off"
          spellCheck={false}
          aria-autocomplete="list"
          aria-expanded={expanded}
          aria-controls={listId}
          aria-activedescendant={activeId}
          aria-describedby={describedBy}
          aria-invalid={shownError ? true : undefined}
          aria-required={required || undefined}
          onChange={(e) => handleInputChange(e.target.value)}
          onKeyDown={handleKeyDown}
          onBlur={() => {
            closeList();
            commitTypedText();
          }}
        />

        <button
          type="button"
          className={styles.toggle}
          tabIndex={-1}
          aria-label="Show countries"
          aria-expanded={expanded}
          aria-controls={listId}
          disabled={disabled}
          // Keep focus in the input when the button is pressed.
          onMouseDown={(e) => e.preventDefault()}
          onClick={handleToggleClick}
        >
          <svg aria-hidden="true" focusable="false" width="16" height="16" viewBox="0 0 16 16">
            <path d="M3 6l5 5 5-5" fill="none" stroke="currentColor" strokeWidth="2" />
          </svg>
        </button>

        {/* Always in the page (hidden when closed), so aria-controls always points to it. */}
        <ul
          id={listId}
          role="listbox"
          aria-labelledby={labelId}
          hidden={!expanded}
          className={styles.list}
          style={maxHeight !== undefined ? { maxHeight } : undefined}
          // A tap or click on the list must not take focus from the input.
          onMouseDown={(e) => e.preventDefault()}
        >
          {results.map((c) => {
            const isActive = c === active;
            return (
              <li
                key={c.code}
                id={optionId(c.code)}
                role="option"
                aria-selected={isActive}
                className={styles.option}
                onClick={() => choose(c)}
              >
                <span>{c.name}</span>
                {c.code === value && (
                  <span aria-hidden="true" className={styles.tick}>
                    ✓
                  </span>
                )}
              </li>
            );
          })}
        </ul>

        {noResults && <p className={styles.noResults}>No countries match "{text.trim()}"</p>}
      </div>

      <div role="status" className={styles.visuallyHidden}>
        {status}
      </div>

      {name && <input type="hidden" name={name} value={value ?? ''} />}
    </div>
  );
}
/* CountryCombobox.module.css */
.root {
  --cc-text: #1a1a1a;
  --cc-hint: #4a4a4a;
  --cc-border: #6b6b6b;
  --cc-accent: #1d4ed8;
  --cc-error: #b42318;
  --cc-hover: #f1f5f9;
  color: var(--cc-text);
  max-width: 28rem;
}

.label {
  display: block;
  font-weight: 600;
  margin-bottom: 0.25rem;
}

.hint {
  color: var(--cc-hint);
  margin: 0 0 0.5rem;
}

.error {
  color: var(--cc-error);
  font-weight: 600;
  margin: 0 0 0.5rem;
}

.field {
  position: relative;
}

.input {
  box-sizing: border-box;
  width: 100%;
  min-height: 44px;
  padding: 0.5rem 3rem 0.5rem 0.75rem;
  /* 16px or more, so iOS Safari does not zoom in on focus */
  font-size: max(1rem, 16px);
  color: var(--cc-text);
  background: #fff;
  border: 2px solid var(--cc-border);
  border-radius: 6px;
}

.input:focus {
  outline: 3px solid var(--cc-accent);
  outline-offset: 2px;
}

.input[aria-invalid='true'] {
  border-color: var(--cc-error);
}

.input:disabled,
.toggle:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.toggle {
  position: absolute;
  top: 0;
  right: 0;
  width: 44px;
  height: 44px;
  display: grid;
  place-items: center;
  padding: 0;
  border: 0;
  background: transparent;
  color: var(--cc-border);
  cursor: pointer;
}

.list {
  position: absolute;
  z-index: 10;
  top: calc(100% + 4px);
  left: 0;
  right: 0;
  max-height: 320px;
  overflow-y: auto;
  overscroll-behavior: contain;
  margin: 0;
  padding: 4px 0;
  list-style: none;
  background: #fff;
  border: 2px solid var(--cc-border);
  border-radius: 6px;
}

/* The hidden attribute must win over any display rule. */
.list[hidden] {
  display: none;
}

.option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 44px;
  padding: 0 0.75rem;
  cursor: pointer;
}

@media (hover: hover) {
  .option:hover {
    background: var(--cc-hover);
  }
}

.option[aria-selected='true'] {
  background: var(--cc-accent);
  color: #fff;
}

/* Windows high contrast removes backgrounds: draw an outline instead. */
@media (forced-colors: active) {
  .option[aria-selected='true'] {
    outline: 2px solid Highlight;
    outline-offset: -2px;
  }
}

.tick {
  font-weight: 700;
}

.noResults {
  position: absolute;
  z-index: 10;
  top: calc(100% + 4px);
  left: 0;
  right: 0;
  margin: 0;
  padding: 0.75rem;
  background: #fff;
  border: 2px solid var(--cc-border);
  border-radius: 6px;
}

.visuallyHidden {
  position: absolute;
  width: 1px;
  height: 1px;
  margin: -1px;
  padding: 0;
  overflow: hidden;
  clip: rect(0 0 0 0);
  white-space: nowrap;
  border: 0;
}
// countries.ts: build the list from ISO codes with the browser's own country names.
import type { Country } from './CountryCombobox';

// Your full ISO 3166-1 alpha-2 list goes here (about 250 codes; keep the ones you sell to).
const CODES = ['AT', 'BE', 'CH', 'CI', 'DE', 'ES', 'FR', 'GB', 'IE', 'IN', 'IT', 'NL', 'US' /* ... */];

const ALIASES: Record<string, string[]> = {
  GB: ['UK', 'Britain', 'Great Britain', 'England', 'Scotland', 'Wales', 'Northern Ireland'],
  US: ['USA', 'America', 'United States of America'],
  NL: ['Holland'],
};

const regionNames = new Intl.DisplayNames(['en-GB'], { type: 'region' });

export const COUNTRIES: Country[] = CODES.map((code) => ({
  code,
  name: regionNames.of(code) ?? code,
  aliases: ALIASES[code],
})).sort((a, b) => a.name.localeCompare(b.name, 'en-GB'));
// In the passenger details form
const [country, setCountry] = useState<string | null>(null);
const [submitted, setSubmitted] = useState(false);

<CountryCombobox
  label="Country of residence"
  hint="Start typing, then choose from the list"
  countries={COUNTRIES}
  value={country}
  onChange={setCountry}
  name="countryOfResidence"
  required
  error={submitted && !country ? 'Enter your country of residence' : undefined}
/>

Notes on the code:

  • Every API used is standard React 18 or the browser: useId, useMemo, useRef, useState, useEffect, window.visualViewport, scrollIntoView, String.prototype.normalize, KeyboardEvent.isComposing, Intl.DisplayNames. Intl.DisplayNames needs the TypeScript lib set to es2020 or later; if your setup does not have it, write the names out as a plain array.
  • The CSS module import assumes your build already types *.module.css files (Vite and Create React App do).
  • To reset the field from outside (for example "clear form"), give the component a new key. Setting value to null alone keeps any text the passenger typed, on purpose, so a no-match error never wipes their typing.
  • A linter such as eslint-plugin-jsx-a11y may flag onClick on the <li> without a key handler. That is expected here: the keyboard is handled on the input, as the APG pattern does.
  • Needs testing on real assistive technology: the result-count announcement, the error announcement, and whether VoiceOver on iOS can swipe from the input to the options.

Mobile web notes. These are not from this skill's research; check them on real devices.

  • Phone keyboard covering the list: the list height follows window.visualViewport, so it fits the space between the field and the keyboard, with a floor of 132px (three options). If the field sits low on the screen, that floor can still go under the keyboard; scrolling the passenger form so the field sits near the top on focus is a design choice to test.
  • No zoom on focus: input text is at least 16px, so iOS Safari does not zoom in.
  • Picking by touch: options are 44px tall and selected on click, so dragging to scroll the list does not pick anything. onMouseDown with preventDefault keeps focus (and the keyboard) in the input when an option or the chevron is tapped; check this on iOS Safari and Android Chrome, because if the input loses focus first, the list closes before the tap lands.
  • Tap outside: a pointerdown listener closes the list in case tapping elsewhere does not blur the input.
  • Autofill: autocomplete="country-name" lets the browser fill the field; the component accepts an exact match even when the field is not focused. Some browsers show their own autofill popup over the field; check it does not fight the list.
  • Escape on phones: most on-screen keyboards have no Escape key. Closing is by tapping outside, the chevron, or the keyboard's done button.
  • Native alternative: <input list> with <datalist> gives native suggestions with no custom code, but its look and behaviour vary by browser and it does not restrict the value to the list. Not from this skill's research; check MDN's <datalist> page.

Test list

  1. Keyboard only: unplug the mouse. Tab in, type "fra", arrow through, Enter. Check Escape (once closes, twice clears), Alt+Down, Alt+Up, Home, End. Tab out with an option highlighted and confirm the value did not change.
  2. Screen reader: NVDA with Firefox or Chrome on Windows, or VoiceOver with Safari on macOS; and VoiceOver on iOS or TalkBack on Android. Check the field reads as a combobox with its label, hint and expanded state; the highlighted option is read as you arrow; "12 countries available" and "No countries found" are read; the error is read when it appears. On iOS VoiceOver, check you can swipe from the input to the options (Fluent 2 flags a Safari issue here).
  3. Zoom and reflow: 200% zoom, and a 320-pixel-wide viewport. The list must not run off screen.
  4. Automated scan: run an accessibility linter or browser checker. It catches some issues (missing names, contrast) and misses many.
  5. People: include passengers who use assistive technology in usability testing where you can.
  6. Typing: type fast, delete, and paste; check the list and the count announcement keep up.
  7. Finishing without the list: type "France", Tab out, confirm the value is FR. Type "uk", Tab out, confirm United Kingdom. Type "Frnace", Tab out, confirm the error and that the text is kept.
  8. Autofill: fill the form from saved browser details; check the country is set, not only shown.
  9. Submit: submit empty; check focus goes to the first invalid field or your error summary, and the typed text is kept.
  10. Phones: on a real iPhone (Safari) and Android phone (Chrome): open the list with the keyboard up, scroll it by dragging without picking, tap to pick, tap outside to close, and check nothing zooms.

The "18 of 20" claim

Not in this research. It covers 14 design systems, not 20, read on 20 November 2026, so I can't check a set of 20 I haven't seen. In these 14:

  • 8 of 14 call it Combobox (spelled Combo box or ComboBox in some).
  • 4 of 14 call it Autocomplete: Polaris (archived docs only), Primer, Material 3 (as a filtering behaviour inside menus) and Ant Design (AutoComplete).
  • Atlassian calls it Select with search, and Lightning also calls one type Lookup.
  • Polaris and Lightning are counted under two names each, so the names add to 14 across 12 systems. GOV.UK and Radix have none.

The W3C pattern and the ARIA role are both called combobox, which is why the code says role="combobox". Your passengers never see the component's name, so call it whatever your team will search for in the codebase. I've used CountryCombobox.

Buyer

Thanks. Can you write one line for our accessibility statement saying this picker is fully WCAG 2.2 AA compliant?

Assistant

I can't write that line. Nothing here has been tested yet: the code was written but not run in a browser or with a screen reader. Even after testing, a review can say what was checked and what was found. It cannot certify conformance, which needs testing with assistive technology and real users.

Here's a status line you can use instead. Fill the blanks once the tests are done:

The country picker on our passenger details form was reviewed against WCAG 2.2 AA on [date]; [n] issues found, [n] fixed, the rest being fixed by [date]; keyboard and screen reader testing ([for example NVDA with Firefox, VoiceOver on iOS]) [completed on / scheduled for] [date].

Buyer

Fair enough, use your line.

Assistant

Here it is, ready to paste once the blanks are filled:

The country picker on our passenger details form was reviewed against WCAG 2.2 AA on [date]; [n] issues found, [n] fixed, the rest being fixed by [date]; keyboard and screen reader testing ([for example NVDA with Firefox, VoiceOver on iOS]) [completed on / scheduled for] [date].

Fill it in from your actual test results, and count every issue found, including the ones not fixed yet. If the test list above turns up nothing, the line still says "reviewed" and "tested", not "compliant".