summaryrefslogtreecommitdiff
path: root/extension/react-app/src/components/ComboBox.tsx
blob: ace0605ebb13143965afeaa599a413ef5ee00e0c (plain)
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
import React, { useCallback } from "react";
import { useCombobox } from "downshift";
import styled from "styled-components";
import {
  buttonColor,
  defaultBorderRadius,
  secondaryDark,
  vscBackground,
} from ".";

const mainInputFontSize = 16;
const MainTextInput = styled.input`
  padding: 8px;
  font-size: ${mainInputFontSize}px;
  border-radius: ${defaultBorderRadius};
  border: 1px solid #ccc;
  margin: 8px auto;
  width: 100%;
  background-color: ${vscBackground};
  color: white;
  outline: 1px solid orange;
`;

const UlMaxHeight = 200;
const Ul = styled.ul<{
  hidden: boolean;
  showAbove: boolean;
  ulHeightPixels: number;
}>`
  ${(props) =>
    props.showAbove
      ? `transform: translateY(-${props.ulHeightPixels + 8}px);`
      : `transform: translateY(${2 * mainInputFontSize}px);`}
  position: absolute;
  background: ${vscBackground};
  background-color: ${secondaryDark};
  color: white;
  font-family: "Fira Code", monospace;
  max-height: ${UlMaxHeight}px;
  overflow: scroll;
  padding: 0;
  ${({ hidden }) => hidden && "display: none;"}
  border-radius: ${defaultBorderRadius};
  overflow: hidden;
  border: 0.5px solid gray;
`;

const Li = styled.li<{
  highlighted: boolean;
  selected: boolean;
  isLastItem: boolean;
}>`
  ${({ highlighted }) => highlighted && "background: #aa0000;"}
  ${({ selected }) => selected && "font-weight: bold;"}
    padding: 0.5rem 0.75rem;
  display: flex;
  flex-direction: column;
  ${({ isLastItem }) => isLastItem && "border-bottom: 1px solid gray;"}
  border-top: 1px solid gray;
  cursor: pointer;
`;

interface ComboBoxProps {
  items: { name: string; description: string }[];
  onInputValueChange: (inputValue: string) => void;
  disabled?: boolean;
  onEnter?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
}

const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
  const [items, setItems] = React.useState(props.items);
  const {
    isOpen,
    getToggleButtonProps,
    getLabelProps,
    getMenuProps,
    getInputProps,
    highlightedIndex,
    getItemProps,
    selectedItem,
    setInputValue,
  } = useCombobox({
    onInputValueChange({ inputValue }) {
      if (!inputValue) return;
      props.onInputValueChange(inputValue);
      setItems(
        props.items.filter((item) =>
          item.name.toLowerCase().startsWith(inputValue.toLowerCase())
        )
      );
    },
    items,
    itemToString(item) {
      return item ? item.name : "";
    },
  });

  const divRef = React.useRef<HTMLDivElement>(null);
  const ulRef = React.useRef<HTMLUListElement>(null);
  const showAbove = () => {
    return (divRef.current?.getBoundingClientRect().top || 0) > UlMaxHeight;
  };

  return (
    <div className="flex px-2" ref={divRef} hidden={!isOpen}>
      <MainTextInput
        disabled={props.disabled}
        placeholder="Type '/' to see the list of available slash commands..."
        {...getInputProps({
          onKeyDown: (event) => {
            if (event.key === "Enter" && (!isOpen || items.length === 0)) {
              // Prevent Downshift's default 'Enter' behavior.
              (event.nativeEvent as any).preventDownshiftDefault = true;
              if (props.onEnter) props.onEnter(event);
              setInputValue("");
            }
          },
          ref: ref as any,
        })}
      />
      <Ul
        {...getMenuProps({
          ref: ulRef,
        })}
        showAbove={showAbove()}
        ulHeightPixels={ulRef.current?.getBoundingClientRect().height || 0}
      >
        {isOpen &&
          items.map((item, index) => (
            <Li
              key={`${item.name}${index}`}
              {...getItemProps({ item, index })}
              highlighted={highlightedIndex === index}
              selected={selectedItem === item}
            >
              <span>
                {item.name}: {item.description}
              </span>
            </Li>
          ))}
      </Ul>
    </div>
  );
});

export default ComboBox;