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"
items={databases}
selected={database}
setSelected={setDatabase}
setItems={setDatabases}
onSearch={onSearch}
onSelect={onSelect}

View file

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

View file

@ -11,12 +11,69 @@ const Dropdown = styled.div<{ expanded: boolean }>`
${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> {
id: string;
name: string;
nullable: boolean;
selected: T | null;
setSelected: (item: T | null) => void;
items: T[] | null;
setItems: (items: T[] | null) => void;
@ -29,12 +86,14 @@ interface SearchableSelectProps<T> {
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 [ expanded, setExpanded ] = useState(false);
const [ inputText, setInputText ] = useState('');
const [ highlighted, setHighlighted ] = useState<number | null>(null);
const searchInput = createRef<HTMLInputElement>();
const itemsList = createRef<HTMLDivElement>();
@ -42,11 +101,14 @@ function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, o
setInputText('');
setItems(null);
setExpanded(true);
setHighlighted(null);
};
const onBlur = () => {
setInputText(getSelectedText(selected) || '');
setItems(null);
setExpanded(false);
setHighlighted(null);
};
const search = debounce((query: string) => {
@ -56,6 +118,7 @@ function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, o
if (query === '' || query.length < 2) {
setItems(null);
setHighlighted(null);
return;
}
@ -63,20 +126,60 @@ function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, o
onSearch(query).then(() => setLoading(false));
}, 250);
useEffect(() => {
setInputText(getSelectedText(selected) || '');
setExpanded(false);
}, [ selected ]);
const handleInputKeydown = (e: React.KeyboardEvent) => {
if (e.key === 'Tab' || e.key === 'Escape') {
onBlur();
return;
}
useEffect(() => {
const keydownHandler = (e: KeyboardEvent) => {
if (e.key !== 'Tab' && e.key !== 'Escape') {
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;
}
onBlur();
};
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 input = searchInput.current;
const menu = itemsList.current;
@ -108,39 +211,55 @@ function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, o
onBlur();
};
window.addEventListener('keydown', keydownHandler);
window.addEventListener('click', clickHandler);
window.addEventListener('contextmenu', contextmenuHandler);
return () => {
window.removeEventListener('keydown', keydownHandler);
window.removeEventListener('click', clickHandler);
window.removeEventListener('contextmenu', contextmenuHandler);
};
}, [ expanded ]);
const onClick = (item: T) => (e: React.MouseEvent) => {
e.preventDefault();
const onClick = (item: T) => () => {
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?
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),
}));
// @ts-ignore
const selectedId = selected?.id;
return (
<div>
<Label htmlFor={id + '-select-label'}>{name}</Label>
<div css={tw`relative mt-1`}>
<InputSpinner visible={loading}>
<Input ref={searchInput} type="text" className="ignoreReadOnly" id={id} name={id} value={inputText} readOnly={!expanded} onFocus={onFocus} onChange={e => {
setInputText(e.currentTarget.value);
search(e.currentTarget.value);
}}
<Input
ref={searchInput}
type="text"
className="ignoreReadOnly"
id={id}
name={id}
value={inputText}
readOnly={!expanded}
onFocus={onFocus}
onChange={e => {
setInputText(e.currentTarget.value);
search(e.currentTarget.value);
}}
onKeyDown={handleInputKeydown}
/>
</InputSpinner>
@ -165,8 +284,8 @@ function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, o
tabIndex={-1}
role={id + '-select'}
aria-labelledby={id + '-select-label'}
aria-activedescendant={id + '-select-item-' + selectedId}
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`}
aria-activedescendant={id + '-select-item-' + selected?.id}
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}
</ul>
@ -175,53 +294,6 @@ function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, o
</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;