@brightlocal/ui-components 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,18 +5,43 @@ import { motion, AnimatePresence } from "framer-motion";
5
5
  import { X } from "@brightlocal/icons";
6
6
 
7
7
  import { cn } from "@brightlocal/ui-components/lib/utils";
8
- import { Button } from "../components/button";
9
- import { FieldDescription, FieldError } from "../components/field";
8
+ import { Button, type ButtonProps } from "../components/button";
10
9
  import { Input } from "../components/input";
11
10
  import { Item, ItemContent, ItemTitle, ItemActions } from "../components/list";
12
11
 
13
12
  /* -------------------------------------------------------------------------------------------------
14
- * InputList
13
+ * InputList Context
14
+ * -----------------------------------------------------------------------------------------------*/
15
+
16
+ interface InputListContextValue {
17
+ value: string[];
18
+ inputValue: string;
19
+ setInputValue: (value: string) => void;
20
+ addItems: (items: string[]) => void;
21
+ removeItem: (index: number) => void;
22
+ /** Stable keys for AnimatePresence tracking */
23
+ stableKeys: number[];
24
+ }
25
+
26
+ const InputListContext = React.createContext<InputListContextValue | null>(
27
+ null
28
+ );
29
+
30
+ function useInputListContext() {
31
+ const context = React.useContext(InputListContext);
32
+ if (!context) {
33
+ throw new Error("InputList components must be used within an <InputList>");
34
+ }
35
+ return context;
36
+ }
37
+
38
+ /* -------------------------------------------------------------------------------------------------
39
+ * InputList (Context provider)
15
40
  * -----------------------------------------------------------------------------------------------*/
16
41
 
17
42
  /**
18
- * Props for the InputList block component.
19
- * Manages a list of text items with add-input, per-row remove controls, and validation states.
43
+ * Props for the InputList context provider.
44
+ * Manages a list of text items with add/remove logic and validation.
20
45
  */
