Open History to see the last commit
1import type { VcsRef } from "@t3tools/contracts";
2import { LegendList, type LegendListRef } from "@legendapp/list/react";
3import {
4 useEffect,
5 useId,
6 useLayoutEffect,
7 useRef,
8 useState,
9 type ComponentProps,
10 type ReactNode,
11} from "react";
12
13import { MiddleTruncate } from "./ui/middle-truncate";
14import { cn } from "../lib/utils";
15import { shouldLoadNextBranchPageAfterScroll } from "../state/paginatedBranches";
16import { RefreshIcon } from "./ui/refresh-icon";
17import { Switch } from "./ui/switch";
18import { getVirtualizedScrollFadeClassName } from "./ui/scroll-area";
19import {
20 Combobox,
21 ComboboxEmpty,
22 ComboboxSearchInput,
23 ComboboxItem,
24 ComboboxListVirtualized,
25 ComboboxPopup,
26 ComboboxStatus,
27} from "./ui/combobox";
28import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
29
30export function BranchPicker({
31 items,
32 filteredItems,
33 value,
34 query,
35 resultsQuery,
36 onQueryChange,
37 open,
38 onOpenChange,
39 onSelectItem,
40 hasNextPage,
41 isFetchingNextPage,
42 onLoadNext,
43 statusText,
44 originControl,
45 popupProps,
46 renderItem,
47 getItemType,
48 children,
49}: {
50 items: string[];
51 filteredItems: string[];
52 value: string | null;
53 query: string;
54 resultsQuery: string;
55 onQueryChange: (value: string) => void;
56 open: boolean;
57 onOpenChange: (open: boolean) => void;
58 onSelectItem: (value: string) => void;
59 hasNextPage: boolean;
60 isFetchingNextPage: boolean;
61 onLoadNext: () => void;
62 statusText: string | null;
63 originControl?: { checked: boolean; onCheckedChange: (checked: boolean) => void } | undefined;
64 popupProps: Omit<ComponentProps<typeof ComboboxPopup>, "children">;
65 renderItem: (value: string, index: number) => ReactNode;
66 getItemType?: ((value: string) => string) | undefined;
67 children: ReactNode;
68}) {
69 const highlightedValueRef = useRef<string | null>(null);
70 const startFromOriginSwitchId = useId();
71 const branchListScrollElementRef = useRef<HTMLElement | null>(null);
72 const previousBranchListScrollTopRef = useRef<number | null>(null);
73 const handleOpenChange = (nextOpen: boolean) => {
74 previousBranchListScrollTopRef.current = null;
75 if (!nextOpen) highlightedValueRef.current = null;
76 onOpenChange(nextOpen);
77 };
78 const [showTopBranchScrollFade, setShowTopBranchScrollFade] = useState(false);
79 const [showBottomBranchScrollFade, setShowBottomBranchScrollFade] = useState(false);
80 const fetchNextBranchPage = () => {
81 if (!hasNextPage || isFetchingNextPage) {
82 return;
83 }
84
85 onLoadNext();
86 };
87 const maybeFetchNextBranchPage = () => {
88 const scrollElement = branchListScrollElementRef.current;
89 if (!scrollElement) {
90 return;
91 }
92
93 const previousScrollTop = previousBranchListScrollTopRef.current;
94 previousBranchListScrollTopRef.current = scrollElement.scrollTop;
95 if (
96 !open ||
97 !hasNextPage ||
98 isFetchingNextPage ||
99 !shouldLoadNextBranchPageAfterScroll({
100 previousScrollTop,
101 scrollTop: scrollElement.scrollTop,
102 scrollHeight: scrollElement.scrollHeight,
103 clientHeight: scrollElement.clientHeight,
104 })
105 ) {
106 return;
107 }
108
109 fetchNextBranchPage();
110 };
111
112 const branchListRef = useRef<LegendListRef | null>(null);
113 const updateBranchListScrollFades = () => {
114 const scrollElement = branchListRef.current?.getScrollableNode?.();
115 if (!(scrollElement instanceof HTMLElement)) {
116 return;
117 }
118 branchListScrollElementRef.current = scrollElement;
119 const maxScrollOffset = Math.max(0, scrollElement.scrollHeight - scrollElement.clientHeight);
120 setShowTopBranchScrollFade(scrollElement.scrollTop > 1);
121 setShowBottomBranchScrollFade(maxScrollOffset - scrollElement.scrollTop > 1);
122 };
123
124 useLayoutEffect(() => {
125 if (!open) {
126 return;
127 }
128
129 let nestedFrame = 0;
130 const frame = requestAnimationFrame(() => {
131 updateBranchListScrollFades();
132 nestedFrame = requestAnimationFrame(updateBranchListScrollFades);
133 });
134 return () => {
135 cancelAnimationFrame(frame);
136 cancelAnimationFrame(nestedFrame);
137 };
138 }, [open, updateBranchListScrollFades]);
139
140 const previousResultsQuery = useRef<string | null>(null);
141 useEffect(() => {
142 if (!open) {
143 previousResultsQuery.current = null;
144 return;
145 }
146 if (previousResultsQuery.current === resultsQuery) return;
147 previousResultsQuery.current = resultsQuery;
148 void branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
149 }, [resultsQuery, open]);
150
151 return (
152 <Combobox
153 items={items}
154 filteredItems={filteredItems}
155 autoHighlight
156 virtualized
157 onItemHighlighted={(value, eventDetails) => {
158 highlightedValueRef.current = typeof value === "string" ? value : null;
159 if (!open || eventDetails.index < 0 || eventDetails.reason !== "keyboard") {
160 return;
161 }
162 void branchListRef.current?.scrollIndexIntoView?.({
163 index: eventDetails.index,
164 animated: false,
165 });
166 }}
167 onOpenChange={handleOpenChange}
168 open={open}
169 value={value}
170 >
171 {children}
172 <ComboboxPopup {...popupProps}>
173 <ComboboxSearchInput
174 placeholder="Search refs..."
175 value={query}
176 onChange={(event) => onQueryChange(event.target.value)}
177 onKeyDown={(event) => {
178 if (event.key !== "Enter" || event.nativeEvent.isComposing || event.keyCode === 229)
179 return;
180 const highlightedValue = highlightedValueRef.current;
181 if (highlightedValue === null || !filteredItems.includes(highlightedValue)) return;
182 (
183 event as typeof event & { preventBaseUIHandler?: () => void }
184 ).preventBaseUIHandler?.();
185 event.preventDefault();
186 event.stopPropagation();
187 highlightedValueRef.current = null;
188 onSelectItem(highlightedValue);
189 }}
190 />
191 <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
192 <ComboboxEmpty>No refs found.</ComboboxEmpty>
193 <div className="relative flex min-h-0 w-full max-h-56 flex-1 flex-col overflow-hidden">
194 <ComboboxListVirtualized className="flex size-full min-h-0 min-w-0 flex-col">
195 <LegendList<string>
196 ref={branchListRef}
197 data={filteredItems}
198 keyExtractor={(item) => item}
199 {...(getItemType ? { getItemType } : {})}
200 renderItem={({ item, index }) => renderItem(item, index)}
201 estimatedItemSize={28}
202 drawDistance={336}
203 onLayout={() => {
204 updateBranchListScrollFades();
205 previousBranchListScrollTopRef.current =
206 branchListScrollElementRef.current?.scrollTop ?? null;
207 }}
208 onScroll={() => {
209 updateBranchListScrollFades();
210 maybeFetchNextBranchPage();
211 }}
212 className={cn(
213 "min-h-0 max-h-56 scrollbar-gutter-stable overflow-x-hidden overscroll-y-contain ps-1 pe-0 py-2",
214 getVirtualizedScrollFadeClassName({
215 top: showTopBranchScrollFade,
216 bottom: showBottomBranchScrollFade,
217 }),
218 )}
219 />
220 </ComboboxListVirtualized>
221 </div>
222 {originControl ? (
223 <Tooltip>
224 <TooltipTrigger
225 render={
226 <label
227 htmlFor={startFromOriginSwitchId}
228 className="flex cursor-pointer items-center justify-between gap-3 border-t border-border/60 px-3 py-2 text-xs"
229 >
230 <span className="flex min-w-0 items-center gap-1.5 font-medium text-muted-foreground">
231 <RefreshIcon aria-hidden="true" className="size-3 shrink-0" />
232 <span className="truncate">Start from origin</span>
233 </span>
234 <Switch
235 id={startFromOriginSwitchId}
236 checked={originControl.checked}
237 size="sm"
238 aria-label="Start worktree from origin"
239 onCheckedChange={(checked) => originControl.onCheckedChange(Boolean(checked))}
240 />
241 </label>
242 }
243 />
244 <TooltipPopup side="top" className="max-w-72 whitespace-normal">
245 Creates the worktree from the latest matching branch on origin instead of your local
246 branch.
247 </TooltipPopup>
248 </Tooltip>
249 ) : null}
250 {statusText ? <ComboboxStatus>{statusText}</ComboboxStatus> : null}
251 </div>
252 </ComboboxPopup>
253 </Combobox>
254 );
255}
256
257export function BranchPickerRefItem({
258 branch: refName,
259 projectCwd: activeProjectCwd,
260 index,
261 value,
262 disabled,
263 onClick,
264 onContextMenu,
265}: {
266 branch: VcsRef;
267 projectCwd: string | null;
268 index: number;
269 value?: string;
270 disabled?: boolean;
271 onClick: ComponentProps<typeof ComboboxItem>["onClick"];
272 onContextMenu?: ComponentProps<typeof ComboboxItem>["onContextMenu"];
273}) {
274 const itemValue = refName.name;
275 const hasSecondaryWorktree =
276 refName.worktreePath && activeProjectCwd && refName.worktreePath !== activeProjectCwd;
277 const badge = refName.current
278 ? "current"
279 : hasSecondaryWorktree
280 ? "worktree"
281 : refName.isRemote
282 ? "remote"
283 : refName.isDefault
284 ? "default"
285 : null;
286 return (
287 <ComboboxItem
288 disabled={disabled}
289 hideIndicator
290 key={itemValue}
291 index={index}
292 value={value ?? itemValue}
293 onClick={onClick}
294 onContextMenu={onContextMenu}
295 >
296 <div className="flex w-full min-w-0 items-center justify-between gap-2">
297 <MiddleTruncate value={itemValue} className="flex-1" />
298 {badge && <span className="shrink-0 text-3xs text-muted-foreground/45">{badge}</span>}
299 </div>
300 </ComboboxItem>
301 );
302}