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

BranchPicker.tsx

287 lines10.0 KB

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