21
46
  export interface InputListProps {
22
47
  /**
@@ -28,40 +53,13 @@ export interface InputListProps {
28
53
  */
29
54
  onValueChange: (value: string[]) => void;
30
55
  /**
31
- * Placeholder text for the text input.
32
- * @default "Add item"
33
- */
34
- placeholder?: string;
35
- /**
36
- * Label for the add button.
37
- * @default "Add"
38
- */
39
- addButtonLabel?: string;
40
- /**
41
- * Number of skeleton rows to render in the loading state.
42
- * @default 3
43
- */
44
- skeletonCount?: number;
45
- /**
46
- * Fully disables the component — input and all remove buttons become non-interactive.
47
- */
48
- disabled?: boolean;
49
- /**
50
- * Shows skeleton placeholder rows instead of the item list.
51
- */
52
- loading?: boolean;
53
- /**
54
- * Applies an error style to the input.
55
- */
56
- error?: boolean;
57
- /**
58
- * Optional validation message shown below the input when `error` is true.
56
+ * Children — compose with InputListItems and InputListInput.
59
57
  */
60
- errorMessage?: string;
58
+ children: React.ReactNode;
61
59
  /**
62
- * Optional description text shown below the input.
60
+ * Additional CSS classes applied to the root element.
63
61
  */
64
- description?: string;
62
+ className?: string;
65
63
  /**
66
64
  * Data hook for automated testing (required).
67
65
  */
@@ -74,44 +72,31 @@ export interface InputListProps {
74
72
  * Tracking label for analytics context.
75
73
  */
76
74
  trackingLabel?: string;
77
- /**
78
- * Additional CSS classes applied to the root element.
79
- */
80
- className?: string;
81
75
  }
82
76
 
83
77
  /**
84
- * InputList block — a managed list of text items with an add-input and per-row remove controls.
85
- *
86
- * Supports multi-line paste (each line becomes a separate item), loading skeletons, disabled state,
87
- * and input error/validation state.
78
+ * InputList context provider — manages state for a list of text items
79
+ * with add, remove, paste, and validation support.
88
80
  *
89
81
  * @example
90
82
  * ```tsx
91
- * <InputList
92
- * value={keywords}
93
- * onValueChange={setKeywords}
94
- * dataHook="keywords"
95
- * />
83
+ * <InputList value={keywords} onValueChange={setKeywords} dataHook="keywords">
84
+ * <InputListItems />
85
+ * <InputListInput placeholder="Add keyword" />
86
+ * </InputList>
96
87
  * ```
97
88
  */
98
89
  function InputList({
99
90
  value,
100
91
  onValueChange,
101
- placeholder = "Add item",
102
- addButtonLabel = "Add",
103
- skeletonCount = 3,
104
- disabled = false,
105
- loading = false,
106
- error = false,
107
- errorMessage,
108
- description,
92
+ children,
93
+ className,
109
94
  dataHook,
110
95
  trackingEl,
111
96
  trackingLabel,
112
- className,
113
97
  }: InputListProps) {
114
98
  const [inputValue, setInputValue] = React.useState("");
99
+ const prevValueLengthRef = React.useRef(value.length);
115
100
 
116
101
  // Stable keys so AnimatePresence can track items across additions/removals
117
102
  const nextIdRef = React.useRef(value.length);
@@ -119,10 +104,20 @@ function InputList({
119
104
  value.map((_, i) => i)
120
105
  );
121
106
 
122
- // Sync keys when value changes externally (not via addItems/removeItem).
123
- // Simple appends preserve existing keys; other changes (removal, reorder)
124
- // regenerate all keys to avoid incorrect exit animations.
107
+ // Counter that triggers key sync even when the consumer rejects an add
108
+ // (value stays the same but stableKeys grew eagerly).
109
+ const [addAttempt, setAddAttempt] = React.useState(0);
110
+
111
+ // Sync keys with value. Runs on value change OR rejected add (via addAttempt).
112
+ // Clear input only when the consumer actually accepted the addition.
125
113
  React.useEffect(() => {
114
+ const prevLength = prevValueLengthRef.current;
115
+ prevValueLengthRef.current = value.length;
116
+
117
+ if (value.length > prevLength) {
118
+ setInputValue("");
119
+ }
120
+
126
121
  setStableKeys((prev) => {
127
122
  if (prev.length === value.length) return prev;
128
123
  if (value.length > prev.length) {
@@ -135,24 +130,26 @@ function InputList({
135
130
  ),
136
131
  ];
137
132
  }
133
+ // Value didn't grow but keys did (rejected add) — trim back
134
+ if (value.length === prevLength) {
135
+ return prev.slice(0, value.length);
136
+ }
138
137
  // Removal or reorder: regenerate all keys
139
138
  return value.map(() => nextIdRef.current++);
140
139
  });
141
- }, [value]);
142
-
143
- const inputDisabled = disabled || loading;
144
- const buttonDisabled = disabled || loading;
140
+ }, [value, addAttempt]);
145
141
 
146
142
  const addItems = React.useCallback(
147
143
  (items: string[]) => {
148
144
  const toAdd = items.map((s) => s.trim()).filter(Boolean);
149
145
  if (!toAdd.length) return;
146
+
150
147
  setStableKeys((prev) => [
151
148
  ...prev,
152
149
  ...toAdd.map(() => nextIdRef.current++),
153
150
  ]);
154
151
  onValueChange([...value, ...toAdd]);
155
- setInputValue("");
152
+ setAddAttempt((c) => c + 1);
156
153
  },
157
154
  [value, onValueChange]
158
155
  );
@@ -165,147 +162,290 @@ function InputList({
165
162
  [value, onValueChange]
166
163
  );
167
164
 
168
- const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
169
- if (e.key === "Enter") {
170
- e.preventDefault();
171
- addItems([inputValue]);
172
- }
173
- };
174
-
175
- const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
176
- const pasted = e.clipboardData.getData("text");
177
- const lines = pasted.split("\n");
178
- if (lines.length > 1) {
179
- e.preventDefault();
180
- addItems(lines);
181
- }
182
- };
165
+ const contextValue = React.useMemo<InputListContextValue>(
166
+ () => ({
167
+ value,
168
+ inputValue,
169
+ setInputValue,
170
+ addItems,
171
+ removeItem,
172
+ stableKeys,
173
+ }),
174
+ [value, inputValue, addItems, removeItem, stableKeys]
175
+ );
183
176
 
