/** * WHAT A PERSON TYPED INTO THE STATE FIELD, RESOLVED TO A STATE - or nothing. * * The address form's State control is a WordPress `ComboboxControl`, which keeps the typed text in its * own internal filter state and calls `onChange` ONLY when a suggestion is clicked. So typing `IL` and * pressing Save refused with "State is required" **while the field visibly contained IL** - the user * looking straight at the value the form said was missing. Every other address field is a plain bound * input; this was the one control that accepted keystrokes and threw them away. * * EXACT MATCHES ONLY, and that is the whole safety argument. A prefix match would resolve `M` to * whichever of Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri or Montana * happens to sort first, and silently write it into an address. Guessing a state on somebody's * behalf is worse than the defect being fixed: a wrong address that saves is not recoverable by * looking at the screen, which is exactly the property that made the original bug so hard to reason * about. * * Three spellings are accepted because all three are things a person actually types into a field * labelled State: the code, the full name, and the label the dropdown itself shows them. */ export interface UspsStateOption { code?: string; display?: string; } const normalise = (value: string): string => value.trim().toLowerCase(); export const matchUspsState = ( options: UspsStateOption[], typed: string | undefined, ): UspsStateOption | undefined => { const needle = normalise(typed ?? ''); if (!needle) return undefined; return options.find((option) => { const code = normalise(option.code ?? ''); const display = normalise(option.display ?? ''); // The dropdown renders "Illinois (IL)", so somebody copying what they saw types that. const label = code && display ? `${display} (${code})` : ''; return (Boolean(code) && needle === code) || (Boolean(display) && needle === display) || (Boolean(label) && needle === label); }); };