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

WorktreeBaseBranchPicker.tsx

175 lines5.8 KB

1import { trimAsciiWhitespace, type EnvironmentId } from "@t3tools/contracts";
2import type { AsyncResult } from "effect/reactivity";
3import { useGT, useMessages, plural, part } from "gt-react";
4import { ChevronDownIcon, GitBranchIcon } from "lucide-react";
5import { useEffect, useEffectEvent, useState } from "react";
6​
7import { usePaginatedBranches } from "../state/queries";
8import { useEnvironmentQuery, useEnvironmentQuerySelector } from "../state/query";
9import { useAtomCommand } from "../state/use-atom-command";
10import { vcsEnvironment } from "../state/vcs";
11import { BranchPicker, BranchPickerRefItem } from "./BranchPicker";
12import {
13 resolveBranchTriggerLabel,
14 sanitizeNewRefName,
15 shouldIncludeBranchPickerItem,
16} from "./BranchToolbar.logic";
17import { MiddleTruncate } from "./ui/middle-truncate";
18import { Button } from "./ui/button";
19import { ComboboxTrigger } from "./ui/combobox";
20​
21const hasStatusSnapshot = (result: AsyncResult.AsyncResult<unknown, unknown>) =>
22 result._tag !== "Initial";
23​
24export function WorktreeBaseBranchPicker({
25 environmentId,
26 cwd,
27 value,
28 onValueChange,
29 startFromOrigin,
30 onStartFromOriginChange,
31 disabled = false,
32 id,
33}: {
34 environmentId: EnvironmentId;
35 cwd: string | null;
36 value: string;
37 onValueChange: (branch: string) => void;
38 startFromOrigin: boolean;
39 onStartFromOriginChange: (checked: boolean) => void;
40 disabled?: boolean;
41 id?: string;
42}) {
43 const gt = useGT();
44 const messages = useMessages();
45 const [open, setOpen] = useState(false);
46 const [query, setQuery] = useState("");
47 if (disabled && open) {
48 setOpen(false);
49 setQuery("");
50 }
51 const refreshLocalStatusForPicker = useAtomCommand(vcsEnvironment.refreshLocalStatusForPicker, {
52 reportFailure: false,
53 });
54 // Status events carry the refs revision, so a fetch while the menu is open reloads its refs.
55 const statusReady = useEnvironmentQuerySelector(
56 open && cwd !== null ? vcsEnvironment.status({ environmentId, input: { cwd } }) : null,
57 hasStatusSnapshot,
58 );
59 const reconcileRefs = useEffectEvent(() => {
60 if (cwd !== null) void refreshLocalStatusForPicker({ environmentId, input: { cwd } });
61 });
62 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a fetch before the status stream's first snapshot becomes its baseline, so reconcile refs once that snapshot exists
63 useEffect(() => {
64 if (statusReady) reconcileRefs();
65 }, [statusReady]);
66 const branches = usePaginatedBranches(
67 {
68 environmentId,
69 cwd,
70 query: sanitizeNewRefName(query),
71 },
72 messages,
73 );
74 const selectedRefQuery = useEnvironmentQuery(
75 cwd && value
76 ? vcsEnvironment.listRefs({
77 environmentId,
78 input: { cwd, query: value, limit: 10 },
79 })
80 : null,
81 );
82 const selectedRef =
83 branches.refs.find((branch) => branch.name === value) ??
84 selectedRefQuery.data?.refs.find((branch) => branch.name === value);
85 const label = resolveBranchTriggerLabel(
86 {
87 activeWorktreePath: null,
88 effectiveEnvMode: "worktree",
89 resolvedActiveBranch: value || null,
90 resolvedActiveBranchIsRemote: selectedRef ? selectedRef.isRemote === true : null,
91 startFromOrigin,
92 },
93 messages,
94 );
95 const branchByName = new Map(branches.refs.map((branch) => [branch.name, branch]));
96 const items = [...branchByName.keys()];
97 const normalizedQuery = trimAsciiWhitespace(query).toLowerCase();
98 const filteredItems = items.filter((itemValue) =>
99 shouldIncludeBranchPickerItem({
100 itemValue,
101 normalizedQuery,
102 createBranchItemValue: null,
103 checkoutPullRequestItemValue: null,
104 }),
105 );
106 const hasNextPage = branches.data?.nextCursor != null;
107 const shown = branches.refs.length;
108 const total = branches.data?.totalCount ?? 0;
109 const statusText =
110 branches.error ??
111 (branches.isLoadingFirstPage
112 ? gt`Loading refs...`
113 : branches.isFetchingNextPage
114 ? gt`Loading more refs...`
115 : hasNextPage
116 ? gt`${plural(
117 { total },
118 {
119 one: part`Showing ${{ shown }} of ${{ total }} refs`,
120 other: part`Showing ${{ shown }} of ${{ total }} refs`,
121 },
122 )}`
123 : null);
124 const handleOpenChange = (next: boolean) => {
125 setOpen(next);
126 if (!next) setQuery("");
127 };
128 return (
129 <BranchPicker
130 items={items}
131 filteredItems={filteredItems}
132 value={value || null}
133 query={query}
134 onQueryChange={setQuery}
135 open={open}
136 onOpenChange={handleOpenChange}
137 onSelectItem={(name) => {
138 onValueChange(name);
139 handleOpenChange(false);
140 }}
141 hasNextPage={hasNextPage}
142 isFetchingNextPage={branches.isFetchingNextPage}
143 onLoadNext={branches.loadNext}
144 statusText={statusText}
145 isLoadingRefs={branches.isLoadingFirstPage}
146 originControl={{ checked: startFromOrigin, onCheckedChange: onStartFromOriginChange }}
147 popupProps={{ align: "start", side: "bottom", className: "flex w-80 flex-col" }}
148 renderItem={(name, index) => {
149 const branch = branchByName.get(name);
150 return branch ? (
151 <BranchPickerRefItem
152 branch={branch}
153 projectCwd={cwd}
154 index={index}
155 onClick={() => {
156 onValueChange(branch.name);
157 handleOpenChange(false);
158 }}
159 />
160 ) : null;
161 }}
162 >
163 <ComboboxTrigger
164 id={id}
165 disabled={disabled || !cwd}
166 render={<Button variant="outline" size="sm" />}
167 className="w-full justify-between "
168 >
169 <GitBranchIcon className="size-3.5 shrink-0 text-muted-foreground" />
170 <MiddleTruncate value={label} className="flex-1 text-left" />
171 <ChevronDownIcon className="size-3.5 shrink-0 text-muted-foreground" />
172 </ComboboxTrigger>
173 </BranchPicker>
174 );