# All files / src/components autocomplete.tsx

78.33% Statements 47/60
61.36% Branches 27/44
91.66% Functions 11/12
78.33% Lines 47/60

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206

    9x
    9x

    50x

    25x

    9x

    15x
    15x
    15x
    8x
    8x

    15x

    9x

    10x
    10x
    10x

    10x
    4x

    10x
    4x

    4x

    10x

    2x
    2x

    2x
    2x
    2x
    2x
    2x

    10x

    2x
    2x
    2x
    2x
    2x
    2x

    10x

    2x

    2x

    2x

    2x
    2x
    2x

    2x

    10x

    10x
    10x

    10x

     import {
      useCallback,
      useEffect,
      useState,
      type HTMLAttributes,
      type ReactNode,
    } from 'react';
    import cn from 'classnames';
    import type { Except } from 'type-fest';

    import AutocompleteItem, {
      type AutocompleteItemType,
    } from './autocomplete-item';
    import SearchInput from './search-input';

    import { getLastIndexOfSubstringIgnoreCase } from '../utils';

    import '../styles/components/dropdown.scss';
    import '../styles/components/autocomplete.scss';

    export const filterOptions = (items: AutocompleteItemType[], query: string) =>
      items.filter(
        (item) =>
          getLastIndexOfSubstringIgnoreCase(item.pathLabel, query) >= 0 ||
          item.tags?.some(
            (tag) => getLastIndexOfSubstringIgnoreCase(tag, query) >= 0
          )
      );

    export const shouldShowDropdown = (
      textInputValue: string,
      data: AutocompleteItemType[],
      selected: boolean,
      filter: boolean,
      minCharsToShowDropdown: number
    ) => {
      const trimmed = textInputValue.trim();
      let showDropdown = false;
      if (trimmed && !selected && trimmed.length >= minCharsToShowDropdown) {
        const found = filter ? filterOptions(data, trimmed) : data;
        showDropdown = found.length > 0;
      }
      return showDropdown;
    };

    type AutocompleteProps = {
      data: AutocompleteItemType[];
      onSelect: (selected: AutocompleteItemType | string) => void;
      onChange?: (textInput: string) => void;
      onDropdownChange?: (dropdownShown: boolean) => void;
      clearOnSelect?: boolean;
      placeholder?: string;
      filter?: boolean;
      value?: string;
      minCharsToShowDropdown?: number;
      isLoading?: boolean;
      autoFocus?: boolean;
    };

    type Props = Except<
      HTMLAttributes<HTMLDivElement>,
      // Need to remove them because we use the same name as existing ones, but
      // but with a different signature
      'onSelect' | 'onChange'
    > &
      AutocompleteProps;

    const Autocomplete = ({
      data,
      onSelect,
      onChange,
      onDropdownChange,
      clearOnSelect = false,
      placeholder = '',
      filter = true,
      value = '',
      minCharsToShowDropdown = 0,
      isLoading = false,
      autoFocus = false,
      className,
      ...props
    }: Props) => {
      const [textInputValue, setTextInputValue] = useState(value);
      const [hoverIndex, setHoverIndex] = useState(-1);
      const [selected, setSelected] = useState(false);

      useEffect(() => {
        setTextInputValue(value);
      }, [value]);

      useEffect(
        () => () => {
          // On unmount tell the parent that the dropdown menu isn't being shown anymore.
          onDropdownChange?.(false);
        },
        [onDropdownChange]
      );

      const handleInputChange = useCallback(
        (event: React.ChangeEvent<HTMLInputElement>) => {
          const { value: textInputValue } = event.target;
          const showDropdown = shouldShowDropdown(
            textInputValue,
            data,
            false,
            filter,
            minCharsToShowDropdown
          );
          onDropdownChange?.(showDropdown);
          setTextInputValue(textInputValue);
          setSelected(false);
          onChange?.(textInputValue);
          Iif (showDropdown) {
            setHoverIndex(0);
          }
        },
        [data, filter, minCharsToShowDropdown, onChange, onDropdownChange]
      );

      const handleNodeSelect = useCallback(
        (selected: AutocompleteItemType | string) => {
          const textInputValue =
            typeof selected === 'string' ? selected : selected?.pathLabel;
          setTextInputValue(clearOnSelect ? '' : textInputValue);
          setHoverIndex(-1);
          setSelected(true);
          onDropdownChange?.(false);
          onSelect(selected);
        },
        [clearOnSelect, onSelect, onDropdownChange]
      );

      const handleOnKeyDown = useCallback(
        (event: React.KeyboardEvent<HTMLInputElement>) => {
          Iif (event.key === 'ArrowUp') {
            event.preventDefault();
            setHoverIndex(hoverIndex <= 0 ? -1 : hoverIndex - 1);
          } else Iif (event.key === 'ArrowDown') {
            event.preventDefault();
            const options = filter ? filterOptions(data, textInputValue) : data;
            setHoverIndex(Math.min(options.length - 1, hoverIndex + 1));
          } else Iif (event.key === 'Escape') {
            event.preventDefault();
            setHoverIndex(-1);
            setSelected(true);
          } else Eif (event.key === 'Enter') {
            event.preventDefault();
            Iif (hoverIndex >= 0) {
              const options = filter ? filterOptions(data, textInputValue) : data;
              handleNodeSelect(options[hoverIndex]);
            } else {
              handleNodeSelect(textInputValue);
            }
          }
        },
        [data, filter, handleNodeSelect, hoverIndex, textInputValue]
      );

      const showDropdown = shouldShowDropdown(
        textInputValue,
        data,
        selected,
        filter,
        minCharsToShowDropdown
      );

      let nodes: ReactNode[] = [];
      Iif (showDropdown) {
        nodes = (filter ? filterOptions(data, textInputValue) : data).map(
          (item, index) => (
            <AutocompleteItem
              item={item}
              active={hoverIndex === index}
              substringToHighlight={textInputValue}
              key={item.id}
              handleOnClick={handleNodeSelect}
            />
          )
        );
      }

      return (
        <div className={cn('autocomplete-container', className)} {...props}>
          <SearchInput
            value={textInputValue}
            onChange={handleInputChange}
            onKeyDown={handleOnKeyDown}
            placeholder={placeholder}
            isLoading={isLoading}
            autoFocus={autoFocus}
          />
          <div
            className={cn('autocomplete-menu', {
              'dropdown-menu-open': showDropdown,
            })}
          >
            <div className="dropdown-menu__panel">
              {nodes.length ? <ul>{nodes}</ul> : null}
            </div>
          </div>
        </div>
      );
    };

    export default Autocomplete;