184
177
  return (
185
- <div
186
- className={cn("flex flex-col gap-4", className)}
187
- data-hook={dataHook}
188
- data-slot="input-list"
189
- data-tracking-el={trackingEl}
190
- data-tracking-label={trackingLabel}
191
- >
192
- {/* Item list or loading skeleton */}
193
- {loading ? (
194
- <ul className="flex flex-col gap-2" data-slot="input-list-skeleton">
195
- {Array.from({ length: skeletonCount }).map((_, i) => (
196
- <Item key={i} variant="loading" />
197
- ))}
198
- </ul>
199
- ) : (
200
- <ul
201
- className="flex flex-col gap-2"
202
- data-hook={`${dataHook}-list`}
203
- data-slot="list"
204
- >
205
- <AnimatePresence initial={false}>
206
- {value.map((item, index) => (
207
- <motion.li
208
- key={stableKeys[index]}
209
- layout
210
- animate={{ opacity: 1, scale: 1 }}
211
- data-hook={`${dataHook}-item-${index}`}
212
- data-slot="item"
213
- exit={{
214
- opacity: 0,
215
- scale: 0.8,
216
- transition: {
217
- opacity: { duration: 0.15 },
218
- scale: { duration: 0.12 },
219
- },
220
- }}
221
- initial={{ opacity: 0, scale: 0.8 }}
222
- transition={{
223
- opacity: { duration: 0.15 },
224
- scale: { duration: 0.15 },
225
- layout: {
226
- type: "spring",
227
- stiffness: 500,
228
- damping: 35,
229
- },
230
- }}
231
- >
232
- <div className="bg-card flex items-center gap-4 rounded-lg py-2 pr-2 pl-4">
233
- <ItemContent>
234
- <ItemTitle>{item}</ItemTitle>
235
- </ItemContent>
236
- <ItemActions>
237
- <button
238
- aria-label={`Remove ${item}`}
239
- className={cn(
240
- "inline-flex size-9 cursor-pointer items-center justify-center rounded-full",
241
- "text-muted-foreground",
242
- "focus-visible:shadow-default outline-none",
243
- "transition-colors duration-150 ease-in-out",
244
- "disabled:pointer-events-none disabled:opacity-50"
245
- )}
246
- data-hook={`${dataHook}-remove-${index}`}
247
- disabled={disabled}
248
- type="button"
249
- onClick={() => removeItem(index)}
250
- >
251
- <X />
252
- </button>
253
- </ItemActions>
254
- </div>
255
- </motion.li>
256
- ))}
257
- </AnimatePresence>
258
- </ul>
259
- )}
260
-
261
- {/* Input row */}
262
- <div className="flex flex-col gap-2" data-slot="input-list-input-area">
263
- <div className="flex gap-2">
264
- <Input
265
- className="flex-1"
266
- dataHook={`${dataHook}-input`}
267
- disabled={inputDisabled}
268
- error={error}
269
- placeholder={placeholder}
270
- value={inputValue}
271
- onChange={(e) => setInputValue(e.target.value)}
272
- onKeyDown={handleKeyDown}
273
- onPaste={handlePaste}
274
- />
275
- <Button
276
- dataHook={`${dataHook}-add`}
277
- disabled={buttonDisabled}
278
- onClick={() => addItems([inputValue])}
279
- >
280
- {addButtonLabel}
281
- </Button>
282
- </div>
283
-
284
- {/* Error message replaces description */}
285
- {error && errorMessage ? (
286
- <FieldError
287
- className="text-left"
288
- data-slot="input-list-error"
289
- dataHook={`${dataHook}-error`}
290
- >
291
- {errorMessage}
292
- </FieldError>
293
- ) : (
294
- description && (
295
- <FieldDescription
296
- className="text-left"
297
- data-slot="input-list-description"
298
- dataHook={`${dataHook}-description`}
299
- >
300
- {description}
301
- </FieldDescription>
302
- )
303
- )}
178
+ <InputListContext.Provider value={contextValue}>
179
+ <div
180
+ className={cn("flex flex-col gap-4", className)}
181
+ data-hook={dataHook}
182
+ data-slot="input-list"
183
+ data-tracking-el={trackingEl}
184
+ data-tracking-label={trackingLabel}
185
+ >
186
+ {children}
304
187
  </div>
305
- </div>
188
+ </InputListContext.Provider>
306
189
  );
307
190
  }
308
191
 
309
192
  InputList.displayName = "InputList";
310
193
 
