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

@ -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;
}