|
| 1 | +import Chip from "@material-ui/core/Chip" |
| 2 | +import { makeStyles } from "@material-ui/core/styles" |
| 3 | +import { FC } from "react" |
| 4 | + |
| 5 | +export type MultiTextFieldProps = { |
| 6 | + label: string |
| 7 | + values: string[] |
| 8 | + onChange: (values: string[]) => void |
| 9 | +} |
| 10 | + |
| 11 | +export const MultiTextField: FC<MultiTextFieldProps> = ({ |
| 12 | + label, |
| 13 | + values, |
| 14 | + onChange, |
| 15 | +}) => { |
| 16 | + const styles = useStyles() |
| 17 | + |
| 18 | + return ( |
| 19 | + <label className={styles.root}> |
| 20 | + {values.map((value, index) => ( |
| 21 | + <Chip |
| 22 | + key={index} |
| 23 | + label={value} |
| 24 | + size="small" |
| 25 | + onDelete={() => { |
| 26 | + onChange(values.filter((oldValue) => oldValue !== value)) |
| 27 | + }} |
| 28 | + /> |
| 29 | + ))} |
| 30 | + <input |
| 31 | + aria-label={label} |
| 32 | + className={styles.input} |
| 33 | + onKeyDown={(event) => { |
| 34 | + if (event.key === ",") { |
| 35 | + event.preventDefault() |
| 36 | + const newValue = event.currentTarget.value |
| 37 | + onChange([...values, newValue]) |
| 38 | + event.currentTarget.value = "" |
| 39 | + return |
| 40 | + } |
| 41 | + |
| 42 | + if (event.key === "Backspace" && event.currentTarget.value === "") { |
| 43 | + event.preventDefault() |
| 44 | + const lastValue = values[values.length - 1] |
| 45 | + onChange(values.slice(0, -1)) |
| 46 | + event.currentTarget.value = lastValue |
| 47 | + return |
| 48 | + } |
| 49 | + }} |
| 50 | + onBlur={(event) => { |
| 51 | + if (event.currentTarget.value !== "") { |
| 52 | + const newValue = event.currentTarget.value |
| 53 | + onChange([...values, newValue]) |
| 54 | + event.currentTarget.value = "" |
| 55 | + } |
| 56 | + }} |
| 57 | + /> |
| 58 | + </label> |
| 59 | + ) |
| 60 | +} |
| 61 | + |
| 62 | +const useStyles = makeStyles((theme) => ({ |
| 63 | + root: { |
| 64 | + border: `1px solid ${theme.palette.divider}`, |
| 65 | + borderRadius: theme.shape.borderRadius, |
| 66 | + minHeight: theme.spacing(5), |
| 67 | + padding: theme.spacing(1.25, 1.75), |
| 68 | + fontSize: theme.spacing(2), |
| 69 | + display: "flex", |
| 70 | + flexWrap: "wrap", |
| 71 | + gap: theme.spacing(1), |
| 72 | + position: "relative", |
| 73 | + margin: theme.spacing(1, 0, 0.5), // Have same margin than TextField |
| 74 | + |
| 75 | + "&:has(input:focus)": { |
| 76 | + borderColor: theme.palette.primary.main, |
| 77 | + borderWidth: 2, |
| 78 | + // Compensate for the border width |
| 79 | + top: -1, |
| 80 | + left: -1, |
| 81 | + }, |
| 82 | + }, |
| 83 | + |
| 84 | + input: { |
| 85 | + flexGrow: 1, |
| 86 | + fontSize: "inherit", |
| 87 | + padding: 0, |
| 88 | + border: "none", |
| 89 | + background: "none", |
| 90 | + |
| 91 | + "&:focus": { |
| 92 | + outline: "none", |
| 93 | + }, |
| 94 | + }, |
| 95 | +})) |
0 commit comments