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

BranchPicker.tsx

306 lines10.1 KB

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