| 1 | "use client"; |
| 2 | |
| 3 | import { useVirtualizer } from |
| 4 | import { useMemo, useState |
| 5 | |
| 6 | import { Button } |
| 7 | import { |
| 8 | Combobox, |
| 9 | ComboboxContent, |
| 10 | ComboboxEmpty, |
| 11 | ComboboxInput, |
| 12 | ComboboxItem, |
| 13 | ComboboxList, |
| 14 | ComboboxTrigger, |
| 15 | ComboboxValue, |
| 16 | } from "@/components/ui/combobox"; |
| 17 | import { cn } |
| 18 | |
| 19 | const ROW_HEIGHT = 32 |
| 20 | |
| 21 | /** A branch picker that stays fast with thousands of branches: the list is searched, and only the rows in view are rendered. */ |
| 22 | export function BranchSelect({ |
| 23 | branches, |
| 24 | value, |
| 25 | onValueChange, |
| 26 | placeholder = "Select a branch" |
| 27 | id, |
| 28 | className, |
| 29 | }: { |
| 30 | branches: string |
| 31 | value: string |
| 32 | onValueChange: (branch |
| 33 | placeholder?: string |
| 34 | id?: string |
| 35 | className?: string |
| 36 | }) { |
| 37 | const [query, |
| 38 | const [list, |
| 39 | |
| 40 | const matches = |
| 41 | const needle = |
| 42 | return needle |
| 43 | ? branches.filter( |
| 44 | : branches; |
| 45 | }, [branches, |
| 46 | |
| 47 | const virtualizer = |
| 48 | count: matches.length, |
| 49 | getScrollElement: () => |
| 50 | estimateSize: () => |
| 51 | overscan: 10, |
| 52 | }); |
| 53 | |
| 54 | return ( |
| 55 | <Combobox |
| 56 | items={matches} |
| 57 | // filtered above, so the virtualizer and the list agree on every index |
| 58 | filter={null} |
| 59 | virtualized |
| 60 | value={value || |
| 61 | onValueChange={(branch: |
| 62 | if (branch) onValueChange( |
| 63 | }} |
| 64 | inputValue={query} |
| 65 | onInputValueChange={setQuery} |
| 66 | onItemHighlighted={(_, |
| 67 | if (reason === " |
| 68 | }} |
| 69 | > |
| 70 | <ComboboxTrigger |
| 71 | id={id} |
| 72 | render={ |
| 73 | <Button |
| 74 | variant="outline" |
| 75 | className={cn(" |
| 76 | /> |
| 77 | } |
| 78 | > |
| 79 | <span className="truncate |
| 80 | <ComboboxValue placeholder={ |
| 81 | </span> |
| 82 | </ComboboxTrigger> |
| 83 | <ComboboxContent className=" |
| 84 | <ComboboxInput placeholder=" |
| 85 | <ComboboxEmpty>No branch matches</ComboboxEmpty |
| 86 | <ComboboxList ref={ |
| 87 | {matches.length > |
| 88 | <div |
| 89 | role="presentation" |
| 90 | className="relative w-full" |
| 91 | style={{ height: |
| 92 | > |
| 93 | {virtualizer.getVirtualItems(). |
| 94 | <ComboboxItem |
| 95 | key={row.key |
| 96 | index={row.index |
| 97 | value={matches[row |
| 98 | aria-setsize={matches.length |
| 99 | aria-posinset={row.index |
| 100 | className="absolute top-0 left-0" |
| 101 | style={{ |
| 102 | height: row.size |
| 103 | transform: `translateY(${row |
| 104 | }} |
| 105 | > |
| 106 | <span className="truncate |
| 107 | </ComboboxItem> |
| 108 | ))} |
| 109 | </div> |
| 110 | )} |
| 111 | </ComboboxList> |
| 112 | </ComboboxContent> |
| 113 | </Combobox> |
| 114 | ); |
| 115 | } |