bigbuffet-rw/packages/pl-fe/src/components/autosuggest-input.tsx

296 lines
8.7 KiB
TypeScript
Raw Normal View History

2023-02-06 10:01:03 -08:00
import clsx from 'clsx';
import React, { useEffect, useRef, useState } from 'react';
import AutosuggestEmoji from 'pl-fe/components/autosuggest-emoji';
import Icon from 'pl-fe/components/icon';
import Input from 'pl-fe/components/ui/input';
import Portal from 'pl-fe/components/ui/portal';
import AutosuggestAccount from 'pl-fe/features/compose/components/autosuggest-account';
import { textAtCursorMatchesToken } from 'pl-fe/utils/suggestions';
import AutosuggestLocation from './autosuggest-location';
import type { Location } from 'pl-api';
import type { Menu, MenuItem } from 'pl-fe/components/dropdown-menu';
import type { InputThemes } from 'pl-fe/components/ui/input';
import type { Emoji } from 'pl-fe/features/emoji';
type AutoSuggestion = string | Emoji | Location;
2022-06-04 16:35:04 -07:00
interface IAutosuggestInput extends Pick<React.HTMLAttributes<HTMLInputElement>, 'lang' | 'onChange' | 'onKeyUp' | 'onKeyDown'> {
value: string;
suggestions: Array<AutoSuggestion>;
disabled?: boolean;
placeholder?: string;
onSuggestionSelected: (tokenStart: number, lastToken: string | null, suggestion: AutoSuggestion) => void;
onSuggestionsClearRequested: () => void;
onSuggestionsFetchRequested: (token: string) => void;
autoFocus?: boolean;
autoSelect?: boolean;
className?: string;
id?: string;
searchTokens?: string[];
maxLength?: number;
menu?: Menu;
hidePortal?: boolean;
theme?: InputThemes;
2022-06-04 16:21:16 -07:00
}
const AutosuggestInput: React.FC<IAutosuggestInput> = ({
autoFocus = false,
autoSelect = true,
searchTokens = ['@', ':', '#'],
...props
}) => {
const getFirstIndex = () => autoSelect ? 0 : -1;
2020-03-27 13:59:38 -07:00
const [suggestionsHidden, setSuggestionsHidden] = useState(true);
const [focused, setFocused] = useState(false);
const [selectedSuggestion, setSelectedSuggestion] = useState(getFirstIndex());
const [lastToken, setLastToken] = useState<string | null>(null);
const [tokenStart, setTokenStart] = useState<number | null>(0);
const inputRef = useRef<HTMLInputElement>(null);
2020-03-27 13:59:38 -07:00
const onChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
2022-11-22 06:55:31 -08:00
const [tokenStart, token] = textAtCursorMatchesToken(
e.target.value,
e.target.selectionStart || 0,
searchTokens,
2022-11-22 06:55:31 -08:00
);
2020-03-27 13:59:38 -07:00
if (token !== null && lastToken !== token) {
setLastToken(token);
setSelectedSuggestion(0);
setTokenStart(tokenStart);
props.onSuggestionsFetchRequested(token);
2020-03-27 13:59:38 -07:00
} else if (token === null) {
setLastToken(null);
props.onSuggestionsClearRequested();
2020-03-27 13:59:38 -07:00
}
if (props.onChange) {
props.onChange(e);
2022-06-04 16:21:16 -07:00
}
2023-01-05 09:55:08 -08:00
};
2020-03-27 13:59:38 -07:00
const onKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
const { suggestions, menu, disabled } = props;
const firstIndex = getFirstIndex();
const lastIndex = suggestions.length + (menu || []).length - 1;
2020-03-27 13:59:38 -07:00
if (disabled) {
e.preventDefault();
return;
}
2022-06-04 16:21:16 -07:00
if (e.which === 229) {
2020-03-27 13:59:38 -07:00
// Ignore key events during text composition
// e.key may be a name of the physical key even in this case (e.x. Safari / Chrome on Mac)
return;
}
switch (e.key) {
2022-05-11 14:06:35 -07:00
case 'Escape':
if (suggestions.length === 0 || suggestionsHidden) {
2022-06-04 16:21:16 -07:00
document.querySelector('.ui')?.parentElement?.focus();
2021-11-01 11:45:17 -07:00
} else {
2022-05-11 14:06:35 -07:00
e.preventDefault();
setSuggestionsHidden(true);
2022-05-11 14:06:35 -07:00
}
break;
case 'ArrowDown':
if (!suggestionsHidden && (suggestions.length > 0 || menu)) {
2022-05-11 14:06:35 -07:00
e.preventDefault();
setSelectedSuggestion((selectedSuggestion) => Math.min(selectedSuggestion + 1, lastIndex));
2022-05-11 14:06:35 -07:00
}
break;
case 'ArrowUp':
if (!suggestionsHidden && (suggestions.length > 0 || menu)) {
2022-05-11 14:06:35 -07:00
e.preventDefault();
setSelectedSuggestion((selectedSuggestion) => Math.min(selectedSuggestion - 1, lastIndex));
2022-05-11 14:06:35 -07:00
}
break;
case 'Enter':
case 'Tab':
2022-06-04 16:21:16 -07:00
// Select suggestion
if (!suggestionsHidden && selectedSuggestion > -1 && (suggestions.length > 0 || menu)) {
2022-05-11 14:06:35 -07:00
e.preventDefault();
e.stopPropagation();
setSelectedSuggestion(firstIndex);
2022-05-11 14:06:35 -07:00
if (selectedSuggestion < suggestions.length) {
props.onSuggestionSelected(tokenStart!, lastToken, suggestions[selectedSuggestion]);
2022-06-04 16:21:16 -07:00
} else if (menu) {
const item = menu[selectedSuggestion - suggestions.length];
handleMenuItemAction(item, e);
2022-05-11 14:06:35 -07:00
}
2021-11-01 11:45:17 -07:00
}
2020-03-27 13:59:38 -07:00
2022-05-11 14:06:35 -07:00
break;
2020-03-27 13:59:38 -07:00
}
if (e.defaultPrevented || !props.onKeyDown) {
2020-03-27 13:59:38 -07:00
return;
}
if (props.onKeyDown) {
props.onKeyDown(e);
2022-06-04 16:21:16 -07:00
}
2023-01-05 09:55:08 -08:00
};
2020-03-27 13:59:38 -07:00
const onBlur = () => {
setSuggestionsHidden(true);
setFocused(true);
2023-01-05 09:55:08 -08:00
};
2020-03-27 13:59:38 -07:00
const onFocus = () => {
setFocused(true);
2023-01-05 09:55:08 -08:00
};
2020-03-27 13:59:38 -07:00
const onSuggestionClick: React.EventHandler<React.MouseEvent | React.TouchEvent> = (e) => {
2022-06-04 16:21:16 -07:00
const index = Number(e.currentTarget?.getAttribute('data-index'));
const suggestion = props.suggestions[index];
props.onSuggestionSelected(tokenStart!, lastToken, suggestion);
inputRef.current?.focus();
2022-06-04 16:21:16 -07:00
e.preventDefault();
2023-01-05 09:55:08 -08:00
};
2020-03-27 13:59:38 -07:00
useEffect(() => {
if (suggestionsHidden && focused) setSuggestionsHidden(false);
}, [props.suggestions]);
2020-03-27 13:59:38 -07:00
const renderSuggestion = (suggestion: AutoSuggestion, i: number) => {
2020-03-27 13:59:38 -07:00
let inner, key;
if (typeof suggestion === 'object' && 'origin_id' in suggestion) {
inner = <AutosuggestLocation location={suggestion} />;
key = suggestion.origin_id;
} else if (typeof suggestion === 'object') {
2020-03-27 13:59:38 -07:00
inner = <AutosuggestEmoji emoji={suggestion} />;
2022-06-07 08:11:28 -07:00
key = suggestion.id;
2020-03-27 13:59:38 -07:00
} else {
2022-03-21 11:09:01 -07:00
inner = <AutosuggestAccount id={suggestion} />;
2022-06-07 08:11:28 -07:00
key = suggestion;
2020-03-27 13:59:38 -07:00
}
return (
2022-03-21 11:09:01 -07:00
<div
role='button'
2022-06-04 16:21:16 -07:00
tabIndex={0}
2022-03-21 11:09:01 -07:00
key={key}
data-index={i}
2023-02-06 10:01:03 -08:00
className={clsx({
'px-4 py-2.5 text-sm text-gray-700 dark:text-gray-500 focus:bg-gray-100 dark:focus:bg-primary-800 group': true,
'hover:bg-gray-100 dark:hover:bg-gray-800': i !== selectedSuggestion,
'bg-gray-100 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-800': i === selectedSuggestion,
2022-03-21 11:09:01 -07:00
})}
onMouseDown={onSuggestionClick}
onTouchEnd={onSuggestionClick}
2022-03-21 11:09:01 -07:00
>
2020-03-27 13:59:38 -07:00
{inner}
</div>
);
2023-01-05 09:55:08 -08:00
};
2020-03-27 13:59:38 -07:00
const handleMenuItemAction = (item: MenuItem | null, e: React.MouseEvent | React.KeyboardEvent) => {
onBlur();
2022-06-04 16:21:16 -07:00
if (item?.action) {
item.action(e);
}
2023-01-05 09:55:08 -08:00
};
2021-11-01 11:45:17 -07:00
const handleMenuItemClick = (item: MenuItem | null): React.MouseEventHandler => e => {
e.preventDefault();
handleMenuItemAction(item, e);
2023-01-05 09:55:08 -08:00
};
2021-11-01 11:45:17 -07:00
const renderMenu = () => {
const { menu, suggestions } = props;
2021-11-01 11:45:17 -07:00
if (!menu) {
return null;
}
return menu.map((item, i) => (
<a
className={clsx('flex cursor-pointer items-center space-x-2 px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-100 focus:bg-gray-100 dark:text-gray-500 dark:hover:bg-gray-800 dark:focus:bg-primary-800', {
selected: suggestions.length - selectedSuggestion === i,
})}
2021-11-01 11:45:17 -07:00
href='#'
role='button'
2022-06-04 16:21:16 -07:00
tabIndex={0}
onMouseDown={handleMenuItemClick(item)}
2021-11-01 11:45:17 -07:00
key={i}
>
2022-06-04 16:21:16 -07:00
{item?.icon && (
2021-11-01 11:53:30 -07:00
<Icon src={item.icon} />
)}
2022-06-04 16:21:16 -07:00
<span>{item?.text}</span>
2021-11-01 11:45:17 -07:00
</a>
));
};
const setPortalPosition = () => {
if (!inputRef.current) {
return {};
}
const { top, height, left, width } = inputRef.current.getBoundingClientRect();
return { left, width, top: top + height };
};
const visible = !suggestionsHidden && (props.suggestions.length || (props.menu && props.value));
return [
<div key='input' className='relative w-full'>
<label className='sr-only'>{props.placeholder}</label>
<Input
type='text'
className={props.className}
outerClassName='mt-0'
ref={inputRef}
disabled={props.disabled}
placeholder={props.placeholder}
autoFocus={autoFocus}
value={props.value}
onChange={onChange}
onKeyDown={onKeyDown}
onKeyUp={props.onKeyUp}
onFocus={onFocus}
onBlur={onBlur}
aria-autocomplete='list'
id={props.id}
maxLength={props.maxLength}
data-testid='autosuggest-input'
theme={props.theme}
lang={props.lang}
/>
</div>,
<Portal key='portal'>
<div
style={setPortalPosition()}
className={clsx({
'fixed w-full z-[1001] shadow bg-white dark:bg-gray-900 rounded-lg py-1 dark:ring-2 dark:ring-primary-700 focus:outline-none': true,
hidden: !visible,
block: visible,
})}
>
<div className='space-y-0.5'>
{props.suggestions.map(renderSuggestion)}
2020-03-27 13:59:38 -07:00
</div>
{renderMenu()}
</div>
</Portal>,
];
};
export { type AutoSuggestion, type IAutosuggestInput, AutosuggestInput as default };