File size: 1,550 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import type { Dispatch, SetStateAction } from "react";
import { forwardRef, useCallback, useEffect, useState } from "react";

import type { InputProps } from "./input";
import { Input } from "./input";

type BadgeInputProps = Omit<InputProps, "value" | "onChange"> & {
  value: string[];
  onChange: (value: string[]) => void;
  setPendingKeyword?: Dispatch<SetStateAction<string>>;
};

export const BadgeInput = forwardRef<HTMLInputElement, BadgeInputProps>(
  ({ value, onChange, setPendingKeyword, ...props }, ref) => {
    const [label, setLabel] = useState("");

    const processInput = useCallback(() => {
      const newLabels = label
        .split(",")
        .map((str) => str.trim())
        .filter(Boolean)
        .filter((str) => !value.includes(str));
      onChange([...new Set([...value, ...newLabels])]);
      setLabel("");
    }, [label, value, onChange]);

    useEffect(() => {
      if (label.includes(",")) {
        processInput();
      }
    }, [label, processInput]);

    useEffect(() => {
      if (setPendingKeyword) setPendingKeyword(label);
    }, [label, setPendingKeyword]);

    const onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
      if (event.key === "Enter") {
        event.preventDefault();
        event.stopPropagation();

        processInput();
      }
    };

    return (
      <Input
        {...props}
        ref={ref}
        value={label}
        onKeyDown={onKeyDown}
        onChange={(event) => {
          setLabel(event.target.value);
        }}
      />
    );
  },
);