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>
This commit is contained in:
danny 2026-10-26 17:40:33 +01:00
parent b3642e53ea
commit 149a6c7049
18 changed files with 1585 additions and 17 deletions

View file

@ -18,14 +18,14 @@
* but the go-to open commands closes it. So is the app menu (M3.9): any
* command but `menu.open` closes it.
* - **Navigation (M3.5):** the definition picker and the inline rename field
* are exclusive modals too.
* are exclusive modals too. So is the branches popup (M4.5).
*/
import { defineStore } from "pinia";
import { ref, watch } from "vue";
import { useEditorStore } from "../stores/editor";
/** The exclusive modals. */
export type ModalId = "palette" | "goto" | "menu" | "settings" | "closePrompt" | "navPicker" | "rename";
export type ModalId = "palette" | "goto" | "menu" | "settings" | "closePrompt" | "navPicker" | "rename" | "branches";
/** Store of the open exclusive modal. */
export const useModalsStore = defineStore("modals", () => {

View file

@ -35,7 +35,10 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [
{ id: "settings.open", labelKey: "command.settings.open", menuPath: "View/Settings…", defaultShortcut: "Mod+," },
{ id: "terminal.open", labelKey: "command.terminal.open", menuPath: "View/Terminal", defaultShortcut: "Mod+Shift+T" },
{ id: "view.toggleProjectTree", labelKey: "command.view.toggleProjectTree", menuPath: "View/Project", defaultShortcut: "Mod+1" },
{ id: "vcs.branches", labelKey: "command.vcs.branches", menuPath: "Git/Branches…" },
{ id: "vcs.checkout", labelKey: "command.vcs.checkout" },
{ id: "vcs.commit", labelKey: "command.vcs.commit", menuPath: "Git/Commit…", defaultShortcut: "Mod+Alt+Shift+M" },
{ id: "vcs.newBranch", labelKey: "command.vcs.newBranch", menuPath: "Git/New Branch…" },
{ id: "vcs.openChanges", labelKey: "command.vcs.openChanges", menuPath: "Git/Changes", defaultShortcut: "Mod+Alt+Shift+G" },
{ id: "vcs.refresh", labelKey: "command.vcs.refresh", menuPath: "Git/Refresh Changes" },
{ id: "vcs.showDiff", labelKey: "command.vcs.showDiff", menuPath: "Git/Show Diff", defaultShortcut: "Mod+Alt+Shift+D" },

View file

@ -2,12 +2,13 @@
/**
* Status bar along the bottom of the main window. Shows the product name and
* version, or the last engine error, and on the right the language server's
* progress (H3).
* progress (H3) and the Git branch (M4.5).
*/
import { computed } from "vue";
import { t } from "../i18n";
import { useAppStore } from "../stores/app";
import LspProgressItem from "./problems/LspProgressItem.vue";
import BranchStatusItem from "./vcs/branches/BranchStatusItem.vue";
const app = useAppStore();
@ -28,6 +29,7 @@ const label = computed(() => {
>
<span>{{ label }}</span>
<LspProgressItem />
<BranchStatusItem />
</footer>
</template>

View file

@ -0,0 +1,536 @@
<script setup lang="ts">
/**
* The branches popup (M4.5), above the status bar's branch item.
*
* - **List:** a filter field, then "New branch…", the local branches (the
* current one marked) and the remote branches, each under a heading.
* Typing filters both lists. Up/Down, Page Up/Down move the selection;
* Enter or a click checks the branch out (through `vcs.checkout`, which
* saves dirty buffers first) or starts a new branch. Choosing the current
* branch only closes the popup.
* - **New branch:** a name field and a "Check out" checkbox (on). Enter
* or Create makes the branch at HEAD through `git.createBranch`; git's
* refusal (bad name, branch exists) shows under the field and the popup
* stays. Escape goes back to the list.
* - **Closing:** Escape in the list or a click outside; the focus goes back
* where it was. The popup is an exclusive modal (`commands/modals.ts`).
*/
import { Check, GitBranch, Plus } from "@lucide/vue";
import { computed, nextTick, ref, watch } from "vue";
import { useModalsStore } from "../../../commands/modals";
import { useCommandsStore } from "../../../commands/store";
import { t } from "../../../i18n";
import { EMPTY_NAME, useBranchesStore, type Branch } from "./branches";
const branches = useBranchesStore();
const modals = useModalsStore();
const commands = useCommandsStore();
/** The filter field. */
const filterInput = ref<HTMLInputElement | null>(null);
/** The new branch's name field. */
const nameInput = ref<HTMLInputElement | null>(null);
/** The list. */
const list = ref<HTMLElement | null>(null);
/** The element that had the focus before the popup opened. */
let returnFocus: HTMLElement | null = null;
/** Rows moved by Page Up and Page Down. */
const PAGE = 10;
/** The current branch's name, if not detached. */
const current = computed(() => branches.list?.current ?? null);
/** Index in `rows` of the first local branch. */
const localStart = 1;
/** Index in `rows` of the first remote branch. */
const remoteStart = computed(() => localStart + branches.local.length);
/** The line under the field: loading, an error, no matches, or nothing. */
const hint = computed<string | null>(() => {
if (branches.loadError !== null) {
return t("vcs.branches.loadFailed", { reason: branches.loadError });
}
if (branches.list === null) {
return branches.loading ? t("vcs.branches.loading") : null;
}
if (branches.local.length === 0 && branches.remote.length === 0 && branches.filter.trim() !== "") {
return t("vcs.branches.noMatches");
}
return null;
});
/** The error under the name field, or null. */
const newError = computed(() =>
branches.newError === null
? null
: branches.newError === EMPTY_NAME
? t("vcs.branches.nameEmpty")
: branches.newError,
);
/**
* The DOM id of a row.
*
* @param index - its index in `rows`.
*/
function rowId(index: number): string {
return `lt-branch-${String(index)}`;
}
/** Closes the popup and gives the focus back. */
function close(): void {
if (!branches.open) {
return;
}
branches.hide();
}
watch(
() => branches.open,
(isOpen) => {
if (isOpen) {
const active = document.activeElement;
returnFocus = active instanceof HTMLElement ? active : null;
modals.opened("branches", close);
} else {
modals.closed("branches");
returnFocus?.focus();
returnFocus = null;
}
},
);
watch(
() => branches.focusRequest,
async () => {
await nextTick();
const field = branches.mode === "new" ? nameInput.value : filterInput.value;
field?.focus();
field?.select();
},
);
/**
* Chooses a row: "New branch…" (null) or a branch.
*
* @param row - the row.
*/
function choose(row: { kind: "local" | "remote"; branch: Branch } | null | undefined): void {
if (row === undefined) {
return;
}
if (row === null) {
branches.startNew();
return;
}
if (row.kind === "local" && row.branch.name === current.value) {
close();
return;
}
close();
void commands.execute("vcs.checkout", { branch: row.branch.name });
}
/** Keeps the selected row in view. */
function scrollSelected(): void {
void nextTick(() => {
const row = list.value?.querySelector<HTMLElement>(`#${rowId(branches.selected)}`);
if (row && typeof row.scrollIntoView === "function") {
row.scrollIntoView({ block: "nearest" });
}
});
}
/**
* Keyboard handling of the filter field.
*
* @param event - the key press.
*/
function onFilterKey(event: KeyboardEvent): void {
const moves: Record<string, number> = { ArrowDown: 1, ArrowUp: -1, PageDown: PAGE, PageUp: -PAGE };
const delta = moves[event.key];
if (delta !== undefined) {
branches.move(delta);
scrollSelected();
} else if (event.key === "Enter") {
choose(branches.rows[branches.selected]);
} else if (event.key === "Escape") {
close();
} else {
return;
}
event.preventDefault();
event.stopPropagation();
}
/** Creates the branch from the name field; closes the popup when it worked. */
async function createBranch(): Promise<void> {
const refused = await branches.create(branches.newName, branches.newCheckout);
if (refused === null) {
close();
} else {
nameInput.value?.focus();
}
}
/**
* Keyboard handling of the new branch's form.
*
* @param event - the key press.
*/
function onNewKey(event: KeyboardEvent): void {
if (event.key !== "Escape") {
return;
}
event.preventDefault();
event.stopPropagation();
branches.backToList();
}
</script>
<template>
<div
v-if="branches.open"
class="branches"
data-test="branches"
@mousedown.self.prevent="close()"
>
<div
class="branches__dialog"
role="dialog"
aria-modal="true"
:aria-label="t('vcs.branches.label')"
>
<template v-if="branches.mode === 'list'">
<input
ref="filterInput"
:value="branches.filter"
class="branches__input"
type="text"
role="combobox"
aria-autocomplete="list"
aria-expanded="true"
aria-controls="lt-branch-list"
:aria-activedescendant="rowId(branches.selected)"
:aria-label="t('vcs.branches.filter')"
:placeholder="t('vcs.branches.filter')"
spellcheck="false"
autocomplete="off"
data-test="branches-filter"
@input="branches.setFilter(($event.target as HTMLInputElement).value)"
@keydown="onFilterKey"
>
<p
v-if="hint !== null"
class="branches__hint"
:class="{ 'branches__hint--error': branches.loadError !== null }"
role="status"
data-test="branches-hint"
>
{{ hint }}
</p>
<ul
id="lt-branch-list"
ref="list"
class="branches__list"
role="listbox"
:aria-label="t('vcs.branches.label')"
>
<li
:id="rowId(0)"
class="branches__row branches__row--action"
:class="{ 'branches__row--selected': branches.selected === 0 }"
role="option"
:aria-selected="branches.selected === 0"
data-test="branches-new"
@mousemove="branches.selected = 0"
@mousedown.prevent
@click="choose(null)"
>
<Plus
class="branches__icon"
:size="14"
aria-hidden="true"
/>
<span>{{ t("vcs.branches.new") }}</span>
</li>
<li
v-if="branches.local.length > 0"
class="branches__heading"
role="presentation"
>
{{ t("vcs.branches.local") }}
</li>
<li
v-for="(branch, i) in branches.local"
:id="rowId(localStart + i)"
:key="`l:${branch.name}`"
class="branches__row"
:class="{ 'branches__row--selected': branches.selected === localStart + i }"
role="option"
:aria-selected="branches.selected === localStart + i"
:aria-current="branch.name === current ? 'true' : undefined"
:data-branch="branch.name"
data-test="branches-local"
@mousemove="branches.selected = localStart + i"
@mousedown.prevent
@click="choose({ kind: 'local', branch })"
>
<component
:is="branch.name === current ? Check : GitBranch"
class="branches__icon"
:size="14"
aria-hidden="true"
/>
<span class="branches__name">{{ branch.name }}</span>
<span
v-if="branch.name === current"
class="branches__detail"
>{{ t("vcs.branches.current") }}</span>
<span
v-else-if="branch.upstream"
class="branches__detail"
>{{ branch.upstream }}</span>
</li>
<li
v-if="branches.remote.length > 0"
class="branches__heading"
role="presentation"
>
{{ t("vcs.branches.remote") }}
</li>
<li
v-for="(branch, i) in branches.remote"
:id="rowId(remoteStart + i)"
:key="`r:${branch.name}`"
class="branches__row"
:class="{ 'branches__row--selected': branches.selected === remoteStart + i }"
role="option"
:aria-selected="branches.selected === remoteStart + i"
:data-branch="branch.name"
data-test="branches-remote"
@mousemove="branches.selected = remoteStart + i"
@mousedown.prevent
@click="choose({ kind: 'remote', branch })"
>
<GitBranch
class="branches__icon"
:size="14"
aria-hidden="true"
/>
<span class="branches__name">{{ branch.name }}</span>
</li>
</ul>
</template>
<form
v-else
class="branches__new"
data-test="branches-new-form"
@submit.prevent="createBranch()"
@keydown="onNewKey"
>
<label
class="branches__new-label"
for="lt-branch-new-name"
>{{ t("vcs.branches.newName") }}</label>
<input
id="lt-branch-new-name"
ref="nameInput"
v-model="branches.newName"
class="branches__input branches__input--boxed"
type="text"
spellcheck="false"
autocomplete="off"
:aria-invalid="newError !== null"
:aria-describedby="newError !== null ? 'lt-branch-new-error' : undefined"
data-test="branches-new-name"
>
<p
v-if="newError !== null"
id="lt-branch-new-error"
class="branches__hint branches__hint--error"
role="alert"
data-test="branches-new-error"
>
{{ newError }}
</p>
<div class="branches__new-row">
<label class="branches__checkout">
<input
v-model="branches.newCheckout"
type="checkbox"
data-test="branches-new-checkout"
>
{{ t("vcs.branches.newCheckout") }}
</label>
<button
type="submit"
class="branches__create"
:disabled="branches.busy"
data-test="branches-create"
>
{{ t("vcs.branches.create") }}
</button>
</div>
</form>
</div>
</div>
</template>
<style scoped>
.branches {
position: fixed;
inset: 0;
display: flex;
align-items: flex-end;
justify-content: flex-end;
padding: 0 8px 28px 0;
z-index: 30;
}
.branches__dialog {
width: min(360px, 90vw);
max-height: 60vh;
display: flex;
flex-direction: column;
background: var(--lt-bg);
color: var(--lt-fg);
border: 1px solid var(--lt-border);
border-radius: 6px;
overflow: hidden;
}
.branches__input {
padding: 6px 10px;
font: inherit;
color: var(--lt-fg);
background: var(--lt-editor-bg);
border: none;
border-bottom: 1px solid var(--lt-border);
outline: none;
}
.branches__input--boxed {
border: 1px solid var(--lt-border);
border-radius: var(--lt-radius, 4px);
}
.branches__input--boxed:focus-visible {
outline: 2px solid var(--lt-accent);
outline-offset: -1px;
}
.branches__hint {
margin: 0;
padding: 4px 10px;
color: var(--lt-fg-muted);
}
.branches__hint--error {
color: var(--lt-error);
}
.branches__list {
margin: 0;
padding: 4px 0;
list-style: none;
overflow-y: auto;
}
.branches__heading {
padding: 6px 10px 2px;
font-size: 0.85em;
font-weight: 600;
color: var(--lt-fg-muted);
}
.branches__row {
display: flex;
align-items: center;
gap: 8px;
padding: 3px 10px;
white-space: nowrap;
cursor: default;
}
.branches__row--selected {
background: var(--lt-editor-selection-bg);
}
.branches__icon {
flex: none;
color: var(--lt-fg-muted);
}
.branches__row--selected .branches__icon {
color: var(--lt-fg);
}
.branches__name {
overflow: hidden;
text-overflow: ellipsis;
}
.branches__detail {
flex: none;
margin-left: auto;
color: var(--lt-fg-muted);
}
.branches__row--selected .branches__detail {
color: var(--lt-fg);
}
.branches__new {
display: flex;
flex-direction: column;
gap: 6px;
padding: 10px;
}
.branches__new-label {
color: var(--lt-fg);
}
.branches__new .branches__hint {
padding: 0;
}
.branches__new-row {
display: flex;
align-items: center;
gap: 8px;
}
.branches__checkout {
display: inline-flex;
align-items: center;
gap: 4px;
}
.branches__checkout input {
accent-color: var(--lt-accent);
}
.branches__create {
margin-left: auto;
padding: 2px 16px;
font: inherit;
color: var(--lt-fg);
background: color-mix(in srgb, var(--lt-accent) 18%, transparent);
border: 1px solid var(--lt-accent);
border-radius: var(--lt-radius, 4px);
cursor: pointer;
}
.branches__create:disabled {
opacity: 0.5;
cursor: default;
}
.branches__create:focus-visible {
outline: 2px solid var(--lt-fg);
outline-offset: 1px;
}
</style>

View file

@ -0,0 +1,177 @@
<script setup lang="ts">
/**
* Status-bar item (M4.5): the current Git branch, or the short hash when
* HEAD is detached. Hidden outside a repository and while git is missing.
* A click opens the branches popup ({@link BranchPopup}).
*
* The item supplies the UI commands of the branches feature, so they work
* wherever the status bar is shown:
* - `vcs.branches` opens the popup;
* - `vcs.newBranch {name?, checkout?}` opens it on the new branch's name,
* or, with a `name` (an agent), creates the branch at HEAD and checks it
* out unless `checkout` is false; a refusal becomes an error toast;
* - `vcs.checkout {branch}` saves every dirty buffer, then checks the
* branch out (see the Branches store); without `branch` (the palette)
* it opens the popup to pick one.
* All three need an open project (the engine's `git.branches`).
*/
import { GitBranch } from "@lucide/vue";
import { computed, onBeforeUnmount, onMounted } from "vue";
import { useCommandsStore } from "../../../commands/store";
import { t } from "../../../i18n";
import type { JsonValue } from "../../../ipc";
import { useNotificationsStore } from "../../../stores/notifications";
import { useChangesStore } from "../changes/changes";
import BranchPopup from "./BranchPopup.vue";
import { headLabel, useBranchesStore } from "./branches";
const changes = useChangesStore();
const branches = useBranchesStore();
const commands = useCommandsStore();
const notifications = useNotificationsStore();
/** The repository of the last status, if any. */
const repo = computed(() => (changes.status?.available ? changes.status.repo : null));
/** The text of the item, or null when it is hidden. */
const text = computed(() => headLabel(repo.value));
/** The tooltip and accessible name. */
const label = computed(() => {
const value = text.value ?? "";
return repo.value?.detached
? t("vcs.branchItem.detached", { hash: value })
: t("vcs.branchItem.label", { branch: value });
});
/**
* Reads an object's fields; empty for anything else.
*
* @param params - the command's params; untrusted when an agent sent them.
*/
function fields(params: JsonValue): Record<string, JsonValue> {
return typeof params === "object" && params !== null && !Array.isArray(params) ? params : {};
}
/**
* Runs `vcs.checkout`.
*
* @param params - `{branch}`; without it the popup opens.
*/
async function runCheckout(params: JsonValue): Promise<void> {
const given = fields(params);
if (!("branch" in given)) {
await branches.show("list");
return;
}
const branch = given.branch;
if (typeof branch !== "string" || branch.trim() === "") {
notifications.notify({ level: "error", message: t("vcs.checkout.invalidParams") });
return;
}
branches.hide();
await branches.checkout(branch.trim());
}
/**
* Runs `vcs.newBranch`.
*
* @param params - `{name?, checkout?}`.
*/
async function runNewBranch(params: JsonValue): Promise<void> {
const { name, checkout } = fields(params);
if (typeof name !== "string") {
await branches.show("new");
return;
}
const refused = await branches.create(name, checkout !== false);
if (refused !== null) {
notifications.notify({
level: "error",
messageKey: "notification.vcs.newBranchFailed",
message: refused,
params: { branch: name, reason: refused },
});
}
}
/** Withdraws the command handlers; filled while mounted. */
let withdraw: (() => void)[] = [];
onMounted(() => {
const enabled = (): boolean => commands.isEnabled("git.branches");
withdraw = [
commands.provide("vcs.branches", { run: () => branches.show("list"), enabled }),
commands.provide("vcs.newBranch", { run: runNewBranch, enabled }),
commands.provide("vcs.checkout", { run: runCheckout, enabled }),
];
});
onBeforeUnmount(() => {
for (const fn of withdraw) {
fn();
}
withdraw = [];
});
</script>
<template>
<span
v-if="text !== null"
class="branch-item"
>
<button
type="button"
class="branch-item__button"
:title="label"
:aria-label="label"
aria-haspopup="dialog"
:aria-expanded="branches.open"
data-test="branch-item"
@click="commands.execute('vcs.branches')"
>
<GitBranch
:size="12"
aria-hidden="true"
/>
<span class="branch-item__text">{{ text }}</span>
</button>
</span>
<BranchPopup />
</template>
<style scoped>
.branch-item {
display: inline-flex;
margin-left: auto;
min-width: 0;
}
.branch-item__button {
display: inline-flex;
align-items: center;
gap: 4px;
max-width: 24ch;
padding: 0 6px;
font: inherit;
color: inherit;
background: transparent;
border: none;
border-radius: var(--lt-radius, 4px);
cursor: pointer;
}
.branch-item__button:hover {
background: color-mix(in srgb, var(--lt-statusbar-fg) 12%, transparent);
}
.branch-item__button:focus-visible {
outline: 2px solid var(--lt-accent);
}
.branch-item__text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>

View file

@ -0,0 +1,396 @@
/**
* 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,
};
});

View file

@ -19,7 +19,10 @@
"command.settings.open": "Settings…",
"command.terminal.open": "Terminal",
"command.unavailable": "{command} cannot run right now",
"command.vcs.branches": "Branches…",
"command.vcs.checkout": "Check Out Branch",
"command.vcs.commit": "Commit…",
"command.vcs.newBranch": "New Branch…",
"command.vcs.nextChange": "Next Change",
"command.vcs.openChanges": "Changes",
"command.vcs.previousChange": "Previous Change",
@ -152,8 +155,13 @@
"notification.toolchain.downloadFailed": "Phpactor {version} could not be downloaded: {reason}",
"notification.toolchain.downloadStarted": "Downloading Phpactor {version} from GitHub for PHP language features…",
"notification.toolchain.phpMissing": "PHP language features need PHP {min} or newer: {reason}. Install PHP or set the PHP executable in Settings.",
"notification.vcs.branchCreated": "Created branch {branch}",
"notification.vcs.checkedOut": "Checked out {branch}",
"notification.vcs.checkoutFailed": "Git did not check out {branch}: {reason}",
"notification.vcs.checkoutNotSaved": "Checkout of {branch} cancelled: not every file could be saved first.",
"notification.vcs.commitNotSaved": "Commit cancelled: not every file could be saved first.",
"notification.vcs.committed": "Committed {hash}: {summary}",
"notification.vcs.newBranchFailed": "Branch {branch} was not created: {reason}",
"notification.vfs.pumpFailed": "Applying changes on disk failed: {reason}",
"notification.watch.failed": "Lutra stopped watching the project for changes on disk: {reason}",
"palette.label": "Command palette",
@ -273,6 +281,21 @@
"terminal.toolWindow.title": "Terminal",
"theme.lutraDark": "Lutra Dark",
"theme.lutraLight": "Lutra Light",
"vcs.branchItem.detached": "Detached HEAD at {hash}. Click for branches.",
"vcs.branchItem.label": "Git branch {branch}. Click for branches.",
"vcs.branches.create": "Create",
"vcs.branches.current": "current",
"vcs.branches.filter": "Filter branches",
"vcs.branches.label": "Branches",
"vcs.branches.loadFailed": "The branches cannot be read: {reason}",
"vcs.branches.loading": "Reading branches…",
"vcs.branches.local": "Local",
"vcs.branches.nameEmpty": "Enter a name for the branch.",
"vcs.branches.new": "New branch…",
"vcs.branches.newCheckout": "Check out",
"vcs.branches.newName": "Name of the new branch",
"vcs.branches.noMatches": "No branch matches",
"vcs.branches.remote": "Remote",
"vcs.changes.clean": "{branch}: no changes",
"vcs.changes.group.changes": "Changes",
"vcs.changes.group.staged": "Staged",
@ -292,6 +315,7 @@
"vcs.changes.unavailableHint": "Install Git 2.30 or newer, or set the Git executable in Settings.",
"vcs.changes.unstageAll": "Unstage all",
"vcs.changes.unstageFile": "Unstage {path}",
"vcs.checkout.invalidParams": "vcs.checkout needs a branch name (params: branch).",
"vcs.commit.amend": "Amend",
"vcs.commit.amendButton": "Amend Commit",
"vcs.commit.button": "Commit",