Files
gwcf-review-front/src/components/ui/multi-select.tsx

1526 lines
54 KiB
TypeScript

/* eslint-disable react-hooks/refs, react-hooks/immutability, react-hooks/preserve-manual-memoization */
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import {
CheckIcon,
XCircle,
ChevronDown,
XIcon,
WandSparkles,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { Separator } from "@/components/ui/separator";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
} from "@/components/ui/command";
import {useEffect} from "react";
/**
* Animation types and configurations
*/
export interface AnimationConfig {
/** Badge animation type */
badgeAnimation?: "bounce" | "pulse" | "wiggle" | "fade" | "slide" | "none";
/** Popover animation type */
popoverAnimation?: "scale" | "slide" | "fade" | "flip" | "none";
/** Option hover animation type */
optionHoverAnimation?: "highlight" | "scale" | "glow" | "none";
/** Animation duration in seconds */
duration?: number;
/** Animation delay in seconds */
delay?: number;
}
/**
* Variants for the multi-select component to handle different styles.
* Uses class-variance-authority (cva) to define different styles based on "variant" prop.
*/
const multiSelectVariants = cva(
"mx-1 my-0 transition-all duration-300 ease-in-out",
{
variants: {
variant: {
default: "border-foreground/10 text-foreground bg-card hover:bg-card/80",
secondary:
"border-foreground/10 bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
inverted: "inverted",
},
badgeAnimation: {
bounce: "hover:-translate-y-1 hover:scale-110",
pulse: "hover:animate-pulse",
wiggle: "hover:animate-wiggle",
fade: "hover:opacity-60",
slide: "hover:translate-x-1",
none: "",
},
},
defaultVariants: {
variant: "default",
badgeAnimation: "fade",
},
}
);
/**
* Option interface for MultiSelect component
*/
export interface MultiSelectOption<T = unknown> {
/** The text to display for the option. */
label: string;
/** The unique value associated with the option. */
value: string;
info?: T;
/** Optional icon component to display alongside the option. */
icon?: React.ComponentType<{ className?: string }>;
/** Whether this option is disabled */
disabled?: boolean;
/** Custom styling for the option */
style?: {
/** Custom badge color */
badgeColor?: string;
/** Custom icon color */
iconColor?: string;
/** Gradient background for badge */
gradient?: string;
};
}
/**
* Group interface for organizing options
*/
export interface MultiSelectGroup<T = unknown> {
/** Group heading */
heading: string;
/** Options in this group */
options: MultiSelectOption<T>[];
}
/**
* Props for MultiSelect component
*/
export interface MultiSelectProps<T = unknown>
extends Omit<
React.ButtonHTMLAttributes<HTMLButtonElement>,
"animationConfig"
>,
VariantProps<typeof multiSelectVariants> {
/**
* An array of option objects or groups to be displayed in the multi-select component.
*/
options: MultiSelectOption<T>[] | MultiSelectGroup<T>[];
/**
* Callback function triggered when the selected values change.
* Receives an array of the new selected values.
*/
onValueChange: (value: string[]) => void;
/** (선택) 선택된 옵션(원본 포함) 반환 */
onOptionChange?: (selectedOptions: MultiSelectOption<T>[]) => void;
/** (선택) info만 받고 싶으면 이것도 추가 가능 */
onInfoChange?: (infos: T[]) => void;
/** The default selected values when the component mounts. */
defaultValue?: string[];
/**
* (선택) searchMode="inputOnly" (서버 검색)에서,
* 선택된 값이 현재 options(예: 20개 조회 결과)에 포함되지 않더라도
* 선택 상태/표시(라벨)를 유지하기 위한 "고정(sticky) 옵션" 목록입니다.
*
* - defaultValue에 포함된 값이 options에 없을 수 있는 경우(페이징/서버검색) 사용하세요.
* - value/label을 포함해야 하며, 필요 시 info/icon/style도 함께 전달 가능합니다.
*/
stickySelectedOptions?: MultiSelectOption<T>[];
/**
* (선택) searchMode="inputOnly"에서 options가 갱신되며(서버 검색/페이징),
* 선택된 값에 대한 label/info/style 등이 더 정확한 값으로 확인되는 경우가 있습니다.
*
* React props는 컴포넌트 내부에서 "자동으로 변경"할 수 없으므로,
* 상위 상태의 stickySelectedOptions를 최신 값으로 동기화하고 싶다면 이 콜백을 사용하세요.
*/
onStickySelectedOptionsChange?: (
stickySelectedOptions: MultiSelectOption<T>[]
) => void;
/**
* Placeholder text to be displayed when no values are selected.
* Optional, defaults to "Select options".
*/
placeholder?: string;
/**
* Animation duration in seconds for the visual effects (e.g., bouncing badges).
* Optional, defaults to 0 (no animation).
*/
animation?: number;
/**
* Advanced animation configuration for different component parts.
* Optional, allows fine-tuning of various animation effects.
*/
animationConfig?: AnimationConfig;
/**
* Maximum number of items to display. Extra selected items will be summarized.
* Optional, defaults to 3.
*/
maxCount?: number;
/**
* Maximum number of items that can be selected at once.
* Optional, defaults to undefined.
*/
maxSelected?: number;
/**
* Component selection mode.
* single - Only a single item can be selected at a time.
* multiple - Multiple items can be selected at once.
* Optional, defaults to multiple.
*/
selectionMode?: "single" | "multiple";
/**
* The modality of the popover. When set to true, interaction with outside elements
* will be disabled and only popover content will be visible to screen readers.
* Optional, defaults to false.
*/
modalPopover?: boolean;
/**
* If true, renders the multi-select component as a child of another component.
* Optional, defaults to false.
*/
asChild?: boolean;
/**
* Additional class names to apply custom styles to the multi-select component.
* Optional, can be used to add custom styles.
*/
className?: string;
spanClassName?: string;
badgeClassName?: string;
/**
* If true, disables the select all functionality.
* Optional, defaults to false.
*/
hideSelectAll?: boolean;
/**
* If true, shows search functionality in the popover.
* If false, hides the search input completely.
* Optional, defaults to true.
*/
searchable?: boolean;
/**
* Search behavior when search input is enabled.
* - "filter": filters options locally (current behavior)
* - "inputOnly": shows search box only; does not filter options locally
*/
searchMode?: "filter" | "inputOnly";
defaultSearchValue?: string;
/**
* Callback invoked when search input value changes.
* (server search용)
*/
onSearchValueChange?: (value: string) => void;
/**
* Custom empty state message when no options match search.
* Optional, defaults to "No results found."
*/
emptyIndicator?: React.ReactNode;
/**
* If true, allows the component to grow and shrink with its content.
* If false, uses fixed width behavior.
* Optional, defaults to false.
*/
autoSize?: boolean;
/**
* If true, shows badges in a single line with horizontal scroll.
* If false, badges wrap to multiple lines.
* Optional, defaults to false.
*/
singleLine?: boolean;
/**
* Custom CSS class for the popover content.
* Optional, can be used to customize popover appearance.
*/
popoverClassName?: string;
/**
* If true, disables the component completely.
* Optional, defaults to false.
*/
disabled?: boolean;
/**
* Responsive configuration for different screen sizes.
* Allows customizing maxCount and other properties based on viewport.
* Can be boolean true for default responsive behavior or an object for custom configuration.
*/
responsive?:
| boolean
| {
/** Configuration for mobile devices (< 640px) */
mobile?: {
maxCount?: number;
hideIcons?: boolean;
compactMode?: boolean;
};
/** Configuration for tablet devices (640px - 1024px) */
tablet?: {
maxCount?: number;
hideIcons?: boolean;
compactMode?: boolean;
};
/** Configuration for desktop devices (> 1024px) */
desktop?: {
maxCount?: number;
hideIcons?: boolean;
compactMode?: boolean;
};
};
/**
* Minimum width for the component.
* Optional, defaults to auto-sizing based on content.
* When set, component will not shrink below this width.
*/
minWidth?: string;
/**
* Maximum width for the component.
* Optional, defaults to 100% of container.
* Component will not exceed container boundaries.
*/
maxWidth?: string;
/**
* If true, automatically removes duplicate options based on their value.
* Optional, defaults to false (shows warning in dev mode instead).
*/
deduplicateOptions?: boolean;
/**
* If true, the component will reset its internal state when defaultValue changes.
* Useful for React Hook Form integration and form reset functionality.
* Optional, defaults to true.
*/
resetOnDefaultValueChange?: boolean;
/**
* If true, automatically closes the popover after selecting an option.
* Useful for single-selection-like behavior or mobile UX.
* Optional, defaults to false.
*/
closeOnSelect?: boolean;
/** 선택된 옵션 취소 막기*/
preventDeselect?: boolean;
/** 체크 박스 감추기*/
hideOptionCheck?: boolean;
}
/**
* Imperative methods exposed through ref
*/
export interface MultiSelectRef {
/**
* Programmatically reset the component to its default value
*/
reset: () => void;
/**
* Get current selected values
*/
getSelectedValues: () => string[];
/**
* Set selected values programmatically
*/
setSelectedValues: (values: string[]) => void;
/**
* Clear all selected values
*/
clear: () => void;
/**
* Focus the component
*/
focus: () => void;
}
function MultiSelectInner(
{
options,
onValueChange,
onOptionChange,
onInfoChange,
variant,
defaultValue = [],
stickySelectedOptions = [],
onStickySelectedOptionsChange,
placeholder = "Select options",
animation = 0,
animationConfig,
maxCount = 3,
maxSelected,
selectionMode = "multiple",
modalPopover = false,
asChild = false,
className,
spanClassName,
badgeClassName,
hideSelectAll = false,
searchable = true,
searchMode = "filter",
defaultSearchValue = "",
onSearchValueChange,
emptyIndicator,
autoSize = false,
singleLine = false,
popoverClassName,
disabled = false,
responsive,
minWidth,
maxWidth,
deduplicateOptions = false,
resetOnDefaultValueChange = true,
closeOnSelect = false,
preventDeselect = false,
hideOptionCheck = false,
...props
}: MultiSelectProps<any>,
ref: React.Ref<MultiSelectRef>
) {
const [selectedValues, setSelectedValues] =
React.useState<string[]>(defaultValue);
const [isPopoverOpen, setIsPopoverOpen] = React.useState(false);
const [isAnimating, setIsAnimating] = React.useState(false);
const [searchValue, setSearchValue] = React.useState(defaultSearchValue);
const [politeMessage, setPoliteMessage] = React.useState("");
const [assertiveMessage, setAssertiveMessage] = React.useState("");
const prevSelectedCount = React.useRef(selectedValues.length);
const prevIsOpen = React.useRef(isPopoverOpen);
const prevSearchValue = React.useRef(searchValue);
const announce = React.useCallback(
(message: string, priority: "polite" | "assertive" = "polite") => {
if (priority === "assertive") {
setAssertiveMessage(message);
setTimeout(() => setAssertiveMessage(""), 100);
} else {
setPoliteMessage(message);
setTimeout(() => setPoliteMessage(""), 100);
}
},
[]
);
const handleSearchValueChange = React.useCallback(
(value: string) => {
setSearchValue(value);
},
[onSearchValueChange]
);
const multiSelectId = React.useId();
const listboxId = `${multiSelectId}-listbox`;
const triggerDescriptionId = `${multiSelectId}-description`;
const selectedCountId = `${multiSelectId}-count`;
const prevDefaultValueRef = React.useRef<string[]>(defaultValue);
const isGroupedOptions = React.useCallback(
(
opts: MultiSelectOption<any>[] | MultiSelectGroup<any>[]
): opts is MultiSelectGroup<any>[] => {
return opts.length > 0 && "heading" in opts[0];
},
[]
);
const arraysEqual = React.useCallback((a: string[], b: string[]): boolean => {
if (a.length !== b.length) return false;
const sortedA = [...a].sort();
const sortedB = [...b].sort();
return sortedA.every((val, index) => val === sortedB[index]);
}, []);
const buttonRef = React.useRef<HTMLButtonElement>(null);
const [triggerWidthPx, setTriggerWidthPx] = React.useState<number | null>(
null
);
const measureTriggerWidth = React.useCallback(() => {
const el = buttonRef.current;
if (!el) return;
const { width } = el.getBoundingClientRect();
const next = Math.round(width);
setTriggerWidthPx((prev) => (prev === next ? prev : next));
}, []);
React.useEffect(() => {
if (typeof window === "undefined") return;
measureTriggerWidth();
const el = buttonRef.current;
if (!el || !("ResizeObserver" in window)) return;
const ro = new ResizeObserver(() => measureTriggerWidth());
ro.observe(el);
return () => ro.disconnect();
}, [measureTriggerWidth]);
React.useEffect(() => {
if (isPopoverOpen) measureTriggerWidth();
}, [isPopoverOpen, measureTriggerWidth]);
const isSingle = selectionMode === "single";
React.useImperativeHandle(
ref,
() => ({
reset: () => {
setSelectedValues(defaultValue);
setIsPopoverOpen(false);
setSearchValue("");
emitChange(defaultValue);
},
getSelectedValues: () => selectedValues,
setSelectedValues: (values: string[]) => {
setSelectedValues(values);
emitChange(values);
},
clear: () => {
setSelectedValues([]);
emitChange([]);
},
focus: () => {
if (buttonRef.current) {
buttonRef.current.focus();
const originalOutline = buttonRef.current.style.outline;
const originalOutlineOffset =
buttonRef.current.style.outlineOffset;
buttonRef.current.style.outline = "2px solid hsl(var(--ring))";
buttonRef.current.style.outlineOffset = "2px";
setTimeout(() => {
if (buttonRef.current) {
buttonRef.current.style.outline = originalOutline;
buttonRef.current.style.outlineOffset = originalOutlineOffset;
}
}, 1000);
}
},
}),
[defaultValue, selectedValues]
);
const [screenSize, setScreenSize] =
React.useState<"mobile" | "tablet" | "desktop">("desktop");
React.useEffect(() => {
if (typeof window === "undefined") return;
const handleResize = () => {
const width = window.innerWidth;
if (width < 640) {
setScreenSize("mobile");
} else if (width < 1024) {
setScreenSize("tablet");
} else {
setScreenSize("desktop");
}
};
handleResize();
window.addEventListener("resize", handleResize);
return () => {
if (typeof window !== "undefined") {
window.removeEventListener("resize", handleResize);
}
};
}, []);
const getResponsiveSettings = () => {
if (!responsive) {
return {
maxCount: maxCount,
hideIcons: false,
compactMode: false,
};
}
if (responsive === true) {
const defaultResponsive = {
mobile: { maxCount: 2, hideIcons: false, compactMode: true },
tablet: { maxCount: 4, hideIcons: false, compactMode: false },
desktop: { maxCount: 6, hideIcons: false, compactMode: false },
};
const currentSettings = defaultResponsive[screenSize];
return {
maxCount: currentSettings?.maxCount ?? maxCount,
hideIcons: currentSettings?.hideIcons ?? false,
compactMode: currentSettings?.compactMode ?? false,
};
}
const currentSettings = responsive[screenSize];
return {
maxCount: currentSettings?.maxCount ?? maxCount,
hideIcons: currentSettings?.hideIcons ?? false,
compactMode: currentSettings?.compactMode ?? false,
};
};
const responsiveSettings = getResponsiveSettings();
const getBadgeAnimationClass = () => {
if (animationConfig?.badgeAnimation) {
switch (animationConfig.badgeAnimation) {
case "bounce":
return isAnimating
? "animate-bounce"
: "hover:-translate-y-1 hover:scale-110";
case "pulse":
return "hover:animate-pulse";
case "wiggle":
return "hover:animate-wiggle";
case "fade":
return "hover:opacity-80";
case "slide":
return "hover:translate-x-1";
case "none":
return "";
default:
return "";
}
}
return isAnimating ? "animate-bounce" : "";
};
const getPopoverAnimationClass = () => {
if (animationConfig?.popoverAnimation) {
switch (animationConfig.popoverAnimation) {
case "scale":
return "animate-scaleIn";
case "slide":
return "animate-slideInDown";
case "fade":
return "animate-fadeIn";
case "flip":
return "animate-flipIn";
case "none":
return "";
default:
return "";
}
}
return "";
};
const getAllOptions = React.useCallback((): MultiSelectOption<any>[] => {
if (options.length === 0) return [];
let allOptions: MultiSelectOption<any>[];
if (isGroupedOptions(options)) {
allOptions = options.flatMap((group) => group.options);
} else {
allOptions = options;
}
const valueSet = new Set<string>();
const duplicates: string[] = [];
const uniqueOptions: MultiSelectOption<any>[] = [];
allOptions.forEach((option) => {
if (valueSet.has(option.value)) {
duplicates.push(option.value);
if (!deduplicateOptions) {
uniqueOptions.push(option);
}
} else {
valueSet.add(option.value);
uniqueOptions.push(option);
}
});
if (process.env.NODE_ENV === "development" && duplicates.length > 0) {
const action = deduplicateOptions ? "automatically removed" : "detected";
console.warn(
`MultiSelect: Duplicate option values ${action}: ${duplicates.join(
", "
)}. ` +
`${
deduplicateOptions
? "Duplicates have been removed automatically."
: "This may cause unexpected behavior. Consider setting 'deduplicateOptions={true}' or ensure all option values are unique."
}`
);
}
return deduplicateOptions ? uniqueOptions : allOptions;
}, [options, deduplicateOptions, isGroupedOptions]);
const stickySelectedOptionMapRef = React.useRef<Map<string, MultiSelectOption<any>>>(
new Map()
);
React.useEffect(() => {
if (searchMode !== "inputOnly") return;
if (!stickySelectedOptions?.length) return;
for (const opt of stickySelectedOptions) {
if (!opt?.value) continue;
stickySelectedOptionMapRef.current.set(opt.value, opt);
}
}, [searchMode, stickySelectedOptions]);
// options에 포함된 선택값은 캐시를 최신으로 갱신 (라벨/스타일 변경 반영)
React.useEffect(() => {
if (searchMode !== "inputOnly") return;
for (const value of selectedValues) {
const fromOptions = getAllOptions().find((o) => o.value === value);
if (fromOptions) stickySelectedOptionMapRef.current.set(value, fromOptions);
}
}, [searchMode, selectedValues, getAllOptions]);
// 선택 해제된 값은 캐시에서 제거 (무한 증가 방지)
React.useEffect(() => {
if (searchMode !== "inputOnly") return;
const cache = stickySelectedOptionMapRef.current;
for (const key of Array.from(cache.keys())) {
if (!selectedValues.includes(key)) cache.delete(key);
}
}, [searchMode, selectedValues]);
const getOptionByValue = React.useCallback(
(value: string): MultiSelectOption<any> | undefined => {
const option = getAllOptions().find((o) => o.value === value);
if (option) {
if (searchMode === "inputOnly") {
stickySelectedOptionMapRef.current.set(value, option);
}
return option;
}
// searchMode="inputOnly": 현재 options에 없어도 선택 상태/표시를 유지
if (searchMode === "inputOnly") {
const cached = stickySelectedOptionMapRef.current.get(value);
if (cached) return cached;
const fallback: MultiSelectOption<any> = { value, label: value };
stickySelectedOptionMapRef.current.set(value, fallback);
return fallback;
}
if (!option && process.env.NODE_ENV === "development") {
console.warn(
`MultiSelect: Option with value "${value}" not found in options list`
);
}
return undefined;
},
[getAllOptions, searchMode]
);
const lastStickyEmitKeyRef = React.useRef<string>("");
// (선택) 상위에서 stickySelectedOptions를 상태로 관리하는 경우,
// options(검색 결과) 갱신에 따라 label/info/style 등이 업데이트되면 콜백으로 최신 값을 전달
React.useEffect(() => {
if (searchMode !== "inputOnly") return;
if (!onStickySelectedOptionsChange) return;
const seen = new Set<string>();
const nextSticky: MultiSelectOption<any>[] = [];
for (const v of selectedValues) {
if (seen.has(v)) continue;
seen.add(v);
const opt = getOptionByValue(v);
if (opt) nextSticky.push(opt);
}
// icon/info는 직렬화/비교에서 제외(불필요한 재호출 및 순환 참조 방지)
const key = JSON.stringify(
nextSticky.map((o) => ({
value: o.value,
label: o.label,
disabled: o.disabled ?? false,
style: o.style ?? null,
}))
);
if (key === lastStickyEmitKeyRef.current) return;
lastStickyEmitKeyRef.current = key;
onStickySelectedOptionsChange(nextSticky);
}, [searchMode, selectedValues, getOptionByValue, onStickySelectedOptionsChange]);
const emitChange = React.useCallback(
(values: string[]) => {
onValueChange(values);
if (!onOptionChange && !onInfoChange) return;
const selectedOptions = values
.map((v) => getOptionByValue(v))
.filter(
(o): o is MultiSelectOption<any> =>
o !== undefined && o !== null
);
onOptionChange?.(selectedOptions as MultiSelectOption<any>[]);
if (onInfoChange) {
const infos = selectedOptions
.map((o) => o.info)
.filter((x): x is any => x !== undefined);
onInfoChange(infos);
}
},
[onValueChange, onOptionChange, onInfoChange, getOptionByValue]
);
const resetToDefault = React.useCallback(() => {
setSelectedValues(defaultValue);
setIsPopoverOpen(false);
setSearchValue("");
emitChange(defaultValue);
}, [defaultValue, emitChange]);
const filteredOptions = React.useMemo(() => {
if (!searchable || !searchValue) return options;
if (searchMode === "inputOnly") return options;
if (options.length === 0) return [];
if (isGroupedOptions(options)) {
return options
.map((group) => ({
...group,
options: group.options.filter(
(option) =>
option.label
.toLowerCase()
.includes(searchValue.toLowerCase()) ||
option.value.toLowerCase().includes(searchValue.toLowerCase())
),
}))
.filter((group) => group.options.length > 0);
}
return options.filter(
(option) =>
option.label.toLowerCase().includes(searchValue.toLowerCase()) ||
option.value.toLowerCase().includes(searchValue.toLowerCase())
);
}, [options, searchValue, searchable, isGroupedOptions, searchMode]);
const handleInputKeyDown = (
event: React.KeyboardEvent<HTMLInputElement>
) => {
if (event.key === "Enter") {
setIsPopoverOpen(true);
} else if (event.key === "Backspace" && !event.currentTarget.value) {
if (preventDeselect) return;
const newSelectedValues = [...selectedValues];
newSelectedValues.pop();
setSelectedValues(newSelectedValues);
emitChange(newSelectedValues);
}
};
const toggleOption = (optionValue: string) => {
if (disabled) return;
const option = getOptionByValue(optionValue);
if (option?.disabled) return;
const isSelected = selectedValues.includes(optionValue);
let newSelectedValues: string[];
if (isSingle) {
// single: 기존을 clear하고 "교체"
if (isSelected && preventDeselect) return;
newSelectedValues = isSelected ? [] : [optionValue];
} else {
if (isSelected) {
newSelectedValues = selectedValues.filter((v) => v !== optionValue);
} else {
if (
maxSelected &&
maxSelected > 0 &&
selectedValues.length >= maxSelected
) {
announce(
`최대 ${maxSelected}개까지 선택할 수 있어요.`,
"assertive"
);
return;
}
newSelectedValues = [...selectedValues, optionValue];
}
}
setSelectedValues(newSelectedValues);
emitChange(newSelectedValues);
if (closeOnSelect) {
setIsPopoverOpen(false);
}
};
const handleClear = () => {
if (disabled || preventDeselect) return;
if (disabled) return;
setSelectedValues([]);
emitChange([]);
};
const handleTogglePopover = () => {
if (disabled) return;
setIsPopoverOpen((prev) => !prev);
};
const clearExtraOptions = () => {
if (disabled || preventDeselect) return;
if (disabled) return;
const newSelectedValues = selectedValues.slice(
0,
responsiveSettings.maxCount
);
setSelectedValues(newSelectedValues);
emitChange(newSelectedValues);
};
const toggleAll = () => {
if (disabled) return;
if (isSingle) return;
if (preventDeselect && isAllSelected) return;
const allOptions = getAllOptions().filter((o) => !o.disabled);
const allValuesUnclamped = allOptions.map((o) => o.value);
const allValues =
maxSelected && maxSelected > 0
? allValuesUnclamped.slice(0, maxSelected)
: allValuesUnclamped;
const allSelectableCount =
maxSelected && maxSelected > 0
? Math.min(allOptions.length, maxSelected)
: allOptions.length;
if (selectedValues.length === allSelectableCount) {
handleClear();
} else {
setSelectedValues(allValues);
emitChange(allValues);
}
if (closeOnSelect) {
setIsPopoverOpen(false);
}
};
React.useEffect(() => {
if (!resetOnDefaultValueChange) return;
const prevDefaultValue = prevDefaultValueRef.current;
if (!arraysEqual(prevDefaultValue, defaultValue)) {
if (!arraysEqual(selectedValues, defaultValue)) {
setSelectedValues(defaultValue);
}
prevDefaultValueRef.current = [...defaultValue];
}
}, [
defaultValue,
selectedValues,
arraysEqual,
resetOnDefaultValueChange,
]);
const getWidthConstraints = () => {
const effectiveMinWidth = minWidth || "100%";
const effectiveMaxWidth = maxWidth || "100%";
return {
minWidth: effectiveMinWidth,
maxWidth: effectiveMaxWidth,
};
};
const widthConstraints = getWidthConstraints();
const enabledCount = getAllOptions().filter((opt) => !opt.disabled).length;
const selectableCount =
maxSelected && maxSelected > 0
? Math.min(enabledCount, maxSelected)
: enabledCount;
const isAllSelected = !isSingle && selectedValues.length === selectableCount;
React.useEffect(() => {
if (!isPopoverOpen && searchMode !== "inputOnly") {
setSearchValue("");
}
}, [isPopoverOpen]);
useEffect(() => {
onSearchValueChange?.(searchValue);
}, [searchValue]);
React.useEffect(() => {
const selectedCount = selectedValues.length;
const allOptions = getAllOptions();
const totalOptions = allOptions.filter((opt) => !opt.disabled).length;
if (selectedCount !== prevSelectedCount.current) {
const diff = selectedCount - prevSelectedCount.current;
if (diff > 0) {
const addedItems = selectedValues.slice(-diff);
const addedLabels = addedItems
.map(
(value) => allOptions.find((opt) => opt.value === value)?.label
)
.filter(Boolean);
if (addedLabels.length === 1) {
announce(
`${addedLabels[0]} selected. ${selectedCount} of ${totalOptions} options selected.`
);
} else {
announce(
`${addedLabels.length} options selected. ${selectedCount} of ${totalOptions} total selected.`
);
}
} else if (diff < 0) {
announce(
`Option removed. ${selectedCount} of ${totalOptions} options selected.`
);
}
prevSelectedCount.current = selectedCount;
}
if (isPopoverOpen !== prevIsOpen.current) {
if (isPopoverOpen) {
announce(
`Dropdown opened. ${totalOptions} options available. Use arrow keys to navigate.`
);
} else {
announce("Dropdown closed.");
}
prevIsOpen.current = isPopoverOpen;
}
if (
searchValue !== prevSearchValue.current &&
searchValue !== undefined
) {
if (searchValue && isPopoverOpen) {
const filteredCount = allOptions.filter(
(opt) =>
opt.label.toLowerCase().includes(searchValue.toLowerCase()) ||
opt.value.toLowerCase().includes(searchValue.toLowerCase())
).length;
announce(
`${filteredCount} option${
filteredCount === 1 ? "" : "s"
} found for "${searchValue}"`
);
}
prevSearchValue.current = searchValue;
}
}, [
selectedValues,
isPopoverOpen,
searchValue,
announce,
getAllOptions,
]);
return (
<>
<div className="sr-only">
<div aria-live="polite" aria-atomic="true" role="status">
{politeMessage}
</div>
<div aria-live="assertive" aria-atomic="true" role="alert">
{assertiveMessage}
</div>
</div>
<Popover
open={isPopoverOpen}
onOpenChange={setIsPopoverOpen}
modal={modalPopover}
>
<div id={triggerDescriptionId} className="sr-only">
Multi-select dropdown. Use arrow keys to navigate, Enter to select,
and Escape to close.
</div>
<div id={selectedCountId} className="sr-only" aria-live="polite">
{selectedValues.length === 0
? "No options selected"
: `${selectedValues.length} option${
selectedValues.length === 1 ? "" : "s"
} selected: ${selectedValues
.map((value) => getOptionByValue(value)?.label)
.filter(Boolean)
.join(", ")}`}
</div>
<PopoverTrigger asChild>
<Button
ref={buttonRef}
{...props}
onClick={handleTogglePopover}
disabled={disabled}
role="combobox"
aria-expanded={isPopoverOpen}
aria-haspopup="listbox"
aria-controls={isPopoverOpen ? listboxId : undefined}
aria-describedby={`${triggerDescriptionId} ${selectedCountId}`}
aria-label={`Multi-select: ${selectedValues.length} of ${
getAllOptions().length
} options selected. ${placeholder}`}
className={cn(
"flex p-1 rounded-md border min-h-9 h-auto items-center justify-between",
autoSize ? "w-auto" : "w-full",
responsiveSettings.compactMode && "min-h-8 text-sm",
screenSize === "mobile" && "min-h-9 text-base",
disabled && "opacity-50 cursor-not-allowed",
singleLine && "overflow-hidden",
className,
"bg-white hover:!bg-white focus:!bg-white active:!bg-white data-[state=open]:!bg-white"
)}
style={{
...widthConstraints,
maxWidth: `min(${widthConstraints.maxWidth}, 100%)`,
height: "100%",
}}
>
{selectedValues.length > 0 ? (
<div className="flex justify-between items-center w-full">
{isSingle ? (
<span className={cn("mx-3 flex-1 min-w-0 truncate text-left text-foreground", spanClassName)}>
{selectedValues[0]
? (getOptionByValue(selectedValues[0])?.label ?? selectedValues[0])
: ""}
</span>
) : (
<div
className={cn(
"flex items-center",
singleLine
? "overflow-x-hidden"
: "flex-wrap",
responsiveSettings.compactMode && "gap-0.5"
)}
>
{
selectedValues.length <= responsiveSettings.maxCount?
selectedValues
.slice(0, responsiveSettings.maxCount)
.map((value) => {
const option =
getOptionByValue(value) ??
({ value, label: value } as MultiSelectOption<any>);
const IconComponent = option.icon;
const customStyle = option.style;
const badgeStyle: React.CSSProperties = {
animationDuration: `${animation}s`,
...(customStyle?.badgeColor && {
backgroundColor: customStyle.badgeColor,
}),
...(customStyle?.gradient && {
background: customStyle.gradient,
color: "white",
}),
};
return (
<Badge
key={value}
className={cn(
getBadgeAnimationClass(),
multiSelectVariants({ variant }),
customStyle?.gradient &&
"text-white border-transparent",
responsiveSettings.compactMode &&
"px-1.5 py-0.5",
screenSize === "mobile" &&
"max-w-[120px] truncate",
singleLine &&
"flex-shrink-0 whitespace-nowrap",
"[&>svg]:pointer-events-auto",
badgeClassName
)}
style={{
...badgeStyle,
animationDuration: `${
animationConfig?.duration || animation
}s`,
animationDelay: `${
animationConfig?.delay || 0
}s`,
}}
>
{IconComponent &&
!responsiveSettings.hideIcons && (
<IconComponent
className={cn(
"h-4 w-4 mr-2",
responsiveSettings.compactMode &&
"h-3 w-3 mr-1",
customStyle?.iconColor &&
"text-current"
)}
{...(customStyle?.iconColor && {
style: { color: customStyle.iconColor },
})}
/>
)}
<span
className={cn(
screenSize === "mobile" && "truncate"
)}
>
{option.label}
</span>
<div
role="button"
tabIndex={0}
onClick={(event) => {
event.stopPropagation();
toggleOption(value);
}}
onKeyDown={(event) => {
if (
event.key === "Enter" ||
event.key === " "
) {
event.preventDefault();
event.stopPropagation();
toggleOption(value);
}
}}
aria-label={`Remove ${option.label} from selection`}
className="ml-2 h-4.5 w-4.5 cursor-pointer hover:bg-white/20 rounded-sm p-0.5 -m-0.5 focus:outline-none focus:ring-1 focus:ring-white/50"
>
{!preventDeselect &&
<XCircle
className={cn(
"h-3 w-3",
responsiveSettings.compactMode &&
"h-2.5 w-2.5"
)}
/>
}
</div>
</Badge>
);
})
.filter(Boolean)
:
<Badge
className={cn(
"bg-transparent text-foreground border-foreground/1 hover:bg-transparent",
getBadgeAnimationClass(),
multiSelectVariants({ variant }),
responsiveSettings.compactMode &&
"px-1.5 py-0.5",
singleLine &&
"flex-shrink-0 whitespace-nowrap",
"[&>svg]:pointer-events-auto",
badgeClassName
)}
style={{
animationDuration: `${
animationConfig?.duration || animation
}s`,
animationDelay: `${
animationConfig?.delay || 0
}s`,
}}
>
{`+ ${
selectedValues.length
}`}
<XCircle
className={cn(
"ml-2 h-4 w-4 mt-0.5 cursor-pointer",
responsiveSettings.compactMode &&
"ml-1 h-3 w-3"
)}
onClick={(event) => {
event.stopPropagation();
handleClear();
}}
/>
</Badge>
}
</div>
)}
<div className="flex items-center justify-between">
<Separator
orientation="vertical"
className="flex min-h-6 h-full"
/>
<ChevronDown
className="h-4 mx-2 cursor-pointer text-muted-foreground"
aria-hidden="true"
/>
</div>
</div>
) : (
<div className="flex items-center justify-between w-full mx-auto">
<span className={cn("mx-3 text-muted-foreground", spanClassName)}>
{placeholder}
</span>
<ChevronDown className="h-4 cursor-pointer text-muted-foreground mx-2" />
</div>
)}
</Button>
</PopoverTrigger>
<PopoverContent
id={listboxId}
role="listbox"
aria-multiselectable={!isSingle}
aria-label="Available options"
className={cn(
"w-auto p-0",
getPopoverAnimationClass(),
screenSize === "mobile" && "w-[85vw] max-w-[280px]",
screenSize === "tablet" && "w-[70vw] max-w-md",
screenSize === "desktop" && "min-w-[300px]",
popoverClassName
)}
style={{
animationDuration: `${animationConfig?.duration || animation}s`,
animationDelay: `${animationConfig?.delay || 0}s`,
...(triggerWidthPx
? {
width: `${triggerWidthPx}px`,
minWidth: `${triggerWidthPx}px`,
}
: {}),
maxWidth: `min(${widthConstraints.maxWidth}, 85vw)`,
maxHeight: screenSize === "mobile" ? "70vh" : "60vh",
touchAction: "manipulation",
}}
align="start"
onEscapeKeyDown={() => setIsPopoverOpen(false)}
>
<Command shouldFilter={false}>
{searchable && (
<CommandInput
placeholder="검색"
onKeyDown={handleInputKeyDown}
value={searchValue}
onValueChange={handleSearchValueChange}
aria-label="Search through available options"
aria-describedby={`${multiSelectId}-search-help`}
/>
)}
{searchable && (
<div id={`${multiSelectId}-search-help`} className="sr-only">
Type to filter options. Use arrow keys to navigate results.
</div>
)}
<CommandList
onWheelCapture={(e) => e.stopPropagation()}
className={cn(
"min-h-0 max-h-[40vh] overflow-y-auto multiselect-scrollbar",
screenSize === "mobile" && "max-h-[50vh]",
"overscroll-behavior-y-contain"
)}
>
<CommandEmpty>
{emptyIndicator || "검색 결과가 없습니다."}
</CommandEmpty>
{!isSingle && !hideSelectAll && !searchValue && (
<CommandGroup>
<CommandItem
key="all"
value={"all"}
onSelect={toggleAll}
role="option"
aria-selected={isAllSelected}
aria-label={`Select all ${
getAllOptions().length
} options`}
className="cursor-pointer"
>
{!hideOptionCheck &&
<div
className={cn(
"mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
selectedValues.length ===
getAllOptions().filter((opt) => !opt.disabled)
.length
? "bg-primary text-primary-foreground"
: "opacity-50 [&_svg]:invisible"
)}
aria-hidden="true"
>
<CheckIcon className="h-4 w-4" />
</div>
}
<span>
(전체 선택
{getAllOptions().length > 20
? ` - ${getAllOptions().length} options`
: ""}
)
</span>
</CommandItem>
</CommandGroup>
)}
{isGroupedOptions(filteredOptions) ? (
filteredOptions.map((group) => (
<CommandGroup key={group.heading} heading={group.heading}>
{group.options.map((option) => {
const isSelected = selectedValues.includes(
option.value
);
return (
<CommandItem
key={option.value}
value={option.value}
onSelect={() => toggleOption(option.value)}
role="option"
aria-selected={isSelected}
aria-disabled={option.disabled}
aria-label={`${option.label}${
isSelected ? ", selected" : ", not selected"
}${option.disabled ? ", disabled" : ""}`}
className={cn(
"cursor-pointer",
option.disabled &&
"opacity-50 cursor-not-allowed"
)}
disabled={option.disabled}
>
{!hideOptionCheck &&
<div
className={cn(
"mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
isSelected
? "bg-primary text-primary-foreground"
: "opacity-50 [&_svg]:invisible"
)}
aria-hidden="true"
>
<CheckIcon className="h-4 w-4" />
</div>
}
{option.icon && (
<option.icon
className="mr-2 h-4 w-4 text-muted-foreground"
aria-hidden="true"
/>
)}
<span>{option.label}</span>
</CommandItem>
);
})}
</CommandGroup>
))
) : (
<CommandGroup>
{filteredOptions.map((option) => {
const isSelected = selectedValues.includes(option.value);
return (
<CommandItem
key={option.value}
value={option.value}
onSelect={() => toggleOption(option.value)}
role="option"
aria-selected={isSelected}
aria-disabled={option.disabled}
aria-label={`${option.label}${
isSelected ? ", selected" : ", not selected"
}${option.disabled ? ", disabled" : ""}`}
className={cn(
"cursor-pointer",
option.disabled &&
"opacity-50 cursor-not-allowed"
)}
disabled={option.disabled}
>
{!hideOptionCheck &&
<div
className={cn(
"mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
isSelected
? "bg-primary text-primary-foreground"
: "opacity-50 [&_svg]:invisible"
)}
aria-hidden="true"
>
<CheckIcon className="h-4 w-4" />
</div>
}
{option.icon && (
<option.icon
className="mr-2 h-4 w-4 text-muted-foreground"
aria-hidden="true"
/>
)}
<span>{option.label}</span>
</CommandItem>
);
})}
</CommandGroup>
)}
<CommandSeparator />
</CommandList>
</Command>
</PopoverContent>
{animation > 0 && selectedValues.length > 0 && (
<WandSparkles
className={cn(
"cursor-pointer my-2 text-foreground bg-background w-3 h-3",
isAnimating ? "" : "text-muted-foreground"
)}
onClick={() => setIsAnimating(!isAnimating)}
/>
)}
</Popover>
</>
);
}
const ForwardedMultiSelect = React.forwardRef<
MultiSelectRef,
MultiSelectProps<any>
>(MultiSelectInner);
ForwardedMultiSelect.displayName = "MultiSelect";
/**
* 제네릭 friendly 타입 캐스팅
* - 사용 시: <MultiSelect<MyType> ... />
*/
export const MultiSelect = ForwardedMultiSelect as <T = unknown>(
props: MultiSelectProps<T> & React.RefAttributes<MultiSelectRef>
) => React.ReactElement | null;