admin(ui): add arrow key support to SearchableSelect

This commit is contained in:
Matthew Penner 2021-02-17 15:17:37 -07:00
parent dc003a6ada
commit c053ca7c44
3 changed files with 145 additions and 71 deletions

View file

@ -34,6 +34,7 @@ export default ({ selected }: { selected: Database | null }) => {
name="Database" name="Database"
items={databases} items={databases}
selected={database} selected={database}
setSelected={setDatabase}
setItems={setDatabases} setItems={setDatabases}
onSearch={onSearch} onSearch={onSearch}
onSelect={onSelect} onSelect={onSelect}

View file

@ -34,6 +34,7 @@ export default ({ selected }: { selected: Location | null }) => {
name="Location" name="Location"
items={locations} items={locations}
selected={location} selected={location}
setSelected={setLocation}
setItems={setLocations} setItems={setLocations}
onSearch={onSearch} onSearch={onSearch}
onSelect={onSelect} onSelect={onSelect}

View file

@ -11,12 +11,69 @@ const Dropdown = styled.div<{ expanded: boolean }>`
${props => !props.expanded && tw`hidden`}; ${props => !props.expanded && tw`hidden`};
`; `;
interface OptionProps<T> {
selectId: string;
id: number;
item: T;
active: boolean;
isHighlighted?: boolean;
onClick?: (item: T) => (e: React.MouseEvent) => void;
children: React.ReactNode;
}
interface IdObj {
id: number;
}
export const Option = <T extends IdObj>({ selectId, id, item, active, isHighlighted, onClick, children }: OptionProps<T>) => {
if (isHighlighted === undefined) {
isHighlighted = false;
}
// This should never be true, but just in-case we set it to an empty function to make sure shit doesn't blow up.
if (onClick === undefined) {
// eslint-disable-next-line @typescript-eslint/no-empty-function
onClick = () => () => {};
}
if (active) {
return (
<li id={selectId + '-select-item-' + id} role="option" css={[ tw`relative py-2 pl-3 cursor-pointer select-none text-neutral-200 pr-9 hover:bg-neutral-700`, isHighlighted ? tw`bg-neutral-700` : null ]} onClick={onClick(item)}>
<div css={tw`flex items-center`}>
<span css={tw`block font-medium truncate`}>
{children}
</span>
</div>
<span css={tw`absolute inset-y-0 right-0 flex items-center pr-4`}>
<svg css={tw`w-5 h-5 text-primary-400`} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path clipRule="evenodd" fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"/>
</svg>
</span>
</li>
);
}
return (
<li id={selectId + 'select-item-' + id} role="option" css={[ tw`relative py-2 pl-3 cursor-pointer select-none text-neutral-200 pr-9 hover:bg-neutral-700`, isHighlighted ? tw`bg-neutral-700` : null ]} onClick={onClick(item)}>
<div css={tw`flex items-center`}>
<span css={tw`block font-normal truncate`}>
{children}
</span>
</div>
</li>
);
};
interface SearchableSelectProps<T> { interface SearchableSelectProps<T> {
id: string; id: string;
name: string; name: string;
nullable: boolean; nullable: boolean;
selected: T | null; selected: T | null;
setSelected: (item: T | null) => void;
items: T[] | null; items: T[] | null;
setItems: (items: T[] | null) => void; setItems: (items: T[] | null) => void;
@ -29,12 +86,14 @@ interface SearchableSelectProps<T> {
children: React.ReactNode; children: React.ReactNode;
} }
function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, onSelect, getSelectedText, children }: SearchableSelectProps<T>) { export const SearchableSelect = <T extends IdObj>({ id, name, selected, setSelected, items, setItems, onSearch, onSelect, getSelectedText, children }: SearchableSelectProps<T>) => {
const [ loading, setLoading ] = useState(false); const [ loading, setLoading ] = useState(false);
const [ expanded, setExpanded ] = useState(false); const [ expanded, setExpanded ] = useState(false);
const [ inputText, setInputText ] = useState(''); const [ inputText, setInputText ] = useState('');
const [ highlighted, setHighlighted ] = useState<number | null>(null);
const searchInput = createRef<HTMLInputElement>(); const searchInput = createRef<HTMLInputElement>();
const itemsList = createRef<HTMLDivElement>(); const itemsList = createRef<HTMLDivElement>();
@ -42,11 +101,14 @@ function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, o
setInputText(''); setInputText('');
setItems(null); setItems(null);
setExpanded(true); setExpanded(true);
setHighlighted(null);
}; };
const onBlur = () => { const onBlur = () => {
setInputText(getSelectedText(selected) || ''); setInputText(getSelectedText(selected) || '');
setItems(null);
setExpanded(false); setExpanded(false);
setHighlighted(null);
}; };
const search = debounce((query: string) => { const search = debounce((query: string) => {
@ -56,6 +118,7 @@ function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, o
if (query === '' || query.length < 2) { if (query === '' || query.length < 2) {
setItems(null); setItems(null);
setHighlighted(null);
return; return;
} }
@ -63,20 +126,60 @@ function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, o
onSearch(query).then(() => setLoading(false)); onSearch(query).then(() => setLoading(false));
}, 250); }, 250);
useEffect(() => { const handleInputKeydown = (e: React.KeyboardEvent) => {
setInputText(getSelectedText(selected) || ''); if (e.key === 'Tab' || e.key === 'Escape') {
setExpanded(false); onBlur();
}, [ selected ]);
useEffect(() => {
const keydownHandler = (e: KeyboardEvent) => {
if (e.key !== 'Tab' && e.key !== 'Escape') {
return; return;
} }
onBlur(); if (!items) {
return;
}
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
// Prevent up and down arrows from moving the cursor in the input.
e.preventDefault();
if (highlighted === null) {
setHighlighted(items[0].id);
return;
}
const item = items.find((item) => item.id === highlighted);
if (!item) {
return;
}
let index = items.indexOf(item);
if (e.key === 'ArrowUp') {
if (--index < 0) {
return;
}
} else {
if (++index >= items.length) {
return;
}
}
setHighlighted(items[index].id);
return;
}
// Prevent the form from being submitted if the user accidentally hits enter
// while focused on the select.
if (e.key === 'Enter') {
e.preventDefault();
const item = items.find((item) => item.id === highlighted);
if (!item) {
return;
}
setSelected(item);
}
}; };
useEffect(() => {
const clickHandler = (e: MouseEvent) => { const clickHandler = (e: MouseEvent) => {
const input = searchInput.current; const input = searchInput.current;
const menu = itemsList.current; const menu = itemsList.current;
@ -108,39 +211,55 @@ function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, o
onBlur(); onBlur();
}; };
window.addEventListener('keydown', keydownHandler);
window.addEventListener('click', clickHandler); window.addEventListener('click', clickHandler);
window.addEventListener('contextmenu', contextmenuHandler); window.addEventListener('contextmenu', contextmenuHandler);
return () => { return () => {
window.removeEventListener('keydown', keydownHandler);
window.removeEventListener('click', clickHandler); window.removeEventListener('click', clickHandler);
window.removeEventListener('contextmenu', contextmenuHandler); window.removeEventListener('contextmenu', contextmenuHandler);
}; };
}, [ expanded ]); }, [ expanded ]);
const onClick = (item: T) => (e: React.MouseEvent) => { const onClick = (item: T) => () => {
e.preventDefault();
onSelect(item); onSelect(item);
setExpanded(false);
setInputText(getSelectedText(selected) || '');
}; };
useEffect(() => {
if (expanded) {
return;
}
setInputText(getSelectedText(selected) || '');
}, [ selected ]);
// This shit is really stupid but works, so is it really stupid? // This shit is really stupid but works, so is it really stupid?
const c = React.Children.map(children, child => React.cloneElement(child as ReactElement, { const c = React.Children.map(children, child => React.cloneElement(child as ReactElement, {
isHighlighted: ((child as ReactElement).props as OptionProps<T>).id === highlighted,
onClick: onClick.bind(child), onClick: onClick.bind(child),
})); }));
// @ts-ignore
const selectedId = selected?.id;
return ( return (
<div> <div>
<Label htmlFor={id + '-select-label'}>{name}</Label> <Label htmlFor={id + '-select-label'}>{name}</Label>
<div css={tw`relative mt-1`}> <div css={tw`relative mt-1`}>
<InputSpinner visible={loading}> <InputSpinner visible={loading}>
<Input ref={searchInput} type="text" className="ignoreReadOnly" id={id} name={id} value={inputText} readOnly={!expanded} onFocus={onFocus} onChange={e => { <Input
ref={searchInput}
type="text"
className="ignoreReadOnly"
id={id}
name={id}
value={inputText}
readOnly={!expanded}
onFocus={onFocus}
onChange={e => {
setInputText(e.currentTarget.value); setInputText(e.currentTarget.value);
search(e.currentTarget.value); search(e.currentTarget.value);
}} }}
onKeyDown={handleInputKeydown}
/> />
</InputSpinner> </InputSpinner>
@ -165,8 +284,8 @@ function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, o
tabIndex={-1} tabIndex={-1}
role={id + '-select'} role={id + '-select'}
aria-labelledby={id + '-select-label'} aria-labelledby={id + '-select-label'}
aria-activedescendant={id + '-select-item-' + selectedId} aria-activedescendant={id + '-select-item-' + selected?.id}
css={tw`py-1 overflow-auto text-base rounded-md max-h-56 ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm`} css={tw`py-2 overflow-auto text-base rounded-md max-h-56 ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm`}
> >
{c} {c}
</ul> </ul>
@ -175,53 +294,6 @@ function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, o
</div> </div>
</div> </div>
); );
} };
interface OptionProps<T> {
selectId: string;
id: string | number;
item: T;
active: boolean;
onClick?: (item: T) => (e: React.MouseEvent) => void;
children: React.ReactNode;
}
export function Option<T> ({ selectId, id, item, active, onClick, children }: OptionProps<T>) {
// This should never be true, but just in-case we set it to an empty function to make sure shit doesn't blow up.
if (onClick === undefined) {
// eslint-disable-next-line @typescript-eslint/no-empty-function
onClick = () => () => {};
}
if (active) {
return (
<li id={selectId + '-select-item-' + id} role="option" css={tw`relative py-2 pl-3 cursor-pointer select-none text-neutral-200 pr-9 hover:bg-neutral-700`} onClick={onClick(item)}>
<div css={tw`flex items-center`}>
<span css={tw`block font-medium truncate`}>
{children}
</span>
</div>
<span css={tw`absolute inset-y-0 right-0 flex items-center pr-4`}>
<svg css={tw`w-5 h-5 text-primary-400`} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path clipRule="evenodd" fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"/>
</svg>
</span>
</li>
);
}
return (
<li id={'select-item-' + id} role="option" css={tw`relative py-2 pl-3 cursor-pointer select-none text-neutral-200 pr-9 hover:bg-neutral-700`} onClick={onClick(item)}>
<div css={tw`flex items-center`}>
<span css={tw`block font-normal truncate`}>
{children}
</span>
</div>
</li>
);
}
export default SearchableSelect; export default SearchableSelect;