M4.2: Changes tool window with staging and commit

A Changes tab in the bottom panel (ui/src/components/vcs/changes/): the
project's changed files from git.status in Staged, Changes and Untracked
groups, re-read on start, project open, gitChanged and vcs.refresh
(serialised). A checkbox per file and per group stages or unstages through
git.stage / git.unstage (a staged rename passes both paths); Space stages,
Enter or a double-click runs vcs.showDiff when provided, else opens the
file. A message box with Amend and Commit (also Mod+Enter) runs flushDirty()
first, cancels when a save fails, then git.commit and toasts the short hash.
All git calls go through runWaiting.

UI commands vcs.openChanges (Mod+Alt+G), vcs.commit (Mod+K, focuses the
message box) and vcs.refresh in a new Git menu group; gitChanged added to
EngineEventPayload. 19 Vitest tests; palette, menu and catalog tests follow
the new commands. Docs: architecture, gaps G8, Git parity row 4% (est.),
ui/tooling checklists, roadmap M4 row, ROADMAP depth ~5.4% and log, README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-25 17:17:39 +01:00
parent 8701f50d37
commit f67f6b9f7c
18 changed files with 1792 additions and 23 deletions

View file

@ -35,5 +35,8 @@ 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.commit", labelKey: "command.vcs.commit", menuPath: "Git/Commit…", defaultShortcut: "Mod+K" },
{ id: "vcs.openChanges", labelKey: "command.vcs.openChanges", menuPath: "Git/Changes", defaultShortcut: "Mod+Alt+G" },
{ id: "vcs.refresh", labelKey: "command.vcs.refresh", menuPath: "Git/Refresh Changes" },
{ id: "view.toggleStructure", labelKey: "command.view.toggleStructure", menuPath: "View/Structure", defaultShortcut: "Mod+2" },
];

View file

