pl-fe: convert autosuggest input to functional component

Signed-off-by: marcin mikołajczak <git@mkljczk.pl>
This commit is contained in:
marcin mikołajczak 2024-11-09 12:31:35 +01:00
parent e50446dfb2
commit df3b5dfc35
2 changed files with 112 additions and 129 deletions

View file

@ -1,5 +1,5 @@
import clsx from 'clsx'; import clsx from 'clsx';
import React, { PureComponent } from 'react'; import React, { useEffect, useRef, useState } from 'react';
import AutosuggestEmoji from 'pl-fe/components/autosuggest-emoji'; import AutosuggestEmoji from 'pl-fe/components/autosuggest-emoji';
import Icon from 'pl-fe/components/icon'; import Icon from 'pl-fe/components/icon';
@ -22,11 +22,11 @@ interface IAutosuggestInput extends Pick<React.HTMLAttributes<HTMLInputElement>,
onSuggestionSelected: (tokenStart: number, lastToken: string | null, suggestion: AutoSuggestion) => void; onSuggestionSelected: (tokenStart: number, lastToken: string | null, suggestion: AutoSuggestion) => void;
onSuggestionsClearRequested: () => void; onSuggestionsClearRequested: () => void;
onSuggestionsFetchRequested: (token: string) => void; onSuggestionsFetchRequested: (token: string) => void;
autoFocus: boolean; autoFocus?: boolean;
autoSelect: boolean; autoSelect?: boolean;
className?: string; className?: string;
id?: string; id?: string;
searchTokens: string[]; searchTokens?: string[];
maxLength?: number; maxLength?: number;
menu?: Menu; menu?: Menu;
renderSuggestion?: React.FC<{ id: string }>; renderSuggestion?: React.FC<{ id: string }>;
@ -34,50 +34,48 @@ interface IAutosuggestInput extends Pick<React.HTMLAttributes<HTMLInputElement>,
theme?: InputThemes; theme?: InputThemes;
} }
class AutosuggestInput extends PureComponent<IAutosuggestInput> { const AutosuggestInput: React.FC<IAutosuggestInput> = ({
autoFocus = false,
autoSelect = true,
searchTokens = ['@', ':', '#'],
...props
}) => {
const getFirstIndex = () => autoSelect ? 0 : -1;
static defaultProps = { const [suggestionsHidden, setSuggestionsHidden] = useState(true);
autoFocus: false, const [focused, setFocused] = useState(false);
autoSelect: true, const [selectedSuggestion, setSelectedSuggestion] = useState(getFirstIndex());
searchTokens: ['@', ':', '#'], const [lastToken, setLastToken] = useState<string | null>(null);
}; const [tokenStart, setTokenStart] = useState<number | null>(0);
getFirstIndex = () => this.props.autoSelect ? 0 : -1; const inputRef = useRef<HTMLInputElement>(null);
state = {
suggestionsHidden: true,
focused: false,
selectedSuggestion: this.getFirstIndex(),
lastToken: null,
tokenStart: 0,
};
input: HTMLInputElement | null = null; const onChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
onChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
const [tokenStart, token] = textAtCursorMatchesToken( const [tokenStart, token] = textAtCursorMatchesToken(
e.target.value, e.target.value,
e.target.selectionStart || 0, e.target.selectionStart || 0,
this.props.searchTokens, searchTokens,
); );
if (token !== null && this.state.lastToken !== token) { if (token !== null && lastToken !== token) {
this.setState({ lastToken: token, selectedSuggestion: 0, tokenStart }); setLastToken(token);
this.props.onSuggestionsFetchRequested(token); setSelectedSuggestion(0);
setTokenStart(tokenStart);
props.onSuggestionsFetchRequested(token);
} else if (token === null) { } else if (token === null) {
this.setState({ lastToken: null }); setLastToken(null);
this.props.onSuggestionsClearRequested(); props.onSuggestionsClearRequested();
} }
if (this.props.onChange) { if (props.onChange) {
this.props.onChange(e); props.onChange(e);
} }
}; };
onKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => { const onKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
const { suggestions, menu, disabled } = this.props; const { suggestions, menu, disabled } = props;
const { selectedSuggestion, suggestionsHidden } = this.state; const firstIndex = getFirstIndex();
const firstIndex = this.getFirstIndex();
const lastIndex = suggestions.length + (menu || []).length - 1; const lastIndex = suggestions.length + (menu || []).length - 1;
if (disabled) { if (disabled) {
@ -97,21 +95,21 @@ class AutosuggestInput extends PureComponent<IAutosuggestInput> {
document.querySelector('.ui')?.parentElement?.focus(); document.querySelector('.ui')?.parentElement?.focus();
} else { } else {
e.preventDefault(); e.preventDefault();
this.setState({ suggestionsHidden: true }); setSuggestionsHidden(true);
} }
break; break;
case 'ArrowDown': case 'ArrowDown':
if (!suggestionsHidden && (suggestions.length > 0 || menu)) { if (!suggestionsHidden && (suggestions.length > 0 || menu)) {
e.preventDefault(); e.preventDefault();
this.setState({ selectedSuggestion: Math.min(selectedSuggestion + 1, lastIndex) }); setSelectedSuggestion((selectedSuggestion) => Math.min(selectedSuggestion + 1, lastIndex));
} }
break; break;
case 'ArrowUp': case 'ArrowUp':
if (!suggestionsHidden && (suggestions.length > 0 || menu)) { if (!suggestionsHidden && (suggestions.length > 0 || menu)) {
e.preventDefault(); e.preventDefault();
this.setState({ selectedSuggestion: Math.max(selectedSuggestion - 1, firstIndex) }); setSelectedSuggestion((selectedSuggestion) => Math.min(selectedSuggestion - 1, lastIndex));
} }
break; break;
@ -121,61 +119,54 @@ class AutosuggestInput extends PureComponent<IAutosuggestInput> {
if (!suggestionsHidden && selectedSuggestion > -1 && (suggestions.length > 0 || menu)) { if (!suggestionsHidden && selectedSuggestion > -1 && (suggestions.length > 0 || menu)) {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
this.setState({ selectedSuggestion: firstIndex }); setSelectedSuggestion(firstIndex);
if (selectedSuggestion < suggestions.length) { if (selectedSuggestion < suggestions.length) {
this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestions[selectedSuggestion]); props.onSuggestionSelected(tokenStart!, lastToken, suggestions[selectedSuggestion]);
} else if (menu) { } else if (menu) {
const item = menu[selectedSuggestion - suggestions.length]; const item = menu[selectedSuggestion - suggestions.length];
this.handleMenuItemAction(item, e); handleMenuItemAction(item, e);
} }
} }
break; break;
} }
if (e.defaultPrevented || !this.props.onKeyDown) { if (e.defaultPrevented || !props.onKeyDown) {
return; return;
} }
if (this.props.onKeyDown) { if (props.onKeyDown) {
this.props.onKeyDown(e); props.onKeyDown(e);
} }
}; };
onBlur = () => { const onBlur = () => {
this.setState({ suggestionsHidden: true, focused: false }); setSuggestionsHidden(true);
setFocused(true);
}; };
onFocus = () => { const onFocus = () => {
this.setState({ focused: true }); setFocused(true);
}; };
onSuggestionClick: React.EventHandler<React.MouseEvent | React.TouchEvent> = (e) => { const onSuggestionClick: React.EventHandler<React.MouseEvent | React.TouchEvent> = (e) => {
const index = Number(e.currentTarget?.getAttribute('data-index')); const index = Number(e.currentTarget?.getAttribute('data-index'));
const suggestion = this.props.suggestions[index]; const suggestion = props.suggestions[index];
this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestion); props.onSuggestionSelected(tokenStart!, lastToken, suggestion);
this.input?.focus(); inputRef.current?.focus();
e.preventDefault(); e.preventDefault();
}; };
componentDidUpdate(prevProps: IAutosuggestInput, prevState: any) { useEffect(() => {
const { suggestions } = this.props; if (suggestionsHidden && focused) setSuggestionsHidden(false);
if (suggestions !== prevProps.suggestions && suggestions.length > 0 && prevState.suggestionsHidden && prevState.focused) { }, [props.suggestions]);
this.setState({ suggestionsHidden: false });
}
}
setInput = (c: HTMLInputElement) => { const renderSuggestion = (suggestion: AutoSuggestion, i: number) => {
this.input = c;
};
renderSuggestion = (suggestion: AutoSuggestion, i: number) => {
const { selectedSuggestion } = this.state;
let inner, key; let inner, key;
if (this.props.renderSuggestion && typeof suggestion === 'string') { if (props.renderSuggestion && typeof suggestion === 'string') {
const RenderSuggestion = this.props.renderSuggestion; const RenderSuggestion = props.renderSuggestion;
inner = <RenderSuggestion id={suggestion} />; inner = <RenderSuggestion id={suggestion} />;
key = suggestion; key = suggestion;
} else if (typeof suggestion === 'object') { } else if (typeof suggestion === 'object') {
@ -200,29 +191,28 @@ class AutosuggestInput extends PureComponent<IAutosuggestInput> {
'hover:bg-gray-100 dark:hover:bg-gray-800': i !== selectedSuggestion, '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, 'bg-gray-100 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-800': i === selectedSuggestion,
})} })}
onMouseDown={this.onSuggestionClick} onMouseDown={onSuggestionClick}
onTouchEnd={this.onSuggestionClick} onTouchEnd={onSuggestionClick}
> >
{inner} {inner}
</div> </div>
); );
}; };
handleMenuItemAction = (item: MenuItem | null, e: React.MouseEvent | React.KeyboardEvent) => { const handleMenuItemAction = (item: MenuItem | null, e: React.MouseEvent | React.KeyboardEvent) => {
this.onBlur(); onBlur();
if (item?.action) { if (item?.action) {
item.action(e); item.action(e);
} }
}; };
handleMenuItemClick = (item: MenuItem | null): React.MouseEventHandler => e => { const handleMenuItemClick = (item: MenuItem | null): React.MouseEventHandler => e => {
e.preventDefault(); e.preventDefault();
this.handleMenuItemAction(item, e); handleMenuItemAction(item, e);
}; };
renderMenu = () => { const renderMenu = () => {
const { menu, suggestions } = this.props; const { menu, suggestions } = props;
const { selectedSuggestion } = this.state;
if (!menu) { if (!menu) {
return null; return null;
@ -236,7 +226,7 @@ class AutosuggestInput extends PureComponent<IAutosuggestInput> {
href='#' href='#'
role='button' role='button'
tabIndex={0} tabIndex={0}
onMouseDown={this.handleMenuItemClick(item)} onMouseDown={handleMenuItemClick(item)}
key={i} key={i}
> >
{item?.icon && ( {item?.icon && (
@ -248,66 +238,60 @@ class AutosuggestInput extends PureComponent<IAutosuggestInput> {
)); ));
}; };
setPortalPosition() { const setPortalPosition = () => {
if (!this.input) { if (!inputRef.current) {
return {}; return {};
} }
const { top, height, left, width } = this.input.getBoundingClientRect(); const { top, height, left, width } = inputRef.current.getBoundingClientRect();
return { left, width, top: top + height }; return { left, width, top: top + height };
} };
render() { const visible = !suggestionsHidden && (props.suggestions.length || (props.menu && props.value));
const { value, suggestions, disabled, placeholder, onKeyUp, autoFocus, className, id, maxLength, menu, theme } = this.props;
const { suggestionsHidden } = this.state;
const visible = !suggestionsHidden && (suggestions.length || (menu && value)); return [
<div key='input' className='relative w-full'>
<label className='sr-only'>{props.placeholder}</label>
return [ <Input
<div key='input' className='relative w-full'> type='text'
<label className='sr-only'>{placeholder}</label> className={props.className}
outerClassName='mt-0'
<Input ref={inputRef}
type='text' disabled={props.disabled}
className={className} placeholder={props.placeholder}
outerClassName='mt-0' autoFocus={autoFocus}
ref={this.setInput} value={props.value}
disabled={disabled} onChange={onChange}
placeholder={placeholder} onKeyDown={onKeyDown}
autoFocus={autoFocus} onKeyUp={props.onKeyUp}
value={value} onFocus={onFocus}
onChange={this.onChange} onBlur={onBlur}
onKeyDown={this.onKeyDown} aria-autocomplete='list'
onKeyUp={onKeyUp} id={props.id}
onFocus={this.onFocus} maxLength={props.maxLength}
onBlur={this.onBlur} data-testid='autosuggest-input'
aria-autocomplete='list' theme={props.theme}
id={id} />
maxLength={maxLength} </div>,
data-testid='autosuggest-input' <Portal key='portal'>
theme={theme} <div
/> style={setPortalPosition()}
</div>, className={clsx({
<Portal key='portal'> '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,
<div hidden: !visible,
style={this.setPortalPosition()} block: visible,
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, <div className='space-y-0.5'>
block: visible, {props.suggestions.map(renderSuggestion)}
})}
>
<div className='space-y-0.5'>
{suggestions.map(this.renderSuggestion)}
</div>
{this.renderMenu()}
</div> </div>
</Portal>,
];
}
} {renderMenu()}
</div>
</Portal>,
];
};
export { type AutoSuggestion, type IAutosuggestInput, AutosuggestInput as default }; export { type AutoSuggestion, type IAutosuggestInput, AutosuggestInput as default };

View file

@ -15,13 +15,13 @@ interface ISpoilerInput extends Pick<IAutosuggestInput, 'onSuggestionsFetchReque
} }
/** Text input for content warning in composer. */ /** Text input for content warning in composer. */
const SpoilerInput = React.forwardRef<AutosuggestInput, ISpoilerInput>(({ const SpoilerInput: React.FC<ISpoilerInput> = ({
composeId, composeId,
onSuggestionsFetchRequested, onSuggestionsFetchRequested,
onSuggestionsClearRequested, onSuggestionsClearRequested,
onSuggestionSelected, onSuggestionSelected,
theme, theme,
}, ref) => { }) => {
const intl = useIntl(); const intl = useIntl();
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const { language, modified_language, spoiler_text: spoilerText, spoilerTextMap, suggestions } = useCompose(composeId); const { language, modified_language, spoiler_text: spoilerText, spoilerTextMap, suggestions } = useCompose(composeId);
@ -45,9 +45,8 @@ const SpoilerInput = React.forwardRef<AutosuggestInput, ISpoilerInput>(({
searchTokens={[':']} searchTokens={[':']}
id='cw-spoiler-input' id='cw-spoiler-input'
className='rounded-md !bg-transparent dark:!bg-transparent' className='rounded-md !bg-transparent dark:!bg-transparent'
ref={ref}
/> />
); );
}); };
export { SpoilerInput as default }; export { SpoilerInput as default };