1"use client";
2
3import { PlusIcon, XIcon } from "lucide-react";
4import { Slot as SlotPrimitive } from "radix-ui";
5import * as React from "react";
6import { useComposedRefs } from "@/lib/compose-refs";
7import { cn } from "@/lib/utils";
8import { VisuallyHiddenInput } from "@/registry/bases/radix/components/visually-hidden-input";
9import { useAsRef } from "@/registry/bases/radix/hooks/use-as-ref";
10import { useIsomorphicLayoutEffect } from "@/registry/bases/radix/hooks/use-isomorphic-layout-effect";
11import { useLazyRef } from "@/registry/bases/radix/hooks/use-lazy-ref";
12import { Button } from "@/registry/bases/radix/ui/button";
13import { Input } from "@/registry/bases/radix/ui/input";
14import { Textarea } from "@/registry/bases/radix/ui/textarea";
15
16const ROOT_NAME = "KeyValue";
17const LIST_NAME = "KeyValueList";
18const ITEM_NAME = "KeyValueItem";
19const KEY_INPUT_NAME = "KeyValueKeyInput";
20const VALUE_INPUT_NAME = "KeyValueValueInput";
21const REMOVE_NAME = "KeyValueRemove";
22const ADD_NAME = "KeyValueAdd";
23const ERROR_NAME = "KeyValueError";
24
25type Orientation = "vertical" | "horizontal";
26type Field = "key" | "value";
27
28interface DivProps extends React.ComponentProps<"div"> {
29 asChild?: boolean;
30}
31
32type RootElement = React.ComponentRef<typeof KeyValue>;
33type KeyInputElement = React.ComponentRef<typeof KeyValueKeyInput>;
34type RemoveElement = React.ComponentRef<typeof KeyValueRemove>;
35type AddElement = React.ComponentRef<typeof KeyValueAdd>;
36
37function getErrorId(rootId: string, itemId: string, field: Field) {
38 return `${rootId}-${itemId}-${field}-error`;
39}
40
41function removeQuotes(string: string, shouldStrip: boolean): string {
42 if (!shouldStrip) return string;
43
44 const trimmed = string.trim();
45 if (
46 (trimmed.startsWith('"') && trimmed.endsWith('"')) ||
47 (trimmed.startsWith("'") && trimmed.endsWith("'"))
48 ) {
49 return trimmed.slice(1, -1);
50 }
51 return trimmed;
52}
53
54interface Store {
55 subscribe: (callback: () => void) => () => void;
56 getState: () => KeyValueState;
57 setState: <K extends keyof KeyValueState>(
58 key: K,
59 value: KeyValueState[K],
60 ) => void;
61 notify: () => void;
62}
63
64function useStore<T>(
65 selector: (state: KeyValueState) => T,
66 ogStore?: Store | null,
67): T {
68 const contextStore = React.useContext(StoreContext);
69
70 const store = ogStore ?? contextStore;
71
72 if (!store) {
73 throw new Error(`\`useStore\` must be used within \`${ROOT_NAME}\``);
74 }
75
76 const getSnapshot = React.useCallback(
77 () => selector(store.getState()),
78 [store, selector],
79 );
80
81 return React.useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
82}
83
84interface ItemData {
85 id: string;
86 key: string;
87 value: string;
88}
89
90interface KeyValueState {
91 value: ItemData[];
92 focusedId: string | null;
93 errors: Record<string, { key?: string; value?: string }>;
94}
95
96const StoreContext = React.createContext<Store | null>(null);
97
98function useStoreContext(consumerName: string) {
99 const context = React.useContext(StoreContext);
100 if (!context) {
101 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
102 }
103 return context;
104}
105
106interface KeyValueContextValue {
107 onPaste?: (event: ClipboardEvent, items: ItemData[]) => void;
108 onAdd?: (value: ItemData) => void;
109 onRemove?: (value: ItemData) => void;
110 onKeyValidate?: (key: string, value: ItemData[]) => string | undefined;
111 onValueValidate?: (
112 value: string,
113 key: string,
114 items: ItemData[],
115 ) => string | undefined;
116 rootId: string;
117 maxItems?: number;
118 minItems: number;
119 keyPlaceholder: string;
120 valuePlaceholder: string;
121 allowDuplicateKeys: boolean;
122 enablePaste: boolean;
123 trim: boolean;
124 stripQuotes: boolean;
125 disabled: boolean;
126 readOnly: boolean;
127 required: boolean;
128}
129
130const KeyValueContext = React.createContext<KeyValueContextValue | null>(null);
131
132function useKeyValueContext(consumerName: string) {
133 const context = React.useContext(KeyValueContext);
134 if (!context) {
135 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
136 }
137 return context;
138}
139
140interface KeyValueProps extends Omit<DivProps, "onPaste" | "defaultValue"> {
141 id?: string;
142 defaultValue?: ItemData[];
143 value?: ItemData[];
144 onValueChange?: (value: ItemData[]) => void;
145 maxItems?: number;
146 minItems?: number;
147 keyPlaceholder?: string;
148 valuePlaceholder?: string;
149 name?: string;
150 allowDuplicateKeys?: boolean;
151 enablePaste?: boolean;
152 trim?: boolean;
153 stripQuotes?: boolean;
154 disabled?: boolean;
155 readOnly?: boolean;
156 required?: boolean;
157 onPaste?: (event: ClipboardEvent, items: ItemData[]) => void;
158 onAdd?: (value: ItemData) => void;
159 onRemove?: (value: ItemData) => void;
160 onKeyValidate?: (key: string, value: ItemData[]) => string | undefined;
161 onValueValidate?: (
162 value: string,
163 key: string,
164 items: ItemData[],
165 ) => string | undefined;
166}
167
168function KeyValue(props: KeyValueProps) {
169 const {
170 value: valueProp,
171 defaultValue,
172 onValueChange,
173 onPaste,
174 onAdd,
175 onRemove,
176 onKeyValidate,
177 onValueValidate,
178 maxItems,
179 minItems = 0,
180 keyPlaceholder = "Key",
181 valuePlaceholder = "Value",
182 allowDuplicateKeys = false,
183 asChild,
184 enablePaste = true,
185 trim = true,
186 stripQuotes = true,
187 disabled = false,
188 readOnly = false,
189 required = false,
190 className,
191 id,
192 name,
193 ref,
194 ...rootProps
195 } = props;
196
197 const instanceId = React.useId();
198 const rootId = id ?? instanceId;
199
200 const [formTrigger, setFormTrigger] = React.useState<RootElement | null>(
201 null,
202 );
203 const composedRef = useComposedRefs(ref, (node) => setFormTrigger(node));
204 const isFormControl = formTrigger ? !!formTrigger.closest("form") : true;
205
206 const listenersRef = useLazyRef(() => new Set<() => void>());
207 const stateRef = useLazyRef<KeyValueState>(() => ({
208 value: valueProp ??
209 defaultValue ?? [{ id: crypto.randomUUID(), key: "", value: "" }],
210 focusedId: null,
211 errors: {},
212 }));
213 const propsRef = useAsRef({ onValueChange });
214
215 const store = React.useMemo<Store>(() => {
216 return {
217 subscribe: (cb) => {
218 listenersRef.current.add(cb);
219 return () => listenersRef.current.delete(cb);
220 },
221 getState: () => stateRef.current,
222 setState: (key, val) => {
223 if (Object.is(stateRef.current[key], val)) return;
224
225 if (key === "value" && Array.isArray(val)) {
226 stateRef.current.value = val as ItemData[];
227 propsRef.current.onValueChange?.(val as ItemData[]);
228 } else {
229 stateRef.current[key] = val;
230 }
231
232 store.notify();
233 },
234 notify: () => {
235 for (const cb of listenersRef.current) {
236 cb();
237 }
238 },
239 };
240 }, [listenersRef, stateRef, propsRef]);
241
242 const value = useStore((state) => state.value, store);
243 const errors = useStore((state) => state.errors, store);
244 const isInvalid = Object.keys(errors).length > 0;
245
246 useIsomorphicLayoutEffect(() => {
247 if (valueProp !== undefined) {
248 store.setState("value", valueProp);
249 }
250 }, [valueProp]);
251
252 const contextValue = React.useMemo<KeyValueContextValue>(
253 () => ({
254 onPaste,
255 onAdd,
256 onRemove,
257 onKeyValidate,
258 onValueValidate,
259 rootId,
260 maxItems,
261 minItems,
262 keyPlaceholder,
263 valuePlaceholder,
264 allowDuplicateKeys,
265 enablePaste,
266 trim,
267 stripQuotes,
268 disabled,
269 readOnly,
270 required,
271 }),
272 [
273 onPaste,
274 onAdd,
275 onRemove,
276 onKeyValidate,
277 onValueValidate,
278 rootId,
279 disabled,
280 readOnly,
281 required,
282 maxItems,
283 minItems,
284 keyPlaceholder,
285 valuePlaceholder,
286 allowDuplicateKeys,
287 enablePaste,
288 trim,
289 stripQuotes,
290 ],
291 );
292
293 const RootPrimitive = asChild ? SlotPrimitive.Slot : "div";
294
295 return (
296 <StoreContext.Provider value={store}>
297 <KeyValueContext.Provider value={contextValue}>
298 <RootPrimitive
299 id={id}
300 data-slot="key-value"
301 data-disabled={disabled ? "" : undefined}
302 data-invalid={isInvalid ? "" : undefined}
303 data-readonly={readOnly ? "" : undefined}
304 {...rootProps}
305 ref={composedRef}
306 className={cn("flex flex-col gap-2", className)}
307 />
308 {isFormControl && (
309 <VisuallyHiddenInput
310 type="hidden"
311 control={formTrigger}
312 name={name}
313 value={value}
314 disabled={disabled}
315 readOnly={readOnly}
316 required={required}
317 />
318 )}
319 </KeyValueContext.Provider>
320 </StoreContext.Provider>
321 );
322}
323
324interface KeyValueListProps extends DivProps {
325 orientation?: Orientation;
326}
327
328function KeyValueList(props: KeyValueListProps) {
329 const { orientation = "vertical", asChild, className, ...listProps } = props;
330
331 const value = useStore((state) => state.value);
332
333 const ListPrimitive = asChild ? SlotPrimitive.Slot : "div";
334
335 return (
336 <ListPrimitive
337 role="list"
338 aria-orientation={orientation}
339 data-slot="key-value-list"
340 data-orientation={orientation}
341 {...listProps}
342 className={cn(
343 "flex",
344 orientation === "vertical" ? "flex-col gap-2" : "flex-row gap-2",
345 className,
346 )}
347 >
348 {value.map((item) => {
349 const children = React.Children.toArray(props.children);
350
351 return (
352 <KeyValueItemContext.Provider key={item.id} value={item}>
353 {children}
354 </KeyValueItemContext.Provider>
355 );
356 })}
357 </ListPrimitive>
358 );
359}
360
361const KeyValueItemContext = React.createContext<ItemData | null>(null);
362
363function useKeyValueItemContext(consumerName: string) {
364 const context = React.useContext(KeyValueItemContext);
365 if (!context) {
366 throw new Error(`\`${consumerName}\` must be used within \`${LIST_NAME}\``);
367 }
368 return context;
369}
370
371interface KeyValueItemProps extends React.ComponentProps<"div"> {
372 asChild?: boolean;
373}
374
375function KeyValueItem(props: KeyValueItemProps) {
376 const { asChild, className, ...itemProps } = props;
377 const itemData = useKeyValueItemContext(ITEM_NAME);
378
379 const focusedId = useStore((state) => state.focusedId);
380
381 const ItemPrimitive = asChild ? SlotPrimitive.Slot : "div";
382
383 return (
384 <ItemPrimitive
385 role="listitem"
386 data-slot="key-value-item"
387 data-highlighted={focusedId === itemData.id ? "" : undefined}
388 {...itemProps}
389 className={cn("flex items-start gap-2", className)}
390 />
391 );
392}
393
394interface KeyValueKeyInputProps extends React.ComponentProps<"input"> {
395 asChild?: boolean;
396}
397
398function KeyValueKeyInput(props: KeyValueKeyInputProps) {
399 const {
400 onChange: onChangeProp,
401 onPaste: onPasteProp,
402 asChild,
403 disabled,
404 readOnly,
405 required,
406 ...keyInputProps
407 } = props;
408
409 const context = useKeyValueContext(KEY_INPUT_NAME);
410 const itemData = useKeyValueItemContext(KEY_INPUT_NAME);
411 const store = useStoreContext(KEY_INPUT_NAME);
412 const errors = useStore((state) => state.errors);
413
414 const propsRef = useAsRef({
415 onChange: onChangeProp,
416 onPaste: onPasteProp,
417 });
418
419 const isDisabled = disabled || context.disabled;
420 const isReadOnly = readOnly || context.readOnly;
421 const isRequired = required || context.required;
422 const isInvalid = errors[itemData.id]?.key !== undefined;
423
424 const onChange = React.useCallback(
425 (event: React.ChangeEvent<KeyInputElement>) => {
426 const state = store.getState();
427 const newValue = state.value.map((item) => {
428 if (item.id !== itemData.id) return item;
429 const updated = { ...item, key: event.target.value };
430 if (context.trim) updated.key = updated.key.trim();
431 return updated;
432 });
433
434 store.setState("value", newValue);
435
436 const updatedItemData = newValue.find((item) => item.id === itemData.id);
437 if (updatedItemData) {
438 const errors: { key?: string; value?: string } = {};
439
440 if (context.onKeyValidate) {
441 const keyError = context.onKeyValidate(updatedItemData.key, newValue);
442 if (keyError) errors.key = keyError;
443 }
444
445 if (!context.allowDuplicateKeys) {
446 const duplicateKey = newValue.find(
447 (item) =>
448 item.id !== updatedItemData.id &&
449 item.key === updatedItemData.key &&
450 updatedItemData.key !== "",
451 );
452 if (duplicateKey) {
453 errors.key = "Duplicate key";
454 }
455 }
456
457 if (context.onValueValidate) {
458 const valueError = context.onValueValidate(
459 updatedItemData.value,
460 updatedItemData.key,
461 newValue,
462 );
463 if (valueError) errors.value = valueError;
464 }
465
466 const newErrorsState = { ...state.errors };
467 if (Object.keys(errors).length > 0) {
468 newErrorsState[itemData.id] = errors;
469 } else {
470 delete newErrorsState[itemData.id];
471 }
472 store.setState("errors", newErrorsState);
473 }
474
475 propsRef.current.onChange?.(event);
476 },
477 [store, itemData.id, context, propsRef],
478 );
479
480 const onPaste = React.useCallback(
481 (event: React.ClipboardEvent<KeyInputElement>) => {
482 if (!context.enablePaste) return;
483
484 propsRef.current.onPaste?.(event);
485 if (event.defaultPrevented) return;
486
487 const content = event.clipboardData.getData("text");
488 const lines = content.split(/\r?\n/).filter((line) => line.trim());
489
490 if (lines.length > 1) {
491 event.preventDefault();
492
493 const parsed: ItemData[] = [];
494
495 for (const line of lines) {
496 let key = "";
497 let value = "";
498
499 if (line.includes("=")) {
500 const parts = line.split("=");
501 key = parts[0]?.trim() ?? "";
502 value = removeQuotes(
503 parts.slice(1).join("=").trim(),
504 context.stripQuotes,
505 );
506 } else if (line.includes(":")) {
507 const parts = line.split(":");
508 key = parts[0]?.trim() ?? "";
509 value = removeQuotes(
510 parts.slice(1).join(":").trim(),
511 context.stripQuotes,
512 );
513 } else if (/\s{2,}|\t/.test(line)) {
514 const parts = line.split(/\s{2,}|\t/);
515 key = parts[0]?.trim() ?? "";
516 value = removeQuotes(
517 parts.slice(1).join(" ").trim(),
518 context.stripQuotes,
519 );
520 }
521
522 if (key) {
523 parsed.push({ id: crypto.randomUUID(), key, value });
524 }
525 }
526
527 if (parsed.length > 0) {
528 const state = store.getState();
529 const currentIndex = state.value.findIndex(
530 (item) => item.id === itemData.id,
531 );
532
533 let newValue: ItemData[];
534 if (itemData.key === "" && itemData.value === "") {
535 newValue = [
536 ...state.value.slice(0, currentIndex),
537 ...parsed,
538 ...state.value.slice(currentIndex + 1),
539 ];
540 } else {
541 newValue = [
542 ...state.value.slice(0, currentIndex + 1),
543 ...parsed,
544 ...state.value.slice(currentIndex + 1),
545 ];
546 }
547
548 if (context.maxItems !== undefined) {
549 newValue = newValue.slice(0, context.maxItems);
550 }
551
552 store.setState("value", newValue);
553
554 if (context.onPaste) {
555 context.onPaste(
556 event.nativeEvent as unknown as ClipboardEvent,
557 parsed,
558 );
559 }
560 }
561 }
562 },
563 [context, store, itemData, propsRef],
564 );
565
566 const KeyInputPrimitive = asChild ? SlotPrimitive.Slot : Input;
567
568 return (
569 <KeyInputPrimitive
570 aria-invalid={isInvalid}
571 aria-describedby={
572 isInvalid ? getErrorId(context.rootId, itemData.id, "key") : undefined
573 }
574 data-slot="key-value-key-input"
575 autoCapitalize="off"
576 autoComplete="off"
577 autoCorrect="off"
578 spellCheck="false"
579 disabled={isDisabled}
580 readOnly={isReadOnly}
581 required={isRequired}
582 placeholder={context.keyPlaceholder}
583 {...keyInputProps}
584 value={itemData.key}
585 onChange={onChange}
586 onPaste={onPaste}
587 />
588 );
589}
590
591interface KeyValueValueInputProps
592 extends Omit<React.ComponentProps<"textarea">, "rows"> {
593 maxRows?: number;
594 asChild?: boolean;
595}
596
597function KeyValueValueInput(props: KeyValueValueInputProps) {
598 const {
599 onChange: onChangeProp,
600 asChild,
601 disabled,
602 readOnly,
603 required,
604 className,
605 maxRows,
606 style,
607 ...valueInputProps
608 } = props;
609
610 const context = useKeyValueContext(VALUE_INPUT_NAME);
611 const itemData = useKeyValueItemContext(VALUE_INPUT_NAME);
612 const store = useStoreContext(VALUE_INPUT_NAME);
613 const errors = useStore((state) => state.errors);
614
615 const propsRef = useAsRef({
616 onChange: onChangeProp,
617 });
618
619 const isDisabled = disabled || context.disabled;
620 const isReadOnly = readOnly || context.readOnly;
621 const isRequired = required || context.required;
622 const isInvalid = errors[itemData.id]?.value !== undefined;
623 const maxHeight = maxRows ? `calc(${maxRows} * 1.5em + 1rem)` : undefined;
624
625 const onChange = React.useCallback(
626 (event: React.ChangeEvent<HTMLTextAreaElement>) => {
627 propsRef.current.onChange?.(event);
628
629 const state = store.getState();
630 const newValue = state.value.map((item) => {
631 if (item.id !== itemData.id) return item;
632 const updated = { ...item, value: event.target.value };
633 if (context.trim) updated.value = updated.value.trim();
634 return updated;
635 });
636
637 store.setState("value", newValue);
638
639 const updatedItemData = newValue.find((item) => item.id === itemData.id);
640 if (updatedItemData) {
641 const errors: { key?: string; value?: string } = {};
642
643 if (context.onKeyValidate) {
644 const keyError = context.onKeyValidate(updatedItemData.key, newValue);
645 if (keyError) errors.key = keyError;
646 }
647
648 if (!context.allowDuplicateKeys) {
649 const duplicateKey = newValue.find(
650 (item) =>
651 item.id !== updatedItemData.id &&
652 item.key === updatedItemData.key &&
653 updatedItemData.key !== "",
654 );
655 if (duplicateKey) {
656 errors.key = "Duplicate key";
657 }
658 }
659
660 if (context.onValueValidate) {
661 const valueError = context.onValueValidate(
662 updatedItemData.value,
663 updatedItemData.key,
664 newValue,
665 );
666 if (valueError) errors.value = valueError;
667 }
668
669 const newErrorsState = { ...state.errors };
670 if (Object.keys(errors).length > 0) {
671 newErrorsState[itemData.id] = errors;
672 } else {
673 delete newErrorsState[itemData.id];
674 }
675 store.setState("errors", newErrorsState);
676 }
677 },
678 [store, itemData.id, context, propsRef],
679 );
680
681 const ValueInputPrimitive = asChild ? SlotPrimitive.Slot : Textarea;
682
683 return (
684 <ValueInputPrimitive
685 aria-invalid={isInvalid}
686 aria-describedby={
687 isInvalid ? getErrorId(context.rootId, itemData.id, "value") : undefined
688 }
689 data-slot="key-value-value-input"
690 autoCapitalize="off"
691 autoComplete="off"
692 autoCorrect="off"
693 spellCheck="false"
694 disabled={isDisabled}
695 readOnly={isReadOnly}
696 required={isRequired}
697 placeholder={context.valuePlaceholder}
698 {...valueInputProps}
699 className={cn(
700 "field-sizing-content min-h-9 resize-none",
701 maxRows && "overflow-y-auto",
702 className,
703 )}
704 style={{
705 ...style,
706 ...(maxHeight && { maxHeight }),
707 }}
708 value={itemData.value}
709 onChange={onChange}
710 />
711 );
712}
713
714interface KeyValueRemoveProps extends React.ComponentProps<typeof Button> {}
715
716function KeyValueRemove(props: KeyValueRemoveProps) {
717 const { onClick: onClickProp, children, ...removeProps } = props;
718
719 const context = useKeyValueContext(REMOVE_NAME);
720 const itemData = useKeyValueItemContext(REMOVE_NAME);
721 const store = useStoreContext(REMOVE_NAME);
722
723 const propsRef = useAsRef({
724 onClick: onClickProp,
725 });
726 const value = useStore((state) => state.value);
727 const isDisabled = context.disabled || value.length <= context.minItems;
728
729 const onClick = React.useCallback(
730 (event: React.MouseEvent<RemoveElement>) => {
731 propsRef.current.onClick?.(event);
732
733 const state = store.getState();
734 if (state.value.length <= context.minItems) return;
735
736 const itemToRemove = state.value.find((item) => item.id === itemData.id);
737 if (!itemToRemove) return;
738
739 const newValue = state.value.filter((item) => item.id !== itemData.id);
740 const newErrors = { ...state.errors };
741 delete newErrors[itemData.id];
742
743 store.setState("value", newValue);
744 store.setState("errors", newErrors);
745
746 context.onRemove?.(itemToRemove);
747 },
748 [store, context, itemData.id, propsRef],
749 );
750
751 return (
752 <Button
753 type="button"
754 data-slot="key-value-remove"
755 variant="outline"
756 size="icon"
757 disabled={isDisabled}
758 {...removeProps}
759 onClick={onClick}
760 >
761 {children ?? <XIcon />}
762 </Button>
763 );
764}
765
766function KeyValueAdd(props: React.ComponentProps<typeof Button>) {
767 const { onClick: onClickProp, children, ...addProps } = props;
768
769 const context = useKeyValueContext(ADD_NAME);
770 const store = useStoreContext(ADD_NAME);
771
772 const propsRef = useAsRef({
773 onClick: onClickProp,
774 });
775 const value = useStore((state) => state.value);
776 const isDisabled =
777 context.disabled ||
778 (context.maxItems !== undefined && value.length >= context.maxItems);
779
780 const onClick = React.useCallback(
781 (event: React.MouseEvent<AddElement>) => {
782 propsRef.current.onClick?.(event);
783
784 const state = store.getState();
785 if (
786 context.maxItems !== undefined &&
787 state.value.length >= context.maxItems
788 ) {
789 return;
790 }
791
792 const newItem: ItemData = {
793 id: crypto.randomUUID(),
794 key: "",
795 value: "",
796 };
797
798 const newValue = [...state.value, newItem];
799 store.setState("value", newValue);
800 store.setState("focusedId", newItem.id);
801
802 context.onAdd?.(newItem);
803 },
804 [store, context, propsRef],
805 );
806
807 return (
808 <Button
809 type="button"
810 data-slot="key-value-add"
811 variant="outline"
812 disabled={isDisabled}
813 {...addProps}
814 onClick={onClick}
815 >
816 {children ?? (
817 <>
818 <PlusIcon />
819 Add
820 </>
821 )}
822 </Button>
823 );
824}
825
826interface KeyValueErrorProps extends DivProps {
827 field: Field;
828}
829
830function KeyValueError(props: KeyValueErrorProps) {
831 const { field, asChild, className, ...errorProps } = props;
832
833 const context = useKeyValueContext(ERROR_NAME);
834 const itemData = useKeyValueItemContext(ERROR_NAME);
835
836 const errors = useStore((state) => state.errors);
837 const error = errors[itemData.id]?.[field];
838
839 if (!error) return null;
840
841 const ErrorPrimitive = asChild ? SlotPrimitive.Slot : "span";
842
843 return (
844 <ErrorPrimitive
845 id={getErrorId(context.rootId, itemData.id, field)}
846 role="alert"
847 {...errorProps}
848 className={cn("font-medium text-destructive text-sm", className)}
849 >
850 {error}
851 </ErrorPrimitive>
852 );
853}
854
855export {
856 type ItemData as KeyValueItemData,
857 KeyValue,
858 KeyValueAdd,
859 KeyValueError,
860 KeyValueItem,
861 KeyValueKeyInput,
862 KeyValueList,
863 type KeyValueProps,
864 KeyValueRemove,
865 KeyValueValueInput,
866 useStore as useKeyValueStore,
867};
868