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

BranchPicker.tsx

303 lines10.0 KB

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 remote</span>
233 </span>
234 <Switch
235 id={startFromOriginSwitchId}
236 checked={originControl.checked}
237 size="sm"
238 aria-label="Start worktree from remote"
239 onCheckedChange={(checked) => originControl.onCheckedChange(Boolean(checked))}
240 />
241 </label>
242 }
243 />
244 <TooltipPopup side="top" className="max-w-72 whitespace-normal">
245 Uses the latest commit of the base branch’s tracked remote branch, even if its name
246 differs. Otherwise uses the same-named branch on origin. Uses your local branch if
247 that remote branch is missing.
248 </TooltipPopup>
249 </Tooltip>
250 ) : null}
251 {statusText ? <ComboboxStatus>{statusText}</ComboboxStatus> : null}
252 </div>
253 </ComboboxPopup>
254 </Combobox>
255 );
257​
258export function BranchPickerRefItem({
259 branch: refName,
260 projectCwd: activeProjectCwd,
261 index,
262 value,
263 disabled,
264 onClick,
265 onContextMenu,
266}: {
267 branch: VcsRef;
268 projectCwd: string | null;
269 index: number;
270 value?: string;
271 disabled?: boolean;
272 onClick: ComponentProps<typeof ComboboxItem>["onClick"];
273 onContextMenu?: ComponentProps<typeof ComboboxItem>["onContextMenu"];
274}) {
275 const itemValue = refName.name;
276 const hasSecondaryWorktree =
277 refName.worktreePath && activeProjectCwd && refName.worktreePath !== activeProjectCwd;
278 const badge = refName.current
279 ? "current"
280 : hasSecondaryWorktree
281 ? "worktree"
282 : refName.isRemote
283 ? "remote"
284 : refName.isDefault
285 ? "default"
286 : null;
287 return (
288 <ComboboxItem
289 disabled={disabled}
290 hideIndicator
291 key={itemValue}
292 index={index}
293 value={value ?? itemValue}
294 onClick={onClick}
295 onContextMenu={onContextMenu}
296 >
297 <div className="flex w-full min-w-0 items-center justify-between gap-2">
298 <MiddleTruncate value={itemValue} className="flex-1" />
299 {badge && <span className="shrink-0 text-3xs text-muted-foreground/45">{badge}</span>}
300 </div>
301 </ComboboxItem>
302 );