@brightlocal/ui-components 1.4.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,55 +53,13 @@ export interface InputListProps {
28
53
  */
29
54
  onValueChange: (value: string[]) => void;
30
55
  /**
31
- * Called before items are added to the list.
32
- * Return `true` to allow the addition, or a `string` to block it
33
- * and display that string as an error message.
34
- * The input value is preserved when addition is blocked.
35
- * @example
36
- * ```tsx
37
- * onBeforeAdd={(newItems, current) => {
38
- * const existing = new Set(current.map((k) => k.toLowerCase()));
39
- * const hasDupe = newItems.some((item) => existing.has(item.toLowerCase()));
40
- * return hasDupe ? "Keyword already added" : true;
41
- * }}
42
- * ```
43
- */
44
- onBeforeAdd?: (newItems: string[], currentValue: string[]) => true | string;
45
- /**
46
- * Placeholder text for the text input.
47
- * @default "Add item"
48
- */
49
- placeholder?: string;
50
- /**
51
- * Label for the add button.
52
- * @default "Add"
53
- */
54
- addButtonLabel?: string;
55
- /**
56
- * Number of skeleton rows to render in the loading state.
57
- * @default 3
58
- */
59
- skeletonCount?: number;
60
- /**
61
- * Fully disables the component — input and all remove buttons become non-interactive.
56
+ * Children — compose with InputListItems and InputListInput.
62
57
  */
63
- disabled?: boolean;
64
- /**
65
- * Shows skeleton placeholder rows instead of the item list.
66
- */
67
- loading?: boolean;
58
+ children: React.ReactNode;
68
59
  /**
69
- * Applies an error style to the input.
70
- */
71
- error?: boolean;
72
- /**
73
- * Optional validation message shown below the input when `error` is true.
74
- */
75
- errorMessage?: string;
76
- /**
77
- * Optional description text shown below the input.
60
+ * Additional CSS classes applied to the root element.
78
61
  */
79
- description?: string;
62
+ className?: string;
80
63
  /**
81
64
  * Data hook for automated testing (required).
82
65
  */
@@ -89,48 +72,31 @@ export interface InputListProps {
89
72
  * Tracking label for analytics context.
90
73
  */
91
74
  trackingLabel?: string;
92
- /**
93
- * Additional CSS classes applied to the root element.
94
- */
95
- className?: string;
96
75
  }
97
76
 
98
77
  /**
99
- * InputList block — a managed list of text items with an add-input and per-row remove controls.
100
- *
101
- * Supports multi-line paste (each line becomes a separate item), loading skeletons, disabled state,
102
- * 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.
103
80
  *
104
81
  * @example
105
82
  * ```tsx
106
- * <InputList
107
- * value={keywords}
108
- * onValueChange={setKeywords}
109
- * dataHook="keywords"
110
- * />
83
+ * <InputList value={keywords} onValueChange={setKeywords} dataHook="keywords">
84
+ * <InputListItems />
85
+ * <InputListInput placeholder="Add keyword" />
86
+ * </InputList>
111
87
  * ```
112
88
  */
113
89
  function InputList({
114
90
  value,
115
91
  onValueChange,
116
- onBeforeAdd,
117
- placeholder = "Add item",
118
- addButtonLabel = "Add",
119
- skeletonCount = 3,
120
- disabled = false,
121
- loading = false,
122
- error = false,
123
- errorMessage,
124
- description,
92
+ children,
93
+ className,
125
94
  dataHook,
126
95
  trackingEl,
127
96
  trackingLabel,
128
- className,
129
97
  }: InputListProps) {
130
98
  const [inputValue, setInputValue] = React.useState("");
131
- const [validationError, setValidationError] = React.useState<string | null>(
132
- null
133
- );
99
+ const prevValueLengthRef = React.useRef(value.length);
134
100
 
135
101
  // Stable keys so AnimatePresence can track items across additions/removals
136
102
  const nextIdRef = React.useRef(value.length);
@@ -138,10 +104,20 @@ function InputList({
138
104
  value.map((_, i) => i)
139
105
  );
140
106
 
141
- // Sync keys when value changes externally (not via addItems/removeItem).
142
- // Simple appends preserve existing keys; other changes (removal, reorder)
143
- // 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.
144
113
  React.useEffect(() => {
114
+ const prevLength = prevValueLengthRef.current;
115
+ prevValueLengthRef.current = value.length;
116
+
117
+ if (value.length > prevLength) {
118
+ setInputValue("");
119
+ }
120
+
145
121
  setStableKeys((prev) => {
146
122
  if (prev.length === value.length) return prev;
147
123
  if (value.length > prev.length) {
@@ -154,36 +130,28 @@ function InputList({
154
130
  ),
155
131
  ];
156
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
+ }
157
137
  // Removal or reorder: regenerate all keys
158
138
  return value.map(() => nextIdRef.current++);
159
139
  });
160
- }, [value]);
161
-
162
- const inputDisabled = disabled || loading;
163
- const buttonDisabled = disabled || loading;
140
+ }, [value, addAttempt]);
164
141
 
165
142
  const addItems = React.useCallback(
166
143
  (items: string[]) => {
167
144
  const toAdd = items.map((s) => s.trim()).filter(Boolean);
168
145
  if (!toAdd.length) return;
169
146
 
170
- if (onBeforeAdd) {
171
- const result = onBeforeAdd(toAdd, value);
172
- if (result !== true) {
173
- setValidationError(result);
174
- return;
175
- }
176
- }
177
-
178
- setValidationError(null);
179
147
  setStableKeys((prev) => [
180
148
  ...prev,
181
149
  ...toAdd.map(() => nextIdRef.current++),
182
150
  ]);
183
151
  onValueChange([...value, ...toAdd]);
184
- setInputValue("");
152
+ setAddAttempt((c) => c + 1);
185
153
  },
186
- [value, onValueChange, onBeforeAdd]
154
+ [value, onValueChange]
187
155
  );
188
156
 
189
157
  const removeItem = React.useCallback(
@@ -194,150 +162,290 @@ function InputList({
194
162
  [value, onValueChange]
195
163
  );
196
164
 
197
- const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
198
- if (e.key === "Enter") {
199
- e.preventDefault();
200
- addItems([inputValue]);
201
- }
202
- };
203
-
204
- const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
205
- const pasted = e.clipboardData.getData("text");
206
- const lines = pasted.split("\n");
207
- if (lines.length > 1) {
208
- e.preventDefault();
209
- addItems(lines);
210
- }
211
- };
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
+ );
212
176
 
