mtg-deck-completion / web /src /components /CardSearch.tsx
nsaroiu's picture
Deploy 41a05c7
08b6c63 verified
Raw History Blame Contribute Delete
5 kB
import { useEffect, useId, useRef, useState } from 'react'
import { searchCards, type CardSummary, type SearchOptions } from '../api'
import { ColorPips } from './ManaCost'
interface Props {
label: string
value: string
onChange: (value: string) => void
/** Called when a suggestion is picked; if given, the input isn't filled with the name. */
onSelect?: (card: CardSummary) => void
/** Called on Enter when no suggestion is highlighted; if given, Enter never submits the surrounding form. */
onEnter?: () => void
commanderOnly?: boolean
/** Only suggest cards within this color identity (see SearchOptions). */
colors?: string
/** Also suggest basic lands. */
basics?: boolean
placeholder?: string
autoFocus?: boolean
invalid?: boolean
}
// Combobox (WAI-ARIA 1.2 pattern): free text input with a debounced
// suggestion list, arrow keys to move, Enter to pick, Escape to close.
export function CardSearch({
label, value, onChange, onSelect, onEnter, commanderOnly = false, colors, basics = false, placeholder, autoFocus, invalid,
}: Props) {
const id = useId()
const listId = `${id}-list`
const [results, setResults] = useState<CardSummary[]>([])
const [open, setOpen] = useState(false)
const [active, setActive] = useState(-1)
const skipNextSearch = useRef(false)
const inputRef = useRef<HTMLInputElement>(null)
useEffect(() => {
if (skipNextSearch.current) {
skipNextSearch.current = false
return
}
const q = value.trim()
if (q.length < 2) return
const ctrl = new AbortController()
const timer = setTimeout(() => {
const options: SearchOptions = { commanderOnly, colors, basics }
searchCards(q, options, ctrl.signal)
.then((cards) => {
setResults(cards)
setActive(-1)
// Results can land after the user has moved on; don't reopen then.
setOpen(document.activeElement === inputRef.current)
})
.catch(() => {})
}, 150)
return () => {
clearTimeout(timer)
ctrl.abort()
}
}, [value, commanderOnly, colors, basics])
// Hide stale results once the query is too short to search.
const visible = value.trim().length >= 2 ? results : []
const expanded = open && visible.length > 0
const choose = (card: CardSummary) => {
skipNextSearch.current = true
if (onSelect) onSelect(card)
else onChange(card.name)
setOpen(false)
setResults([])
}
const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
const highlighted = open && visible.length > 0 && active >= 0
if (e.key === 'Enter' && onEnter && !highlighted) {
e.preventDefault()
setOpen(false)
onEnter()
return
}
if (!open || visible.length === 0) return
if (e.key === 'ArrowDown') {
e.preventDefault()
setActive((i) => (i + 1) % visible.length)
} else if (e.key === 'ArrowUp') {
e.preventDefault()
setActive((i) => (i <= 0 ? visible.length - 1 : i - 1))
} else if (e.key === 'Enter' && active >= 0) {
e.preventDefault()
choose(visible[active])
} else if (e.key === 'Escape') {
setOpen(false)
}
}
return (
<div className="field combobox">
<label htmlFor={id}>{label}</label>
<input
ref={inputRef}
id={id}
type="text"
role="combobox"
autoComplete="off"
spellCheck={false}
aria-expanded={expanded}
aria-controls={listId}
aria-autocomplete="list"
aria-activedescendant={expanded && active >= 0 ? `${id}-opt-${active}` : undefined}
aria-invalid={invalid || undefined}
value={value}
placeholder={placeholder}
autoFocus={autoFocus}
onChange={(e) => onChange(e.target.value)}
onKeyDown={onKeyDown}
onFocus={() => visible.length > 0 && setOpen(true)}
onBlur={() => setOpen(false)}
/>
{expanded && (
<ul id={listId} role="listbox" className="combobox-list">
{visible.map((card, i) => (
<li
key={card.name}
id={`${id}-opt-${i}`}
role="option"
aria-selected={i === active}
className={i === active ? 'active' : undefined}
// mousedown, not click: fires before the input's blur closes the list
onMouseDown={(e) => {
e.preventDefault()
choose(card)
}}
onMouseEnter={() => setActive(i)}
>
<span className="option-name">
{card.name}
{card.banned && <span className="tag tag-warn">Commander-banned</span>}
</span>
<span className="option-meta">
<ColorPips colors={card.color_identity} />
<span className="option-type">{card.type_line.split('//')[0].trim()}</span>
</span>
</li>
))}
</ul>
)}
</div>
)
}