|
| 1 | +import { useState } from "react" |
| 2 | +import type { Meta, StoryObj } from "@storybook/react" |
| 3 | +import { CaretSortIcon, CheckIcon } from "@radix-ui/react-icons" |
| 4 | + |
| 5 | +import { cn } from "@/lib/utils" |
| 6 | +import { |
| 7 | + Button, |
| 8 | + Command, |
| 9 | + CommandEmpty, |
| 10 | + CommandGroup, |
| 11 | + CommandInput, |
| 12 | + CommandItem, |
| 13 | + CommandList, |
| 14 | + Popover, |
| 15 | + PopoverContent, |
| 16 | + PopoverTrigger, |
| 17 | +} from "@/components/ui" |
| 18 | + |
| 19 | +const meta = { |
| 20 | + title: "@shadcn/Combobox", |
| 21 | + component: Combobox, |
| 22 | + parameters: { layout: "centered" }, |
| 23 | + tags: ["autodocs"], |
| 24 | +} satisfies Meta<typeof Combobox> |
| 25 | + |
| 26 | +export default meta |
| 27 | + |
| 28 | +type Story = StoryObj<typeof meta> |
| 29 | + |
| 30 | +export const Default: Story = { |
| 31 | + name: "Combobox", |
| 32 | + render: () => <Combobox />, |
| 33 | +} |
| 34 | + |
| 35 | +const frameworks = [ |
| 36 | + { |
| 37 | + value: "next.js", |
| 38 | + label: "Next.js", |
| 39 | + }, |
| 40 | + { |
| 41 | + value: "sveltekit", |
| 42 | + label: "SvelteKit", |
| 43 | + }, |
| 44 | + { |
| 45 | + value: "nuxt.js", |
| 46 | + label: "Nuxt.js", |
| 47 | + }, |
| 48 | + { |
| 49 | + value: "remix", |
| 50 | + label: "Remix", |
| 51 | + }, |
| 52 | + { |
| 53 | + value: "astro", |
| 54 | + label: "Astro", |
| 55 | + }, |
| 56 | +] |
| 57 | + |
| 58 | +function Combobox() { |
| 59 | + const [open, setOpen] = useState(false) |
| 60 | + const [value, setValue] = useState("") |
| 61 | + |
| 62 | + return ( |
| 63 | + <Popover open={open} onOpenChange={setOpen}> |
| 64 | + <PopoverTrigger asChild> |
| 65 | + <Button variant="secondary" role="combobox" aria-expanded={open} className="w-[200px] justify-between"> |
| 66 | + {value ? frameworks.find((framework) => framework.value === value)?.label : "Select framework..."} |
| 67 | + <CaretSortIcon className="opacity-50" /> |
| 68 | + </Button> |
| 69 | + </PopoverTrigger> |
| 70 | + <PopoverContent className="w-[200px] p-0"> |
| 71 | + <Command> |
| 72 | + <CommandInput placeholder="Search framework..." className="h-9" /> |
| 73 | + <CommandList> |
| 74 | + <CommandEmpty>No framework found.</CommandEmpty> |
| 75 | + <CommandGroup> |
| 76 | + {frameworks.map((framework) => ( |
| 77 | + <CommandItem |
| 78 | + key={framework.value} |
| 79 | + value={framework.value} |
| 80 | + onSelect={(currentValue) => { |
| 81 | + setValue(currentValue === value ? "" : currentValue) |
| 82 | + setOpen(false) |
| 83 | + }}> |
| 84 | + {framework.label} |
| 85 | + <CheckIcon |
| 86 | + className={cn( |
| 87 | + "ml-auto", |
| 88 | + value === framework.value ? "opacity-100" : "opacity-0", |
| 89 | + )} |
| 90 | + /> |
| 91 | + </CommandItem> |
| 92 | + ))} |
| 93 | + </CommandGroup> |
| 94 | + </CommandList> |
| 95 | + </Command> |
| 96 | + </PopoverContent> |
| 97 | + </Popover> |
| 98 | + ) |
| 99 | +} |
0 commit comments