213
177
  return (
214
- <div
215
- className={cn("flex flex-col gap-4", className)}
216
- data-hook={dataHook}
217
- data-slot="input-list"
218
- data-tracking-el={trackingEl}
219
- data-tracking-label={trackingLabel}
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}
187
+ </div>
188
+ </InputListContext.Provider>
189
+ );
190
+ }
191
+
192
+ InputList.displayName = "InputList";
193
+
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"
220
266
  >
221
- {/* Item list or loading skeleton */}
222
- {loading ? (
223
- <ul className="flex flex-col gap-2" data-slot="input-list-skeleton">
224
- {Array.from({ length: skeletonCount }).map((_, i) => (
225
- <Item key={i} variant="loading" />
226
- ))}
227
- </ul>
228
- ) : (
229
- <ul
230
- className="flex flex-col gap-2"
231
- data-hook={`${dataHook}-list`}
232
- data-slot="list"
233
- >
234
- <AnimatePresence initial={false}>
235
- {value.map((item, index) => (
236
- <motion.li
237
- key={stableKeys[index]}
238
- layout
239
- animate={{ opacity: 1, scale: 1 }}
240
- data-hook={`${dataHook}-item-${index}`}
241
- data-slot="item"
242
- exit={{
243
- opacity: 0,
244
- scale: 0.8,
245
- transition: {
246
- opacity: { duration: 0.15 },
247
- scale: { duration: 0.12 },
248
- },
249
- }}
250
- initial={{ opacity: 0, scale: 0.8 }}
251
- transition={{
252
- opacity: { duration: 0.15 },
253
- scale: { duration: 0.15 },
254
- layout: {
255
- type: "spring",
256
- stiffness: 500,
257
- damping: 35,
258
- },
259
- }}
260
- >
261
- <div className="bg-card flex items-center gap-4 rounded-lg py-2 pr-2 pl-4">
262
- <ItemContent>
263
- <ItemTitle>{item}</ItemTitle>
264
- </ItemContent>
265
- <ItemActions>
266
- <button
267
- aria-label={`Remove ${item}`}
268
- className={cn(
269
- "inline-flex size-9 cursor-pointer items-center justify-center rounded-full",
270
- "text-muted-foreground",
271
- "focus-visible:shadow-default outline-none",
272
- "transition-colors duration-150 ease-in-out",
273
- "disabled:pointer-events-none disabled:opacity-50"
274
- )}
275
- data-hook={`${dataHook}-remove-${index}`}
276
- disabled={disabled}
277
- type="button"
278
- onClick={() => removeItem(index)}
279
- >
280
- <X />
281
- </button>
282
- </ItemActions>
283
- </div>
284
- </motion.li>
285
- ))}
286
- </AnimatePresence>
287
- </ul>
288
- )}
289
-
290
- {/* Input row */}
291
- <div className="flex flex-col gap-2" data-slot="input-list-input-area">
292
- <div className="flex gap-2">
293
- <Input
294
- className="flex-1"
295
- dataHook={`${dataHook}-input`}
296
- disabled={inputDisabled}
297
- error={error || !!validationError}
298
- placeholder={placeholder}
299
- value={inputValue}
300
- onChange={(e) => {
301
- setInputValue(e.target.value);
302
- if (validationError) setValidationError(null);
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
+ },
303
291
  }}
304
- onKeyDown={handleKeyDown}
305
- onPaste={handlePaste}
306
- />
307
- <Button
308
- dataHook={`${dataHook}-add`}
309
- disabled={buttonDisabled}
310
- onClick={() => addItems([inputValue])}
311
- >
312
- {addButtonLabel}
313
- </Button>
314
- </div>
315
-
316
- {/* Error message replaces description */}
317
- {(error && errorMessage) || validationError ? (
318
- <FieldError
319
- className="text-left"
320
- data-slot="input-list-error"
321
- dataHook={`${dataHook}-error`}
322
292
  >
323
- {validationError ?? errorMessage}
324
- </FieldError>
325
- ) : (
326
- description && (
327
- <FieldDescription
328
- className="text-left"
329
- data-slot="input-list-description"
330
- dataHook={`${dataHook}-description`}
331
- >
332
- {description}
333
- </FieldDescription>
334
- )
335
- )}
336
- </div>
337
- </div>
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>
338
322
  );
339
323
  }
340
324
 
341
- InputList.displayName = "InputList";
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
+ * -----------------------------------------------------------------------------------------------*/
342
444
 
343
- export { InputList };
445
+ export {
446
+ InputList,
447
+ InputListItems,
448
+ InputListInput,
449
+ InputListAddButton,
450
+ useInputListContext,
451
+ };