soapbox/app/soapbox/components/autosuggest-input.tsx

321 wiersze
9.6 KiB
TypeScript
Czysty Zwykły widok Historia

2023-02-06 18:01:03 +00:00
import clsx from 'clsx';
import { List as ImmutableList } from 'immutable';
2020-03-27 20:59:38 +00:00
import React from 'react';
import ImmutablePureComponent from 'react-immutable-pure-component';
2022-11-15 16:11:42 +00:00
import AutosuggestEmoji, { Emoji } from 'soapbox/components/autosuggest-emoji';
2021-11-01 18:53:30 +00:00
import Icon from 'soapbox/components/icon';
import { Input, Portal } from 'soapbox/components/ui';
2022-11-15 17:23:36 +00:00
import AutosuggestAccount from 'soapbox/features/compose/components/autosuggest-account';
import { isRtl } from 'soapbox/rtl';
2022-11-22 14:55:31 +00:00
import { textAtCursorMatchesToken } from 'soapbox/utils/suggestions';
2022-11-15 14:10:14 +00:00
import type { Menu, MenuItem } from 'soapbox/components/dropdown-menu';
import type { InputThemes } from 'soapbox/components/ui/input/input';
2022-06-04 23:36:34 +00:00
export type AutoSuggestion = string | Emoji;
2022-06-04 23:35:04 +00:00
2022-10-31 21:19:51 +00:00
export interface IAutosuggestInput extends Pick<React.HTMLAttributes<HTMLInputElement>, 'onChange' | 'onKeyUp' | 'onKeyDown'> {
value: string
suggestions: ImmutableList<any>
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
renderSuggestion?: React.FC<{ id: string }>
hidePortal?: boolean
theme?: InputThemes
2022-06-04 23:21:16 +00:00
}
export default class AutosuggestInput extends ImmutablePureComponent<IAutosuggestInput> {
2020-03-27 20:59:38 +00:00
static defaultProps = {
2021-10-14 17:35:05 +00:00
autoFocus: false,
autoSelect: true,
2020-03-27 20:59:38 +00:00
searchTokens: ImmutableList(['@', ':', '#']),
};
getFirstIndex = () => {
return this.props.autoSelect ? 0 : -1;
2023-01-05 17:55:08 +00:00
};
2020-03-27 20:59:38 +00:00
state = {
suggestionsHidden: true,
focused: false,
selectedSuggestion: this.getFirstIndex(),
2020-03-27 20:59:38 +00:00
lastToken: null,
tokenStart: 0,
};
2022-06-04 23:21:16 +00:00
input: HTMLInputElement | null = null;
onChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
2022-11-22 14:55:31 +00:00
const [tokenStart, token] = textAtCursorMatchesToken(
e.target.value,
e.target.selectionStart || 0,
this.props.searchTokens,
);
2020-03-27 20:59:38 +00:00
if (token !== null && this.state.lastToken !== token) {
this.setState({ lastToken: token, selectedSuggestion: 0, tokenStart });
this.props.onSuggestionsFetchRequested(token);
} else if (token === null) {
this.setState({ lastToken: null });
this.props.onSuggestionsClearRequested();
}
2022-06-04 23:21:16 +00:00
if (this.props.onChange) {
this.props.onChange(e);
}
2023-01-05 17:55:08 +00:00
};
2020-03-27 20:59:38 +00:00
2022-06-04 23:21:16 +00:00
onKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
2021-11-01 18:45:17 +00:00
const { suggestions, menu, disabled } = this.props;
2020-03-27 20:59:38 +00:00
const { selectedSuggestion, suggestionsHidden } = this.state;
const firstIndex = this.getFirstIndex();
2021-11-01 18:45:17 +00:00
const lastIndex = suggestions.size + (menu || []).length - 1;
2020-03-27 20:59:38 +00:00
if (disabled) {
e.preventDefault();
return;
}
2022-06-04 23:21:16 +00:00
if (e.which === 229) {
2020-03-27 20:59:38 +00: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 21:06:35 +00:00
case 'Escape':
if (suggestions.size === 0 || suggestionsHidden) {
2022-06-04 23:21:16 +00:00
document.querySelector('.ui')?.parentElement?.focus();
2021-11-01 18:45:17 +00:00
} else {
2022-05-11 21:06:35 +00:00
e.preventDefault();
this.setState({ suggestionsHidden: true });
}
break;
case 'ArrowDown':
if (!suggestionsHidden && (suggestions.size > 0 || menu)) {
e.preventDefault();
this.setState({ selectedSuggestion: Math.min(selectedSuggestion + 1, lastIndex) });
}
break;
case 'ArrowUp':
if (!suggestionsHidden && (suggestions.size > 0 || menu)) {
e.preventDefault();
this.setState({ selectedSuggestion: Math.max(selectedSuggestion - 1, firstIndex) });
}
break;
case 'Enter':
case 'Tab':
2022-06-04 23:21:16 +00:00
// Select suggestion
2022-05-11 21:06:35 +00:00
if (!suggestionsHidden && selectedSuggestion > -1 && (suggestions.size > 0 || menu)) {
e.preventDefault();
e.stopPropagation();
this.setState({ selectedSuggestion: firstIndex });
if (selectedSuggestion < suggestions.size) {
this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestions.get(selectedSuggestion));
2022-06-04 23:21:16 +00:00
} else if (menu) {
2022-05-11 21:06:35 +00:00
const item = menu[selectedSuggestion - suggestions.size];
2022-06-04 23:21:16 +00:00
this.handleMenuItemAction(item, e);
2022-05-11 21:06:35 +00:00
}
2021-11-01 18:45:17 +00:00
}
2020-03-27 20:59:38 +00:00
2022-05-11 21:06:35 +00:00
break;
2020-03-27 20:59:38 +00:00
}
if (e.defaultPrevented || !this.props.onKeyDown) {
return;
}
2022-06-04 23:21:16 +00:00
if (this.props.onKeyDown) {
this.props.onKeyDown(e);
}
2023-01-05 17:55:08 +00:00
};
2020-03-27 20:59:38 +00:00
onBlur = () => {
this.setState({ suggestionsHidden: true, focused: false });
2023-01-05 17:55:08 +00:00
};
2020-03-27 20:59:38 +00:00
onFocus = () => {
this.setState({ focused: true });
2023-01-05 17:55:08 +00:00
};
2020-03-27 20:59:38 +00:00
onSuggestionClick: React.EventHandler<React.MouseEvent | React.TouchEvent> = (e) => {
2022-06-04 23:21:16 +00:00
const index = Number(e.currentTarget?.getAttribute('data-index'));
const suggestion = this.props.suggestions.get(index);
2020-03-27 20:59:38 +00:00
this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestion);
2022-06-04 23:21:16 +00:00
this.input?.focus();
e.preventDefault();
2023-01-05 17:55:08 +00:00
};
2020-03-27 20:59:38 +00:00
2022-06-04 23:21:16 +00:00
componentDidUpdate(prevProps: IAutosuggestInput, prevState: any) {
const { suggestions } = this.props;
if (suggestions !== prevProps.suggestions && suggestions.size > 0 && prevState.suggestionsHidden && prevState.focused) {
this.setState({ suggestionsHidden: false });
2020-03-27 20:59:38 +00:00
}
}
2022-06-04 23:21:16 +00:00
setInput = (c: HTMLInputElement) => {
2020-03-27 20:59:38 +00:00
this.input = c;
2023-01-05 17:55:08 +00:00
};
2020-03-27 20:59:38 +00:00
2022-06-04 23:36:34 +00:00
renderSuggestion = (suggestion: AutoSuggestion, i: number) => {
2020-03-27 20:59:38 +00:00
const { selectedSuggestion } = this.state;
let inner, key;
if (this.props.renderSuggestion && typeof suggestion === 'string') {
const RenderSuggestion = this.props.renderSuggestion;
inner = <RenderSuggestion id={suggestion} />;
key = suggestion;
} else if (typeof suggestion === 'object') {
2020-03-27 20:59:38 +00:00
inner = <AutosuggestEmoji emoji={suggestion} />;
2022-06-07 15:11:28 +00:00
key = suggestion.id;
2020-03-27 20:59:38 +00:00
} else if (suggestion[0] === '#') {
inner = suggestion;
2022-06-07 15:11:28 +00:00
key = suggestion;
2020-03-27 20:59:38 +00:00
} else {
2022-03-21 18:09:01 +00:00
inner = <AutosuggestAccount id={suggestion} />;
2022-06-07 15:11:28 +00:00
key = suggestion;
2020-03-27 20:59:38 +00:00
}
return (
2022-03-21 18:09:01 +00:00
<div
role='button'
2022-06-04 23:21:16 +00:00
tabIndex={0}
2022-03-21 18:09:01 +00:00
key={key}
data-index={i}
2023-02-06 18:01:03 +00:00
className={clsx({
'px-4 py-2.5 text-sm text-gray-700 dark:text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-800 focus:bg-gray-100 dark:focus:bg-primary-800 group': true,
'bg-gray-100 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-800': i === selectedSuggestion,
2022-03-21 18:09:01 +00:00
})}
onMouseDown={this.onSuggestionClick}
onTouchEnd={this.onSuggestionClick}
2022-03-21 18:09:01 +00:00
>
2020-03-27 20:59:38 +00:00
{inner}
</div>
);
2023-01-05 17:55:08 +00:00
};
2020-03-27 20:59:38 +00:00
2022-06-04 23:21:16 +00:00
handleMenuItemAction = (item: MenuItem | null, e: React.MouseEvent | React.KeyboardEvent) => {
2021-11-01 18:45:17 +00:00
this.onBlur();
2022-06-04 23:21:16 +00:00
if (item?.action) {
item.action(e);
}
2023-01-05 17:55:08 +00:00
};
2021-11-01 18:45:17 +00:00
2022-06-04 23:21:16 +00:00
handleMenuItemClick = (item: MenuItem | null): React.MouseEventHandler => {
2021-11-01 18:45:17 +00:00
return e => {
e.preventDefault();
2022-06-04 23:21:16 +00:00
this.handleMenuItemAction(item, e);
2021-11-01 18:45:17 +00:00
};
2023-01-05 17:55:08 +00:00
};
2021-11-01 18:45:17 +00:00
renderMenu = () => {
const { menu, suggestions } = this.props;
const { selectedSuggestion } = this.state;
if (!menu) {
return null;
}
return menu.map((item, i) => (
<a
2023-02-06 18:06:44 +00:00
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.size - selectedSuggestion === i })}
2021-11-01 18:45:17 +00:00
href='#'
role='button'
2022-06-04 23:21:16 +00:00
tabIndex={0}
2021-11-01 18:45:17 +00:00
onMouseDown={this.handleMenuItemClick(item)}
key={i}
>
2022-06-04 23:21:16 +00:00
{item?.icon && (
2021-11-01 18:53:30 +00:00
<Icon src={item.icon} />
)}
2022-06-04 23:21:16 +00:00
<span>{item?.text}</span>
2021-11-01 18:45:17 +00:00
</a>
));
};
setPortalPosition() {
if (!this.input) {
return {};
}
const { top, height, left, width } = this.input.getBoundingClientRect();
return { left, width, top: top + height };
}
render() {
const { value, suggestions, disabled, placeholder, onKeyUp, autoFocus, className, id, maxLength, menu, theme } = this.props;
2020-03-27 20:59:38 +00:00
const { suggestionsHidden } = this.state;
const style: React.CSSProperties = { direction: 'ltr' };
const visible = !suggestionsHidden && (!suggestions.isEmpty() || (menu && value));
2021-11-01 18:45:17 +00:00
// TODO: convert to functional component and use `useLocale()` hook instead of checking placeholder text.
if (isRtl(value) || (!value && placeholder && isRtl(placeholder))) {
style.direction = 'rtl';
}
return [
<div key='input' className='relative w-full'>
2022-03-21 18:09:01 +00:00
<label className='sr-only'>{placeholder}</label>
<Input
2022-03-21 18:09:01 +00:00
type='text'
className={className}
2022-10-04 21:25:02 +00:00
outerClassName='mt-0'
2022-03-21 18:09:01 +00:00
ref={this.setInput}
disabled={disabled}
placeholder={placeholder}
autoFocus={autoFocus}
value={value}
onChange={this.onChange}
onKeyDown={this.onKeyDown}
onKeyUp={onKeyUp}
onFocus={this.onFocus}
onBlur={this.onBlur}
style={style}
2022-03-21 18:09:01 +00:00
aria-autocomplete='list'
id={id}
maxLength={maxLength}
2022-04-06 14:10:21 +00:00
data-testid='autosuggest-input'
theme={theme}
2022-03-21 18:09:01 +00:00
/>
</div>,
<Portal key='portal'>
<div
style={this.setPortalPosition()}
2023-02-06 18:01:03 +00:00
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,
})}
2022-03-21 18:09:01 +00:00
>
<div className='space-y-0.5'>
{suggestions.map(this.renderSuggestion)}
</div>
2021-11-01 18:45:17 +00:00
{this.renderMenu()}
2020-03-27 20:59:38 +00:00
</div>
</Portal>,
];
2020-03-27 20:59:38 +00:00
}
}