admin(ui): fix remaining problems with SearchableSelect.tsx

This commit is contained in:
Matthew Penner 2021-02-15 22:41:19 -07:00
parent 3971c4499d
commit 93be6db530
7 changed files with 118 additions and 161 deletions

View file

@ -1,25 +1,18 @@
import { Database, rawDataToDatabase } from '@/api/admin/databases/getDatabases';
import http from '@/api/http'; import http from '@/api/http';
import { Database, rawDataToDatabase } from '@/api/admin/databases/getDatabases';
interface Filters { interface Filters {
name?: string; name?: string;
host?: string; host?: string;
} }
interface Wow {
[index: string]: string;
}
export default (filters?: Filters): Promise<Database[]> => { export default (filters?: Filters): Promise<Database[]> => {
let params = {}; const params = {};
if (filters !== undefined) { if (filters !== undefined) {
params = Object.keys(filters).map((key) => { Object.keys(filters).forEach(key => {
const a: Wow = {}; // @ts-ignore
a[`filter[${key}]`] = (filters as unknown as Wow)[key]; params['filter[' + key + ']'] = filters[key];
return a;
}); });
console.log(params);
} }
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {

View file

@ -1,7 +1,12 @@
import http from '@/api/http'; import http from '@/api/http';
import { Location, rawDataToLocation } from '@/api/admin/locations/getLocations'; import { Location, rawDataToLocation } from '@/api/admin/locations/getLocations';
export default (filters?: Record<string, string>): Promise<Location[]> => { interface Filters {
short?: string;
long?: string;
}
export default (filters?: Filters): Promise<Location[]> => {
const params = {}; const params = {};
if (filters !== undefined) { if (filters !== undefined) {
Object.keys(filters).forEach(key => { Object.keys(filters).forEach(key => {

View file

@ -61,7 +61,7 @@ export const rawDataToNode = ({ attributes }: FractalResponseData): Node => ({
updatedAt: new Date(attributes.updated_at), updatedAt: new Date(attributes.updated_at),
relations: { relations: {
databaseHost: attributes.relationships?.databaseHost !== undefined ? rawDataToDatabase(attributes.relationships.databaseHost as FractalResponseData) : undefined, databaseHost: attributes.relationships?.database_host !== undefined ? rawDataToDatabase(attributes.relationships.database_host as FractalResponseData) : undefined,
location: attributes.relationships?.location !== undefined ? rawDataToLocation(attributes.relationships.location as FractalResponseData) : undefined, location: attributes.relationships?.location !== undefined ? rawDataToLocation(attributes.relationships.location as FractalResponseData) : undefined,
}, },
}); });

View file

@ -1,10 +1,10 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import SearchableSelect, { Option } from '@/components/elements/SearchableSelect';
import searchDatabases from '@/api/admin/databases/searchDatabases';
import { Database } from '@/api/admin/databases/getDatabases'; import { Database } from '@/api/admin/databases/getDatabases';
import searchDatabases from '@/api/admin/databases/searchDatabases';
import SearchableSelect, { Option } from '@/components/elements/SearchableSelect';
export default ({ selected }: { selected?: Database | null }) => { export default ({ selected }: { selected: Database | null }) => {
const [ database, setDatabase ] = useState<Database | null>(selected || null); const [ database, setDatabase ] = useState<Database | null>(selected);
const [ databases, setDatabases ] = useState<Database[]>([]); const [ databases, setDatabases ] = useState<Database[]>([]);
const onSearch = (query: string): Promise<void> => { const onSearch = (query: string): Promise<void> => {
@ -37,7 +37,7 @@ export default ({ selected }: { selected?: Database | null }) => {
nullable nullable
> >
{databases.map(d => ( {databases.map(d => (
<Option key={d.id} id={d.id} item={d} active={d.id === database?.id}> <Option key={d.id} selectId="database" id={d.id} item={d} active={d.id === database?.id}>
{d.name} {d.name}
</Option> </Option>
))} ))}

View file

@ -1,140 +1,46 @@
import React, { useEffect, useState } from 'react'; import React, { useState } from 'react';
import styled from 'styled-components/macro';
import tw from 'twin.macro';
import Input from '@/components/elements/Input';
import Label from '@/components/elements/Label';
import { Location } from '@/api/admin/locations/getLocations'; import { Location } from '@/api/admin/locations/getLocations';
import searchLocations from '@/api/admin/locations/searchLocations'; import searchLocations from '@/api/admin/locations/searchLocations';
import InputSpinner from '@/components/elements/InputSpinner'; import SearchableSelect, { Option } from '@/components/elements/SearchableSelect';
import { debounce } from 'debounce';
const Dropdown = styled.div<{ expanded: boolean }>` export default ({ selected }: { selected: Location | null }) => {
${tw`absolute mt-1 w-full rounded-md bg-neutral-900 shadow-lg z-10`}; const [ location, setLocation ] = useState<Location | null>(selected);
${props => !props.expanded && tw`hidden`};
`;
export default ({ defaultLocation }: { defaultLocation: Location | null }) => {
const [ loading, setLoading ] = useState(false);
const [ expanded, setExpanded ] = useState(false);
const [ location, setLocation ] = useState<Location | null>(defaultLocation);
const [ locations, setLocations ] = useState<Location[]>([]); const [ locations, setLocations ] = useState<Location[]>([]);
const [ inputText, setInputText ] = useState(''); const onSearch = (query: string): Promise<void> => {
return new Promise((resolve, reject) => {
const onFocus = () => {
setInputText('');
setLocations([]);
setExpanded(true);
};
const search = debounce((query: string) => {
if (!expanded) {
return;
}
if (query === '' || query.length < 2) {
setLocations([]);
return;
}
setLoading(true);
searchLocations({ short: query }).then((locations) => { searchLocations({ short: query }).then((locations) => {
setLocations(locations); setLocations(locations);
}).then(() => setLoading(false)); return resolve();
}, 250); }).catch(reject);
});
};
const selectLocation = (location: Location) => { const onSelect = (location: Location) => {
setLocation(location); setLocation(location);
}; };
useEffect(() => { const getSelectedText = (location: Location | null): string => {
setInputText(location?.short || ''); return location?.short || '';
setExpanded(false);
}, [ location ]);
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.key !== 'Escape') {
return;
}
setInputText(location?.short || '');
setExpanded(false);
}; };
window.addEventListener('keydown', handler);
return () => {
window.removeEventListener('keydown', handler);
};
}, [ expanded ]);
return ( return (
<div> <SearchableSelect
<Label htmlFor="listbox-label">Location</Label> id="location"
name="Location"
<div css={tw`mt-1 relative`}> items={locations}
<InputSpinner visible={loading}> selected={location}
<Input type="text" className="ignoreReadOnly" value={inputText} readOnly={!expanded} onFocus={onFocus} onChange={e => { setItems={setLocations}
setInputText(e.currentTarget.value); onSearch={onSearch}
search(e.currentTarget.value); onSelect={onSelect}
}} getSelectedText={getSelectedText}
/> nullable
</InputSpinner>
<div css={tw`ml-3 absolute inset-y-0 right-0 flex items-center pr-2 pointer-events-none`}>
<svg css={tw`h-5 w-5 text-neutral-400`} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path clipRule="evenodd" fillRule="evenodd" d="M10 3a1 1 0 01.707.293l3 3a1 1 0 01-1.414 1.414L10 5.414 7.707 7.707a1 1 0 01-1.414-1.414l3-3A1 1 0 0110 3zm-3.707 9.293a1 1 0 011.414 0L10 14.586l2.293-2.293a1 1 0 011.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z"/>
</svg>
</div>
<Dropdown expanded={expanded}>
{locations.length < 1 ?
inputText.length < 2 ?
<div css={tw`h-10 flex flex-row items-center px-3`}>
<p css={tw`text-sm`}>Please type 2 or more characters.</p>
</div>
:
<div css={tw`h-10 flex flex-row items-center px-3`}>
<p css={tw`text-sm`}>No results found.</p>
</div>
:
<ul tabIndex={-1} role="listbox" aria-labelledby="listbox-label" aria-activedescendant="listbox-item-3" css={tw`max-h-56 rounded-md py-1 text-base ring-1 ring-black ring-opacity-5 overflow-auto focus:outline-none sm:text-sm`}>
{locations.map(l => (
l.id === location?.id ?
<li key={l.id} id={'listbox-item-' + l.id} role="option" css={tw`text-neutral-200 cursor-pointer select-none relative py-2 pl-3 pr-9 hover:bg-neutral-700`} onClick={(e) => {
e.stopPropagation();
selectLocation(l);
}}
> >
<div css={tw`flex items-center`}> {locations.map(d => (
<span css={tw`block font-medium truncate`}> <Option key={d.id} selectId="location" id={d.id} item={d} active={d.id === location?.id}>
{l.short} {d.short}
</span> </Option>
</div>
<span css={tw`absolute inset-y-0 right-0 flex items-center pr-4`}>
<svg css={tw`h-5 w-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>
:
<li key={l.id} id={'listbox-item-' + l.id} role="option" css={tw`text-neutral-200 cursor-pointer select-none relative py-2 pl-3 pr-9 hover:bg-neutral-700`} onClick={(e) => {
e.stopPropagation();
selectLocation(l);
}}
>
<div css={tw`flex items-center`}>
<span css={tw`block font-normal truncate`}>
{l.short}
</span>
</div>
</li>
))} ))}
</ul> </SearchableSelect>
}
</Dropdown>
</div>
</div>
); );
}; };

View file

@ -98,11 +98,11 @@ export default () => {
</div> </div>
<div css={tw`mb-6`}> <div css={tw`mb-6`}>
<LocationSelect defaultLocation={node?.relations.location || null}/> <LocationSelect selected={node?.relations.location || null}/>
</div> </div>
<div css={tw`mb-6`}> <div css={tw`mb-6`}>
<DatabaseSelect selected={node?.relations.databaseHost}/> <DatabaseSelect selected={node?.relations.databaseHost || null}/>
</div> </div>
<div css={tw`mb-6`}> <div css={tw`mb-6`}>

View file

@ -1,4 +1,4 @@
import React, { ReactElement, useEffect, useState } from 'react'; import React, { createRef, ReactElement, useEffect, useState } from 'react';
import { debounce } from 'debounce'; import { debounce } from 'debounce';
import styled from 'styled-components/macro'; import styled from 'styled-components/macro';
import tw from 'twin.macro'; import tw from 'twin.macro';
@ -35,12 +35,20 @@ function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, o
const [ inputText, setInputText ] = useState(''); const [ inputText, setInputText ] = useState('');
const searchInput = createRef<HTMLInputElement>();
const itemsList = createRef<HTMLDivElement>();
const onFocus = () => { const onFocus = () => {
setInputText(''); setInputText('');
setItems([]); setItems([]);
setExpanded(true); setExpanded(true);
}; };
const onBlur = () => {
setInputText(getSelectedText(selected) || '');
setExpanded(false);
};
const search = debounce((query: string) => { const search = debounce((query: string) => {
if (!expanded) { if (!expanded) {
return; return;
@ -53,7 +61,7 @@ function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, o
setLoading(true); setLoading(true);
onSearch(query).then(() => setLoading(false)); onSearch(query).then(() => setLoading(false));
}, 250); }, 1000);
useEffect(() => { useEffect(() => {
setInputText(getSelectedText(selected) || ''); setInputText(getSelectedText(selected) || '');
@ -61,18 +69,52 @@ function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, o
}, [ selected ]); }, [ selected ]);
useEffect(() => { useEffect(() => {
const handler = (e: KeyboardEvent) => { const keydownHandler = (e: KeyboardEvent) => {
if (e.key !== 'Escape') { if (e.key !== 'Tab' && e.key !== 'Escape') {
return; return;
} }
setInputText(getSelectedText(selected) || ''); onBlur();
setExpanded(false);
}; };
window.addEventListener('keydown', handler); const clickHandler = (e: MouseEvent) => {
const input = searchInput.current;
const menu = itemsList.current;
if (e.button === 2 || !expanded || !input || !menu) {
return;
}
if (e.target === input || input.contains(e.target as Node)) {
return;
}
if (e.target === menu || menu.contains(e.target as Node)) {
return;
}
if (e.target === input || input.contains(e.target as Node)) {
return;
}
if (e.target === menu || menu.contains(e.target as Node)) {
return;
}
onBlur();
};
const contextmenuHandler = () => {
onBlur();
};
window.addEventListener('keydown', keydownHandler);
window.addEventListener('click', clickHandler);
window.addEventListener('contextmenu', contextmenuHandler);
return () => { return () => {
window.removeEventListener('keydown', handler); window.removeEventListener('keydown', keydownHandler);
window.removeEventListener('click', clickHandler);
window.removeEventListener('contextmenu', contextmenuHandler);
}; };
}, [ expanded ]); }, [ expanded ]);
@ -86,13 +128,16 @@ function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, o
onClick: onClick.bind(child), onClick: onClick.bind(child),
})); }));
// @ts-ignore
const selectedId = selected?.id;
return ( return (
<div> <div>
<Label htmlFor={id}>{name}</Label> <Label htmlFor={id + '-select-label'}>{name}</Label>
<div css={tw`mt-1 relative`}> <div css={tw`mt-1 relative`}>
<InputSpinner visible={loading}> <InputSpinner visible={loading}>
<Input 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);
}} }}
@ -105,7 +150,7 @@ function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, o
</svg> </svg>
</div> </div>
<Dropdown expanded={expanded}> <Dropdown ref={itemsList} expanded={expanded}>
{ items.length < 1 ? { items.length < 1 ?
inputText.length < 2 ? inputText.length < 2 ?
<div css={tw`h-10 flex flex-row items-center px-3`}> <div css={tw`h-10 flex flex-row items-center px-3`}>
@ -116,7 +161,13 @@ function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, o
<p css={tw`text-sm`}>No results found.</p> <p css={tw`text-sm`}>No results found.</p>
</div> </div>
: :
<ul tabIndex={-1} css={tw`max-h-56 rounded-md py-1 text-base ring-1 ring-black ring-opacity-5 overflow-auto focus:outline-none sm:text-sm`}> <ul
tabIndex={-1}
role={id + '-select'}
aria-labelledby={id + '-select-label'}
aria-activedescendant={id + '-select-item-' + selectedId}
css={tw`max-h-56 rounded-md py-1 text-base ring-1 ring-black ring-opacity-5 overflow-auto focus:outline-none sm:text-sm`}
>
{c} {c}
</ul> </ul>
} }
@ -127,6 +178,7 @@ function SearchableSelect<T> ({ id, name, selected, items, setItems, onSearch, o
} }
interface OptionProps<T> { interface OptionProps<T> {
selectId: string;
id: string | number; id: string | number;
item: T; item: T;
active: boolean; active: boolean;
@ -136,7 +188,8 @@ interface OptionProps<T> {
children: React.ReactNode; children: React.ReactNode;
} }
export function Option<T> ({ id, item, active, onClick, children }: OptionProps<T>) { 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) { if (onClick === undefined) {
// eslint-disable-next-line @typescript-eslint/no-empty-function // eslint-disable-next-line @typescript-eslint/no-empty-function
onClick = () => () => {}; onClick = () => () => {};
@ -144,7 +197,7 @@ export function Option<T> ({ id, item, active, onClick, children }: OptionProps<
if (active) { if (active) {
return ( return (
<li id={'select-item-' + id} role="option" css={tw`text-neutral-200 cursor-pointer select-none relative py-2 pl-3 pr-9 hover:bg-neutral-700`} onClick={onClick(item)}> <li id={selectId + '-select-item-' + id} role="option" css={tw`text-neutral-200 cursor-pointer select-none relative py-2 pl-3 pr-9 hover:bg-neutral-700`} onClick={onClick(item)}>
<div css={tw`flex items-center`}> <div css={tw`flex items-center`}>
<span css={tw`block font-medium truncate`}> <span css={tw`block font-medium truncate`}>
{children} {children}