M4.3: side-by-side diff viewer with next/previous change

vcs.showDiff {path?, staged?} (Mod+Alt+Shift+D) opens a "Diff: <name>"
tab in the editor area: @codemirror/merge (MIT, loaded lazily, 27 kB /
9.7 kB gzip), with the index (or HEAD for the staged view) read-only on
the left, line breaks normalised to LF, and the working copy on the right,
editable through its normal engine buffer. vcs.nextChange (Alt+Shift+])
and vcs.previousChange (Alt+Shift+[) move between chunks. Binary, too
large, failed and deleted files show a notice. Entry points: the Changes
window, a new project tree context menu (Open, Show Diff; right click or
Shift+F10) and the palette/menu. Colours come from the --lt-vcs-* tokens.
21 Vitest tests; parity docs updated (Git 6% -> 8%, est.).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-26 17:23:52 +01:00
parent 468b9928a7
commit 8360ffc2e2
23 changed files with 1836 additions and 24 deletions

View file

@ -38,5 +38,8 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [
{ id: "vcs.commit", labelKey: "command.vcs.commit", menuPath: "Git/Commit…", defaultShortcut: "Mod+Alt+Shift+M" },
{ 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" },
{ id: "vcs.nextChange", labelKey: "command.vcs.nextChange", menuPath: "Git/Next Change", defaultShortcut: "Alt+Shift+]" },
{ id: "vcs.previousChange", labelKey: "command.vcs.previousChange", menuPath: "Git/Previous Change", defaultShortcut: "Alt+Shift+[" },
{ id: "view.toggleStructure", labelKey: "command.view.toggleStructure", menuPath: "View/Structure", defaultShortcut: "Mod+2" },
];

View file

@ -7,9 +7,11 @@
* palette (`commands/store.ts`): the area supplies their behaviour with the
* active buffer as context and says when they can run. It also supplies the
* UI commands `editor.reveal` (`reveal.ts`) and the assist commands
* (`assist/commands.ts`).
* (`assist/commands.ts`). Diff tabs (M4.3, `vcs/diff/`) share the tab bar;
* while one is active the diff view replaces the editor, and the area
* supplies the diff commands.
*/
import { onBeforeUnmount, onMounted } from "vue";
import { defineAsyncComponent, onBeforeUnmount, onMounted } from "vue";
import { useCommandsStore } from "../../commands/store";
import { t } from "../../i18n";
import { useEditorStore } from "../../stores/editor";
@ -18,9 +20,15 @@ import CodeEditor from "./CodeEditor.vue";
import EditorTabs from "./EditorTabs.vue";
import { reveal, REVEAL_COMMAND } from "./reveal";
import * as assist from "./assist/commands";
import { provideDiffCommands } from "../vcs/diff/commands";
import { useDiffStore } from "../vcs/diff/diff";
/** The diff view, loaded on first use so `@codemirror/merge` stays out of the start bundle. */
const DiffView = defineAsyncComponent(() => import("../vcs/diff/DiffView.vue"));
const editor = useEditorStore();
const commands = useCommandsStore();
const diff = useDiffStore();
/** Withdraws the command handlers; filled while mounted. */
let withdraw: (() => void)[] = [];
@ -36,6 +44,7 @@ onMounted(() => {
commands.provide(assist.COMPLETE_COMMAND, { run: assist.completeAtCursor, enabled: assist.assistEnabled }),
commands.provide(assist.QUICK_DOC_COMMAND, { run: assist.quickDocumentation, enabled: assist.assistEnabled }),
commands.provide(assist.PARAMETER_INFO_COMMAND, { run: assist.parameterInfo, enabled: assist.assistEnabled }),
...provideDiffCommands(commands),
];
});
@ -53,10 +62,10 @@ onBeforeUnmount(() => {
class="editor-area"
data-test="editor-area"
>
<template v-if="editor.tabs.length > 0">
<template v-if="editor.tabs.length > 0 || diff.tabs.length > 0">
<EditorTabs />
<div
v-if="editor.activeTab?.notice"
v-if="!diff.visible && editor.activeTab?.notice"
class="editor-area__notice"
:class="{ 'editor-area__notice--error': editor.activeTab.notice.kind === 'error' }"
role="status"
@ -72,7 +81,8 @@ onBeforeUnmount(() => {
{{ t("common.dismiss") }}
</button>
</div>
<CodeEditor />
<DiffView v-if="diff.visible" />
<CodeEditor v-else-if="editor.activeTab" />
</template>
<div
v-else

View file

@ -5,15 +5,51 @@
* A click activates a tab, a middle click or the close button closes it,
* Left/Right move between tabs. A dot marks unsaved changes. Closing a
* dirty tab asks first (see the editor store). Names are coloured by their
* Git status (`--lt-vcs-*`, M4.4).
* Git status (`--lt-vcs-*`, M4.4). Diff tabs (M4.3, `vcs/diff/diff.ts`)
* follow the editor tabs; while one is active, no editor tab is marked
* active.
*/
import { X } from "@lucide/vue";
import { t } from "../../i18n";
import { useEditorStore } from "../../stores/editor";
import { useVcsStatusStore } from "../../stores/vcsStatus";
import { useDiffStore } from "../vcs/diff/diff";
const editor = useEditorStore();
const vcs = useVcsStatusStore();
const diff = useDiffStore();
/**
* Whether an editor tab is the active one.
*
* @param id - buffer id of the tab.
*/
function isActive(id: number): boolean {
return id === editor.activeId && !diff.visible;
}
/**
* Shows an editor tab (and hides an active diff).
*
* @param id - buffer id of the tab.
*/
function activateTab(id: number): void {
diff.deactivate();
editor.activate(id);
}
/**
* Closes a diff tab on a middle click.
*
* @param event - the auxiliary click.
* @param key - key of the diff tab.
*/
function onDiffAuxClick(event: MouseEvent, key: string): void {
if (event.button === 1) {
event.preventDefault();
diff.close(key);
}
}
/**
* Closes a tab on a middle click.
@ -42,7 +78,7 @@ function onKeydown(event: KeyboardEvent): void {
event.preventDefault();
const next = editor.tabs[(index + step + editor.tabs.length) % editor.tabs.length];
if (next) {
editor.activate(next.id);
activateTab(next.id);
}
}
</script>
@ -59,14 +95,14 @@ function onKeydown(event: KeyboardEvent): void {
v-for="tab in editor.tabs"
:key="tab.id"
class="tabs__tab"
:class="{ 'tabs__tab--active': tab.id === editor.activeId }"
:class="{ 'tabs__tab--active': isActive(tab.id) }"
role="tab"
:tabindex="tab.id === editor.activeId ? 0 : -1"
:aria-selected="tab.id === editor.activeId"
:tabindex="isActive(tab.id) ? 0 : -1"
:aria-selected="isActive(tab.id)"
:title="tab.path"
:data-id="tab.id"
data-test="editor-tab"
@click="editor.activate(tab.id)"
@click="activateTab(tab.id)"
@mousedown.middle.prevent
@auxclick="onAuxClick($event, tab.id)"
>
@ -92,6 +128,33 @@ function onKeydown(event: KeyboardEvent): void {
<X :size="12" />
</button>
</div>
<div
v-for="tab in diff.tabs"
:key="tab.key"
class="tabs__tab"
:class="{ 'tabs__tab--active': tab.key === diff.activeKey }"
role="tab"
:tabindex="tab.key === diff.activeKey ? 0 : -1"
:aria-selected="tab.key === diff.activeKey"
:title="tab.path"
:data-key="tab.key"
data-test="diff-tab"
@click="diff.activate(tab.key)"
@mousedown.middle.prevent
@auxclick="onDiffAuxClick($event, tab.key)"
>
<span class="tabs__name">{{ tab.staged ? t("vcs.diff.tabTitleStaged", { name: tab.name }) : t("vcs.diff.tabTitle", { name: tab.name }) }}</span>
<button
class="tabs__close"
type="button"
tabindex="-1"
:aria-label="t('vcs.diff.closeTab', { name: tab.name })"
data-test="diff-tab-close"
@click.stop="diff.close(tab.key)"
>
<X :size="12" />
</button>
</div>
</div>
</template>

View file

@ -10,6 +10,8 @@
* the engine listed only partly ends with a "listing truncated" note.
* File names are coloured by their Git status (`--lt-vcs-*`, M4.4); inside
* a repository, ignored entries take the ignored colour.
* A right click on a file, or Shift+F10 / the context-menu key on the
* selected file, opens its context menu (`TreeContextMenu.vue`, M4.3).
*/
import { ChevronDown, ChevronRight, File, FileCode, Folder, FolderOpen } from "@lucide/vue";
import { computed, nextTick, ref } from "vue";
@ -18,6 +20,7 @@ import { parentOf, useProjectStore, type TreeRow } from "../../stores/project";
import { useEditorStore } from "../../stores/editor";
import { useVcsStatusStore, type VcsColour } from "../../stores/vcsStatus";
import type { TreeEntry } from "./engineEvents";
import TreeContextMenu from "./TreeContextMenu.vue";
const project = useProjectStore();
const editor = useEditorStore();
@ -89,6 +92,40 @@ function isPhp(name: string): boolean {
return /\.(php|phtml|inc)$/i.test(name);
}
/** The open context menu: the file and where it shows; null when closed. */
const menu = ref<{ path: string; name: string; x: number; y: number } | null>(null);
/**
* Opens the context menu of a file; folders have none yet.
*
* @param entry - the entry.
* @param x - window x of the menu.
* @param y - window y of the menu.
*/
function openMenu(entry: TreeEntry, x: number, y: number): void {
if (entry.kind !== "file") {
return;
}
project.select(entry.path);
menu.value = { path: entry.path, name: entry.name, x, y };
}
/**
* Opens the context menu of the selected file from the keyboard, below its row.
*
* @param entry - the selected entry.
*/
function openMenuAtRow(entry: TreeEntry): void {
const rect = document.getElementById(rowId(entry.path))?.getBoundingClientRect();
openMenu(entry, rect ? rect.left + 24 : 0, rect ? rect.bottom : 0);
}
/** Closes the context menu and gives the focus back to the tree. */
function closeMenu(): void {
menu.value = null;
treeEl.value?.focus();
}
/** Scrolls the selected row into view after the DOM updated. */
async function revealSelected(): Promise<void> {
await nextTick();
@ -209,6 +246,13 @@ function onKeydown(event: KeyboardEvent): void {
activate(row.entry);
}
break;
case "ContextMenu":
case "F10":
if (!row || (event.key === "F10" && !event.shiftKey)) {
return;
}
openMenuAtRow(row.entry);
break;
default:
return;
}
@ -256,6 +300,7 @@ function onFocus(): void {
data-test="tree-row"
@click="onRowClick(row.entry, false)"
@dblclick="activate(row.entry)"
@contextmenu.prevent="openMenu(row.entry, $event.clientX, $event.clientY)"
>
<span
class="tree__chevron"
@ -325,6 +370,16 @@ function onFocus(): void {
{{ row.error.message }}
</div>
</template>
<Teleport to="body">
<TreeContextMenu
v-if="menu"
:path="menu.path"
:name="menu.name"
:x="menu.x"
:y="menu.y"
@close="closeMenu"
/>
</Teleport>
</div>
</template>

View file

@ -0,0 +1,201 @@
<script setup lang="ts">
/**
* The project tree's context menu for a file (M4.3): Open and Show Diff
* (`vcs.showDiff {path}`, dimmed while the command is disabled).
*
* Follows the WAI-ARIA menu pattern: it takes the focus when it opens,
* Up/Down move between items (wrapping), Enter or Space runs one, Escape,
* Tab or a press outside closes it. The position is clamped into the
* window.
*/
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from "vue";
import { useCommandsStore } from "../../commands/store";
import { t } from "../../i18n";
import { useEditorStore } from "../../stores/editor";
import { SHOW_DIFF_COMMAND } from "../vcs/diff/diff";
const props = defineProps<{
/** Project-relative path of the file. */
path: string;
/** File name, for the accessible label. */
name: string;
/** Window x of the pointer (or the row) in pixels. */
x: number;
/** Window y of the pointer (or the row) in pixels. */
y: number;
}>();
const emit = defineEmits<{
/** The menu should close (an item ran or the user dismissed it). */
close: [];
}>();
const editor = useEditorStore();
const commands = useCommandsStore();
/** The menu element. */
const menuEl = ref<HTMLElement | null>(null);
/** Index of the focused item. */
const focused = ref(0);
/** One item of the menu. */
interface MenuItem {
/** Stable id, also used by tests. */
id: string;
/** Text shown. */
label: string;
/** Whether it can run now. */
enabled: boolean;
/** Runs it. */
run: () => Promise<void>;
}
/** The items, in order. */
const items = computed<MenuItem[]>(() => [
{
id: "open",
label: t("project.tree.menu.open"),
enabled: true,
run: async () => {
await editor.openFile(props.path);
},
},
{
id: "showDiff",
label: t("project.tree.menu.showDiff"),
enabled: commands.isEnabled(SHOW_DIFF_COMMAND),
run: () => commands.execute(SHOW_DIFF_COMMAND, { path: props.path }),
},
]);
/** The menu's position, kept inside the window. */
const position = computed(() => ({
left: `${String(Math.max(0, Math.min(props.x, window.innerWidth - 200)))}px`,
top: `${String(Math.max(0, Math.min(props.y, window.innerHeight - 80)))}px`,
}));
/**
* Runs an item and closes the menu.
*
* @param item - the item.
*/
async function choose(item: MenuItem): Promise<void> {
if (!item.enabled) {
return;
}
emit("close");
await item.run();
}
/**
* Keyboard handling of the menu.
*
* @param event - the key event.
*/
function onKeydown(event: KeyboardEvent): void {
const count = items.value.length;
switch (event.key) {
case "ArrowDown":
focused.value = (focused.value + 1) % count;
break;
case "ArrowUp":
focused.value = (focused.value - 1 + count) % count;
break;
case "Enter":
case " ": {
const item = items.value[focused.value];
if (item) {
void choose(item);
}
break;
}
case "Escape":
case "Tab":
emit("close");
break;
default:
return;
}
event.preventDefault();
event.stopPropagation();
}
/**
* Closes the menu on a press outside it.
*
* @param event - the pointer event on the window.
*/
function onPointerDown(event: PointerEvent): void {
if (menuEl.value && event.target instanceof Node && !menuEl.value.contains(event.target)) {
emit("close");
}
}
onMounted(() => {
window.addEventListener("pointerdown", onPointerDown, true);
void nextTick(() => menuEl.value?.focus());
});
onBeforeUnmount(() => {
window.removeEventListener("pointerdown", onPointerDown, true);
});
</script>
<template>
<div
ref="menuEl"
class="tree-menu"
role="menu"
tabindex="-1"
:aria-label="t('project.tree.menu.label', { name })"
:aria-activedescendant="`lt-tree-menu-${items[focused]?.id ?? ''}`"
:style="position"
data-test="tree-menu"
@keydown="onKeydown"
@contextmenu.prevent
>
<div
v-for="(item, index) in items"
:id="`lt-tree-menu-${item.id}`"
:key="item.id"
class="tree-menu__item"
:class="{ 'tree-menu__item--focused': index === focused, 'tree-menu__item--disabled': !item.enabled }"
role="menuitem"
:aria-disabled="!item.enabled"
:data-item="item.id"
data-test="tree-menu-item"
@mouseenter="focused = index"
@click="choose(item)"
>
{{ item.label }}
</div>
</div>
</template>
<style scoped>
.tree-menu {
position: fixed;
z-index: 50;
min-width: 160px;
padding: 4px 0;
color: var(--lt-fg);
background: var(--lt-bg);
border: 1px solid var(--lt-border);
border-radius: 4px;
outline: none;
}
.tree-menu__item {
padding: 4px 16px;
cursor: default;
white-space: nowrap;
}
.tree-menu__item--focused {
background: var(--lt-editor-selection-bg);
}
.tree-menu__item--disabled {
color: var(--lt-fg-muted);
}
</style>

View file

@ -0,0 +1,338 @@
<script setup lang="ts">
/**
* The active diff tab (M4.3): a side-by-side `@codemirror/merge` view of
* the ref (left, read-only) and the working copy (right, editable), or a
* notice for binary, too large and failed diffs.
*
* - **Right side and the buffer:** the right editor starts from the
* working copy's {@link BufferSync} state. Every local change of it is
* handed to the sync, which sends it to the engine like typing in the
* file's own tab (the file's tab is hidden while the diff shows, so the
* sync has no view of its own). Engine changes to the buffer (a reload
* from disk, an agent's edit) come back through `bufferChanged`: once the
* sync has taken them over, the difference is applied to the right
* editor outside its undo history.
* - **Left side:** replaced in place when the store re-reads it
* (`gitChanged` after staging).
* - **Colours:** only `--lt-*` tokens; changed lines are tinted with
* `--lt-vcs-deleted` (left) and `--lt-vcs-added` (right).
* - **Navigation:** a navigator over the merge view is registered for
* `vcs.nextChange` / `vcs.previousChange` (`navigation.ts`): the focused
* side, else the working copy, moves to the next or previous chunk.
*/
import { getChunks, goToNextChunk, goToPreviousChunk, MergeView } from "@codemirror/merge";
import { Annotation, EditorState, Transaction, type Extension } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { basicSetup } from "codemirror";
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { t } from "../../../i18n";
import { onEngineEvent } from "../../../ipc";
import { useEditorStore } from "../../../stores/editor";
import type { BufferSync } from "../../editor/bufferSync";
import { diffDocs } from "../../editor/engineText";
import { editorExtensions, lutraEditorTheme } from "../../editor/extensions";
import { languageExtensions } from "../../editor/language";
import { refFor, useDiffStore } from "./diff";
import { setNavigator } from "./navigation";
const diff = useDiffStore();
const editor = useEditorStore();
/** Element the merge view is mounted in. */
const host = ref<HTMLElement | null>(null);
/** The merge view, null while none is built. */
let merge: MergeView | null = null;
/** The sync of the right side, null when the working copy is missing. */
let sync: BufferSync | null = null;
/** What the current merge view was built for, to rebuild only on a change. */
let builtFor = "";
/** Ends the engine event subscription. */
let unsubscribe: (() => void) | null = null;
/** Marks right-side transactions that carry the buffer's changes, so they are not sent back. */
const fromBuffer = Annotation.define<boolean>();
/** Colours of the diff, from tokens only. */
const diffTheme: Extension = EditorView.theme({
"&.cm-merge-a .cm-changedLine, .cm-deletedChunk": {
backgroundColor: "color-mix(in srgb, var(--lt-vcs-deleted) 14%, var(--lt-editor-bg))",
},
"&.cm-merge-b .cm-changedLine, .cm-inlineChangedLine": {
backgroundColor: "color-mix(in srgb, var(--lt-vcs-added) 14%, var(--lt-editor-bg))",
},
"&.cm-merge-a .cm-changedText, .cm-deletedChunk .cm-deletedText": {
background: "color-mix(in srgb, var(--lt-vcs-deleted) 35%, transparent)",
},
"&.cm-merge-b .cm-changedText": {
background: "color-mix(in srgb, var(--lt-vcs-added) 35%, transparent)",
},
"&.cm-merge-b .cm-deletedText": {
background: "color-mix(in srgb, var(--lt-vcs-deleted) 35%, transparent)",
},
".cm-collapsedLines": {
color: "var(--lt-fg-muted)",
background: "var(--lt-bg)",
borderTop: "1px solid var(--lt-border)",
borderBottom: "1px solid var(--lt-border)",
},
"&.cm-merge-a .cm-changedLineGutter, .cm-deletedLineGutter": {
background: "var(--lt-vcs-deleted)",
},
"&.cm-merge-b .cm-changedLineGutter": {
background: "var(--lt-vcs-added)",
},
});
/** The header line: what is compared with what. */
const caption = computed(() => {
const tab = diff.activeTab;
if (!tab) {
return "";
}
return refFor(tab.staged) === "HEAD"
? t("vcs.diff.captionHead", { path: tab.path })
: t("vcs.diff.captionIndex", { path: tab.path });
});
/** The notice shown instead of, or above, the diff; null if none. */
const notice = computed(() => {
const content = diff.activeContent;
switch (content?.phase) {
case "binary":
return t("vcs.diff.binary");
case "tooLarge":
return t("vcs.diff.tooLarge");
case "error":
return t("vcs.diff.failed", { reason: content.message ?? "" });
case "ready":
return content.message;
default:
return null;
}
});
/**
* Hands local changes of the right editor to the buffer's sync.
*
* @param transactions - transactions the right editor applied.
*/
function forward(transactions: readonly Transaction[]): void {
if (!sync) {
return;
}
for (const tr of transactions) {
if (!tr.docChanged || tr.annotation(fromBuffer) === true) {
continue;
}
const changes = sync.state.doc.eq(tr.startState.doc) ? tr.changes : diffDocs(sync.state.doc, tr.state.doc);
const userEvent = tr.annotation(Transaction.userEvent);
sync.dispatch(userEvent === undefined ? { changes } : { changes, userEvent });
}
}
/** Brings the right editor up to the buffer's text, outside its undo history. */
function pullFromBuffer(): void {
if (!merge || !sync) {
return;
}
const from = merge.b.state.doc;
const to = sync.state.doc;
if (from.eq(to)) {
return;
}
merge.b.dispatch({
changes: diffDocs(from, to),
annotations: [fromBuffer.of(true), Transaction.addToHistory.of(false)],
});
}
/** Destroys the merge view. */
function destroy(): void {
setNavigator(null);
merge?.destroy();
merge = null;
sync = null;
builtFor = "";
}
/** Builds the merge view for the active tab, or rebuilds it when its inputs changed. */
function build(): void {
const tab = diff.activeTab;
const content = diff.activeContent;
const key = tab && content?.phase === "ready" ? `${tab.key}#${String(content.bufferId ?? "none")}` : "";
if (key === builtFor && merge) {
return;
}
destroy();
if (!tab || !content || content.phase !== "ready" || !host.value) {
return;
}
const bufferId = content.bufferId;
sync = bufferId === null ? null : (editor.syncOf(bufferId) ?? null);
const readOnly = [EditorState.readOnly.of(true), EditorView.editable.of(false)];
const right: Extension = sync
? [
editorExtensions(tab.path, { id: sync.id, idle: () => sync?.idle() ?? Promise.resolve() }),
diffTheme,
EditorView.updateListener.of((update) => {
forward(update.transactions);
}),
]
: [basicSetup, lutraEditorTheme, languageExtensions(tab.path), diffTheme, readOnly];
merge = new MergeView({
a: { doc: content.left, extensions: [basicSetup, lutraEditorTheme, languageExtensions(tab.path), diffTheme, readOnly] },
b: sync ? { doc: sync.state.doc, selection: sync.state.selection, extensions: right } : { doc: "", extensions: right },
parent: host.value,
gutter: true,
highlightChanges: true,
collapseUnchanged: { margin: 3, minSize: 8 },
});
builtFor = key;
const view = merge;
const side = (): EditorView => (view.a.hasFocus ? view.a : view.b);
setNavigator({
view,
hasChanges: () => (getChunks(side().state)?.chunks.length ?? 0) > 0,
go: (direction) => {
const target = side();
const moved = (direction > 0 ? goToNextChunk : goToPreviousChunk)(target);
target.focus();
return moved;
},
});
}
/** Replaces the left document with the store's text after a re-read. */
function updateLeft(): void {
const content = diff.activeContent;
if (!merge || content?.phase !== "ready") {
return;
}
const doc = merge.a.state.doc;
if (doc.toString() !== content.left) {
merge.a.dispatch({ changes: { from: 0, to: doc.length, insert: content.left } });
}
}
watch(
() => [diff.activeKey, diff.activeContent] as const,
() => {
build();
},
);
watch(
() => diff.leftRevision,
() => {
updateLeft();
},
);
onMounted(() => {
build();
unsubscribe = onEngineEvent((event) => {
if (event.kind !== "bufferChanged" || !sync || event.id !== sync.id) {
return;
}
const target = sync;
void Promise.resolve()
.then(() => target.idle())
.then(() => {
if (sync === target) {
pullFromBuffer();
}
});
});
});
onBeforeUnmount(() => {
unsubscribe?.();
unsubscribe = null;
destroy();
});
</script>
<template>
<div
class="diff-view"
data-test="diff-view"
:data-path="diff.activeTab?.path"
>
<div
class="diff-view__caption"
data-test="diff-caption"
>
{{ caption }}
</div>
<div
v-if="notice"
class="diff-view__notice"
role="status"
data-test="diff-notice"
>
{{ notice }}
</div>
<div
v-if="diff.activeContent?.phase === 'loading'"
class="diff-view__loading"
data-test="diff-loading"
>
{{ t("vcs.diff.loading") }}
</div>
<div
v-show="diff.activeContent?.phase === 'ready'"
ref="host"
class="diff-view__merge"
data-test="diff-merge"
/>
</div>
</template>
<style scoped>
.diff-view {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
background: var(--lt-editor-bg);
}
.diff-view__caption {
flex-shrink: 0;
padding: 3px 12px;
color: var(--lt-fg-muted);
background: var(--lt-bg);
border-bottom: 1px solid var(--lt-border);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.diff-view__notice {
flex-shrink: 0;
padding: 4px 12px;
color: var(--lt-fg);
background: var(--lt-notice-bg);
border-bottom: 1px solid var(--lt-border);
}
.diff-view__loading {
padding: 12px;
color: var(--lt-fg-muted);
}
.diff-view__merge {
flex: 1;
min-height: 0;
overflow: auto;
user-select: text;
}
.diff-view__merge :deep(.cm-mergeView) {
min-height: 100%;
}
.diff-view__merge :deep(.cm-mergeViewEditor + .cm-mergeViewEditor) {
border-left: 1px solid var(--lt-border);
}
</style>

View file

@ -0,0 +1,43 @@
/**
* The diff viewer's UI commands, supplied by the editor area:
*
* - `vcs.showDiff {path?, staged?}`: opens the diff of a file; without a
* path, of the active diff or editor tab (the palette). Enabled while a
* project is open.
* - `vcs.nextChange` / `vcs.previousChange`: move to the next or previous
* change of the visible diff. Enabled while a diff with changes shows.
*/
import type { useCommandsStore } from "../../../commands/store";
import { useProjectStore } from "../../../stores/project";
import { NEXT_CHANGE_COMMAND, PREVIOUS_CHANGE_COMMAND, SHOW_DIFF_COMMAND, useDiffStore } from "./diff";
import { goToChange, hasChanges } from "./navigation";
/**
* Supplies the diff commands and starts the diff store.
*
* @param commands - the command store.
* @returns functions that withdraw the handlers and stop the store.
*/
export function provideDiffCommands(commands: ReturnType<typeof useCommandsStore>): (() => void)[] {
const diff = useDiffStore();
const project = useProjectStore();
diff.start();
return [
commands.provide(SHOW_DIFF_COMMAND, { run: (params) => diff.showDiff(params), enabled: () => project.root !== null }),
commands.provide(NEXT_CHANGE_COMMAND, {
run: () => {
goToChange(1);
},
enabled: () => diff.activeContent?.phase === "ready" && hasChanges(),
}),
commands.provide(PREVIOUS_CHANGE_COMMAND, {
run: () => {
goToChange(-1);
},
enabled: () => diff.activeContent?.phase === "ready" && hasChanges(),
}),
() => {
diff.stop();
},
];
}

View file

@ -0,0 +1,475 @@
/**
* The diff viewer's state (M4.3): the "Diff: <name>" tabs of the editor
* area and what each one compares.
*
* - **Opening:** the UI command `vcs.showDiff {path, staged?}` (Changes
* window, the project tree's context menu, the palette). One tab per path
* and side; opening it again activates and reloads it.
* - **Left side:** `git.show {path, ref}` (a pending outcome, so through
* `runWaiting`). `staged: true` compares with HEAD; otherwise with the
* index, which equals HEAD for a file without staged changes, so a
* partly staged file shows only what is not staged yet. A path missing at
* that ref (a new or untracked file) gives an empty left side. Git
* returns the blob as stored (LF when autocrlf normalised it), so line
* breaks are normalised to `\n` ({@link normaliseEol}); CodeMirror keeps
* lines, not break characters, so a CRLF working copy lines up.
* - **Right side:** the working copy as an ordinary engine buffer, opened
* through the editor store, so its edits, saves, autosave and the
* recovery journal work as in any tab (the buffer also gets its normal
* tab). A file missing from the working copy (deleted) shows an empty,
* read-only right side and a notice.
* - **Notices instead of a diff:** binary files and files over git's cap
* (`binary` / `tooLarge` of `git.show`).
* - **Active tab:** a diff tab is shown over the editor tab that was
* active when it was activated (the anchor). Any other editor tab
* becoming active hides the diff again; the editor tabs bar deactivates
* it on a click.
* - **Refresh:** `gitChanged` re-reads the left side of every text tab
* (staging changes the index). A project open or close drops every tab;
* closing the working copy's buffer closes its diff tabs.
* - **Untrusted input:** `git.show` results are checked field by field.
*/
import { defineStore } from "pinia";
import { computed, ref, shallowRef, watch } from "vue";
import { t } from "../../../i18n";
import { onEngineEvent, runWaiting, type EngineEventPayload, type JsonValue } from "../../../ipc";
import { baseName, useEditorStore } from "../../../stores/editor";
/** Command id that opens a diff. */
export const SHOW_DIFF_COMMAND = "vcs.showDiff";
/** Command id that moves to the next change of the active diff. */
export const NEXT_CHANGE_COMMAND = "vcs.nextChange";
/** Command id that moves to the previous change of the active diff. */
export const PREVIOUS_CHANGE_COMMAND = "vcs.previousChange";
/** The ref a diff compares the working copy with. */
export type DiffRef = "HEAD" | "index";
/** Params of `vcs.showDiff`, checked. */
export interface ShowDiffParams {
/** Project-relative path; null for the active editor tab's file. */
path: string | null;
/** Whether to compare with HEAD (the staged view). */
staged: boolean;
}
/** One diff tab. */
export interface DiffTab {
/** Stable key: side and path. */
key: string;
/** Project-relative path with `/`. */
path: string;
/** Whether it compares with HEAD instead of the index. */
staged: boolean;
/** File name shown on the tab. */
name: string;
}
/** What a diff tab shows. */
export type DiffPhase = "loading" | "ready" | "binary" | "tooLarge" | "error";
/** The loaded contents of a diff tab. */
export interface DiffContent {
/** What the tab shows. */
phase: DiffPhase;
/** The left text with `\n` breaks; empty when missing at the ref. */
left: string;
/** Whether the path does not exist at the ref (a new file). */
leftMissing: boolean;
/** Engine buffer of the working copy, null when it could not be opened. */
bufferId: number | null;
/** Error text, or why the working copy is missing; null if none. */
message: string | null;
}
/** A `git.show` result, checked. */
export interface ShowResult {
/** The text, null when the path does not exist at the ref. */
text: string | null;
/** Whether git sees the file as binary. */
binary: boolean;
/** Whether the file is over git's size cap. */
tooLarge: boolean;
}
/**
* Turns every line break into `\n`.
*
* @param text - text with any mix of `\r\n`, `\r` and `\n`.
*/
export function normaliseEol(text: string): string {
return text.replace(/\r\n?/g, "\n");
}
/**
* The ref to compare with.
*
* @param staged - whether the staged view (HEAD) is asked for.
*/
export function refFor(staged: boolean): DiffRef {
return staged ? "HEAD" : "index";
}
/**
* The key of a diff tab.
*
* @param path - project-relative path.
* @param staged - the side.
*/
export function diffKey(path: string, staged: boolean): string {
return `${staged ? "staged" : "work"}:${path}`;
}
/**
* Reads the params of `vcs.showDiff`; null when malformed.
*
* @param params - untrusted (`{}` from the palette and the keyboard).
*/
export function parseShowDiff(params: unknown): ShowDiffParams | null {
const p = typeof params === "object" && params !== null && !Array.isArray(params) ? (params as Record<string, unknown>) : {};
const path = p.path === undefined || p.path === null ? null : typeof p.path === "string" && p.path !== "" ? p.path : undefined;
const staged = p.staged === undefined || p.staged === null ? false : typeof p.staged === "boolean" ? p.staged : undefined;
if (path === undefined || staged === undefined) {
return null;
}
return { path, staged };
}
/**
* Reads a `git.show` result; null when malformed.
*
* @param raw - untrusted.
*/
export function toShowResult(raw: unknown): ShowResult | null {
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
return null;
}
const r = raw as Record<string, unknown>;
if (r.text !== null && typeof r.text !== "string") {
return null;
}
return { text: r.text, binary: r.binary === true, tooLarge: r.tooLarge === true };
}
/** A tab's content while it loads. */
const LOADING: DiffContent = { phase: "loading", left: "", leftMissing: false, bufferId: null, message: null };
/** The diff store. */
export const useDiffStore = defineStore("diff", () => {
const editor = useEditorStore();
/** Open diff tabs in display order. */
const tabs = ref<DiffTab[]>([]);
/** Key of the active diff tab, null when an editor tab is shown. */
const activeKey = ref<string | null>(null);
/** Contents by tab key; replaced as a whole on every change. */
const contents = shallowRef<Record<string, DiffContent>>({});
/** Bumped whenever a tab's left text is re-read with a different result. */
const leftRevision = ref(0);
/** The editor tab shown under the active diff (see the module docs). */
let anchor: number | null = null;
/** Loads opening the working copy now; the editor tab they activate becomes the anchor. */
let anchoring = 0;
/** Load generation by tab key, so only the newest load of a tab lands. */
const generations = new Map<string, number>();
/** The active diff tab, null when none is shown. */
const activeTab = computed(() => tabs.value.find((tab) => tab.key === activeKey.value) ?? null);
/** Whether a diff tab covers the editor now. */
const visible = computed(() => activeTab.value !== null);
/** The content of the active tab, null when none is shown. */
const activeContent = computed(() => (activeTab.value ? (contents.value[activeTab.value.key] ?? LOADING) : null));
watch(
() => editor.activeId,
(id) => {
if (anchoring > 0) {
anchor = id;
} else if (id !== anchor) {
activeKey.value = null;
}
},
{ flush: "sync" },
);
watch(
() => editor.tabs.map((tab) => tab.id),
(ids) => {
for (const tab of [...tabs.value]) {
const bufferId = contents.value[tab.key]?.bufferId;
if (bufferId !== undefined && bufferId !== null && !ids.includes(bufferId)) {
close(tab.key);
}
}
},
);
/**
* Stores the content of a tab.
*
* @param key - the tab key.
* @param content - its content.
*/
function setContent(key: string, content: DiffContent): void {
contents.value = { ...contents.value, [key]: content };
}
/**
* The content of a tab.
*
* @param key - the tab key.
*/
function contentOf(key: string): DiffContent | null {
return contents.value[key] ?? null;
}
/**
* Shows a diff tab over the active editor tab.
*
* @param key - the tab key.
*/
function activate(key: string): void {
if (tabs.value.some((tab) => tab.key === key)) {
anchor = editor.activeId;
activeKey.value = key;
}
}
/** Shows the editor tab again. */
function deactivate(): void {
activeKey.value = null;
}
/**
* Reads the left side of a diff.
*
* @param tab - the tab.
* @returns the checked result, or the error text.
*/
async function readLeft(tab: DiffTab): Promise<ShowResult | string> {
const result = await runWaiting("git.show", { path: tab.path, ref: refFor(tab.staged) });
if (!result.ok) {
return result.error.message;
}
return toShowResult(result.value) ?? t("common.error.unexpectedResult", { command: "git.show" });
}
/**
* Opens the working copy of a tab as an engine buffer.
*
* @param tab - the tab.
* @returns the buffer id, or the reason it could not be opened.
*/
async function openRight(tab: DiffTab): Promise<number | string> {
const existing = editor.tabs.find((editorTab) => editorTab.path === tab.path);
if (existing && editor.syncOf(existing.id)) {
return existing.id;
}
const before = editor.lastError;
const wasActive = activeKey.value === tab.key;
if (wasActive) {
anchoring += 1;
}
try {
const id = await editor.openFile(tab.path);
if (id !== null) {
return id;
}
const reason = editor.lastError?.message ?? "";
editor.lastError = before;
return reason;
} finally {
if (wasActive) {
anchoring -= 1;
if (activeKey.value === tab.key) {
anchor = editor.activeId;
}
}
}
}
/**
* Loads both sides of a tab.
*
* @param tab - the tab.
*/
async function load(tab: DiffTab): Promise<void> {
const generation = (generations.get(tab.key) ?? 0) + 1;
generations.set(tab.key, generation);
const current = (): boolean => generations.get(tab.key) === generation && tabs.value.some((t) => t.key === tab.key);
setContent(tab.key, LOADING);
const left = await readLeft(tab);
if (!current()) {
return;
}
if (typeof left === "string") {
setContent(tab.key, { ...LOADING, phase: "error", message: left });
return;
}
if (left.binary || left.tooLarge) {
setContent(tab.key, { ...LOADING, phase: left.binary ? "binary" : "tooLarge" });
return;
}
const right = await openRight(tab);
if (!current()) {
return;
}
setContent(tab.key, {
phase: "ready",
left: normaliseEol(left.text ?? ""),
leftMissing: left.text === null,
bufferId: typeof right === "number" ? right : null,
message: typeof right === "number" ? null : t("vcs.diff.workingCopyMissing", { reason: right }),
});
}
/**
* Opens (or activates and reloads) the diff of a file.
*
* @param path - project-relative path.
* @param staged - compare with HEAD instead of the index.
*/
async function open(path: string, staged: boolean): Promise<void> {
const key = diffKey(path, staged);
let tab = tabs.value.find((t) => t.key === key);
if (!tab) {
tab = { key, path, staged, name: baseName(path) };
tabs.value.push(tab);
}
activate(key);
await load(tab);
}
/**
* Re-reads the left side of every loaded text tab; a changed text
* replaces the left document (`gitChanged`).
*/
async function refreshLeft(): Promise<void> {
await Promise.all(
tabs.value.map(async (tab) => {
const before = contents.value[tab.key];
if (before?.phase !== "ready") {
return;
}
const generation = generations.get(tab.key);
const left = await readLeft(tab);
const now = contents.value[tab.key];
if (generations.get(tab.key) !== generation || now?.phase !== "ready" || typeof left === "string") {
return;
}
if (left.binary || left.tooLarge) {
setContent(tab.key, { ...LOADING, phase: left.binary ? "binary" : "tooLarge" });
return;
}
const text = normaliseEol(left.text ?? "");
if (text !== now.left || (left.text === null) !== now.leftMissing) {
setContent(tab.key, { ...now, left: text, leftMissing: left.text === null });
leftRevision.value += 1;
}
}),
);
}
/**
* Closes a diff tab; the working copy's buffer stays open.
*
* @param key - the tab key.
*/
function close(key: string): void {
const index = tabs.value.findIndex((tab) => tab.key === key);
if (index < 0) {
return;
}
tabs.value.splice(index, 1);
generations.delete(key);
contents.value = Object.fromEntries(Object.entries(contents.value).filter(([k]) => k !== key));
if (activeKey.value === key) {
activeKey.value = null;
const next = tabs.value[Math.min(index, tabs.value.length - 1)];
if (next && editor.tabs.length === 0) {
activate(next.key);
}
}
}
/** Drops every tab (project opened or closed). */
function clear(): void {
tabs.value = [];
activeKey.value = null;
contents.value = {};
generations.clear();
}
/**
* Applies one engine event.
*
* @param event - the event.
*/
function onEvent(event: EngineEventPayload): void {
if (event.kind === "projectOpened" || event.kind === "projectClosed") {
clear();
} else if (event.kind === "gitChanged") {
void refreshLeft();
}
}
/** Ends the event subscription; set while started. */
let unsubscribe: (() => void) | null = null;
/** Subscribes to engine events; calling it again has no effect. */
function start(): void {
unsubscribe ??= onEngineEvent(onEvent);
}
/** Ends the subscription. */
function stop(): void {
unsubscribe?.();
unsubscribe = null;
}
/**
* Runs `vcs.showDiff`: the given file, else the active diff's or editor
* tab's file.
*
* @param params - untrusted params.
* @throws Error with a catalog message when the params are malformed or
* there is no file to compare.
*/
async function showDiff(params: JsonValue): Promise<void> {
const parsed = parseShowDiff(params);
if (!parsed) {
throw new Error(t("vcs.diff.invalidParams"));
}
const path = parsed.path ?? activeTab.value?.path ?? editor.activeTab?.path ?? null;
if (path === null) {
throw new Error(t("vcs.diff.noFile"));
}
const staged = parsed.path === null && activeTab.value ? activeTab.value.staged : parsed.staged;
await open(path, staged);
}
return {
tabs,
activeKey,
activeTab,
activeContent,
visible,
contents,
leftRevision,
contentOf,
activate,
deactivate,
open,
showDiff,
refreshLeft,
close,
clear,
onEvent,
start,
stop,
};
});

View file

@ -0,0 +1,58 @@
/**
* Next/previous change in the diff shown now (`vcs.nextChange`,
* `vcs.previousChange`). The diff view registers a navigator here while it
* shows a merge view; the commands move the cursor of the side that has
* the focus (the working copy otherwise) to the next or previous changed
* chunk, wrapping around, and scroll it into view.
*
* This module does not import `@codemirror/merge`, so the package stays in
* the lazily loaded diff view's chunk.
*/
import type { MergeView } from "@codemirror/merge";
/** What the diff view offers the commands. */
export interface DiffNavigator {
/** The merge view (tests read it). */
view: MergeView;
/** Whether the diff has at least one change. */
hasChanges(): boolean;
/**
* Moves to the next or previous change.
*
* @param direction - 1 for the next change, -1 for the previous one.
* @returns whether the cursor moved.
*/
go(direction: 1 | -1): boolean;
}
/** The navigator of the diff shown now, null when none is visible. */
let current: DiffNavigator | null = null;
/**
* Registers the navigator of the diff shown now.
*
* @param navigator - the navigator, or null when the merge view goes away.
*/
export function setNavigator(navigator: DiffNavigator | null): void {
current = navigator;
}
/** The merge view shown now, null when none. */
export function currentMerge(): MergeView | null {
return current?.view ?? null;
}
/** Whether the visible diff has at least one change. */
export function hasChanges(): boolean {
return current?.hasChanges() ?? false;
}
/**
* Moves to the next or previous change of the visible diff.
*
* @param direction - 1 for the next change, -1 for the previous one.
* @returns whether the cursor moved.
*/
export function goToChange(direction: 1 | -1): boolean {
return current?.go(direction) ?? false;
}

View file

@ -20,8 +20,11 @@
"command.terminal.open": "Terminal",
"command.unavailable": "{command} cannot run right now",
"command.vcs.commit": "Commit…",
"command.vcs.nextChange": "Next Change",
"command.vcs.openChanges": "Changes",
"command.vcs.previousChange": "Previous Change",
"command.vcs.refresh": "Refresh Changes",
"command.vcs.showDiff": "Show Diff",
"command.view.toggleProjectTree": "Show or Hide Project",
"command.view.toggleStructure": "Show or Hide Structure",
"common.cancel": "Cancel",
@ -177,6 +180,9 @@
"project.openFolder": "Open Folder…",
"project.toolWindow.title": "Project",
"project.tree.loading": "Loading…",
"project.tree.menu.label": "Actions for {name}",
"project.tree.menu.open": "Open",
"project.tree.menu.showDiff": "Show Diff",
"project.tree.truncated": "Listing truncated: more entries than can be shown",
"recovery.dialog.changedOnDisk": "The file changed on disk since then",
"recovery.dialog.discard": "Discard",
@ -292,6 +298,18 @@
"vcs.commit.hint": "Commit the staged changes ({keys})",
"vcs.commit.messageLabel": "Commit message",
"vcs.commit.placeholder": "Commit message",
"vcs.diff.binary": "Binary file: no text diff to show.",
"vcs.diff.captionHead": "{path}: last commit (left) and working copy (right)",
"vcs.diff.captionIndex": "{path}: staged version (left) and working copy (right)",
"vcs.diff.closeTab": "Close the diff of {name}",
"vcs.diff.failed": "The diff cannot be shown: {reason}",
"vcs.diff.invalidParams": "vcs.showDiff takes {path?: string, staged?: boolean}",
"vcs.diff.loading": "Reading the file from Git…",
"vcs.diff.noFile": "Open a file or pass a path to show its diff",
"vcs.diff.tabTitle": "Diff: {name}",
"vcs.diff.tabTitleStaged": "Diff: {name} (staged)",
"vcs.diff.tooLarge": "The file is too large to compare.",
"vcs.diff.workingCopyMissing": "The working copy cannot be opened ({reason}); it may have been deleted.",
"vcs.state.added": "added",
"vcs.state.conflicted": "conflicted",
"vcs.state.copied": "copied",