311
- export { InputList };
194
+ /* -------------------------------------------------------------------------------------------------
195
+ * InputListItems (Renders item list or loading skeletons)
196
+ * -----------------------------------------------------------------------------------------------*/
197
+
198
+ /**
199
+ * Props for the InputListItems sub-component.
200
+ */
201
+ export interface InputListItemsProps {
202
+ /**
203
+ * Data hook prefix for item elements.
204
+ * @default "input-list"
205
+ */
206
+ dataHook?: string;
207
+ /**
208
+ * Shows skeleton placeholder rows instead of the item list.
209
+ */
210
+ loading?: boolean;
211
+ /**
212
+ * Number of skeleton rows to render in the loading state.
213
+ * @default 5
214
+ */
215
+ skeletonCount?: number;
216
+
217
+ /**
218
+ * Disables all remove buttons in the list.
219
+ */
220
+ disabled?: boolean;
221
+ /**
222
+ * Additional CSS classes applied to the list element.
223
+ */
224
+ className?: string;
225
+ }
226
+
227
+ /**
228
+ * Renders the animated item list or loading skeletons.
229
+ * Must be used within an `<InputList>` component.
230
+ *
231
+ * @example
232
+ * ```tsx
233
+ * <InputList value={items} onValueChange={setItems} dataHook="my-list">
234
+ * <InputListItems skeletonCount={5} />
235
+ * <InputListInput placeholder="Add item" />
236
+ * </InputList>
237
+ * ```
238
+ */
239
+ function InputListItems({
240
+ dataHook = "input-list",
241
+ loading = false,
242
+ skeletonCount = 5,
243
+ disabled = false,
244
+ className,
245
+ }: InputListItemsProps) {
246
+ const { value, removeItem, stableKeys } = useInputListContext();
247
+
248
+ if (loading) {
249
+ return (
250
+ <ul
251
+ className={cn("flex flex-col gap-2", className)}
252
+ data-slot="input-list-skeleton"
253
+ >
254
+ {Array.from({ length: skeletonCount }).map((_, i) => (
255
+ <Item key={i} variant="loading" />
256
+ ))}
257
+ </ul>
258
+ );
259
+ }
260
+
261
+ return (
262
+ <ul
263
+ className={cn("flex flex-col gap-2", className)}
264
+ data-hook={`${dataHook}-list`}
265
+ data-slot="list"
266
+ >
267
+ <AnimatePresence initial={false}>
268
+ {value.map((item, index) => (
269
+ <motion.li
270
+ key={stableKeys[index]}
271
+ layout
272
+ animate={{ opacity: 1, scale: 1 }}
273
+ data-hook={`${dataHook}-item-${index}`}
274
+ exit={{
275
+ opacity: 0,
276
+ scale: 0.8,
277
+ transition: {
278
+ opacity: { duration: 0.15 },
279
+ scale: { duration: 0.12 },
280
+ },
281
+ }}
282
+ initial={{ opacity: 0, scale: 0.8 }}
283
+ transition={{
284
+ opacity: { duration: 0.15 },
285
+ scale: { duration: 0.15 },
286
+ layout: {
287
+ type: "spring",
288
+ stiffness: 500,
289
+ damping: 35,
290
+ },
291
+ }}
292
+ >
293
+ <Item asChild variant="filled">
294
+ <div>
295
+ <ItemContent>
296
+ <ItemTitle>{item}</ItemTitle>
297
+ </ItemContent>
298
+ <ItemActions>
299
+ <button
300
+ aria-label={`Remove ${item}`}
301
+ className={cn(
302
+ "inline-flex size-9 cursor-pointer items-center justify-center rounded-full",
303
+ "text-muted-foreground",
304
+ "focus-visible:shadow-default outline-none",
305
+ "transition-colors duration-150 ease-in-out",
306
+ "disabled:pointer-events-none disabled:opacity-50"
307
+ )}
308
+ data-hook={`${dataHook}-remove-${index}`}
309
+ disabled={disabled}
310
+ type="button"
311
+ onClick={() => removeItem(index)}
312
+ >
313
+ <X />
314
+ </button>
315
+ </ItemActions>
316
+ </div>
317
+ </Item>
318
+ </motion.li>
319
+ ))}
320
+ </AnimatePresence>
321
+ </ul>
322
+ );
323
+ }
324
+
325
+ InputListItems.displayName = "InputListItems";
326
+
327
+ /* -------------------------------------------------------------------------------------------------
328
+ * InputListInput (Input field + Add button + messages)
329
+ * -----------------------------------------------------------------------------------------------*/
330
+
331
+ /**
332
+ * Props for the InputListInput sub-component.
333
+ *
334
+ * Inherits native input props except `value` and `type` (managed by InputList context).
335
+ * `onChange` fires as a notification only — the input value is controlled by context,
336
+ * so it cannot be used to filter or transform input.
337
+ */
338
+ export interface InputListInputProps extends Omit<
339
+ React.ComponentPropsWithoutRef<"input">,
340
+ "value" | "type"
341
+ > {
342
+ /**
343
+ * Data hook for the input element.
344
+ */
345
+ dataHook: string;
346
+ /**
347
+ * Applies an error style to the input.
348
+ */
349
+ error?: boolean;
350
+ }
351
+
352
+ /**
353
+ * Text input that adds items on Enter and supports multi-line paste.
354
+ * Must be used within an `<InputList>` component.
355
+ *
356
+ * @example
357
+ * ```tsx
358
+ * <InputListInput dataHook="keywords-input" placeholder="Add keyword" />
359
+ * ```
360
+ */
361
+ const InputListInput = React.forwardRef<HTMLInputElement, InputListInputProps>(
362
+ ({ dataHook, error = false, className, ...props }, ref) => {
363
+ const { inputValue, setInputValue, addItems } = useInputListContext();
364
+
365
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
366
+ if (e.key === "Enter") {
367
+ e.preventDefault();
368
+ addItems([inputValue]);
369
+ }
370
+ props.onKeyDown?.(e);
371
+ };
372
+
373
+ const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
374
+ const pasted = e.clipboardData.getData("text");
375
+ const lines = pasted.split("\n");
376
+ if (lines.length > 1) {
377
+ e.preventDefault();
378
+ addItems(lines);
379
+ }
380
+ props.onPaste?.(e);
381
+ };
382
+
383
+ return (
384
+ <Input
385
+ ref={ref}
386
+ {...props}
387
+ className={cn("flex-1", className)}
388
+ dataHook={dataHook}
389
+ error={error}
390
+ value={inputValue}
391
+ onChange={(e) => {
392
+ setInputValue(e.target.value);
393
+ props.onChange?.(e);
394
+ }}
395
+ onKeyDown={handleKeyDown}
396
+ onPaste={handlePaste}
397
+ />
398
+ );
399
+ }
400
+ );
401
+ InputListInput.displayName = "InputListInput";
402
+
403
+ /* -------------------------------------------------------------------------------------------------
404
+ * InputListAddButton (Add button)
405
+ * -----------------------------------------------------------------------------------------------*/
406
+
407
+ /**
408
+ * Props for the InputListAddButton sub-component.
409
+ * Inherits all Button props except `onClick` (wired internally to add items).
410
+ */
411
+ export type InputListAddButtonProps = Omit<ButtonProps, "onClick">;
412
+
413
+ /**
414
+ * Button that adds the current input value to the list.
415
+ * Must be used within an `<InputList>` component.
416
+ *
417
+ * @example
418
+ * ```tsx
419
+ * <InputListAddButton dataHook="keywords-add">Add</InputListAddButton>
420
+ * ```
421
+ */
422
+ const InputListAddButton = React.forwardRef<
423
+ HTMLButtonElement,
424
+ InputListAddButtonProps
425
+ >(({ dataHook, children, ...props }, ref) => {
426
+ const { inputValue, addItems } = useInputListContext();
427
+
428
+ return (
429
+ <Button
430
+ ref={ref}
431
+ {...props}
432
+ dataHook={dataHook}
433
+ onClick={() => addItems([inputValue])}
434
+ >
435
+ {children}
436
+ </Button>
437
+ );
438
+ });
439
+ InputListAddButton.displayName = "InputListAddButton";
440
+
441
+ /* -------------------------------------------------------------------------------------------------
442
+ * Exports
443
+ * -----------------------------------------------------------------------------------------------*/
444
+
445
+ export {
446
+ InputList,
447
+ InputListItems,
448
+ InputListInput,
449
+ InputListAddButton,
450
+ useInputListContext,
451
+ };