Lutra/ui/src/components/vcs/branches/branches.ts
danny 149a6c7049 M4.5: branch status-bar item and branches popup
The status bar shows the current branch (short hash when detached). Its
popup lists local, then remote branches with a filter and New branch;
checkout runs flushDirty first and toasts git's refusal. Commands
vcs.branches, vcs.newBranch and vcs.checkout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:56:24 +01:00

396 lines
12 KiB
TypeScript

/**
* The branches popup's state (M4.5): the repository's branches from
* `git.branches`, the filter, and switching to or creating a branch.
*
* - **Current branch:** the status-bar item reads it from the Changes
* store's `git.status` ({@link headLabel}), which already follows
* `gitChanged`, so there is no second status query.
* - **List:** `git.branches` (a pending outcome, so through `runWaiting`)
* each time the popup opens. Local branches come first, then remote
* ones; a filter keeps the names that contain every word of it,
* ignoring case. Malformed entries are dropped and the count capped
* ({@link MAX_BRANCHES}).
* - **Checkout:** `flushDirty()` first, so git sees what the editor shows
* and refuses instead of losing an unsaved edit; a save that failed
* cancels the checkout. git's own refusal (local changes would be
* overwritten, unknown branch) becomes an error toast that names the
* branch and quotes git. Buffers whose files changed reload through the
* file watcher.
* - **New branch:** `git.createBranch {name, checkout}` from HEAD. Creating
* and switching from HEAD leaves the files as they are, so nothing is
* saved first. A refusal stays in the popup next to the name.
*/
import { defineStore } from "pinia";
import { computed, ref, shallowRef } from "vue";
import { runWaiting, type JsonValue } from "../../../ipc";
import { useAutosaveStore } from "../../../stores/autosave";
import { useNotificationsStore } from "../../../stores/notifications";
import { SHORT_HASH, type RepoSummary } from "../changes/changes";
/** Most branches kept per kind from one answer. */
export const MAX_BRANCHES = 10_000;
/** A branch as `git.branches` reports it. */
export interface Branch {
/** Short name: `main`, or `origin/main` for a remote branch. */
name: string;
/** Full hash of the commit it points to. */
head: string;
/** The upstream of a local branch, such as `origin/main`. */
upstream?: string;
}
/** The result of `git.branches`, as the store keeps it. */
export interface BranchList {
/** The checked-out branch; null when detached. */
current: string | null;
/** Local branches, sorted by name. */
local: Branch[];
/** Remote-tracking branches, sorted by name. */
remote: Branch[];
}
/** The value of `newError` when the name was blank. */
export const EMPTY_NAME = "\u0000empty";
/** Which part of the popup shows. */
export type BranchesMode = "list" | "new";
/**
* Reads the branches of one kind; malformed entries are dropped.
*
* @param raw - the untrusted `local` or `remote` field.
*/
function toBranchArray(raw: unknown): Branch[] {
if (!Array.isArray(raw)) {
return [];
}
const out: Branch[] = [];
for (const entry of raw as unknown[]) {
if (out.length >= MAX_BRANCHES) {
break;
}
if (typeof entry !== "object" || entry === null) {
continue;
}
const b = entry as Record<string, unknown>;
if (typeof b.name !== "string" || b.name === "") {
continue;
}
const branch: Branch = { name: b.name, head: typeof b.head === "string" ? b.head : "" };
if (typeof b.upstream === "string" && b.upstream !== "") {
branch.upstream = b.upstream;
}
out.push(branch);
}
return out.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
}
/**
* Reads the result of `git.branches`; null if it is not an object.
*
* @param raw - untrusted.
*/
export function toBranches(raw: unknown): BranchList | null {
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
return null;
}
const r = raw as Record<string, unknown>;
return {
current: typeof r.current === "string" && r.current !== "" ? r.current : null,
local: toBranchArray(r.local),
remote: toBranchArray(r.remote),
};
}
/**
* Keeps the branches whose name contains every word of the filter,
* ignoring case.
*
* @param branches - the branches.
* @param filter - the filter text; blank keeps everything.
*/
export function filterBranches(branches: Branch[], filter: string): Branch[] {
const words = filter.toLowerCase().split(/\s+/).filter((w) => w !== "");
if (words.length === 0) {
return branches;
}
return branches.filter((b) => {
const name = b.name.toLowerCase();
return words.every((w) => name.includes(w));
});
}
/**
* What the status bar shows for HEAD: the branch, the short hash when
* detached, or null when there is nothing to name (no repository, no
* commit and no branch).
*
* @param repo - the repository summary of `git.status`.
*/
export function headLabel(repo: RepoSummary | null | undefined): string | null {
if (!repo) {
return null;
}
if (repo.branch !== undefined && !repo.detached) {
return repo.branch;
}
return repo.head ? repo.head.slice(0, SHORT_HASH) : (repo.branch ?? null);
}
/**
* The text of an engine error for people: git's message as it is.
*
* @param message - the error message.
*/
function reasonOf(message: string): string {
return message.trim() === "" ? "?" : message.trim();
}
/** The Branches store. */
export const useBranchesStore = defineStore("branches", () => {
const notifications = useNotificationsStore();
/** Whether the popup is open. */
const open = ref(false);
/** Which part of the popup shows. */
const mode = ref<BranchesMode>("list");
/** The last list read; null before it arrived. */
const list = shallowRef<BranchList | null>(null);
/** Whether `git.branches` runs. */
const loading = ref(false);
/** Why the list could not be read. */
const loadError = ref<string | null>(null);
/** The filter text. */
const filter = ref("");
/** Index of the selected row of {@link rows}. */
const selected = ref(0);
/** The name typed for a new branch. */
const newName = ref("");
/** Whether a new branch is checked out right away. */
const newCheckout = ref(true);
/** Why the last new branch was refused. */
const newError = ref<string | null>(null);
/** Whether a checkout or a branch creation runs. */
const busy = ref(false);
/** Bumped when the popup's field should take the focus. */
const focusRequest = ref(0);
/** Local branches that match the filter. */
const local = computed(() => filterBranches(list.value?.local ?? [], filter.value));
/** Remote branches that match the filter. */
const remote = computed(() => filterBranches(list.value?.remote ?? [], filter.value));
/**
* The selectable rows in display order: "New branch…" (as null), then
* the local and the remote branches.
*/
const rows = computed<({ kind: "local" | "remote"; branch: Branch } | null)[]>(() => [
null,
...local.value.map((branch) => ({ kind: "local" as const, branch })),
...remote.value.map((branch) => ({ kind: "remote" as const, branch })),
]);
/** Counts loads, so an older answer never replaces a newer one. */
let loads = 0;
/** Whether the next list selects its first branch (set when the popup opens). */
let pickFirst = false;
/** Reads `git.branches`. */
async function load(): Promise<void> {
loads += 1;
const mine = loads;
loading.value = true;
const result = await runWaiting("git.branches");
if (mine !== loads) {
return;
}
loading.value = false;
if (!result.ok) {
loadError.value = reasonOf(result.error.message);
return;
}
const next = toBranches(result.value);
loadError.value = next ? null : "unexpected result of git.branches";
list.value = next;
if (pickFirst) {
pickFirst = false;
selected.value = rows.value.length > 1 ? 1 : 0;
}
clampSelection();
}
/** Keeps {@link selected} inside {@link rows}. */
function clampSelection(): void {
selected.value = Math.min(Math.max(0, selected.value), rows.value.length - 1);
}
/**
* Opens the popup and reads the branches.
*
* @param as - `list` for the branches, `new` for the name of a new one.
* @returns when the list arrived.
*/
function show(as: BranchesMode = "list"): Promise<void> {
open.value = true;
mode.value = as;
filter.value = "";
newError.value = null;
if (as === "new") {
newName.value = "";
newCheckout.value = true;
}
selected.value = rows.value.length > 1 ? 1 : 0;
pickFirst = true;
focusRequest.value += 1;
return load();
}
/** Closes the popup. */
function hide(): void {
open.value = false;
mode.value = "list";
}
/** Switches to entering a new branch's name. */
function startNew(): void {
mode.value = "new";
newName.value = filter.value.trim();
newCheckout.value = true;
newError.value = null;
focusRequest.value += 1;
}
/** Goes back from the new branch's name to the list. */
function backToList(): void {
mode.value = "list";
newError.value = null;
focusRequest.value += 1;
}
/**
* Sets the filter and selects the first branch that matches.
*
* @param text - the filter.
*/
function setFilter(text: string): void {
filter.value = text;
pickFirst = false;
selected.value = rows.value.length > 1 ? 1 : 0;
}
/**
* Moves the selection by `delta` rows, clamped.
*
* @param delta - rows to move; positive is down.
*/
function move(delta: number): void {
pickFirst = false;
selected.value += delta;
clampSelection();
}
/**
* Saves every dirty buffer, then checks out a branch. A remote branch
* (`origin/x`) checks out its local tracking branch `x`, created when
* missing.
*
* @param branch - the branch name.
* @returns whether git checked it out.
*/
async function checkout(branch: string): Promise<boolean> {
if (busy.value) {
return false;
}
busy.value = true;
try {
const flushed = await useAutosaveStore().flushDirty();
if (flushed.error !== null || flushed.failed.length > 0) {
notifications.notify({
level: "warning",
messageKey: "notification.vcs.checkoutNotSaved",
params: { branch },
});
return false;
}
const result = await runWaiting("git.checkout", { branch });
if (!result.ok) {
const reason = reasonOf(result.error.message);
notifications.notify({
level: "error",
messageKey: "notification.vcs.checkoutFailed",
message: reason,
params: { branch, reason },
});
return false;
}
notifications.notify({ level: "info", messageKey: "notification.vcs.checkedOut", params: { branch } });
return true;
} finally {
busy.value = false;
}
}
/**
* Creates a branch at HEAD.
*
* @param name - its name; surrounding blanks are dropped.
* @param thenCheckout - whether to switch to it.
* @returns null when created, else why not (also kept in {@link newError}).
*/
async function create(name: string, thenCheckout: boolean): Promise<string | null> {
const trimmed = name.trim();
if (trimmed === "") {
newError.value = EMPTY_NAME;
return newError.value;
}
if (busy.value) {
return "busy";
}
busy.value = true;
try {
const params: JsonValue = { name: trimmed, checkout: thenCheckout };
const result = await runWaiting("git.createBranch", params);
if (!result.ok) {
newError.value = reasonOf(result.error.message);
return newError.value;
}
newError.value = null;
notifications.notify({
level: "info",
messageKey: "notification.vcs.branchCreated",
params: { branch: trimmed },
});
return null;
} finally {
busy.value = false;
}
}
return {
open,
mode,
list,
loading,
loadError,
filter,
selected,
newName,
newCheckout,
newError,
busy,
focusRequest,
local,
remote,
rows,
load,
show,
hide,
startNew,
backToList,
setFilter,
move,
checkout,
create,
};
});