File size: 11,826 Bytes
a8fb296
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import { useCallback, useEffect, useId, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import type { LocationData } from '../../contexts/LocationContext'
import { STATE_CODES } from '../../lib/usStates'
import { countyNotice, placeToScope } from '../../utils/placeScope'
import { resolveCoordsToLocation, resolveQueryToChoices, resolveZipToChoices } from '../../utils/resolvePlace'
import { STATE_CODE_TO_NAME } from '../../utils/stateMapping'

interface Props {
  stateCode: string | undefined
  city: string | null
  open: boolean
  onOpenChange: (open: boolean) => void
  onApply: (stateCode: string | null, city: string | null) => void
  /** `blank`: the toggle is an inline, underlined blank in a sentence ("What did [Alabama] say ...") and "National only" reads "the United States". */
  variant?: 'button' | 'blank'
  /** The blank's current text (the place label). */
  display?: string
  /**
   * Optional (#1206): a class added to the control and to the dialog's scrim, for a page outside `.folio` (the home page)
   * that supplies the house tokens itself. Story pages leave it out and keep their look.
   */
  themeClassName?: string
}

interface Suggestion {
  key: string
  text: string
  loc: LocationData
}

const FOCUSABLE = 'button:not([disabled]), input:not([disabled]), select:not([disabled]), [href], [tabindex]:not([tabindex="-1"])'

/** A readable name for a resolved place: "Tuscaloosa, Alabama" or "Jefferson County, Alabama". */
function suggestionText(loc: LocationData): string {
  const state = STATE_CODE_TO_NAME[loc.state] ?? loc.state
  const place = loc.city || (loc.county ? (/county$/i.test(loc.county) ? loc.county : `${loc.county} County`) : '')
  return [place, state].filter(Boolean).join(', ')
}

/**
 * "Your place": a dialog with one search box (city, county or ZIP), one-click "the United States" / "All of [state]",
 * and a state list. It reads the same geocoder helpers as the home page's location search (utils/resolvePlace) but
 * never touches the saved site-wide location; the page's `?state=&city=` stays the authority via `onApply`.
 */
export default function PlaceControl({ stateCode, city, open, onOpenChange, onApply, variant = 'button', display, themeClassName }: Props) {
  const blank = variant === 'blank'
  const toggleRef = useRef<HTMLButtonElement>(null)
  const dialogRef = useRef<HTMLDivElement>(null)
  const inputRef = useRef<HTMLInputElement>(null)
  const wasOpen = useRef(false)
  const requestId = useRef(0)
  const uid = useId()
  const titleId = `${uid}-title`
  const listId = `${uid}-list`

  const [query, setQuery] = useState('')
  const [suggestions, setSuggestions] = useState<Suggestion[]>([])
  const [active, setActive] = useState(-1)
  const [status, setStatus] = useState<'idle' | 'loading' | 'empty' | 'error'>('idle')
  const [notice, setNotice] = useState<string | null>(null)
  const [locating, setLocating] = useState(false)

  const stateName = stateCode ? STATE_CODE_TO_NAME[stateCode] : undefined
  const close = useCallback(() => onOpenChange(false), [onOpenChange])

  // Focus goes into the dialog on open and back to the blank on close.
  useEffect(() => {
    if (open) {
      wasOpen.current = true
      setQuery('')
      setSuggestions([])
      setActive(-1)
      setStatus('idle')
      setNotice(null)
      inputRef.current?.focus()
    } else if (wasOpen.current) {
      wasOpen.current = false
      toggleRef.current?.focus()
    }
  }, [open])

  // Look up as the person types; a ZIP and a name go through the same helpers the home page uses.
  useEffect(() => {
    const q = query.trim()
    const isZip = /^\d{5}$/.test(q)
    if (!open || (q.length < 3 && !isZip)) {
      requestId.current += 1
      setSuggestions([])
      setStatus('idle')
      return
    }
    const id = ++requestId.current
    setStatus('loading')
    const t = setTimeout(async () => {
      try {
        const choices = isZip ? await resolveZipToChoices(q) : await resolveQueryToChoices(q)
        if (id !== requestId.current) return
        const seen = new Set<string>()
        const out: Suggestion[] = []
        for (const c of choices) {
          if (!placeToScope(c.loc)) continue
          const text = suggestionText(c.loc)
          if (seen.has(text)) continue
          seen.add(text)
          out.push({ key: text, text, loc: c.loc })
        }
        setSuggestions(out)
        setActive(out.length ? 0 : -1)
        setStatus(out.length ? 'idle' : 'empty')
      } catch {
        if (id !== requestId.current) return
        setSuggestions([])
        setStatus('error')
      }
    }, 300)
    return () => clearTimeout(t)
  }, [query, open])

  const pick = (loc: LocationData) => {
    const scope = placeToScope(loc)
    if (!scope) return
    onApply(scope.stateCode, scope.city)
    const note = countyNotice(scope)
    if (note) {
      // A county has no city grain here: the state is applied, and the dialog says so.
      setNotice(note)
      setSuggestions([])
      setStatus('idle')
      setQuery('')
    } else {
      close()
    }
  }

  const useMyLocation = () => {
    if (!navigator.geolocation) {
      setStatus('error')
      return
    }
    setLocating(true)
    navigator.geolocation.getCurrentPosition(
      async (pos) => {
        try {
          const loc = await resolveCoordsToLocation(pos.coords.latitude, pos.coords.longitude)
          if (loc && placeToScope(loc)) pick(loc)
          else setStatus('empty')
        } catch {
          setStatus('error')
        } finally {
          setLocating(false)
        }
      },
      () => {
        setLocating(false)
        setStatus('error')
      },
      { timeout: 10000 },
    )
  }

  const onDialogKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Escape') {
      e.stopPropagation()
      close()
      return
    }
    if (e.key === 'Tab' && dialogRef.current) {
      const items = Array.from(dialogRef.current.querySelectorAll<HTMLElement>(FOCUSABLE))
      if (!items.length) return
      const first = items[0]
      const last = items[items.length - 1]
      if (e.shiftKey && document.activeElement === first) {
        e.preventDefault()
        last.focus()
      } else if (!e.shiftKey && document.activeElement === last) {
        e.preventDefault()
        first.focus()
      }
    }
  }

  const onInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'ArrowDown' && suggestions.length) {
      e.preventDefault()
      setActive((i) => (i + 1) % suggestions.length)
    } else if (e.key === 'ArrowUp' && suggestions.length) {
      e.preventDefault()
      setActive((i) => (i <= 0 ? suggestions.length - 1 : i - 1))
    } else if (e.key === 'Enter') {
      e.preventDefault()
      const s = suggestions[active >= 0 ? active : 0]
      if (s) pick(s.loc)
    }
  }

  const choose = (code: string | null) => {
    onApply(code, null)
    close()
  }

  // The dialog sits inside the page's `.folio` root so it keeps the house tokens, but outside the heading it was opened from.
  const host = typeof document === 'undefined' ? null : (toggleRef.current?.closest('.folio') as HTMLElement | null) ?? document.body

  const dialog = open && host && (
    <div
      className={`stance-dialog-scrim${themeClassName ? ` ${themeClassName}` : ''}`}
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) close()
      }}
    >
      <div
        ref={dialogRef}
        className="stance-dialog"
        role="dialog"
        aria-modal="true"
        aria-labelledby={titleId}
        onKeyDown={onDialogKeyDown}
      >
        <div className="stance-dialog-head">
          <h2 id={titleId} className="stance-dialog-title">
            Choose a place
          </h2>
          <button type="button" className="stance-dialog-close" aria-label="Close" onClick={close}>
            <span aria-hidden="true">×</span>
          </button>
        </div>

        <label className="folio-field" htmlFor={`${uid}-q`}>
          City, county or ZIP
        </label>
        <input
          id={`${uid}-q`}
          ref={inputRef}
          className="folio-select stance-dialog-input"
          type="text"
          role="combobox"
          aria-expanded={suggestions.length > 0}
          aria-controls={listId}
          aria-autocomplete="list"
          aria-activedescendant={active >= 0 && suggestions[active] ? `${uid}-opt-${active}` : undefined}
          autoComplete="off"
          maxLength={120}
          value={query}
          placeholder="Tuscaloosa, Jefferson County or 35401"
          onChange={(e) => {
            setQuery(e.target.value)
            setNotice(null)
          }}
          onKeyDown={onInputKeyDown}
        />
        <ul id={listId} className="stance-dialog-list" role="listbox" aria-label="Matching places" hidden={suggestions.length === 0}>
          {suggestions.map((s, i) => (
            <li
              key={s.key}
              id={`${uid}-opt-${i}`}
              role="option"
              aria-selected={i === active}
              className={`stance-dialog-option${i === active ? ' is-active' : ''}`}
              onMouseDown={(e) => e.preventDefault()}
              onClick={() => pick(s.loc)}
              onMouseEnter={() => setActive(i)}
            >
              {s.text}
            </li>
          ))}
        </ul>
        <p className="stance-note" role="status" aria-live="polite">
          {status === 'loading' && 'Looking up places...'}
          {status === 'empty' && 'No place found for that. Try a city, county or ZIP in the United States.'}
          {status === 'error' && "We couldn't look up places right now. You can still pick a state below."}
          {status === 'idle' && notice}
        </p>

        <div className="stance-dialog-quick">
          <button type="button" className="folio-btn" onClick={() => choose(null)}>
            {blank ? 'The United States' : 'National only'}
          </button>
          {stateCode && (
            <button type="button" className="folio-btn" onClick={() => choose(stateCode)}>
              All of {stateName ?? stateCode}
            </button>
          )}
          {typeof navigator !== 'undefined' && 'geolocation' in navigator && (
            <button type="button" className="folio-btn" disabled={locating} onClick={useMyLocation}>
              {locating ? 'Locating...' : 'Use my location'}
            </button>
          )}
        </div>

        <label className="folio-field" htmlFor={`${uid}-state`}>
          Or pick a state
        </label>
        <select
          id={`${uid}-state`}
          className="folio-select stance-dialog-input"
          value={stateCode && !city ? stateCode : ''}
          onChange={(e) => e.target.value && choose(e.target.value)}
        >
          <option value="">{stateCode && city ? `${stateName ?? stateCode} (city chosen)` : 'Choose a state'}</option>
          {STATE_CODES.map((c) => (
            <option key={c} value={c}>
              {STATE_CODE_TO_NAME[c] ?? c}
            </option>
          ))}
        </select>
      </div>
    </div>
  )

  return (
    <div className={`stance-place${blank ? ' is-blank' : ''}${themeClassName ? ` ${themeClassName}` : ''}`}>
      <button
        type="button"
        ref={toggleRef}
        className={blank ? 'stance-blank' : 'folio-btn'}
        aria-haspopup="dialog"
        aria-expanded={open}
        aria-label={blank ? `Place, ${display ?? ''}` : undefined}
        onClick={() => onOpenChange(!open)}
      >
        {blank ? (
          <>
            {display} <span aria-hidden="true" className="stance-blank-caret">▾</span>
          </>
        ) : (
          <>Your place</>
        )}
      </button>
      {dialog && createPortal(dialog, host)}
    </div>
  )
}