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

BranchToolbar.logic.ts

323 lines10.9 KB

1import type { EnvironmentId, EnvironmentMachineKind, VcsRef, ProjectId } from "@t3tools/contracts";
2import * as Schema from "effect/Schema";
3import { toSortableTimestamp } from "../lib/threadSort";
4export {
5 dedupeRemoteBranchesWithLocalMatches,
6 deriveLocalBranchNameFromRemoteRef,
7} from "@t3tools/shared/git";
8​
9export interface EnvironmentOption {
10 environmentId: EnvironmentId;
11 projectId: ProjectId;
12 label: string;
13 isPrimary: boolean;
14 machine: EnvironmentMachineKind;
16​
17export const EnvMode = Schema.Literals(["local", "worktree"]);
18export type EnvMode = typeof EnvMode.Type;
19​
20const GENERIC_LOCAL_ENVIRONMENT_LABELS = new Set(["local", "local environment"]);
21​
22function normalizeDisplayLabel(value: string | null | undefined): string | null {
23 const trimmed = value?.trim();
24 return trimmed && trimmed.length > 0 ? trimmed : null;
26​
27export function resolveEnvironmentOptionLabel(input: {
28 isPrimary: boolean;
29 environmentId: EnvironmentId;
30 runtimeLabel?: string | null;
31 savedLabel?: string | null;
32}): string {
33 const runtimeLabel = normalizeDisplayLabel(input.runtimeLabel);
34 const savedLabel = normalizeDisplayLabel(input.savedLabel);
35​
36 if (input.isPrimary) {
37 const preferredLocalLabel = [runtimeLabel, savedLabel].find((label) => {
38 if (!label) return false;
39 return !GENERIC_LOCAL_ENVIRONMENT_LABELS.has(label.toLowerCase());
40 });
41 return preferredLocalLabel ?? "This device";
42 }
43​
44 return runtimeLabel ?? savedLabel ?? input.environmentId;
46​
47// A remote (non-primary) environment is always surfaced, even when it is the
48// only environment available: with a single connected machine there is nothing
49// to pick, but the user still needs to see where the project runs.
50export function shouldShowEnvironmentIndicator(input: {
51 activeEnvironment: Pick<EnvironmentOption, "isPrimary"> | null;
52 canPickEnvironment: boolean;
53}): boolean {
54 if (input.canPickEnvironment) return true;
55 return input.activeEnvironment !== null && !input.activeEnvironment.isPrimary;
57​
58export function shouldShowComposerContextStrip(input: {
59 isDraftHeroState: boolean;
60 persistInActiveThreads: boolean;
61 hasActiveProject: boolean;
62 isGitRepo: boolean;
63 showEnvironmentIndicator: boolean;
64 /** A collapsed composer's controls currently fit in their measured strip host. */
65 hostsRestingComposerControls: boolean;
66}): boolean {
67 return (
68 input.hasActiveProject &&
69 (input.isDraftHeroState || input.persistInActiveThreads) &&
70 (input.isGitRepo || input.showEnvironmentIndicator || input.hostsRestingComposerControls)
71 );
73​
74// Labels collapse to icons when the strip's content no longer fits. A small
75// hysteresis on the way back out keeps the boundary from flapping.
76const CONTEXT_STRIP_COMPACT_EXPAND_HYSTERESIS_PX = 16;
77​
78export function resolveContextStripLabelsCompact(input: {
79 compact: boolean;
80 neededWidth: number;
81 availableWidth: number;
82}): boolean {
83 return input.compact
84 ? input.neededWidth > input.availableWidth - CONTEXT_STRIP_COMPACT_EXPAND_HYSTERESIS_PX
85 : input.neededWidth > input.availableWidth;
87​
88export function resolveEnvModeLabel(mode: EnvMode): string {
89 return mode === "worktree" ? "New worktree" : "Current checkout";
91​
92export function resolveCurrentWorkspaceLabel(activeWorktreePath: string | null): string {
93 return activeWorktreePath ? "Current worktree" : resolveEnvModeLabel("local");
95​
96export function resolveLockedWorkspaceLabel(activeWorktreePath: string | null): string {
97 return activeWorktreePath ? "Worktree" : "Local checkout";
99​
100export function resolveWorkspaceDisplayName(path: string | null): string | null {
101 if (!path) return null;
102 const normalizedPath = path.replace(/[\\/]+$/, "");
103 if (normalizedPath.length === 0) return path;
104 return normalizedPath.split(/[\\/]/).at(-1) ?? normalizedPath;
106​
107export interface PreviousWorktreeSeed {
108 branch: string | null;
109 worktreePath: string;
111​
112// The most recently touched worktree in the project that the composer isn't
113// already pointing at. Backs the "Previous worktree" entry in the workspace
114// selector so a follow-up thread can hop back into the worktree you just
115// worked in without hunting for its branch. Archived threads don't compete —
116// the rest of the UI hides them, so their worktrees shouldn't resurface here.
117export function resolvePreviousWorktreeSeed(input: {
118 threads: ReadonlyArray<{
119 branch: string | null;
120 worktreePath: string | null;
121 updatedAt: string;
122 archivedAt?: string | null;
123 }>;
124 currentWorktreePath: string | null;
125}): PreviousWorktreeSeed | null {
126 let latest: { branch: string | null; worktreePath: string; updatedAt: number } | null = null;
127 for (const thread of input.threads) {
128 if (
129 !thread.worktreePath ||
130 thread.worktreePath === input.currentWorktreePath ||
131 (thread.archivedAt ?? null) !== null
132 ) {
133 continue;
134 }
135 const updatedAt = toSortableTimestamp(thread.updatedAt);
136 if (updatedAt === null) {
137 continue;
138 }
139 if (latest === null || updatedAt > latest.updatedAt) {
140 latest = {
141 branch: thread.branch,
142 worktreePath: thread.worktreePath,
143 updatedAt,
144 };
145 }
146 }
147 return latest === null ? null : { branch: latest.branch, worktreePath: latest.worktreePath };
149​
150export function resolvePreviousWorktreeLabel(seed: PreviousWorktreeSeed): string {
151 return seed.branch ? `Previous worktree (${seed.branch})` : "Previous worktree";
153​
154export function resolveEffectiveEnvMode(input: {
155 activeWorktreePath: string | null;
156 hasServerThread: boolean;
157 draftThreadEnvMode: EnvMode | undefined;
158}): EnvMode {
159 const { activeWorktreePath, hasServerThread, draftThreadEnvMode } = input;
160 if (!hasServerThread) {
161 if (activeWorktreePath) {
162 return "local";
163 }
164 return draftThreadEnvMode === "worktree" ? "worktree" : "local";
165 }
166 return activeWorktreePath ? "worktree" : "local";
168​
169export function resolveDraftEnvModeAfterBranchChange(input: {
170 nextWorktreePath: string | null;
171 currentWorktreePath: string | null;
172 effectiveEnvMode: EnvMode;
173}): EnvMode {
174 const { nextWorktreePath, currentWorktreePath, effectiveEnvMode } = input;
175 if (nextWorktreePath) {
176 return "worktree";
177 }
178 if (effectiveEnvMode === "worktree" && !currentWorktreePath) {
179 return "worktree";
180 }
181 return "local";
183​
184export function resolveBranchToolbarValue(input: {
185 envMode: EnvMode;
186 activeWorktreePath: string | null;
187 activeThreadBranch: string | null;
188 currentGitBranch: string | null;
189}): string | null {
190 const { envMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
191 if (envMode === "worktree" && !activeWorktreePath) {
192 return activeThreadBranch ?? currentGitBranch;
193 }
194 return currentGitBranch ?? activeThreadBranch;
196​
197export function resolveBranchTriggerLabel(input: {
198 activeWorktreePath: string | null;
199 effectiveEnvMode: EnvMode;
200 resolvedActiveBranch: string | null;
201 resolvedActiveBranchIsRemote: boolean | null;
202 startFromOrigin: boolean;
203}): string {
204 const {
205 activeWorktreePath,
206 effectiveEnvMode,
207 resolvedActiveBranch,
208 resolvedActiveBranchIsRemote,
209 startFromOrigin,
210 } = input;
211 if (!resolvedActiveBranch) {
212 return "Select ref";
213 }
214 if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
215 const baseRef =
216 startFromOrigin && resolvedActiveBranchIsRemote === false
217 ? `origin/${resolvedActiveBranch}`
218 : resolvedActiveBranch;
219 return `From ${baseRef}`;
220 }
221 return resolvedActiveBranch;
223​
224export function resolveBranchToolbarPrBranch(input: {
225 activeThreadBranch: string | null;
226 resolvedActiveBranch: string | null;
227}): string | null {
228 return input.activeThreadBranch === input.resolvedActiveBranch ? input.activeThreadBranch : null;
230​
231export function resolveLocalCheckoutBranchMismatch(input: {
232 effectiveEnvMode: EnvMode;
233 activeWorktreePath: string | null;
234 activeThreadBranch: string | null;
235 currentGitBranch: string | null;
236}): { threadBranch: string; currentBranch: string } | null {
237 const { effectiveEnvMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
238 if (effectiveEnvMode !== "local" || activeWorktreePath !== null) {
239 return null;
240 }
241 if (!activeThreadBranch || !currentGitBranch || activeThreadBranch === currentGitBranch) {
242 return null;
243 }
244 return { threadBranch: activeThreadBranch, currentBranch: currentGitBranch };
246​
247export function resolveBranchSelectionTarget(input: {
248 activeProjectCwd: string;
249 activeWorktreePath: string | null;
250 refName: Pick<VcsRef, "isDefault" | "worktreePath">;
251}): {
252 checkoutCwd: string;
253 nextWorktreePath: string | null;
254 reuseExistingWorktree: boolean;
255} {
256 const { activeProjectCwd, activeWorktreePath, refName } = input;
257​
258 if (refName.worktreePath) {
259 return {
260 checkoutCwd: refName.worktreePath,
261 nextWorktreePath: refName.worktreePath === activeProjectCwd ? null : refName.worktreePath,
262 reuseExistingWorktree: true,
263 };
264 }
265​
266 const nextWorktreePath =
267 activeWorktreePath !== null && refName.isDefault ? null : activeWorktreePath;
268​
269 return {
270 checkoutCwd: nextWorktreePath ?? activeProjectCwd,
271 nextWorktreePath,
272 reuseExistingWorktree: false,
273 };
275​
276// Git rejects ASCII space and the ASCII control characters (tab, newline and
277// friends) in ref names, so the picker's "Create new ref" entry can only fail
278// for a typed name like "new branch". Replacing runs of those with a dash makes
279// the name usable without reimplementing check-ref-format: names invalid for
280// other reasons still surface the git error. Only the whitespace git actually
281// rejects is replaced — git accepts U+00A0 and friends, and rewriting those
282// would silently create a ref the user never asked for. Case and existing
283// dashes are left alone, since ref names are case sensitive and consecutive
284// dashes are valid.
285export function sanitizeNewRefName(rawName: string): string {
286 return rawName.trim().replace(/[ \t\n\r\f\v]+/g, "-");
288​
289export function shouldIncludeBranchPickerItem(input: {
290 itemValue: string;
291 normalizedQuery: string;
292 createBranchItemValue: string | null;
293 checkoutPullRequestItemValue: string | null;
294}): boolean {
295 const { itemValue, normalizedQuery, createBranchItemValue, checkoutPullRequestItemValue } = input;
296​
297 if (normalizedQuery.length === 0) {
298 return true;
299 }
300​
301 if (createBranchItemValue && itemValue === createBranchItemValue) {
302 return true;
303 }
304​
305 if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
306 return true;
307 }
308​
309 const lowerItemValue = itemValue.toLowerCase();
310 if (lowerItemValue.includes(normalizedQuery)) {
311 return true;
312 }
313​
314 // A query containing whitespace can only ever match a ref under its sanitized
315 // name, because that is the name such a ref would have been created with.
316 // Without this, typing "new branch" hides an existing "new-branch".
317 const sanitizedQuery = sanitizeNewRefName(normalizedQuery);
318 return (
319 sanitizedQuery.length > 0 &&
320 sanitizedQuery !== normalizedQuery &&
321 lowerItemValue.includes(sanitizedQuery)
322 );