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

BranchPicker.tsx

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