Files
2026-09-28 12:00:59 +05:30

328 lines
10 KiB
TypeScript

"use client"
import * as React from "react"
import { Select as SelectPrimitive } from "@base-ui/react/select"
import { cn } from "@/lib/utils"
import { HugeiconsIcon } from "@hugeicons/react"
import { UnfoldMoreIcon, Tick02Icon, ArrowUp01Icon, ArrowDown01Icon, Search01Icon } from "@hugeicons/core-free-icons"
const SEARCH_THRESHOLD = 7
function collectSelectItems(children: React.ReactNode): Array<{ value: unknown; label: string }> {
const items: Array<{ value: unknown; label: string }> = []
React.Children.forEach(children, (child) => {
if (!React.isValidElement<{ value?: unknown; label?: string; children?: React.ReactNode }>(child)) {
return
}
if ("value" in child.props) {
items.push({
value: child.props.value ?? null,
label: child.props.label ?? getItemLabel(child.props.children) ?? String(child.props.value ?? ""),
})
}
if (child.props.children) {
items.push(...collectSelectItems(child.props.children))
}
})
return items
}
function Select<Value, Multiple extends boolean | undefined = false>({
children,
items,
...props
}: SelectPrimitive.Root.Props<Value, Multiple>) {
const derivedItems = React.useMemo(
() => (items == null ? collectSelectItems(children) : items),
[children, items]
)
return (
<SelectPrimitive.Root {...props} items={derivedItems}>
{children}
</SelectPrimitive.Root>
)
}
function getItemLabel(children: React.ReactNode): string | undefined {
if (typeof children === "string" || typeof children === "number") {
return String(children)
}
if (Array.isArray(children)) {
const parts = children
.map(getItemLabel)
.filter((part): part is string => Boolean(part))
return parts.length > 0 ? parts.join(" ") : undefined
}
if (React.isValidElement<{ children?: React.ReactNode }>(children)) {
return getItemLabel(children.props.children)
}
return undefined
}
function filterSelectChildren(children: React.ReactNode, query: string): React.ReactNode {
const normalizedQuery = query.trim().toLowerCase()
if (!normalizedQuery) return children
const filtered = React.Children.map(children, (child) => {
if (!React.isValidElement<{ value?: unknown; label?: string; children?: React.ReactNode }>(child)) {
return child
}
if ("value" in child.props) {
const label = child.props.label ?? getItemLabel(child.props.children) ?? ""
return label.toLowerCase().includes(normalizedQuery) ? child : null
}
if (child.props.children) {
const filteredChildren = filterSelectChildren(child.props.children, query)
if (React.Children.count(filteredChildren) === 0) return null
return React.cloneElement(child, undefined, filteredChildren)
}
return child
})
return filtered
}
function SelectSearchInput({
query,
onQueryChange,
}: {
query: string
onQueryChange: (value: string) => void
}) {
return (
<div
data-slot="select-search"
className="sticky top-0 z-10 flex items-center gap-1.5 rounded-t-2xl border-b border-border/50 bg-popover px-2.5 py-1.5"
>
<HugeiconsIcon icon={Search01Icon} strokeWidth={2} className="size-3.5 shrink-0 text-muted-foreground" />
<input
autoFocus
value={query}
onChange={(event) => onQueryChange(event.target.value)}
onKeyDown={(event) => event.stopPropagation()}
placeholder="Search..."
className="w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground"
/>
</div>
)
}
function SelectGroup({ className, ...props }: SelectPrimitive.Group.Props) {
return (
<SelectPrimitive.Group
data-slot="select-group"
className={cn("scroll-my-1.5 p-1", className)}
{...props}
/>
)
}
function SelectValue({ className, ...props }: SelectPrimitive.Value.Props) {
return (
<SelectPrimitive.Value
data-slot="select-value"
className={cn("flex flex-1 text-left", className)}
{...props}
/>
)
}
function SelectTrigger({
className,
size = "default",
children,
...props
}: SelectPrimitive.Trigger.Props & {
size?: "sm" | "default"
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"flex w-fit items-center justify-between gap-1.5 rounded-2xl border border-transparent bg-input/50 px-3 py-2 text-sm whitespace-nowrap transition-[color,box-shadow] duration-200 outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/30 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon
render={
<HugeiconsIcon icon={UnfoldMoreIcon} strokeWidth={2} className="pointer-events-none size-4 text-muted-foreground" />
}
/>
</SelectPrimitive.Trigger>
)
}
function SelectContent({
className,
children,
side = "bottom",
sideOffset = 4,
align = "center",
alignOffset = 0,
alignItemWithTrigger = false,
collisionAvoidance = { side: "shift", align: "shift", fallbackAxisSide: "none" },
...props
}: SelectPrimitive.Popup.Props &
Pick<
SelectPrimitive.Positioner.Props,
"align" | "alignOffset" | "side" | "sideOffset" | "alignItemWithTrigger" | "collisionAvoidance"
>) {
const [query, setQuery] = React.useState("")
const itemCount = React.useMemo(() => collectSelectItems(children).length, [children])
const showSearch = itemCount > SEARCH_THRESHOLD
const filteredChildren = showSearch ? filterSelectChildren(children, query) : children
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Positioner
side={side}
sideOffset={sideOffset}
align={align}
alignOffset={alignOffset}
alignItemWithTrigger={alignItemWithTrigger}
collisionAvoidance={collisionAvoidance}
className="isolate z-50"
>
<SelectPrimitive.Popup
data-slot="select-content"
data-align-trigger={alignItemWithTrigger}
className={cn("relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-2xl bg-popover text-popover-foreground shadow-lg ring-1 ring-foreground/5 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:ring-foreground/10 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
{...props}
>
{showSearch && <SelectSearchInput query={query} onQueryChange={setQuery} />}
<SelectScrollUpButton />
<SelectPrimitive.List>
{React.Children.count(filteredChildren) === 0 ? (
<div className="px-2.5 py-2 text-sm text-muted-foreground">No results found.</div>
) : (
filteredChildren
)}
</SelectPrimitive.List>
<SelectScrollDownButton />
</SelectPrimitive.Popup>
</SelectPrimitive.Positioner>
</SelectPrimitive.Portal>
)
}
function SelectLabel({
className,
...props
}: SelectPrimitive.GroupLabel.Props) {
return (
<SelectPrimitive.GroupLabel
data-slot="select-label"
className={cn("px-2 py-1 text-xs text-muted-foreground", className)}
{...props}
/>
)
}
function SelectItem({
className,
children,
...props
}: SelectPrimitive.Item.Props) {
const label = props.label ?? getItemLabel(children)
return (
<SelectPrimitive.Item
{...props}
data-slot="select-item"
label={label}
className={cn(
"relative flex min-h-7 w-full items-center gap-2 rounded-xl py-1.5 pr-8 pl-2 text-sm text-popover-foreground outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
>
<SelectPrimitive.ItemIndicator
render={
<span className="pointer-events-none flex size-4 shrink-0 items-center justify-center" />
}
>
<HugeiconsIcon icon={Tick02Icon} strokeWidth={2} className="pointer-events-none" />
</SelectPrimitive.ItemIndicator>
<SelectPrimitive.ItemText className="block flex-1 whitespace-nowrap text-popover-foreground">
{children}
</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
)
}
function SelectSeparator({
className,
...props
}: SelectPrimitive.Separator.Props) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpArrow>) {
return (
<SelectPrimitive.ScrollUpArrow
data-slot="select-scroll-up-button"
className={cn(
"top-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<HugeiconsIcon icon={ArrowUp01Icon} strokeWidth={2} />
</SelectPrimitive.ScrollUpArrow>
)
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownArrow>) {
return (
<SelectPrimitive.ScrollDownArrow
data-slot="select-scroll-down-button"
className={cn(
"bottom-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<HugeiconsIcon icon={ArrowDown01Icon} strokeWidth={2} />
</SelectPrimitive.ScrollDownArrow>
)
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
}