summaryrefslogtreecommitdiff
path: root/extension/react-app/src/components/ComboBox.tsx
blob: 81b148b91025130ff6e47f1213a1f6ca3dab096c (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
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
import React, { useCallback, useEffect, useState } from "react";
import { useCombobox } from "downshift";
import styled from "styled-components";
import {
  buttonColor,
  defaultBorderRadius,
  secondaryDark,
  vscBackground,
} from ".";
import CodeBlock from "./CodeBlock";
import { RangeInFile } from "../../../src/client";
import PillButton from "./PillButton";
import HeaderButtonWithText from "./HeaderButtonWithText";
import {
  Trash,
  LockClosed,
  LockOpen,
  Plus,
} from "@styled-icons/heroicons-outline";

// #region styled components
const mainInputFontSize = 16;

const ContextDropdown = styled.div`
  position: absolute;
  padding: 4px;
  width: calc(100% - 16px - 8px);
  background-color: ${secondaryDark};
  color: white;
  border-bottom-right-radius: ${defaultBorderRadius};
  border-bottom-left-radius: ${defaultBorderRadius};
  /* border: 1px solid white; */
  border-top: none;
  margin: 8px;
  outline: 1px solid orange;
  z-index: 5;
`;

const MainTextInput = styled.textarea`
  resize: none;

  padding: 8px;
  font-size: ${mainInputFontSize}px;
  border-radius: ${defaultBorderRadius};
  border: 1px solid white;
  margin: 8px auto;
  width: 100%;
  background-color: ${vscBackground};
  color: white;
  z-index: 1;

  &:focus {
    border: 1px solid transparent;
    outline: 1px solid orange;
  }
`;

const UlMaxHeight = 400;
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;
  z-index: 2;
`;

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;
`;

// #endregion

interface ComboBoxProps {
  items: { name: string; description: string }[];
  onInputValueChange: (inputValue: string) => void;
  disabled?: boolean;
  onEnter: (e: React.KeyboardEvent<HTMLInputElement>) => void;
  highlightedCodeSections: (RangeInFile & { contents: string })[];
  deleteContextItems: (indices: number[]) => void;
  onTogglePin: () => void;
  onToggleAddContext: () => void;
  addingHighlightedCode: boolean;
}

const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
  const [history, setHistory] = React.useState<string[]>([]);
  // The position of the current command you are typing now, so the one that will be appended to history once you press enter
  const [positionInHistory, setPositionInHistory] = React.useState<number>(0);
  const [items, setItems] = React.useState(props.items);
  const [hoveringButton, setHoveringButton] = React.useState(false);
  const [hoveringContextDropdown, setHoveringContextDropdown] =
    React.useState(false);
  const [pinned, setPinned] = useState(false);
  const [highlightedCodeSections, setHighlightedCodeSections] = React.useState(
    props.highlightedCodeSections || [
      {
        filepath: "test.ts",
        range: {
          start: { line: 0, character: 0 },
          end: { line: 0, character: 0 },
        },
        contents: "import * as a from 'a';",
      },
    ]
  );

  useEffect(() => {
    setHighlightedCodeSections(props.highlightedCodeSections || []);
  }, [props.highlightedCodeSections]);

  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="Ask a question, give instructions, or type '/' to see slash commands"
          {...getInputProps({
            onChange: (e) => {
              const target = e.target as HTMLTextAreaElement;
              // Update the height of the textarea to match the content, up to a max of 200px.
              target.style.height = "auto";
              target.style.height = `${Math.min(
                target.scrollHeight,
                300
              ).toString()}px`;

              // setShowContextDropdown(target.value.endsWith("@"));
            },
            onKeyDown: (event) => {
              if (event.key === "Enter" && event.shiftKey) {
                // Prevent Downshift's default 'Enter' behavior.
                (event.nativeEvent as any).preventDownshiftDefault = true;
              } else if (
                event.key === "Enter" &&
                (!isOpen || items.length === 0)
              ) {
                // Prevent Downshift's default 'Enter' behavior.
                (event.nativeEvent as any).preventDownshiftDefault = true;

                // cmd+enter to /edit
                if (event.metaKey) {
                  event.currentTarget.value = `/edit ${event.currentTarget.value}`;
                }
                if (props.onEnter) props.onEnter(event);
                setInputValue("");
                const value = event.currentTarget.value;
                if (value !== "") {
                  setPositionInHistory(history.length + 1);
                  setHistory([...history, value]);
                }
              } else if (event.key === "Tab" && items.length > 0) {
                setInputValue(items[0].name);
                event.preventDefault();
              } else if (
                event.key === "ArrowUp" ||
                (event.key === "ArrowDown" &&
                  event.currentTarget.value.split("\n").length > 1)
              ) {
                (event.nativeEvent as any).preventDownshiftDefault = true;
              } else if (
                event.key === "ArrowUp" &&
                event.currentTarget.value.split("\n").length > 1
              ) {
                if (positionInHistory == 0) return;
                setInputValue(history[positionInHistory - 1]);
                setPositionInHistory((prev) => prev - 1);
              } else if (
                event.key === "ArrowDown" &&
                event.currentTarget.value.split("\n").length > 1
              ) {
                if (positionInHistory < history.length - 1) {
                  setInputValue(history[positionInHistory + 1]);
                }
                setPositionInHistory((prev) =>
                  Math.min(prev + 1, history.length)
                );
              }
            },
            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>
      <div className="px-2 flex gap-2 items-center flex-wrap">
        {highlightedCodeSections.length === 0 && (
          <HeaderButtonWithText
            text={
              props.addingHighlightedCode ? "Adding Context" : "Add Context"
            }
            onClick={() => {
              props.onToggleAddContext();
            }}
            inverted={props.addingHighlightedCode}
          >
            <Plus size="1.6em" />
          </HeaderButtonWithText>
        )}
        {highlightedCodeSections.length > 0 && (
          <>
            <HeaderButtonWithText
              text="Clear Context"
              onClick={() => {
                props.deleteContextItems(
                  highlightedCodeSections.map((_, idx) => idx)
                );
              }}
            >
              <Trash size="1.6em" />
            </HeaderButtonWithText>
            <HeaderButtonWithText
              text={pinned ? "Unpin Context" : "Pin Context"}
              inverted={pinned}
              onClick={() => {
                setPinned((prev) => !prev);
                props.onTogglePin();
              }}
            >
              {pinned ? (
                <LockClosed size="1.6em"></LockClosed>
              ) : (
                <LockOpen size="1.6em"></LockOpen>
              )}
            </HeaderButtonWithText>
          </>
        )}
        {highlightedCodeSections.map((section, idx) => (
          <PillButton
            title={`${section.filepath} (${section.range.start.line + 1}-${
              section.range.end.line + 1
            })`}
            onDelete={() => {
              if (props.deleteContextItems) {
                props.deleteContextItems([idx]);
              }
              setHighlightedCodeSections((prev) => {
                const newSections = [...prev];
                newSections.splice(idx, 1);
                return newSections;
              });
            }}
            onHover={(val: boolean) => {
              if (val) {
                setHoveringButton(val);
              } else {
                setTimeout(() => {
                  setHoveringButton(val);
                }, 100);
              }
            }}
          />
        ))}

        <span className="text-trueGray-400 ml-auto mr-4 text-xs text-right">
          Highlight code to include as context. Currently open file included by
          default. {highlightedCodeSections.length === 0 && ""}
        </span>
      </div>
      <ContextDropdown
        onMouseEnter={() => {
          setHoveringContextDropdown(true);
        }}
        onMouseLeave={() => {
          setHoveringContextDropdown(false);
        }}
        hidden={true || (!hoveringContextDropdown && !hoveringButton)}
      >
        {highlightedCodeSections.map((section, idx) => (
          <>
            <p>{section.filepath}</p>
            <CodeBlock showCopy={false} key={idx}>
              {section.contents}
            </CodeBlock>
          </>
        ))}
      </ContextDropdown>
    </>
  );
});

export default ComboBox;