Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

BranchPicker.tsx

235 lines8.2 KB

1import { useLegendListRef } from "~/hooks/useLegendListRef";
2import type { VcsRef } from "@t3tools/contracts";
3import { LegendList, type LegendListRef } from "@legendapp/list/react";
4import { useId, useRef, useState, type ComponentProps, type ReactNode } from "react";
5​
6import { MiddleTruncate } from "./ui/middle-truncate";
7import { cn } from "../lib/utils";
8import { RefreshIcon } from "./ui/refresh-icon";
9import { Switch } from "./ui/switch";
10import { getVirtualizedScrollFadeClassName } from "./ui/scroll-area";
11import {
12 Combobox,
13 ComboboxEmpty,
14 ComboboxSearchInput,
15 ComboboxItem,
16 ComboboxListVirtualized,
17 ComboboxPopup,
18 ComboboxStatus,
19} from "./ui/combobox";
20import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
21​
22export function BranchPicker({
23 items,
24 filteredItems,
25 value,
26 query,
27 onQueryChange,
28 open,
29 onOpenChange,
30 onSelectItem,
31 hasNextPage,
32 isFetchingNextPage,
33 onLoadNext,
34 statusText,
35 originControl,
36 popupProps,
37 renderItem,
38 getItemType,
39 children,
40}: {
41 items: string[];
42 filteredItems: string[];
43 value: string | null;
44 query: string;
45 onQueryChange: (value: string) => void;
46 open: boolean;
47 onOpenChange: (open: boolean) => void;
48 onSelectItem: (value: string) => void;
49 hasNextPage: boolean;
50 isFetchingNextPage: boolean;
51 onLoadNext: () => void;
52 statusText: string | null;
53 originControl?: { checked: boolean; onCheckedChange: (checked: boolean) => void } | undefined;
54 popupProps: Omit<ComponentProps<typeof ComboboxPopup>, "children">;
55 renderItem: (value: string, index: number) => ReactNode;
56 getItemType?: ((value: string) => string) | undefined;
57 children: ReactNode;
58}) {
59 const highlightedValueRef = useRef<string | null>(null);
60 const startFromOriginSwitchId = useId();
61 const handleOpenChange = (nextOpen: boolean) => {
62 if (!nextOpen) highlightedValueRef.current = null;
63 onOpenChange(nextOpen);
64 };
65 const [showTopBranchScrollFade, setShowTopBranchScrollFade] = useState(false);
66 const [showBottomBranchScrollFade, setShowBottomBranchScrollFade] = useState(false);
67 const fetchNextBranchPage = () => {
68 if (!hasNextPage || isFetchingNextPage) {
69 return;
70 }
71​
72 onLoadNext();
73 };
74 const branchListRef = useRef<LegendListRef | null>(null);
75 const updateBranchListScrollFades = () => {
76 const metrics = branchListRef.current?.getState();
77 if (!metrics) return;
78 setShowTopBranchScrollFade(!metrics.isAtStart);
79 setShowBottomBranchScrollFade(!metrics.isAtEnd);
80 };
81 const branchScrollRef = useLegendListRef(branchListRef, updateBranchListScrollFades);
82​
83 return (
84 <Combobox
85 items={items}
86 filteredItems={filteredItems}
87 autoHighlight
88 virtualized
89 onItemHighlighted={(value, eventDetails) => {
90 highlightedValueRef.current = typeof value === "string" ? value : null;
91 if (!open || eventDetails.index < 0 || eventDetails.reason !== "keyboard") {
92 return;
93 }
94 void branchListRef.current?.scrollIndexIntoView?.({
95 index: eventDetails.index,
96 animated: false,
97 });
98 }}
99 onOpenChange={handleOpenChange}
100 open={open}
101 value={value}
102 >
103 {children}
104 <ComboboxPopup {...popupProps}>
105 <ComboboxSearchInput
106 placeholder="Search refs..."
107 value={query}
108 onChange={(event) => {
109 onQueryChange(event.target.value);
110 void branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
111 }}
112 onKeyDown={(event) => {
113 if (event.key !== "Enter" || event.nativeEvent.isComposing || event.keyCode === 229)
114 return;
115 const highlightedValue = highlightedValueRef.current;
116 if (highlightedValue === null || !filteredItems.includes(highlightedValue)) return;
117 (
118 event as typeof event & { preventBaseUIHandler?: () => void }
119 ).preventBaseUIHandler?.();
120 event.preventDefault();
121 event.stopPropagation();
122 highlightedValueRef.current = null;
123 onSelectItem(highlightedValue);
124 }}
125 />
126 <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
127 <ComboboxEmpty>No refs found.</ComboboxEmpty>
128 <div className="relative flex min-h-0 w-full max-h-56 flex-1 flex-col overflow-hidden">
129 <ComboboxListVirtualized className="flex size-full min-h-0 min-w-0 flex-col">
130 <LegendList<string>
131 ref={branchScrollRef}
132 data={filteredItems}
133 initialScrollOffset={0}
134 keyExtractor={(item) => item}
135 {...(getItemType ? { getItemType } : {})}
136 renderItem={({ item, index }) => renderItem(item, index)}
137 estimatedItemSize={28}
138 drawDistance={336}
139 onScroll={updateBranchListScrollFades}
140 onLayout={updateBranchListScrollFades}
141 onReady={updateBranchListScrollFades}
142 onEndReached={fetchNextBranchPage}
143 onEndReachedThreshold={0.5}
144 className={cn(
145 "min-h-0 max-h-56 scrollbar-gutter-stable overflow-x-hidden overscroll-y-contain ps-1 pe-0 py-2",
146 getVirtualizedScrollFadeClassName({
147 top: showTopBranchScrollFade,
148 bottom: showBottomBranchScrollFade,
149 }),
150 )}
151 />
152 </ComboboxListVirtualized>
153 </div>
154 {originControl ? (
155 <Tooltip>
156 <TooltipTrigger
157 render={
158 <label
159 htmlFor={startFromOriginSwitchId}
160 className="flex cursor-pointer items-center justify-between gap-3 border-t border-border/60 px-3 py-2 text-xs"
161 >
162 <span className="flex min-w-0 items-center gap-1.5 font-medium text-muted-foreground">
163 <RefreshIcon aria-hidden="true" className="size-3 shrink-0" />
164 <span className="truncate">Start from remote</span>
165 </span>
166 <Switch
167 id={startFromOriginSwitchId}
168 checked={originControl.checked}
169 size="sm"
170 aria-label="Start worktree from remote"
171 onCheckedChange={(checked) => originControl.onCheckedChange(Boolean(checked))}
172 />
173 </label>
174 }
175 />
176 <TooltipPopup side="top" className="max-w-72 whitespace-normal">
177 Uses the latest commit of the base branch’s tracked remote branch, even if its name
178 differs. Otherwise uses the same-named branch on origin. Uses your local branch if
179 that remote branch is missing.
180 </TooltipPopup>
181 </Tooltip>
182 ) : null}
183 {statusText ? <ComboboxStatus>{statusText}</ComboboxStatus> : null}
184 </div>
185 </ComboboxPopup>
186 </Combobox>
187 );
189​
190export function BranchPickerRefItem({
191 branch: refName,
192 projectCwd: activeProjectCwd,
193 index,
194 value,
195 disabled,
196 onClick,
197 onContextMenu,
198}: {
199 branch: VcsRef;
200 projectCwd: string | null;
201 index: number;
202 value?: string;
203 disabled?: boolean;
204 onClick: ComponentProps<typeof ComboboxItem>["onClick"];
205 onContextMenu?: ComponentProps<typeof ComboboxItem>["onContextMenu"];
206}) {
207 const itemValue = refName.name;
208 const hasSecondaryWorktree =
209 refName.worktreePath && activeProjectCwd && refName.worktreePath !== activeProjectCwd;
210 const badge = refName.current
211 ? "current"
212 : hasSecondaryWorktree
213 ? "worktree"
214 : refName.isRemote
215 ? "remote"
216 : refName.isDefault
217 ? "default"
218 : null;
219 return (
220 <ComboboxItem
221 disabled={disabled}
222 hideIndicator
223 key={itemValue}
224 index={index}
225 value={value ?? itemValue}
226 onClick={onClick}
227 onContextMenu={onContextMenu}
228 >
229 <div className="flex w-full min-w-0 items-center justify-between gap-2">
230 <MiddleTruncate value={itemValue} className="flex-1" />
231 {badge && <span className="shrink-0 text-3xs text-muted-foreground/45">{badge}</span>}
232 </div>
233 </ComboboxItem>
234 );