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

BranchToolbar.logic.ts

336 lines10.9 KB

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