Files
HiveGrid-Wireframes/hivegrid-cloud/apps/web/app/components/ui/multi-select.tsx
T

401 lines
16 KiB
TypeScript

import { t as i18nT } from "i18next";
// src/components/multi-select.tsx
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { CheckIcon, XCircle, ChevronDown, XIcon, WandSparkles, CaretSortIcon } from "~/components/ui/icons/vendor";
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 { Checkbox } from "./checkbox";
import { useTranslation } from "react-i18next";
import GearIcon from "./icons/GearIcon";
import { useLocaleFormatters } from "~/locale/format";
/**
* 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("m-1 transition ease-in-out delay-150 hover:-translate-y-1 duration-300", {
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",
},
},
defaultVariants: {
variant: "default",
},
});
/**
* Props for MultiSelect component
*/
interface MultiSelectProps extends React.ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof multiSelectVariants> {
/**
* An array of option objects to be displayed in the multi-select component.
* Each option object has a label, value, and an optional icon.
*/
options: {
/** The text to display for the option. */
label: string | React.ReactNode;
/** The unique value associated with the option. */
value: string;
/** Optional icon component to display alongside the option. */
icon?: React.ComponentType<{ className?: string }>;
}[];
/**
* Callback function triggered when the selected values change.
* Receives an array of the new selected values.
*/
onValueChange: (value: string[]) => void;
value?: string[];
/** The default selected values when the component mounts. */
defaultValue?: string[];
/**
* Placeholder text to be displayed when no values are selected.
* Optional, defaults to "Select options".
*/
placeholder?: string | React.ReactNode;
/**
* Animation duration in seconds for the visual effects (e.g., bouncing badges).
* Optional, defaults to 0 (no animation).
*/
animation?: number;
/**
* Maximum number of items to display. Extra selected items will be summarized.
* Optional, defaults to 3.
*/
maxCount?: number;
/**
* 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;
size?: "default" | "xs" | "sm" | "lg" | "icon";
onSettingsClick?: () => void;
renderComponents?: boolean;
icon?: React.ReactNode;
popoverClassName?: string;
selectedTitle?: string;
selectedTitlePlural?: string;
selectedTitleAll?: string;
}
export const MultiSelect = React.forwardRef<HTMLButtonElement, MultiSelectProps>(
(
{
size = "default",
options,
onValueChange,
variant,
value,
defaultValue = [],
placeholder = i18nT("components.multiSelect.select"),
animation = 0,
maxCount = 3,
modalPopover = true,
asChild = false,
className,
onSettingsClick,
renderComponents = false,
popoverClassName = "max-w-[300px]",
selectedTitle = "selected",
selectedTitlePlural = "selected",
selectedTitleAll,
...props
},
ref
) => {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const [selectedValues, setSelectedValues] = React.useState<string[]>(value || defaultValue);
const [isPopoverOpen, setIsPopoverOpen] = React.useState(false);
const [isAnimating, setIsAnimating] = React.useState(false);
const selectedValueSet = React.useMemo(() => new Set(selectedValues), [selectedValues]);
const optionByValue = React.useMemo(() => new Map(options.map((option) => [option.value, option])), [options]);
const selectedSummaryText = React.useMemo(
() =>
selectedValues
.map((selectedValue) => {
const label = optionByValue.get(selectedValue)?.label;
return typeof label === "string" || typeof label === "number" ? String(label) : selectedValue;
})
.join(", "),
[optionByValue, selectedValues]
);
React.useEffect(() => {
if (value !== undefined) {
setSelectedValues(value);
}
}, [value]);
const handleInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === "Enter") {
setIsPopoverOpen(true);
} else if (event.key === "Backspace" && !event.currentTarget.value) {
const newSelectedValues = [...selectedValues];
newSelectedValues.pop();
setSelectedValues(newSelectedValues);
onValueChange(newSelectedValues);
}
};
const toggleOption = (option: string) => {
const newSelectedValues = selectedValueSet.has(option) ? selectedValues.filter((value) => value !== option) : [...selectedValues, option];
setSelectedValues(newSelectedValues);
onValueChange(newSelectedValues);
};
const handleClear = () => {
setSelectedValues([]);
onValueChange([]);
};
const handleTogglePopover = () => {
setIsPopoverOpen((prev) => !prev);
};
const clearExtraOptions = () => {
const newSelectedValues = selectedValues.slice(0, maxCount);
setSelectedValues(newSelectedValues);
onValueChange(newSelectedValues);
};
const toggleAll = () => {
if (selectedValues.length === options.length) {
setSelectedValues([]);
onValueChange([]);
} else {
const allValues = options.map((option) => option.value);
setSelectedValues(allValues);
onValueChange(allValues);
}
};
return (
<Popover open={isPopoverOpen} onOpenChange={setIsPopoverOpen} modal={modalPopover}>
<PopoverTrigger asChild>
<Button
ref={ref}
{...props}
onClick={handleTogglePopover}
size={size}
variant="outline"
className={cn(
// Subframe MultiSelect trigger box layout: h-9, rounded-sm, px-3, gap-2, left-aligned text.
"flex h-9 justify-start gap-2 truncate rounded-sm px-3 text-left font-normal",
className
)}
>
{/* {selectedValues.length > 0 ? (
<div className="flex w-full items-center justify-between">
<div className="flex flex-wrap items-center">
{selectedValues.slice(0, maxCount).map((value) => {
const option = options.find((o) => o.value === value);
const IconComponent = option?.icon;
return (
<Badge
key={value}
className={cn(isAnimating ? "animate-bounce" : "", multiSelectVariants({ variant }))}
style={{ animationDuration: `${animation}s` }}
>
{IconComponent && <IconComponent className="mr-2 h-4 w-4" />}
{option?.label}
<XCircle
className="ml-2 h-4 w-4 cursor-pointer"
onClick={(event) => {
event.stopPropagation();
toggleOption(value);
}}
/>
</Badge>
);
})}
{selectedValues.length > maxCount && (
<Badge
className={cn(
"text-foreground border-foreground/1 bg-transparent hover:bg-transparent",
isAnimating ? "animate-bounce" : "",
multiSelectVariants({ variant })
)}
style={{ animationDuration: `${animation}s` }}
>
{`+ ${selectedValues.length - maxCount} more`}
<XCircle
className="ml-2 h-4 w-4 cursor-pointer"
onClick={(event) => {
event.stopPropagation();
clearExtraOptions();
}}
/>
</Badge>
)}
</div>
<div className="flex items-center justify-between">
<XIcon
className="text-muted-foreground mx-2 h-4 cursor-pointer"
onClick={(event) => {
event.stopPropagation();
handleClear();
}}
/>
<Separator orientation="vertical" className="flex h-full min-h-6" />
<ChevronDown className="text-muted-foreground mx-2 h-4 cursor-pointer" />
</div>
</div>
) : (
<div className="mx-auto flex w-full items-center justify-between">
<span className="text-muted-foreground mx-3 text-sm">{placeholder}</span>
<ChevronDown className="text-muted-foreground mx-2 h-4 cursor-pointer" />
</div>
)} */}
<div className="flex w-full items-center justify-between truncate">
<div className={cn("flex items-center gap-2 truncate", selectedValues.length === 0 && "text-text-neutral-tertiary")}>
{props.icon}
<div className="truncate">
{selectedValues.length > 0 ? (
<span className="truncate">
{selectedValues.length < maxCount ? (
<div className="truncate">
{renderComponents ? (
<div className="flex flex-wrap gap-2">
{selectedValues.map((f: string, idx: number) => (
<div key={f} className="flex items-center gap-0">
{optionByValue.get(f)?.label}
{idx < selectedValues.length - 1 && <span>, </span>}
</div>
))}
</div>
) : (
selectedSummaryText
)}
</div>
) : selectedValues.length === 1 ? (
`${selectedTitle} ${formatters.number(selectedValues.length)}`
) : selectedValues.length === options.length && selectedTitleAll ? (
selectedTitleAll
) : (
`${formatters.number(selectedValues.length)} ${selectedTitlePlural || "selected"}`
)}
</span>
) : (
<span className="text-text-neutral-tertiary text-sm">{placeholder}</span>
)}
</div>
</div>
<CaretSortIcon className="h-4 w-4 opacity-50" />
</div>
</Button>
</PopoverTrigger>
<PopoverContent className={cn("w-auto p-0")} align="start" onEscapeKeyDown={() => setIsPopoverOpen(false)}>
<Command>
<div className="relative">
<CommandInput
placeholder={i18nT("components.multiSelect.search", { value: formatters.number(options.length) })}
onKeyDown={handleInputKeyDown}
className="h-9 border-transparent focus-visible:shadow-none focus-visible:ring-offset-0 focus-visible:outline-none"
/>
{onSettingsClick && (
<div className="absolute top-1 right-2">
<Button type="button" variant="ghost" size="xs" onClick={onSettingsClick}>
<GearIcon className="size-4" />
</Button>
</div>
)}
</div>
<CommandList className={cn(popoverClassName, "max-h-full")}>
<CommandEmpty>{i18nT("components.multiSelect.noResults")}</CommandEmpty>
<CommandGroup className="max-h-[200px] overflow-y-auto sm:max-h-[300px]">
<CommandItem key="all" onSelect={toggleAll} className="cursor-pointer gap-2 rounded-sm px-2 py-2">
<div
className={cn(
// Subframe MultiSelect.Item checkbox: h-4 w-4, rounded-sm, border-2.
"border-brand-brand-surface-solid-default mr-2 flex h-4 w-4 items-center justify-center rounded-sm border-2",
selectedValues.length === options.length ? "bg-brand-brand-surface-solid-default text-text-neutral-on-solid" : "opacity-50 [&_svg]:invisible"
)}
>
<CheckIcon className="h-4 w-4" />
</div>
<span>{t("shared.selectAll")}</span>
</CommandItem>
{options.map((option) => {
const isSelected = selectedValueSet.has(option.value);
return (
<CommandItem key={option.value} onSelect={() => toggleOption(option.value)} className="cursor-pointer gap-2 rounded-sm px-2 py-2">
<div
className={cn(
// Subframe MultiSelect.Item checkbox: h-4 w-4, rounded-sm, border-2.
"border-brand-brand-surface-solid-default mr-2 flex h-4 w-4 items-center justify-center rounded-sm border-2",
isSelected ? "bg-brand-brand-surface-solid-default text-text-neutral-on-solid" : "opacity-50 [&_svg]:invisible"
)}
>
<CheckIcon className="h-4 w-4" />
</div>
{option.icon && <option.icon className="text-text-neutral-tertiary mr-2 h-4 w-4" />}
<span>{option.label}</span>
</CommandItem>
);
})}
</CommandGroup>
<CommandSeparator />
<CommandGroup>
<div className="flex items-center justify-between">
{selectedValues.length > 0 && (
<>
<CommandItem onSelect={handleClear} className="flex-1 cursor-pointer justify-center">
{t("shared.clear")}
</CommandItem>
<Separator orientation="vertical" className="flex h-full min-h-6" />
</>
)}
<CommandItem onSelect={() => setIsPopoverOpen(false)} className="max-w-full flex-1 cursor-pointer justify-center">
{t("shared.close")}
</CommandItem>
</div>
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
{/* {animation > 0 && selectedValues.length > 0 && (
<WandSparkles
className={cn("text-foreground bg-background my-2 h-3 w-3 cursor-pointer", isAnimating ? "" : "text-muted-foreground")}
onClick={() => setIsAnimating(!isAnimating)}
/>
)} */}
</Popover>
);
}
);
MultiSelect.displayName = "MultiSelect";