import type { ComponentPropsWithoutRef } from 'react'; import { forwardRef, useCallback, useId, useRef, useState } from 'react'; import { useIntl } from 'react-intl'; import classNames from 'classnames'; import Overlay from 'react-overlays/Overlay'; import KeyboardArrowDownIcon from '@/material-icons/400-24px/keyboard_arrow_down.svg?react'; import KeyboardArrowUpIcon from '@/material-icons/400-24px/keyboard_arrow_up.svg?react'; import { matchWidth } from 'mastodon/components/dropdown/utils'; import { IconButton } from 'mastodon/components/icon_button'; import { useOnClickOutside } from 'mastodon/hooks/useOnClickOutside'; import classes from './combobox.module.scss'; import { FormFieldWrapper } from './form_field_wrapper'; import type { CommonFieldWrapperProps } from './form_field_wrapper'; import { TextInput } from './text_input_field'; interface Item { id: string; } interface ComboboxProps< T extends Item, > extends ComponentPropsWithoutRef<'input'> { value: string; onChange: React.ChangeEventHandler; isLoading?: boolean; items: T[]; getItemId: (item: T) => string; getIsItemDisabled?: (item: T) => boolean; renderItem: (item: T) => React.ReactElement; onSelectItem: (item: T) => void; } interface Props extends ComboboxProps, CommonFieldWrapperProps {} /** * The combobox field allows users to select one or multiple items * from a large list of options by searching or filtering. */ export const ComboboxFieldWithRef = ( { id, label, hint, hasError, required, ...otherProps }: Props, ref: React.ForwardedRef, ) => ( {(inputProps) => } ); // Using a type assertion to maintain the full type signature of ComboboxWithRef // (including its generic type) after wrapping it with `forwardRef`. export const ComboboxField = forwardRef(ComboboxFieldWithRef) as { ( props: Props & { ref?: React.ForwardedRef }, ): ReturnType; displayName: string; }; ComboboxField.displayName = 'ComboboxField'; const ComboboxWithRef = ( { value, isLoading = false, items, getItemId, getIsItemDisabled, renderItem, onSelectItem, onChange, onKeyDown, className, ...otherProps }: ComboboxProps, ref: React.ForwardedRef, ) => { const intl = useIntl(); const wrapperRef = useRef(null); const inputRef = useRef(); const [highlightedItemId, setHighlightedItemId] = useState( null, ); const [shouldMenuOpen, setShouldMenuOpen] = useState(false); const statusMessage = useGetA11yStatusMessage({ value, isLoading, itemCount: items.length, }); const showStatusMessageInMenu = !!statusMessage && value.length > 0 && items.length === 0; const hasMenuContent = items.length > 0 || showStatusMessageInMenu; const isMenuOpen = shouldMenuOpen && hasMenuContent; const openMenu = useCallback(() => { setShouldMenuOpen(true); }, []); const closeMenu = useCallback(() => { setShouldMenuOpen(false); }, []); const resetHighlight = useCallback(() => { const firstItem = items[0]; const firstItemId = firstItem ? getItemId(firstItem) : null; setHighlightedItemId(firstItemId); }, [getItemId, items]); const handleInputChange = useCallback( (e: React.ChangeEvent) => { onChange(e); resetHighlight(); setShouldMenuOpen(!!e.target.value); }, [onChange, resetHighlight], ); const handleHighlightItem = useCallback( (e: React.MouseEvent) => { const { itemId } = e.currentTarget.dataset; if (itemId) { setHighlightedItemId(itemId); } }, [], ); const selectItem = useCallback( (itemId: string | null) => { const item = items.find((item) => item.id === itemId); if (item) { const isDisabled = getIsItemDisabled?.(item) ?? false; if (!isDisabled) { onSelectItem(item); } } inputRef.current?.focus(); }, [getIsItemDisabled, items, onSelectItem], ); const handleSelectItem = useCallback( (e: React.MouseEvent) => { const { itemId } = e.currentTarget.dataset; selectItem(itemId ?? null); }, [selectItem], ); const selectHighlightedItem = useCallback(() => { selectItem(highlightedItemId); }, [highlightedItemId, selectItem]); const moveHighlight = useCallback( (direction: number) => { if (items.length === 0) { return; } const highlightedItemIndex = items.findIndex( (item) => getItemId(item) === highlightedItemId, ); if (highlightedItemIndex === -1) { // If no item is highlighted yet, highlight the first or last if (direction > 0) { const firstItem = items.at(0); setHighlightedItemId(firstItem ? getItemId(firstItem) : null); } else { const lastItem = items.at(-1); setHighlightedItemId(lastItem ? getItemId(lastItem) : null); } } else { // If there is a highlighted item, select the next or previous item // and wrap around at the start or end: let newIndex = highlightedItemIndex + direction; if (newIndex >= items.length) { newIndex = 0; } else if (newIndex < 0) { newIndex = items.length - 1; } const newHighlightedItem = items[newIndex]; setHighlightedItemId( newHighlightedItem ? getItemId(newHighlightedItem) : null, ); } }, [getItemId, highlightedItemId, items], ); useOnClickOutside(wrapperRef, closeMenu); const handleInputKeyDown = useCallback( (e: React.KeyboardEvent) => { onKeyDown?.(e); if (e.key === 'ArrowUp') { e.preventDefault(); if (isMenuOpen) { moveHighlight(-1); } else { openMenu(); } } if (e.key === 'ArrowDown') { e.preventDefault(); if (isMenuOpen) { moveHighlight(1); } else { openMenu(); } } if (e.key === 'Tab') { if (isMenuOpen) { selectHighlightedItem(); closeMenu(); } } if (e.key === 'Enter') { if (isMenuOpen) { e.preventDefault(); selectHighlightedItem(); closeMenu(); } } if (e.key === 'Escape') { if (isMenuOpen) { e.preventDefault(); closeMenu(); } } }, [ closeMenu, isMenuOpen, moveHighlight, onKeyDown, openMenu, selectHighlightedItem, ], ); const mergeRefs = useCallback( (element: HTMLInputElement | null) => { inputRef.current = element; if (typeof ref === 'function') { ref(element); } else if (ref) { ref.current = element; } }, [ref], ); const id = useId(); const listId = `${id}-list`; return (
{hasMenuContent && ( )} {isMenuOpen && statusMessage} } container={wrapperRef} popperConfig={{ modifiers: [matchWidth], }} > {({ props, placement }) => (
{showStatusMessageInMenu ? ( {statusMessage} ) : (
    {items.map((item) => { const id = getItemId(item); const isDisabled = getIsItemDisabled?.(item); return ( // eslint-disable-next-line jsx-a11y/click-events-have-key-events
  • {renderItem(item)}
  • ); })}
)}
)}
); }; // Using a type assertion to maintain the full type signature of ComboboxWithRef // (including its generic type) after wrapping it with `forwardRef`. export const Combobox = forwardRef(ComboboxWithRef) as { ( props: ComboboxProps & { ref?: React.ForwardedRef }, ): ReturnType; displayName: string; }; Combobox.displayName = 'Combobox'; function useGetA11yStatusMessage({ itemCount, value, isLoading, }: { itemCount: number; value: string; isLoading: boolean; }): string { const intl = useIntl(); if (isLoading) { return intl.formatMessage({ id: 'combobox.loading', defaultMessage: 'Loading', }); } if (value.length && !itemCount) { return intl.formatMessage({ id: 'combobox.no_results_found', defaultMessage: 'No results for this search', }); } if (itemCount > 0) { return intl.formatMessage( { id: 'combobox.results_available', defaultMessage: '{count, plural, one {# suggestion} other {# suggestions}} available. Use up and down arrow keys to navigate. Press Enter key to select.', }, { count: itemCount, }, ); } return ''; }