דילוג לתוכן הראשי
10

Autocomplete

קשהreactdebouncerace conditionsa11y

הקוד שלכם עדיין לא נשמר: רענון או יציאה מהדף מאפסים אותו. שמירת התקדמות תגיע יחד עם חשבונות משתמשים.

בנו input עם autocomplete (typeahead) לבחירת מדינה. api.js הוא server חיפוש מזויף, ו-App.js מציג את המדינה שנבחרה מתחת ל-input. כרגע ה-input לא עושה כלום.

js
const countries = await searchCountries('ger', { signal })
// [{ code: 'DE', name: 'Germany' }, ...]

ה-API מתנהג כמו רשת אמיתית: כל תשובה לוקחת בין 100 ל-800 ms באקראי, ולכן תשובות יכולות לחזור בסדר אחר מזה שבו שלחתם את הבקשות. חיפוש של error תמיד נכשל.

דרישות

  • בזמן שהמשתמש מקליד, מציגים עד 10 מדינות מתאימות ברשימה מתחת ל-input.
  • Debounce: מחפשים רק אחרי שהמשתמש הפסיק להקליד ל-300 ms, ולא בכל הקשה.
  • Race conditions: הרשימה תמיד צריכה להתאים לשאילתה האחרונה. תשובה איטית לשאילתה ישנה אסור שתחליף את התוצאות של שאילתה חדשה יותר.
  • שאילתה ריקה (או שכולה רווחים) לא מציגה כלום ולא שולחת בקשה.
  • מציגים Searching... בזמן הטעינה, No countries match "…" כשאין תוצאות, והודעת שגיאה כשהבקשה נכשלת.
  • לחיצה על הצעה, או Enter על ההצעה המודגשת, שמה את השם שלה ב-input, סוגרת את הרשימה וקוראת ל-onSelect(country).
  • ArrowDown ו-ArrowUp מזיזים את ההדגשה ברשימה, ומסתובבים בקצוות. Escape סוגר את הרשימה.
  • הרשימה נסגרת כשה-input מאבד focus, אבל לחיצה על הצעה עדיין צריכה לבחור אותה.

נגישות

עקבו אחרי ה-WAI-ARIA combobox pattern:

  • ל-input יש role="combobox", aria-expanded, aria-controls שמצביע על הרשימה ו-aria-autocomplete="list".
  • לרשימה יש role="listbox", ולכל הצעה יש role="option" ו-aria-selected כשהיא מודגשת.
  • ה-focus נשאר ב-input. ההצעה המודגשת מוכרזת דרך aria-activedescendant.

הערה

ה-preview מתעדכן תוך כדי הקלדה. לאתגר הזה עוד אין בדיקות אוטומטיות: הקלידו מהר, מחקו תווים, נסו error, והשתמשו רק במקלדת. אחר כך השוו לפתרון.

שאלות המשך שמראיינים שואלים

  • להדגיש את החלק בכל הצעה שמתאים לשאילתה.
  • cache לתוצאות, כך שהקלדה של ger, אחר כך germ ואז חזרה ל-ger לא מחפשת את ger שוב.
  • מה הייתם משנים לרשימה מקומית של 100,000 פריטים במקום server?
  • איך הייתם הופכים את זה לגנרי, למשל <Autocomplete fetchSuggestions={...} renderItem={...} />?

הגישה

שלוש בעיות יושבות כאן אחת על השנייה, ולכל אחת יש כלי משלה:

בעיהכלי
לא לחפש בכל הקשהhook בשם useDebouncedValue
תשובות ישנות שדורסות חדשותAbortController, שמבוטל ב-cleanup של ה-effect
תמיכה במקלדת וב-screen readersה-combobox pattern עם aria-activedescendant

Debounce על ערך, לא על פונקציה

useDebouncedValue(query, 300) מחזיר את השאילתה רק אחרי שהיא הפסיקה להשתנות ל-300 ms. כל שינוי מתחיל setTimeout מחדש, וה-cleanup של ה-effect מנקה את הקודם. ה-effect של החיפוש תלוי אז בערך המעוכב, ולכן הוא רץ פעם אחת לכל הפסקה בהקלדה.

debounce על ערך קל יותר לעשות נכון ב-React מאשר לעטוף את ה-fetch בפונקציית debounce(). פונקציה מעוכבת צריכה לשרוד renders (עם useMemo או useRef) וצריך לבטל אותה ב-unmount.

ה-race condition

בלי הגנה, זה מה שקורה:

טוען דיאגרמה...

התיקון נמצא ב-cleanup של ה-effect. React מריץ את ה-cleanup של ה-effect הקודם לפני הבא, ולכן כל שאילתה חדשה קוראת ל-controller.abort() על הבקשה של השאילתה הקודמת. בקשה שבוטלה נדחית עם AbortError, שה-.catch מתעלם ממנו, והתוצאות שלה אף פעם לא נכתבות ל-state. בונוס: הדפדפן מבטל גם את בקשת הרשת עצמה.

אם API לא מקבל signal, אותו רעיון עובד עם flag: let ignore = false ב-effect, ignore = true ב-cleanup, וקוראים ל-setResults רק כש-!ignore.

