1 import { XMarkMini } from "@medusajs/icons"
2 import { Badge, clx } from "@medusajs/ui"
3 import { AnimatePresence, motion } from "motion/react"
4 import {
5 FocusEvent,
6 KeyboardEvent,
7 forwardRef,
8 useImperativeHandle,
9 useRef,
10 useState,
11 } from "react"
12
13 type ChipInputProps = {
14 value?: string[]
15 onChange?: (value: string[]) => void
16 onBlur?: () => void
17 name?: string
18 disabled?: boolean
19 allowDuplicates?: boolean
20 showRemove?: boolean
21 variant?: "base" | "contrast"
22 placeholder?: string
23 className?: string
24 }
25
26 export const ChipInput = forwardRef<HTMLInputElement, ChipInputProps>(
27 (
28 {
29 value,
30 onChange,
31 onBlur,
32 disabled,
33 name,
34 showRemove = true,
35 variant = "base",
36 allowDuplicates = false,
37 placeholder,
38 className,
39 },
40 ref
41 ) => {
42 const innerRef = useRef<HTMLInputElement>(null)
43
44 const isControlledRef = useRef(typeof value !== "undefined")
45 const isControlled = isControlledRef.current
46
47 const [uncontrolledValue, setUncontrolledValue] = useState<string[]>([])
48
49 useImperativeHandle<HTMLInputElement | null, HTMLInputElement | null>(
50 ref,
51 () => innerRef.current
52 )
53
54 const [duplicateIndex, setDuplicateIndex] = useState<number | null>(null)
55
56 const chips = isControlled ? (value as string[]) : uncontrolledValue
57
58 const handleAddChip = (chip: string) => {
59 const cleanValue = chip.trim()
60
61 if (!cleanValue) {
62 return
63 }
64
65 if (!allowDuplicates && chips.includes(cleanValue)) {
66 setDuplicateIndex(chips.indexOf(cleanValue))
67
68 setTimeout(() => {
69 setDuplicateIndex(null)
70 }, 300)
71
72 return
73 }
74
75 onChange?.([...chips, cleanValue])
76
77 if (!isControlled) {
78 setUncontrolledValue([...chips, cleanValue])
79 }
80 }
81
82 const handleRemoveChip = (chip: string) => {
83 onChange?.(chips.filter((v) => v !== chip))
84
85 if (!isControlled) {
86 setUncontrolledValue(chips.filter((v) => v !== chip))
87 }
88 }
89
90 const handleBlur = (e: FocusEvent<HTMLInputElement>) => {
91 onBlur?.()
92
93 if (e.target.value) {
94 handleAddChip(e.target.value)
95 e.target.value = ""
96 }
97 }
98
99 const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
100 if (e.key === "Enter" || e.key === ",") {
101 e.preventDefault()
102
103 if (!innerRef.current?.value) {
104 return
105 }
106
107 handleAddChip(innerRef.current?.value ?? "")
108 innerRef.current.value = ""
109 innerRef.current?.focus()
110 }
111
112 if (e.key === "Backspace" && innerRef.current?.value === "") {
113 handleRemoveChip(chips[chips.length - 1])
114 }
115 }
116
117 // create a shake animation using framer motion
118 const shake = {
119 x: [0, -2, 2, -2, 2, 0],
120 transition: { duration: 0.3 },
121 }
122
123 return (
124 <div
125 className={clx(
126 "shadow-borders-base flex min-h-8 flex-wrap items-center gap-1 rounded-md px-2 py-1.5",
127 "transition-fg focus-within:shadow-borders-interactive-with-active",
128 "has-[input:disabled]:bg-ui-bg-disabled has-[input:disabled]:text-ui-fg-disabled has-[input:disabled]:cursor-not-allowed",
129 {
130 "bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover":
131 variant === "contrast",
132 "bg-ui-bg-field hover:bg-ui-bg-field-hover": variant === "base",
133 },
134 className
135 )}
136 tabIndex={-1}
137 onClick={() => innerRef.current?.focus()}
138 >
139 {chips.map((v, index) => {
140 return (
141 <AnimatePresence key={`${v}-${index}`}>
142 <Badge
143 size="2xsmall"
144 className={clx("gap-x-0.5 pl-1.5 pr-1.5 max-w-full min-w-0 overflow-hidden", {
145 "transition-fg pr-1": showRemove,
146 "shadow-borders-focus": index === duplicateIndex,
147 })}
148 asChild
149 >
150 <motion.div
151 animate={index === duplicateIndex ? shake : undefined}
152 >
153 <span className="truncate min-w-0">{v}</span>
154 {showRemove && (
155 <button
156 tabIndex={-1}
157 type="button"
158 onClick={() => handleRemoveChip(v)}
159 className={clx(
160 "text-ui-fg-subtle transition-fg outline-none shrink-0"
161 )}
162 >
163 <XMarkMini />
164 </button>
165 )}
166 </motion.div>
167 </Badge>
168 </AnimatePresence>
169 )
170 })}
171 <input
172 className={clx(
173 "caret-ui-fg-base text-ui-fg-base txt-compact-small flex-1 appearance-none bg-transparent",
174 "disabled:text-ui-fg-disabled disabled:cursor-not-allowed",
175 "focus:outline-none",
176 "placeholder:text-ui-fg-muted"
177 )}
178 onKeyDown={handleKeyDown}
179 onBlur={handleBlur}
180 disabled={disabled}
181 name={name}
182 ref={innerRef}
183 placeholder={chips.length === 0 ? placeholder : undefined}
184 autoComplete="off"
185 />
186 </div>
187 )
188 }
189 )
190
191 ChipInput.displayName = "ChipInput"