@ -26,7 +26,10 @@
* results, the Terminal store the running terminals and the Problems store
* the diagnostics while they are hidden. The References tab (M3.5) shows
* when Find References runs (`lsp.references`); the nav store keeps its
* results.
* results. The Changes tab (M4.2) appears with `vcs.openChanges`
* (`Mod+Alt+G`) and `vcs.commit` (`Mod+K`, which also focuses the commit
* message box); `vcs.refresh` re-reads the Git status. Its store reads the
* status from the start, so it is current when the tab opens.
*
* A slim header bar along the top (M3.9) holds the app menu
* ({@link AppMenu}); its `header` slot can replace it.
@ -43,6 +46,8 @@ import ProblemsToolWindow from "../problems/ProblemsToolWindow.vue";
import { useProblemsStore } from "../problems/problems";
import ReferencesToolWindow from "../editor/nav/ReferencesToolWindow.vue";
import { useNavStore } from "../editor/nav/nav";
import ChangesToolWindow from "../vcs/changes/ChangesToolWindow.vue";
import { useChangesStore } from "../vcs/changes/changes";
import ProjectToolWindow from "../project/ProjectToolWindow.vue";
import StatusBar from "../StatusBar.vue";
import StructureToolWindow from "../structure/StructureToolWindow.vue";
@ -89,9 +94,10 @@ const find = useFindStore();
const terminal = useTerminalStore();
const problems = useProblemsStore();
const nav = useNavStore();
const changes = useChangesStore();
/** Tool windows of the bottom panel. */
type BottomTool = "find" | "terminal" | "problems" | "references";
type BottomTool = "find" | "terminal" | "problems" | "references" | "changes";
/** The bottom tool window last chosen. */
const bottomTool = ref<BottomTool>("find");
/** Bottom tool windows that are shown, in tab order. */
@ -101,6 +107,7 @@ const bottomTools = computed(() => {
if (terminal.visible) tools.push({ id: "terminal", title: t("terminal.toolWindow.title") });
if (problems.visible) tools.push({ id: "problems", title: t("problems.toolWindow.title") });
if (nav.visible) tools.push({ id: "references", title: t("nav.references.title") });
if (changes.visible) tools.push({ id: "changes", title: t("vcs.changes.toolWindow.title") });
return tools;
});
/** The active bottom tool window: the chosen one if shown, else the first. */
@ -116,7 +123,9 @@ const bottomStore = computed(() =>
? problems
: bottomActive.value === "references"
? nav
: find,
: bottomActive.value === "changes"
? changes
: find,
);
/** Expansion of the panel, kept per tool window by its store. */
const bottomOpen = computed({
@ -132,7 +141,7 @@ const bottomOpen = computed({
* @param id - the tool window id from the panel.
*/
function chooseBottom(id: string): void {
if (id === "find" || id === "terminal" || id === "problems" || id === "references") {
if (id === "find" || id === "terminal" || id === "problems" || id === "references" || id === "changes") {
bottomTool.value = id;
}
}
@ -149,6 +158,7 @@ onMounted(() => {
find.start();
terminal.start();
problems.start();
changes.start();
withdraw = [
commands.provide("view.toggleProjectTree", {
run: () => {
@ -174,6 +184,22 @@ onMounted(() => {
problems.open();
},
}),
commands.provide("vcs.openChanges", {
run: () => {
bottomTool.value = "changes";
changes.open();
},
}),
commands.provide("vcs.commit", {
run: () => {
bottomTool.value = "changes";
changes.focusMessage();
},
}),
commands.provide("vcs.refresh", {
run: () => changes.refresh(),
enabled: () => commands.isEnabled("git.status"),
}),
commands.provide("view.toggleStructure", {
run: () => {
toggleLeft("structure");
@ -190,6 +216,7 @@ onBeforeUnmount(() => {
find.stop();
terminal.stop();
problems.stop();
changes.stop();
});
</script>
@ -263,6 +290,7 @@ onBeforeUnmount(() => {
/>
<ProblemsToolWindow v-show="bottomActive === 'problems'" />
<ReferencesToolWindow v-show="bottomActive === 'references'" />
<ChangesToolWindow v-show="bottomActive === 'changes'" />
</BottomPanel>
<StatusBar />
</div>

View file

@ -0,0 +1,632 @@
<script setup lang="ts">
/**
* The Changes tool window (M4.2), shown in the bottom panel: the project's
* changed files from git in the groups Staged, Changes and Untracked, and
* a commit message box.
*
* - **Status line:** the branch (or the short hash when detached) and the
* counts, or why there is nothing to show: git missing or too old (with
* a hint to the setting `git.executable`), no repository, no changes.
* A refresh button runs `vcs.refresh`.
* - **Groups:** a header with a checkbox that stages (Changes, Untracked)
* or unstages (Staged) the whole group, then the files. Each file has a
* checkbox doing the same for itself, its name coloured by its state
* (`--lt-vcs-*`), its directory and its state. Up/Down, Page Up/Down,
* Home and End move the selection, Space stages or unstages it, Enter or
* a double-click opens it.
* - **Opening:** through the UI command `vcs.showDiff {path, staged}` when
* something provides it (the diff viewer, M4.3); until then the file
* opens in the editor (`file.open`), unless it was deleted.
* - **Commit box:** the message, an Amend checkbox and Commit. Commit
* saves dirty buffers first (`flushDirty`); `Mod+Enter` in the box
* commits too.
* - State lives in the Changes store (`changes.ts`), so the status and the
* message survive hiding the window. Icons are Lucide's; colours are
* tokens.
*/
import { RefreshCw } from "@lucide/vue";
import { computed, nextTick, onMounted, ref, watch } from "vue";
import { useCommandsStore } from "../../../commands/store";
import { isMac } from "../../../commands/keymap";
import { t } from "../../../i18n";
import { run } from "../../../ipc";
import { baseName } from "../../../stores/editor";
import { useNotificationsStore } from "../../../stores/notifications";
import { SHORT_HASH, useChangesStore, type ChangeRow, type FileState, type GroupId } from "./changes";
const changes = useChangesStore();
const commands = useCommandsStore();
const notifications = useNotificationsStore();
/** The list element. */
const list = ref<HTMLElement | null>(null);
/** The commit message box. */
const messageBox = ref<HTMLTextAreaElement | null>(null);
/** Rows moved by Page Up and Page Down. */
const PAGE = 10;
/**
* The title of a group.
*
* @param group - the group.
*/
function groupTitle(group: GroupId): string {
const titles: Record<GroupId, () => string> = {
staged: () => t("vcs.changes.group.staged"),
changes: () => t("vcs.changes.group.changes"),
untracked: () => t("vcs.changes.group.untracked"),
};
return titles[group]();
}
/**
* The name of a state, for people.
*
* @param state - the state.
*/
function stateLabel(state: FileState): string {
const labels: Record<FileState, () => string> = {
unmodified: () => t("vcs.state.unmodified"),
modified: () => t("vcs.state.modified"),
added: () => t("vcs.state.added"),
deleted: () => t("vcs.state.deleted"),
renamed: () => t("vcs.state.renamed"),
copied: () => t("vcs.state.copied"),
untracked: () => t("vcs.state.untracked"),
ignored: () => t("vcs.state.ignored"),
conflicted: () => t("vcs.state.conflicted"),
};
return labels[state]();
}
/**
* The colour class suffix of a state (`changes__name--<suffix>`, which
* uses the token `--lt-vcs-<suffix>`).
*
* @param state - the state.
*/
function stateColor(state: FileState): string {
switch (state) {
case "added":
case "copied":
return "added";
case "deleted":
return "deleted";
case "untracked":
return "untracked";
case "ignored":
return "ignored";
case "conflicted":
return "conflicted";
default:
return "modified";
}
}
/** The line above the list. */
const statusLine = computed(() => {
const s = changes.status;
switch (changes.phase) {
case "idle":
return changes.loadError ?? t("vcs.changes.noProject");
case "loading":
return t("vcs.changes.loading");
case "unavailable":
return t("vcs.changes.unavailable", { reason: s?.error ?? "" });
case "noRepo":
return s?.error ? t("vcs.changes.repoError", { reason: s.error }) : t("vcs.changes.noRepo");
default:
break;
}
const repo = s?.repo;
const where = repo?.branch ?? (repo?.head ? repo.head.slice(0, SHORT_HASH) : t("vcs.changes.noCommits"));
const g = changes.groups;
if (changes.rows.length === 0) {
return t("vcs.changes.clean", { branch: where });
}
return t("vcs.changes.summary", {
branch: where,
staged: String(g.staged.length),
changes: String(g.changes.length),
untracked: String(g.untracked.length),
});
});
/** The groups with rows, in display order, with each row's flat index. */
const shownGroups = computed(() => {
let index = 0;
const out: { id: GroupId; rows: { row: ChangeRow; index: number }[] }[] = [];
for (const id of ["staged", "changes", "untracked"] as const) {
const rows = changes.groups[id].map((row) => ({ row, index: index++ }));
if (rows.length > 0) {
out.push({ id, rows });
}
}
return out;
});
/** Label of the commit button. */
const commitLabel = computed(() => (changes.amend ? t("vcs.commit.amendButton") : t("vcs.commit.button")));
/** The shortcut hint of the commit button. */
const commitHint = computed(() => t("vcs.commit.hint", { keys: isMac() ? "⌘↩" : "Ctrl+Enter" }));
/**
* The DOM id of a row.
*
* @param index - the row's index in the flat list.
*/
function optionId(index: number): string {
return `changes-row-${String(index)}`;
}
/**
* The directory part of a path, empty at the root.
*
* @param path - project-relative path.
*/
function dirName(path: string): string {
const slash = path.lastIndexOf("/");
return slash < 0 ? "" : path.slice(0, slash);
}
/**
* What a row shows after the name: the directory, and the old path of a
* rename or copy.
*
* @param row - the row.
*/
function detail(row: ChangeRow): string {
const dir = dirName(row.file.path);
const orig = row.file.origPath;
return orig !== undefined && row.group === "staged" ? t("vcs.changes.renamedFrom", { path: orig }) : dir;
}
/**
* The accessible name of a row's checkbox.
*
* @param row - the row.
*/
function toggleLabel(row: ChangeRow): string {
return row.group === "staged"
? t("vcs.changes.unstageFile", { path: row.file.path })
: t("vcs.changes.stageFile", { path: row.file.path });
}
/**
* The accessible name of a group's checkbox.
*
* @param group - the group.
*/
function groupToggleLabel(group: GroupId): string {
return group === "staged" ? t("vcs.changes.unstageAll") : t("vcs.changes.stageGroup", { group: groupTitle(group) });
}
/**
* Opens a row: the diff when `vcs.showDiff` is provided, else the file.
*
* @param row - the row.
*/
async function openRow(row: ChangeRow): Promise<void> {
changes.select(row.key);
const staged = row.group === "staged";
if (commands.isEnabled("vcs.showDiff")) {
await commands.execute("vcs.showDiff", { path: row.file.path, staged });
return;
}
if (row.state === "deleted") {
return;
}
const result = await run("file.open", { path: row.file.path });
if (!result.ok) {
notifications.notifyError("file.open", result.error);
}
}
/**
* Keyboard navigation in the list.
*
* @param event - the key event.
*/
function onListKey(event: KeyboardEvent): void {
const count = changes.rows.length;
const moves: Record<string, number> = {
ArrowDown: 1,
ArrowUp: -1,
PageDown: PAGE,
PageUp: -PAGE,
Home: -count,
End: count,
};
const delta = moves[event.key];
const row = changes.rows[changes.selectedIndex];
if (delta !== undefined) {
event.preventDefault();
changes.move(delta);
} else if (event.key === "Enter" && row) {
event.preventDefault();
void openRow(row);
} else if (event.key === " " && row) {
event.preventDefault();
void changes.toggle(row);
}
}
/**
* Commits on `Mod+Enter` in the message box.
*
* @param event - the key event.
*/
function onMessageKey(event: KeyboardEvent): void {
if (event.key === "Enter" && (isMac() ? event.metaKey : event.ctrlKey)) {
event.preventDefault();
void changes.commit();
}
}
/** Takes the focus `vcs.commit` asked for, once. */
async function takeFocus(): Promise<void> {
if (!changes.focusPending) {
return;
}
changes.focusPending = false;
await nextTick();
messageBox.value?.focus();
}
watch(() => changes.focusRequest, takeFocus);
onMounted(() => {
void takeFocus();
});
watch(
() => changes.selectedIndex,
async (index) => {
await nextTick();
const element = index < 0 ? null : document.getElementById(optionId(index));
if (element && typeof element.scrollIntoView === "function") {
element.scrollIntoView({ block: "nearest" });
}
},
);
</script>
<template>
<div
class="changes"
data-test="changes"
>
<div class="changes__bar">
<div
class="changes__status"
role="status"
data-test="changes-status"
>
{{ statusLine }}
</div>
<button
type="button"
class="changes__icon-button"
:title="t('command.vcs.refresh')"
:aria-label="t('command.vcs.refresh')"
:disabled="changes.loading"
data-test="changes-refresh"
@click="changes.refresh()"
>
<RefreshCw :size="14" />
</button>
</div>
<div
v-if="changes.phase === 'unavailable'"
class="changes__hint"
data-test="changes-hint"
>
{{ t("vcs.changes.unavailableHint") }}
</div>
<div
ref="list"
class="changes__list"
role="listbox"
tabindex="0"
:aria-label="t('vcs.changes.list.label')"
:aria-activedescendant="changes.selectedIndex >= 0 ? optionId(changes.selectedIndex) : undefined"
data-test="changes-list"
@keydown="onListKey"
>
<div
v-for="group in shownGroups"
:key="group.id"
role="group"
:aria-label="groupTitle(group.id)"
:data-test="`changes-group-${group.id}`"
>
<div class="changes__group">
<input
type="checkbox"
class="changes__check"
:checked="group.id === 'staged'"
:disabled="changes.busy"
:aria-label="groupToggleLabel(group.id)"
:title="groupToggleLabel(group.id)"
:data-test="`changes-group-toggle-${group.id}`"
@click.prevent="changes.toggleGroup(group.id)"
>
<span class="changes__group-title">{{ groupTitle(group.id) }}</span>
<span class="changes__group-count">{{ group.rows.length }}</span>
</div>
<div
v-for="{ row, index } in group.rows"
:id="optionId(index)"
:key="row.key"
role="option"
class="changes__row"
:class="{ 'changes__row--selected': changes.selectedKey === row.key }"
:aria-selected="changes.selectedKey === row.key"
:data-state="row.state"
data-test="changes-row"
@click="changes.select(row.key)"
@dblclick="openRow(row)"
>
<input
type="checkbox"
class="changes__check"
tabindex="-1"
:checked="row.group === 'staged'"
:disabled="changes.busy"
:aria-label="toggleLabel(row)"
:title="toggleLabel(row)"
data-test="changes-row-toggle"
@click.stop.prevent="changes.toggle(row)"
>
<span
class="changes__name"
:class="`changes__name--${stateColor(row.state)}`"
>{{ baseName(row.file.path) }}</span>
<span class="changes__dir">{{ detail(row) }}</span>
<span class="changes__state">{{ stateLabel(row.state) }}</span>
</div>
</div>
</div>
<form
class="changes__commit"
data-test="changes-commit"
@submit.prevent="changes.commit()"
>
<textarea
ref="messageBox"
v-model="changes.message"
class="changes__message"
rows="3"
:placeholder="t('vcs.commit.placeholder')"
:aria-label="t('vcs.commit.messageLabel')"
:disabled="changes.phase !== 'ready'"
data-test="changes-message"
@keydown="onMessageKey"
/>
<div class="changes__commit-row">
<label class="changes__amend">
<input
v-model="changes.amend"
type="checkbox"
:disabled="changes.phase !== 'ready' || changes.busy"
data-test="changes-amend"
>
{{ t("vcs.commit.amend") }}
</label>
<button
type="submit"
class="changes__commit-button"
:disabled="!changes.canCommit"
:title="commitHint"
data-test="changes-commit-button"
>
{{ commitLabel }}
</button>
</div>
</form>
</div>
</template>
<style scoped>
.changes {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
}
.changes__bar {
display: flex;
align-items: center;
gap: var(--lt-space-s, 4px);
padding: var(--lt-space-xs, 2px) var(--lt-space-m, 8px);
}
.changes__status {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--lt-fg-muted);
}
.changes__hint {
padding: 0 var(--lt-space-m, 8px) var(--lt-space-xs, 2px);
color: var(--lt-fg-muted);
}
.changes__icon-button {
display: inline-flex;
align-items: center;
justify-content: center;
padding: var(--lt-space-xs, 2px);
color: var(--lt-fg-muted);
background: transparent;
border: none;
border-radius: var(--lt-radius, 4px);
cursor: pointer;
}
.changes__icon-button:hover:not(:disabled) {
color: var(--lt-fg);
background: color-mix(in srgb, var(--lt-fg) 8%, transparent);
}
.changes__icon-button:focus-visible {
outline: 2px solid var(--lt-accent);
}
.changes__list {
flex: 1;
min-height: 0;
overflow: auto;
border-top: 1px solid var(--lt-border);
outline: none;
}
.changes__list:focus-visible {
box-shadow: inset 0 0 0 1px var(--lt-accent);
}
.changes__group {
display: flex;
align-items: center;
gap: var(--lt-space-s, 4px);
padding: var(--lt-space-xs, 2px) var(--lt-space-m, 8px);
white-space: nowrap;
}
.changes__group-title {
font-weight: 600;
}
.changes__group-count {
color: var(--lt-fg-muted);
}
.changes__check {
flex: none;
margin: 0;
accent-color: var(--lt-accent);
}
.changes__row {
display: flex;
align-items: center;
gap: var(--lt-space-m, 8px);
padding: 0 var(--lt-space-m, 8px) 0 var(--lt-space-l, 24px);
white-space: nowrap;
cursor: default;
}
.changes__row:hover {
background: color-mix(in srgb, var(--lt-fg) 6%, transparent);
}
.changes__row--selected,
.changes__row--selected:hover {
background: var(--lt-editor-selection-bg);
}
.changes__name--added {
color: var(--lt-vcs-added);
}
.changes__name--modified {
color: var(--lt-vcs-modified);
}
.changes__name--deleted {
color: var(--lt-vcs-deleted);
text-decoration: line-through;
}
.changes__name--untracked {
color: var(--lt-vcs-untracked);
}
.changes__name--ignored {
color: var(--lt-vcs-ignored);
}
.changes__name--conflicted {
color: var(--lt-vcs-conflicted);
}
.changes__dir {
overflow: hidden;
text-overflow: ellipsis;
color: var(--lt-fg-muted);
}
.changes__state {
flex: none;
margin-left: auto;
color: var(--lt-fg-muted);
}
.changes__row--selected .changes__dir,
.changes__row--selected .changes__state {
color: var(--lt-fg);
}
.changes__commit {
display: flex;
flex-direction: column;
gap: var(--lt-space-xs, 2px);
padding: var(--lt-space-s, 4px) var(--lt-space-m, 8px);
border-top: 1px solid var(--lt-border);
}
.changes__message {
resize: vertical;
min-height: 3em;
padding: var(--lt-space-xs, 2px) var(--lt-space-s, 4px);
font: inherit;
color: var(--lt-fg);
background: var(--lt-editor-bg);
border: 1px solid var(--lt-border);
border-radius: var(--lt-radius, 4px);
}
.changes__message:focus-visible {
outline: 2px solid var(--lt-accent);
outline-offset: -1px;
}
.changes__commit-row {
display: flex;
align-items: center;
gap: var(--lt-space-m, 8px);
}
.changes__amend {
display: inline-flex;
align-items: center;
gap: var(--lt-space-xs, 2px);
color: var(--lt-fg);
}
.changes__commit-button {
margin-left: auto;
padding: var(--lt-space-xs, 2px) var(--lt-space-l, 24px);
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;
}
.changes__commit-button:disabled {
opacity: 0.5;
cursor: default;
}
.changes__commit-button:focus-visible {
outline: 2px solid var(--lt-fg);
outline-offset: 1px;
}
</style>

View file

@ -0,0 +1,581 @@
/**
* The Changes tool window's state (M4.2): the project's changed files from
* `git.status`, grouped as Staged, Changes and Untracked, plus staging,
* unstaging and committing.
*
* - **Source:** `git.status` (a pending outcome, so through `runWaiting`)
* on start, when a project opens, on `gitChanged` and on `vcs.refresh`.
* Calls are serialised; a refresh asked for while one runs runs once
* more afterwards. A project close clears everything.
* - **Groups:** a file is Staged when its index side changed, in Changes
* when its work tree side changed or it is conflicted, and Untracked when
* git does not track it. A partly staged file is in both Staged and
* Changes. Ignored files are not listed by the backend.
* - **Staging:** `git.stage` / `git.unstage` per file or per group.
* Unstaging a staged rename passes both paths, as the backend asks.
* - **Commit:** `flushDirty()` first, so the files on disk hold what the
* editor shows; a save that failed cancels the commit. Then `git.commit
* {message, amend}`; success toasts the short hash and clears the box.
* - **Untrusted input:** the status comes from the engine and, through it,
* from git; malformed entries are dropped and the count capped
* ({@link MAX_FILES}).
*/
import { defineStore } from "pinia";
import { computed, ref, shallowRef } from "vue";
import { onEngineEvent, runWaiting, type EngineEventPayload, type JsonValue } from "../../../ipc";
import { useAutosaveStore } from "../../../stores/autosave";
import { useNotificationsStore } from "../../../stores/notifications";
/** Most files kept from one status. */
export const MAX_FILES = 50_000;
/** Length of the short commit hash shown to people. */
export const SHORT_HASH = 7;
/** States of one side of a file, as `git.status` names them. */
export const FILE_STATES = [
"unmodified",
"modified",
"added",
"deleted",
"renamed",
"copied",
"untracked",
"ignored",
"conflicted",
] as const;
/** State of one side (index or work tree) of a file. */
export type FileState = (typeof FILE_STATES)[number];
/** A changed file as `git.status` reports it. */
export interface ChangedFile {
/** Project-relative path with `/`. */
path: string;
/** The old path of a rename or copy. */
origPath?: string;
/** State in the index against HEAD. */
index: FileState;
/** State in the work tree against the index. */
worktree: FileState;
}
/** The repository summary of `git.status`. */
export interface RepoSummary {
/** Work tree root, absolute with `/`. */
root: string;
/** Current branch; absent when detached or unborn without a name. */
branch?: string;
/** Whether HEAD is detached. */
detached: boolean;
/** Full hash of HEAD; absent before the first commit. */
head?: string;
}
/** The groups of the window, in display order. */
export const GROUPS = ["staged", "changes", "untracked"] as const;
/** A group of the window. */
export type GroupId = (typeof GROUPS)[number];
/** A file in a group: one row of the list. */
export interface ChangeRow {
/** Stable key: group and path. */
key: string;
/** The group it is shown in. */
group: GroupId;
/** The file. */
file: ChangedFile;
/** The state shown: the index side in Staged, the work tree side otherwise. */
state: FileState;
}
/** What the window shows above the groups. */
export type ChangesPhase = "idle" | "loading" | "unavailable" | "noRepo" | "ready";
/**
* Reads a state; null if unknown.
*
* @param raw - untrusted.
*/
function toState(raw: unknown): FileState | null {
return FILE_STATES.find((s) => s === raw) ?? null;
}
/**
* Reads one file of `git.status`; null if malformed.
*
* @param raw - an untrusted entry of `files`.
*/
export function toFile(raw: unknown): ChangedFile | null {
if (typeof raw !== "object" || raw === null) {
return null;
}
const f = raw as Record<string, unknown>;
const index = toState(f.index);
const worktree = toState(f.worktree);
if (typeof f.path !== "string" || f.path === "" || !index || !worktree) {
return null;
}
const file: ChangedFile = { path: f.path, index, worktree };
if (typeof f.origPath === "string" && f.origPath !== "") {
file.origPath = f.origPath;
}
return file;
}
/**
* Reads the repository summary; null when absent or malformed.
*
* @param raw - the untrusted `repo` field.
*/
export function toRepo(raw: unknown): RepoSummary | null {
if (typeof raw !== "object" || raw === null) {
return null;
}
const r = raw as Record<string, unknown>;
if (typeof r.root !== "string") {
return null;
}
const repo: RepoSummary = { root: r.root, detached: r.detached === true };
if (typeof r.branch === "string" && r.branch !== "") {
repo.branch = r.branch;
}
if (typeof r.head === "string" && r.head !== "") {
repo.head = r.head;
}
return repo;
}
/** A status as the store keeps it. */
export interface StatusSnapshot {
/** Whether a usable git was found. */
available: boolean;
/** Why git is unavailable or the repository could not be opened. */
error: string | null;
/** The repository, or null outside one. */
repo: RepoSummary | null;
/** Changed files sorted by path. */
files: ChangedFile[];
}
/**
* Reads the result of `git.status`; null if it is not an object.
*
* @param raw - untrusted.
*/
export function toStatus(raw: unknown): StatusSnapshot | null {
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
return null;
}
const s = raw as Record<string, unknown>;
const files: ChangedFile[] = [];
if (Array.isArray(s.files)) {
for (const entry of s.files as unknown[]) {
if (files.length >= MAX_FILES) {
break;
}
const file = toFile(entry);
if (file) {
files.push(file);
}
}
}
files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
return {
available: s.available === true,
error: typeof s.error === "string" && s.error !== "" ? s.error : null,
repo: toRepo(s.repo),
files,
};
}
/**
* Whether a side's state means "changed".
*
* @param state - the state.
*/
function changed(state: FileState): boolean {
return state !== "unmodified" && state !== "untracked" && state !== "ignored";
}
/**
* Splits files into the three groups.
*
* @param files - the files sorted by path.
* @returns the rows of each group, in path order.
*/
export function groupFiles(files: ChangedFile[]): Record<GroupId, ChangeRow[]> {
const out: Record<GroupId, ChangeRow[]> = { staged: [], changes: [], untracked: [] };
const add = (group: GroupId, file: ChangedFile, state: FileState): void => {
out[group].push({ key: `${group}:${file.path}`, group, file, state });
};
for (const file of files) {
if (file.index === "untracked" || file.worktree === "untracked") {
add("untracked", file, "untracked");
continue;
}
if (file.index === "conflicted" || file.worktree === "conflicted") {
add("changes", file, "conflicted");
continue;
}
if (changed(file.index)) {
add("staged", file, file.index);
}
if (changed(file.worktree)) {
add("changes", file, file.worktree);
}
}
return out;
}
/**
* The paths to pass to `git.unstage` for some staged rows: a rename or
* copy also passes its old path.
*
* @param rows - staged rows.
*/
export function unstagePaths(rows: ChangeRow[]): string[] {
const paths: string[] = [];
for (const row of rows) {
paths.push(row.file.path);
if (row.file.origPath !== undefined && row.file.index === "renamed") {
paths.push(row.file.origPath);
}
}
return [...new Set(paths)];
}
/** The Changes store. */
export const useChangesStore = defineStore("changes", () => {
const notifications = useNotificationsStore();
/** Whether the tool window is shown in the bottom panel. */
const visible = ref(false);
/** Whether the panel is expanded while Changes is shown. */
const expanded = ref(true);
/** The last status read; null before the first one or without a project. */
const status = shallowRef<StatusSnapshot | null>(null);
/** Whether a `git.status` call runs. */
const loading = ref(false);
/** The error of the last `git.status` call itself (not git's state). */
const loadError = ref<string | null>(null);
/** Whether a stage, unstage or commit runs. */
const busy = ref(false);
/** The commit message being written. */
const message = ref("");
/** Whether the next commit amends HEAD. */
const amend = ref(false);
/** Key of the selected row. */
const selectedKey = ref<string | null>(null);
/** Bumped when the message box should take the keyboard focus. */
const focusRequest = ref(0);
/** Whether a focus request waits for the window (it may mount later). */
const focusPending = ref(false);
/** The rows of each group. */
const groups = computed(() => groupFiles(status.value?.files ?? []));
/** Every row in display order. */
const rows = computed<ChangeRow[]>(() => GROUPS.flatMap((group) => groups.value[group]));
/** Index of the selected row, -1 if none. */
const selectedIndex = computed(() => rows.value.findIndex((row) => row.key === selectedKey.value));
/** What the window shows above the groups. */
const phase = computed<ChangesPhase>(() => {
const s = status.value;
if (!s) {
return loading.value ? "loading" : "idle";
}
if (!s.available) {
return "unavailable";
}
return s.repo ? "ready" : "noRepo";
});
/** Whether Commit can run now. */
const canCommit = computed(
() =>
!busy.value &&
phase.value === "ready" &&
message.value.trim() !== "" &&
(amend.value || groups.value.staged.length > 0),
);
/** Counts refresh requests, so a round knows whether another came in. */
let requests = 0;
/** Reads `git.status` once. */
async function loadOnce(): Promise<void> {
const result = await runWaiting("git.status");
if (!result.ok) {
loadError.value = result.error.message;
if (result.error.code === "disabled") {
status.value = null;
}
return;
}
const next = toStatus(result.value);
loadError.value = next ? null : "unexpected result of git.status";
status.value = next;
if (selectedKey.value !== null && !rows.value.some((row) => row.key === selectedKey.value)) {
selectedKey.value = null;
}
}
/** The `git.status` round running now, shared by callers. */
let running: Promise<void> | null = null;
/**
* Re-reads the status from git: `vcs.refresh`, `gitChanged`, project
* open. Serialised: a call while one runs makes it read once more
* afterwards and shares its promise.
*/
function refresh(): Promise<void> {
requests += 1;
if (running) {
return running;
}
loading.value = true;
running = (async () => {
let seen: number;
do {
seen = requests;
await loadOnce();
} while (seen !== requests);
})().finally(() => {
running = null;
loading.value = false;
});
return running;
}
/** Drops the status and the selection (project closed). */
function clear(): void {
status.value = null;
loadError.value = null;
selectedKey.value = null;
}
/**
* Runs a mutating git command, toasting its failure.
*
* @param command - `git.stage`, `git.unstage` or `git.commit`.
* @param params - its params.
* @returns its value, or null when it failed.
*/
async function mutate(command: string, params: JsonValue): Promise<unknown> {
const result = await runWaiting(command, params);
if (!result.ok) {
notifications.notifyError(command, result.error);
return null;
}
return result.value;
}
/**
* Stages files.
*
* @param list - rows of Changes or Untracked; others are ignored.
*/
async function stage(list: ChangeRow[]): Promise<void> {
const paths = [...new Set(list.filter((row) => row.group !== "staged").map((row) => row.file.path))];
if (paths.length === 0 || busy.value) {
return;
}
busy.value = true;
try {
if ((await mutate("git.stage", { paths })) !== null) {
await refresh();
}
} finally {
busy.value = false;
}
}
/**
* Unstages files.
*
* @param list - rows of Staged; others are ignored.
*/
async function unstage(list: ChangeRow[]): Promise<void> {
const paths = unstagePaths(list.filter((row) => row.group === "staged"));
if (paths.length === 0 || busy.value) {
return;
}
busy.value = true;
try {
if ((await mutate("git.unstage", { paths })) !== null) {
await refresh();
}
} finally {
busy.value = false;
}
}
/**
* Stages a row outside Staged, unstages a staged one.
*
* @param row - the row.
*/
function toggle(row: ChangeRow): Promise<void> {
return row.group === "staged" ? unstage([row]) : stage([row]);
}
/**
* Stages or unstages a whole group.
*
* @param group - the group.
*/
function toggleGroup(group: GroupId): Promise<void> {
const list = groups.value[group];
return group === "staged" ? unstage(list) : stage(list);
}
/**
* Saves every dirty buffer, then commits the staged changes with the
* message (or amends HEAD). Does nothing while {@link canCommit} is
* false. A failed save cancels the commit with a warning; a failed commit
* toasts git's message and keeps the box as it was.
*
* @returns the new commit's hash, or null when nothing was committed.
*/
async function commit(): Promise<string | null> {
if (!canCommit.value) {
return null;
}
busy.value = true;
try {
const flushed = await useAutosaveStore().flushDirty();
if (flushed.error !== null || flushed.failed.length > 0) {
notifications.notify({ level: "warning", messageKey: "notification.vcs.commitNotSaved" });
return null;
}
const value = await mutate("git.commit", { message: message.value, amend: amend.value });
if (value === null) {
return null;
}
const v = typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
const hash = typeof v.commit === "string" ? v.commit : "";
const summary = typeof v.summary === "string" ? v.summary : "";
notifications.notify({
level: "info",
messageKey: "notification.vcs.committed",
params: { hash: hash.slice(0, SHORT_HASH), summary },
});
message.value = "";
amend.value = false;
await refresh();
return hash;
} finally {
busy.value = false;
}
}
/**
* Applies one engine event.
*
* @param event - the event.
*/
function onEvent(event: EngineEventPayload): void {
if (event.kind === "gitChanged" || event.kind === "projectOpened") {
void refresh();
} else if (event.kind === "projectClosed") {
clear();
}
}
/** Ends the event subscription; set while started. */
let unsubscribe: (() => void) | null = null;
/** Subscribes to engine events and reads the status once. */
function start(): void {
if (unsubscribe) {
return;
}
unsubscribe = onEngineEvent(onEvent);
void refresh();
}
/** Ends the subscription. */
function stop(): void {
unsubscribe?.();
unsubscribe = null;
}
/** Shows the tool window: `vcs.openChanges`. */
function open(): void {
visible.value = true;
expanded.value = true;
}
/** Shows the tool window and focuses the message box: `vcs.commit`. */
function focusMessage(): void {
open();
focusPending.value = true;
focusRequest.value += 1;
}
/** Hides the tool window; the status and the message stay. */
function hide(): void {
visible.value = false;
}
/**
* Selects a row.
*
* @param key - the row key, or null for none.
*/
function select(key: string | null): void {
selectedKey.value = key;
}
/**
* Moves the selection by `delta` rows, clamped to the list.
*
* @param delta - rows to move; positive is down.
*/
function move(delta: number): void {
const list = rows.value;
if (list.length === 0) {
return;
}
const from = selectedIndex.value < 0 ? (delta > 0 ? -1 : list.length) : selectedIndex.value;
const index = Math.min(list.length - 1, Math.max(0, from + delta));
selectedKey.value = list[index]?.key ?? null;
}
return {
visible,
expanded,
status,
loading,
loadError,
busy,
message,
amend,
selectedKey,
selectedIndex,
focusRequest,
focusPending,
groups,
rows,
phase,
canCommit,
refresh,
stage,
unstage,
toggle,
toggleGroup,
commit,
onEvent,
start,
stop,
open,
focusMessage,
hide,
select,
move,
};
});

View file

@ -19,6 +19,9 @@
"command.settings.open": "Settings…",
"command.terminal.open": "Terminal",
"command.unavailable": "{command} cannot run right now",
"command.vcs.commit": "Commit…",
"command.vcs.openChanges": "Changes",
"command.vcs.refresh": "Refresh Changes",
"command.view.toggleProjectTree": "Show or Hide Project",
"command.view.toggleStructure": "Show or Hide Structure",
"common.cancel": "Cancel",
@ -142,6 +145,8 @@
"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.commitNotSaved": "Commit cancelled: not every file could be saved first.",
"notification.vcs.committed": "Committed {hash}: {summary}",
"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",
@ -254,5 +259,39 @@
"terminal.tabs.label": "Terminals",
"terminal.toolWindow.title": "Terminal",
"theme.lutraDark": "Lutra Dark",
"theme.lutraLight": "Lutra Light"
"theme.lutraLight": "Lutra Light",
"vcs.changes.clean": "{branch}: no changes",
"vcs.changes.group.changes": "Changes",
"vcs.changes.group.staged": "Staged",
"vcs.changes.group.untracked": "Untracked",
"vcs.changes.list.label": "Changed files",
"vcs.changes.loading": "Reading the Git status…",
"vcs.changes.noCommits": "no commits yet",
"vcs.changes.noProject": "Open a project to see its changes",
"vcs.changes.noRepo": "This project is not in a Git repository",
"vcs.changes.renamedFrom": "from {path}",
"vcs.changes.repoError": "The Git repository cannot be read: {reason}",
"vcs.changes.stageFile": "Stage {path}",
"vcs.changes.stageGroup": "Stage all in {group}",
"vcs.changes.summary": "{branch}: {staged} staged, {changes} changed, {untracked} untracked",
"vcs.changes.toolWindow.title": "Changes",
"vcs.changes.unavailable": "Git is not available: {reason}",
"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.commit.amend": "Amend",
"vcs.commit.amendButton": "Amend Commit",
"vcs.commit.button": "Commit",
"vcs.commit.hint": "Commit the staged changes ({keys})",
"vcs.commit.messageLabel": "Commit message",
"vcs.commit.placeholder": "Commit message",
"vcs.state.added": "added",
"vcs.state.conflicted": "conflicted",
"vcs.state.copied": "copied",
"vcs.state.deleted": "deleted",
"vcs.state.ignored": "ignored",
"vcs.state.modified": "modified",
"vcs.state.renamed": "renamed",
"vcs.state.unmodified": "unmodified",
"vcs.state.untracked": "untracked"
}

View file

@ -134,6 +134,15 @@ export type EngineEventPayload =
path: unknown;
/** `[{range, severity, message, source?, code?}]`, empty when cleared; unchecked. */
items: unknown;
}
| {
kind: "gitChanged";
/** Whether a usable git was found; unchecked. */
available: unknown;
/** The repository summary of `git.status`, or null; unchecked. */
repo: unknown;
/** Always true: re-query `git.status`. */
filesChanged: unknown;
};
/** Callback receiving engine events. */