מקלדת ו-focus

  • ה-focus נשאר ב-input כל הזמן. activeIndex עוקב אחרי ההצעה המודגשת, ו-aria-activedescendant אומר ל-screen readers איזו היא. העברת focus אמיתי לרשימה הייתה הופכת הקלדה לבלתי אפשרית.
  • החיצים מסתובבים עם modulo: (index + step + length) % length.
  • event.preventDefault() על החיצים מונע מהסמן לקפוץ להתחלה או לסוף הטקסט.

בעיית ה-blur

סגירה ב-blur קלה, אבל היא שוברת בחירה עם העכבר: לחיצה על כפתור העכבר מעל הצעה עושה blur ל-input קודם, הרשימה נסגרת, וה-click אף פעם לא נוחת על ההצעה. הפתרון בוחר ב-mousedown וקורא שם ל-event.preventDefault(), מה שמונע מה-input לאבד focus בכלל.

מה מראיינים מחפשים

  • debounce, וטיפול בשאילתה ריקה.
  • לזהות את ה-race condition לפני ששואלים, ולתקן אותו עם AbortController או עם ignore flag.
  • מצבי loading, empty ו-error.
  • ה-combobox ARIA pattern עם aria-activedescendant.
  • בעיית הסדר בין mousedown ל-blur.

פתרון לדוגמה

src/Autocomplete.js

jsx
import { useEffect, useId, useState } from 'react'

import { searchCountries } from './api'

/** `value`, but only after it has stopped changing for `delay` ms. */
function useDebouncedValue(value, delay) {
  const [debounced, setDebounced] = useState(value)
  useEffect(() => {
    const timer = setTimeout(() => setDebounced(value), delay)
    return () => clearTimeout(timer)
  }, [value, delay])
  return debounced
}

export default function Autocomplete({ id, onSelect }) {
  const [query, setQuery] = useState('')
  const [results, setResults] = useState([])
  const [status, setStatus] = useState('idle') // 'idle' | 'loading' | 'success' | 'error'
  const [open, setOpen] = useState(false)
  const [activeIndex, setActiveIndex] = useState(-1)
  const debouncedQuery = useDebouncedValue(query.trim(), 300)
  const listId = useId()

  useEffect(() => {
    if (!debouncedQuery) {
      setResults([])
      setStatus('idle')
      return
    }
    // Every new query aborts the previous request, so a slow old response can
    // never overwrite the results of a newer query.
    const controller = new AbortController()
    setStatus('loading')
    searchCountries(debouncedQuery, { signal: controller.signal })
      .then((items) => {
        setResults(items)
        setActiveIndex(-1)
        setStatus('success')
      })
      .catch((error) => {
        if (error.name !== 'AbortError') setStatus('error')
      })
    return () => controller.abort()
  }, [debouncedQuery])

  const showList = open && status === 'success' && results.length > 0
  const optionId = (index) => `${listId}-option-${index}`

  function select(item) {
    setQuery(item.name)
    setOpen(false)
    onSelect(item)
  }

  function onKeyDown(event) {
    if (event.key === 'Escape') {
      setOpen(false)
      return
    }
    if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
      event.preventDefault()
      setOpen(true)
      if (results.length === 0) return
      const step = event.key === 'ArrowDown' ? 1 : -1
      setActiveIndex((index) => (index + step + results.length) % results.length)
      return
    }
    if (event.key === 'Enter' && showList && activeIndex >= 0) {
      event.preventDefault()
      select(results[activeIndex])
    }
  }

  return (
    <div className="autocomplete">
      <input
        id={id}
        className="input"
        placeholder="Start typing a country..."
        role="combobox"
        aria-autocomplete="list"
        aria-expanded={showList}
        aria-controls={listId}
        aria-activedescendant={showList && activeIndex >= 0 ? optionId(activeIndex) : undefined}
        autoComplete="off"
        value={query}
        onChange={(event) => {
          setQuery(event.target.value)
          setOpen(true)
        }}
        onFocus={() => setOpen(true)}
        onBlur={() => setOpen(false)}
        onKeyDown={onKeyDown}
      />
      <ul id={listId} className="listbox" role="listbox" hidden={!showList}>
        {results.map((item, index) => (
          <li
            key={item.code}
            id={optionId(index)}
            className="option"
            role="option"
            aria-selected={index === activeIndex}
            // mousedown, not click: preventDefault keeps focus in the input, so
            // its blur doesn't close the list before the click lands.
            onMouseDown={(event) => {
              event.preventDefault()
              select(item)
            }}
            onMouseEnter={() => setActiveIndex(index)}
          >
            {item.name}
          </li>
        ))}
      </ul>
      <div role="status">
        {open && status === 'loading' && <p className="message">Searching...</p>}
        {open && status === 'error' && (
          <p className="message error">Something went wrong. Try again.</p>
        )}
        {open && status === 'success' && results.length === 0 && (
          <p className="message">No countries match "{debouncedQuery}".</p>
        )}
      </div>
    </div>
  )
}