feat: enhance OptionCombobox with open state management and close on selection

This commit is contained in:
mlogclub
2026-05-25 12:51:41 +08:00
parent 906a54cd3d
commit 680252598c
2 changed files with 14 additions and 5 deletions
@@ -1,6 +1,7 @@
"use client" "use client"
import { CheckIcon, ChevronsUpDownIcon } from "lucide-react" import { CheckIcon, ChevronsUpDownIcon } from "lucide-react"
import { useState } from "react"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { import {
@@ -44,11 +45,12 @@ export function OptionCombobox({
onChange, onChange,
}: OptionComboboxProps) { }: OptionComboboxProps) {
const t = useI18n() const t = useI18n()
const [open, setOpen] = useState(false)
const selectedLabel = const selectedLabel =
options.find((option) => option.value === value)?.label ?? placeholder options.find((option) => option.value === value)?.label ?? placeholder
return ( return (
<Popover> <Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger <PopoverTrigger
render={ render={
<Button <Button
@@ -72,7 +74,10 @@ export function OptionCombobox({
<CommandItem <CommandItem
key={option.value} key={option.value}
value={`${option.label} ${option.value}`} value={`${option.label} ${option.value}`}
onSelect={() => onChange(option.value)} onSelect={() => {
onChange(option.value)
setOpen(false)
}}
> >
<CheckIcon <CheckIcon
className={cn( className={cn(
+7 -3
View File
@@ -1,6 +1,6 @@
"use client" "use client"
import type { ReactNode } from "react" import { useState, type ReactNode } from "react"
import { CheckIcon, ChevronsUpDownIcon } from "lucide-react" import { CheckIcon, ChevronsUpDownIcon } from "lucide-react"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
@@ -47,11 +47,12 @@ export function OptionCombobox({
renderOptionAction, renderOptionAction,
}: OptionComboboxProps) { }: OptionComboboxProps) {
const t = useI18n() const t = useI18n()
const [open, setOpen] = useState(false)
const selectedLabel = const selectedLabel =
options.find((option) => option.value === value)?.label ?? placeholder options.find((option) => option.value === value)?.label ?? placeholder
return ( return (
<Popover> <Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger <PopoverTrigger
render={ render={
<Button <Button
@@ -75,7 +76,10 @@ export function OptionCombobox({
<CommandItem <CommandItem
key={option.value} key={option.value}
value={`${option.label} ${option.value}`} value={`${option.label} ${option.value}`}
onSelect={() => onChange(option.value)} onSelect={() => {
onChange(option.value)
setOpen(false)
}}
> >
<div className="flex min-w-0 flex-1 items-center justify-between gap-2"> <div className="flex min-w-0 flex-1 items-center justify-between gap-2">
<div className="flex min-w-0 items-center"> <div className="flex min-w-0 items-center">