M4.8: merge conflicts with a three-pane resolve view

Backend (crates/vcs/src/merge.rs, cmd/git_merge.rs via start_with):
git.merge {branch} -> {result: merged|upToDate|conflicts, conflicts},
git.mergeAbort, git.conflictVersions {path} -> {base?, ours, theirs,
binary, tooLarge} from the index stages :1:/:2:/:3:, git.markResolved
{paths}. Repo::lock becomes pub(crate) so merge and abort hold the
mutation lock.

UI (ui/src/components/vcs/merge/): merge dialog with branch picker,
conflicts list from the shared status store, a three-pane resolve view
(ours / editable result / theirs) with accept left/right per chunk,
accept all, previous/next conflict, Apply through the file's buffer then
mark resolved, keep-a-side for modify/delete, abort after confirmation.
Own three-way line merge on @codemirror/merge's diff. UI commands
vcs.merge, vcs.resolveConflicts, vcs.abortMerge (no default shortcuts);
the Changes window opens conflicted rows in the resolve view.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-29 17:48:24 +01:00
parent 74c674ed12
commit d82e57b3ac
26 changed files with 3872 additions and 16 deletions

View file

@ -3,7 +3,7 @@
* Root component: mounts the main window layout with the editor area; the
* slogan shows while no tab is open, and the restore dialog for unsaved
* texts from the recovery journal, the toast stack, the command palette,
* the go-to popup and the settings dialog. Loads product information from the engine on
* the go-to popup, the settings dialog and the merge dialog. Loads product information from the engine on
* mount, starts showing notifications, following the theme (see
* `theme.ts`; a failed theme report raises an error toast) and the global
* keymap with the UI commands (see `commands/store.ts`), and loads the settings so the
@ -21,6 +21,7 @@ import NavLayer from "./components/editor/nav/NavLayer.vue";
import NotificationStack from "./components/notifications/NotificationStack.vue";
import RecoveryDialog from "./components/recovery/RecoveryDialog.vue";
import SettingsDialog from "./components/settings/SettingsDialog.vue";
import MergeDialog from "./components/vcs/merge/MergeDialog.vue";
import { useAppStore } from "./stores/app";
import { useAutosaveStore } from "./stores/autosave";
import { useNotificationsStore } from "./stores/notifications";
@ -71,6 +72,7 @@ onUnmounted(() => {
<CommandPalette />
<GotoPopup />
<SettingsDialog />
<MergeDialog />
<NavLayer />
<NotificationStack />
</template>

View file

@ -19,7 +19,8 @@
* command but `menu.open` closes it.
* - **Navigation (M3.5):** the definition picker and the inline rename field
* are exclusive modals too. So is the branches popup (M4.5), and so are
* "Clone Repository…" and "Manage Remotes…" (M4.10).
* "Clone Repository…" and "Manage Remotes…" (M4.10) and the merge
* dialog (M4.8).
*/
import { defineStore } from "pinia";
import { ref, watch } from "vue";
@ -36,7 +37,8 @@ export type ModalId =
| "rename"
| "branches"
| "clone"
| "remotes";
| "remotes"
| "merge";
/** Store of the open exclusive modal. */
export const useModalsStore = defineStore("modals", () => {

View file

@ -42,6 +42,9 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [
{ id: "vcs.fetch", labelKey: "command.vcs.fetch", menuPath: "Git/Fetch" },
{ id: "vcs.manageRemotes", labelKey: "command.vcs.manageRemotes", menuPath: "Git/Manage Remotes…" },
{ id: "vcs.newBranch", labelKey: "command.vcs.newBranch", menuPath: "Git/New Branch…" },
{ id: "vcs.merge", labelKey: "command.vcs.merge", menuPath: "Git/Merge…" },
{ id: "vcs.resolveConflicts", labelKey: "command.vcs.resolveConflicts", menuPath: "Git/Resolve Conflicts…" },
{ id: "vcs.abortMerge", labelKey: "command.vcs.abortMerge", menuPath: "Git/Abort Merge…" },
{ id: "vcs.openChanges", labelKey: "command.vcs.openChanges", menuPath: "Git/Changes", defaultShortcut: "Mod+Alt+Shift+G" },
{ id: "vcs.pull", labelKey: "command.vcs.pull", menuPath: "Git/Pull" },
{ id: "vcs.push", labelKey: "command.vcs.push", menuPath: "Git/Push" },

View file

@ -14,9 +14,11 @@
* (`--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.
* - **Opening:** a conflicted file through `vcs.resolveConflicts {path}`
* (the merge dialog, M4.8); others 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.
@ -204,12 +206,18 @@ function groupToggleLabel(group: GroupId): string {
}
/**
* Opens a row: the diff when `vcs.showDiff` is provided, else the file.
* Opens a row: a conflicted file's resolve view when `vcs.resolveConflicts`
* is provided (M4.8), else 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);
if (row.state === "conflicted" && commands.isEnabled("vcs.resolveConflicts")) {
await commands.execute("vcs.resolveConflicts", { path: row.file.path });
return;
}
const staged = row.group === "staged";
if (commands.isEnabled("vcs.showDiff")) {
await commands.execute("vcs.showDiff", { path: row.file.path, staged });

View file

@ -0,0 +1,917 @@
<script setup lang="ts">
/**
* The merge dialog (M4.8), an exclusive modal (`commands/modals.ts`).
*
* - **Merge** (`vcs.merge`): the branches other than the current one, with
* a filter; choosing one merges it into the current branch.
* - **Conflicts** (`vcs.resolveConflicts`): the conflicted files, each with
* Resolve; Abort merge; with none left, a hint to commit and a Commit
* button (`vcs.commit`).
* - **Resolve** (`vcs.resolveConflicts {path}`, or Resolve in the list): three
* editors, ours (the current branch) left, the result in the middle,
* theirs right (`resolveView.ts`). Per chunk: the » / « buttons in the side
* gutters, or Accept left / Accept right in the toolbar for the chunk
* navigated to (Previous / Next conflict). Accept all left / right. Apply
* (enabled once no chunk is open) writes the result and marks the file
* resolved. Files deleted on one side offer the other side's version;
* binary and too large files can only be marked resolved as they are.
* - **Abort** (`vcs.abortMerge`, or Abort merge in the list): a confirmation
* first; git's refusal shows in the dialog.
* - **Keys:** Escape closes the dialog, except in the resolve view once the
* result was changed (Back or Apply then); Tab stays inside. No default
* shortcuts.
*/
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useModalsStore } from "../../../commands/modals";
import { useCommandsStore } from "../../../commands/store";
import { t } from "../../../i18n";
import { useProjectStore } from "../../../stores/project";
import { useVcsStatusStore } from "../../../stores/vcsStatus";
import { ABORT_COMMAND, MERGE_COMMAND, RESOLVE_COMMAND, useMergeStore } from "./merge";
import { ResolveView } from "./resolveView";
const merge = useMergeStore();
const modals = useModalsStore();
const commands = useCommandsStore();
const project = useProjectStore();
const status = useVcsStatusStore();
/** The dialog element. */
const dialog = ref<HTMLElement | null>(null);
/** The branch filter. */
const filterInput = ref<HTMLInputElement | null>(null);
/** Hosts of the three editors. */
const oursHost = ref<HTMLElement | null>(null);
const resultHost = ref<HTMLElement | null>(null);
const theirsHost = ref<HTMLElement | null>(null);
/** The branch filter text. */
const filter = ref("");
/** Chunks still open in the resolve view. */
const open = ref(0);
/** How many chunks the file has. */
const total = ref(0);
/** Whether the result was changed since it was built. */
const changed = ref(false);
/** The three editors, while the resolve view shows a text file. */
let view: ResolveView | null = null;
/** The element that had the focus before the dialog opened. */
let returnFocus: HTMLElement | null = null;
/** Withdraws the command handlers. */
let withdraw: (() => void)[] = [];
/** Whether the dialog shows. */
const visible = computed(() => merge.mode !== "closed");
/** Branches matching the filter (every word, ignoring case). */
const shownBranches = computed(() => {
const words = filter.value.toLowerCase().split(/\s+/).filter(Boolean);
return merge.branches.filter((name) => words.every((word) => name.toLowerCase().includes(word)));
});
/** The dialog's title. */
const title = computed(() => {
switch (merge.mode) {
case "branches":
return merge.currentBranch === null ? t("vcs.merge.titleMerge") : t("vcs.merge.titleMergeInto", { branch: merge.currentBranch });
case "resolve":
return t("vcs.merge.titleResolve", { path: merge.path ?? "" });
case "abort":
return t("vcs.merge.titleAbort");
default:
return t("vcs.merge.titleConflicts");
}
});
/** The ours column's caption. */
const oursCaption = computed(() =>
merge.currentBranch === null ? t("vcs.merge.ours") : t("vcs.merge.oursBranch", { branch: merge.currentBranch }),
);
/** The line about a file deleted on one side. */
const deletedNotice = computed(() => {
const v = merge.versions;
if (!v) {
return "";
}
return v.ours === null ? t("vcs.merge.deletedOurs") : t("vcs.merge.deletedTheirs");
});
/** The counter of the resolve toolbar. */
const counter = computed(() =>
open.value === 0 ? t("vcs.merge.allResolved") : t("vcs.merge.openCount", { open: String(open.value), total: String(total.value) }),
);
/** Destroys the editors. */
function destroyView(): void {
view?.destroy();
view = null;
open.value = 0;
total.value = 0;
changed.value = false;
}
/** Builds the editors for the loaded text file. */
function buildView(): void {
destroyView();
const v = merge.versions;
if (merge.mode !== "resolve" || merge.phase !== "text" || !v || v.ours === null || v.theirs === null) {
return;
}
if (!oursHost.value || !resultHost.value || !theirsHost.value || merge.path === null) {
return;
}
view = new ResolveView({
path: merge.path,
base: v.base,
ours: v.ours,
theirs: v.theirs,
oursHost: oursHost.value,
resultHost: resultHost.value,
theirsHost: theirsHost.value,
labels: { acceptOurs: t("vcs.merge.acceptLeft"), acceptTheirs: t("vcs.merge.acceptRight") },
onChange: (count) => {
open.value = count;
changed.value = true;
},
});
total.value = view.layout.chunks.length;
open.value = view.open;
view.go(1);
}
/** Closes the dialog and gives the focus back. */
function close(): void {
if (merge.mode === "closed") {
return;
}
destroyView();
merge.close();
}
watch(
() => merge.mode !== "closed",
async (shown) => {
if (shown) {
const active = document.activeElement;
returnFocus = active instanceof HTMLElement && !dialog.value?.contains(active) ? active : returnFocus;
modals.opened("merge", close);
await nextTick();
focusFirst();
} else {
destroyView();
modals.closed("merge");
returnFocus?.focus();
returnFocus = null;
}
},
);
watch(
() => [merge.mode, merge.phase, merge.versions, merge.path] as const,
async () => {
await nextTick();
buildView();
focusFirst();
},
);
/** Focuses the first useful element of the current mode. */
function focusFirst(): void {
if (merge.mode === "branches") {
filterInput.value?.focus();
return;
}
if (view) {
view.resultView.focus();
return;
}
dialog.value?.querySelector<HTMLElement>("button:not(:disabled)")?.focus();
}
/**
* Merges a branch from the list.
*
* @param branch - its name.
*/
async function mergeBranch(branch: string): Promise<void> {
filter.value = "";
await merge.merge(branch);
}
/** Merges the first branch matching the filter (Enter in the filter). */
async function mergeFirst(): Promise<void> {
const first = shownBranches.value[0];
if (first !== undefined) {
await mergeBranch(first);
}
}
/** Writes the result and marks the file resolved. */
async function apply(): Promise<void> {
if (!view || merge.path === null || open.value > 0) {
return;
}
const ok = await merge.resolve(merge.path, view.result);
if (ok) {
destroyView();
}
}
/**
* Keeps one side's whole file (one side deleted it).
*
* @param side - the side to keep.
*/
async function keep(side: "ours" | "theirs"): Promise<void> {
const v = merge.versions;
const text = side === "ours" ? v?.ours : v?.theirs;
if (merge.path === null || text === null || text === undefined) {
return;
}
await merge.resolve(merge.path, text);
}
/** Marks the file resolved as it is on disk. */
async function markAsIs(): Promise<void> {
if (merge.path !== null) {
await merge.resolve(merge.path, null);
}
}
/** Goes back from the resolve view to the list. */
function back(): void {
destroyView();
merge.showConflicts();
}
/** Runs `vcs.commit` to conclude the merge. */
async function commit(): Promise<void> {
close();
await commands.execute("vcs.commit", {});
}
/** The elements Tab reaches inside the dialog, in order. */
function focusables(): HTMLElement[] {
const root = dialog.value;
if (!root) {
return [];
}
return [...root.querySelectorAll<HTMLElement>("button:not(:disabled), input, .cm-content[contenteditable=true]")];
}
/**
* Escape and the Tab cycle.
*
* @param event - the key event.
*/
function onKeydown(event: KeyboardEvent): void {
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
if (merge.mode === "resolve" && changed.value) {
return;
}
close();
return;
}
if (event.key !== "Tab") {
return;
}
const list = focusables();
const first = list[0];
const last = list.at(-1);
if (!first || !last) {
event.preventDefault();
return;
}
const active = document.activeElement;
const inside = active instanceof HTMLElement && list.some((el) => el === active || el.contains(active));
if (event.shiftKey && (active === first || !inside)) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && (active === last || !inside)) {
event.preventDefault();
first.focus();
}
}
onMounted(() => {
const inRepo = (): boolean => project.root !== null && status.repo;
withdraw = [
commands.provide(MERGE_COMMAND, { run: (params) => merge.mergeCommand(params), enabled: inRepo }),
commands.provide(RESOLVE_COMMAND, { run: (params) => merge.resolveCommand(params), enabled: inRepo }),
commands.provide(ABORT_COMMAND, {
run: () => {
merge.askAbort();
},
enabled: inRepo,
}),
];
});
onBeforeUnmount(() => {
for (const undo of withdraw) {
undo();
}
withdraw = [];
destroyView();
});
</script>
<template>
<div
v-if="visible"
class="merge"
data-test="merge"
@mousedown.self.prevent="merge.mode === 'resolve' && changed ? undefined : close()"
>
<div
ref="dialog"
class="merge__dialog"
:class="{ 'merge__dialog--wide': merge.mode === 'resolve' }"
role="dialog"
aria-modal="true"
aria-labelledby="lt-merge-title"
data-test="merge-dialog"
@keydown="onKeydown"
>
<header class="merge__header">
<h2
id="lt-merge-title"
class="merge__title"
data-test="merge-title"
>
{{ title }}
</h2>
</header>
<section
v-if="merge.mode === 'branches'"
class="merge__body"
>
<input
ref="filterInput"
v-model="filter"
class="merge__filter"
type="search"
spellcheck="false"
:aria-label="t('vcs.merge.filter')"
:placeholder="t('vcs.merge.filter')"
data-test="merge-filter"
@keydown.enter.prevent="mergeFirst()"
>
<p
v-if="merge.branchesError !== null"
class="merge__error"
>
{{ t("vcs.branches.loadFailed", { reason: merge.branchesError }) }}
</p>
<p
v-else-if="shownBranches.length === 0"
class="merge__hint"
>
{{ t("vcs.merge.noBranches") }}
</p>
<ul
class="merge__list"
:aria-label="t('vcs.merge.branchesLabel')"
>
<li
v-for="name in shownBranches"
:key="name"
>
<button
type="button"
class="merge__row"
:disabled="merge.busy"
data-test="merge-branch"
:data-branch="name"
@click="mergeBranch(name)"
>
{{ name }}
</button>
</li>
</ul>
</section>
<section
v-else-if="merge.mode === 'conflicts'"
class="merge__body"
>
<template v-if="merge.conflicts.length > 0">
<p class="merge__hint">
{{ t("vcs.merge.conflictsHint") }}
</p>
<ul
class="merge__list"
:aria-label="t('vcs.merge.conflictsLabel')"
>
<li
v-for="file in merge.conflicts"
:key="file"
class="merge__file"
data-test="merge-conflict"
:data-path="file"
@dblclick="merge.openFile(file)"
>
<span class="merge__path">{{ file }}</span>
<button
type="button"
class="merge__button"
data-test="merge-resolve"
:aria-label="t('vcs.merge.resolveFile', { path: file })"
@click="merge.openFile(file)"
>
{{ t("vcs.merge.resolve") }}
</button>
</li>
</ul>
</template>
<template v-else>
<p
class="merge__hint"
data-test="merge-none"
>
{{ t("vcs.merge.noConflicts") }}
</p>
</template>
<p
v-if="merge.error !== null"
class="merge__error"
>
{{ merge.error }}
</p>
<footer class="merge__footer">
<button
type="button"
class="merge__button"
data-test="merge-ask-abort"
@click="merge.askAbort()"
>
{{ t("vcs.merge.abort") }}
</button>
<button
v-if="merge.conflicts.length === 0"
type="button"
class="merge__button merge__button--primary"
data-test="merge-commit"
@click="commit()"
>
{{ t("vcs.merge.commit") }}
</button>
<button
type="button"
class="merge__button"
data-test="merge-close"
@click="close()"
>
{{ t("vcs.merge.close") }}
</button>
</footer>
</section>
<section
v-else-if="merge.mode === 'abort'"
class="merge__body"
>
<p class="merge__hint">
{{ t("vcs.merge.abortQuestion") }}
</p>
<p
v-if="merge.error !== null"
class="merge__error"
data-test="merge-error"
>
{{ merge.error }}
</p>
<footer class="merge__footer">
<button
type="button"
class="merge__button merge__button--danger"
:disabled="merge.busy"
data-test="merge-abort"
@click="merge.abort()"
>
{{ t("vcs.merge.abortConfirm") }}
</button>
<button
type="button"
class="merge__button"
data-test="merge-abort-cancel"
@click="merge.showConflicts()"
>
{{ t("vcs.merge.keep") }}
</button>
</footer>
</section>
<section
v-else
class="merge__body merge__body--resolve"
>
<p
v-if="merge.phase === 'loading'"
class="merge__hint"
>
{{ t("vcs.merge.loading") }}
</p>
<p
v-else-if="merge.phase === 'error'"
class="merge__error"
data-test="merge-error"
>
{{ t("vcs.merge.loadFailed", { reason: merge.error ?? "" }) }}
</p>
<template v-else-if="merge.phase === 'deleted'">
<p
class="merge__hint"
data-test="merge-deleted"
>
{{ deletedNotice }}
</p>
<footer class="merge__footer">
<button
v-if="merge.versions?.ours !== null"
type="button"
class="merge__button"
:disabled="merge.busy"
data-test="merge-keep-ours"
@click="keep('ours')"
>
{{ t("vcs.merge.keepOurs") }}
</button>
<button
v-if="merge.versions?.theirs !== null"
type="button"
class="merge__button"
:disabled="merge.busy"
data-test="merge-keep-theirs"
@click="keep('theirs')"
>
{{ t("vcs.merge.keepTheirs") }}
</button>
<button
type="button"
class="merge__button"
:disabled="merge.busy"
data-test="merge-mark-as-is"
@click="markAsIs()"
>
{{ t("vcs.merge.markAsIs") }}
</button>
</footer>
</template>
<template v-else-if="merge.phase === 'binary' || merge.phase === 'tooLarge'">
<p
class="merge__hint"
data-test="merge-binary"
>
{{ merge.phase === "binary" ? t("vcs.merge.binary") : t("vcs.merge.tooLarge") }}
</p>
<footer class="merge__footer">
<button
type="button"
class="merge__button"
:disabled="merge.busy"
data-test="merge-mark-as-is"
@click="markAsIs()"
>
{{ t("vcs.merge.markAsIs") }}
</button>
</footer>
</template>
<template v-if="merge.phase === 'text'">
<div
class="merge__toolbar"
role="toolbar"
:aria-label="t('vcs.merge.toolbar')"
>
<button
type="button"
class="merge__button"
:disabled="open === 0"
data-test="merge-previous"
@click="view?.go(-1)"
>
{{ t("vcs.merge.previous") }}
</button>
<button
type="button"
class="merge__button"
:disabled="open === 0"
data-test="merge-next"
@click="view?.go(1)"
>
{{ t("vcs.merge.next") }}
</button>
<button
type="button"
class="merge__button"
:disabled="open === 0"
data-test="merge-accept-left"
@click="view?.acceptCurrent('ours')"
>
{{ t("vcs.merge.acceptLeft") }}
</button>
<button
type="button"
class="merge__button"
:disabled="open === 0"
data-test="merge-accept-right"
@click="view?.acceptCurrent('theirs')"
>
{{ t("vcs.merge.acceptRight") }}
</button>
<button
type="button"
class="merge__button"
:disabled="open === 0"
data-test="merge-all-left"
@click="view?.acceptAll('ours')"
>
{{ t("vcs.merge.allLeft") }}
</button>
<button
type="button"
class="merge__button"
:disabled="open === 0"
data-test="merge-all-right"
@click="view?.acceptAll('theirs')"
>
{{ t("vcs.merge.allRight") }}
</button>
<span
class="merge__counter"
role="status"
data-test="merge-counter"
>{{ counter }}</span>
<button
type="button"
class="merge__button merge__button--primary"
:disabled="open > 0 || merge.busy"
:title="open > 0 ? t('vcs.merge.applyHint') : undefined"
data-test="merge-apply"
@click="apply()"
>
{{ t("vcs.merge.apply") }}
</button>
<button
type="button"
class="merge__button"
data-test="merge-back"
@click="back()"
>
{{ t("vcs.merge.back") }}
</button>
</div>
</template>
<div
v-show="merge.phase === 'text'"
class="merge__panes"
>
<div class="merge__pane">
<span class="merge__caption">{{ oursCaption }}</span>
<div
ref="oursHost"
class="merge__editor"
data-test="merge-ours"
/>
</div>
<div class="merge__pane">
<span class="merge__caption">{{ t("vcs.merge.result") }}</span>
<div
ref="resultHost"
class="merge__editor"
data-test="merge-result"
/>
</div>
<div class="merge__pane">
<span class="merge__caption">{{ t("vcs.merge.theirs") }}</span>
<div
ref="theirsHost"
class="merge__editor"
data-test="merge-theirs"
/>
</div>
</div>
<p
v-if="merge.error !== null && merge.phase !== 'error'"
class="merge__error"
data-test="merge-error"
>
{{ merge.error }}
</p>
<footer
v-if="merge.phase !== 'text'"
class="merge__footer"
>
<button
type="button"
class="merge__button"
data-test="merge-back"
@click="back()"
>
{{ t("vcs.merge.back") }}
</button>
</footer>
</section>
</div>
</div>
</template>
<style scoped>
.merge {
position: fixed;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background: color-mix(in srgb, var(--lt-bg) 40%, transparent);
z-index: 30;
}
.merge__dialog {
width: min(560px, 92vw);
max-height: 84vh;
display: flex;
flex-direction: column;
background: var(--lt-bg);
color: var(--lt-fg);
border: 1px solid var(--lt-border);
border-radius: 6px;
overflow: hidden;
}
.merge__dialog--wide {
width: 96vw;
height: 90vh;
max-height: none;
}
.merge__header {
padding: var(--lt-space-s, 8px) var(--lt-space-m, 12px);
border-bottom: 1px solid var(--lt-border);
}
.merge__title {
margin: 0;
font-size: var(--lt-font-size-ui);
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.merge__body {
display: flex;
flex-direction: column;
gap: var(--lt-space-s, 8px);
padding: var(--lt-space-m, 12px);
min-height: 0;
overflow: auto;
}
.merge__body--resolve {
flex: 1;
overflow: hidden;
}
.merge__filter {
padding: var(--lt-space-xs, 2px) var(--lt-space-s, 8px);
color: var(--lt-fg);
background: var(--lt-editor-bg);
border: 1px solid var(--lt-border);
border-radius: var(--lt-radius, 4px);
}
.merge__list {
margin: 0;
padding: 0;
list-style: none;
overflow: auto;
max-height: 50vh;
}
.merge__row {
width: 100%;
padding: var(--lt-space-xs, 2px) var(--lt-space-s, 8px);
text-align: left;
color: var(--lt-fg);
background: transparent;
border: none;
border-radius: var(--lt-radius, 4px);
cursor: pointer;
}
.merge__row:hover,
.merge__row:focus-visible {
background: var(--lt-editor-selection-bg);
outline: none;
}
.merge__file {
display: flex;
align-items: center;
gap: var(--lt-space-s, 8px);
padding: var(--lt-space-xs, 2px) 0;
}
.merge__path {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--lt-vcs-conflicted);
}
.merge__hint {
margin: 0;
color: var(--lt-fg-muted);
}
.merge__error {
margin: 0;
color: var(--lt-error);
white-space: pre-wrap;
}
.merge__toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--lt-space-xs, 4px);
}
.merge__counter {
margin-left: auto;
color: var(--lt-fg-muted);
}
.merge__panes {
flex: 1;
min-height: 0;
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: var(--lt-space-xs, 4px);
}
.merge__pane {
display: flex;
flex-direction: column;
min-width: 0;
min-height: 0;
}
.merge__caption {
padding: var(--lt-space-xs, 2px) 0;
color: var(--lt-fg-muted);
font-size: var(--lt-font-size-small);
}
.merge__editor {
flex: 1;
min-height: 0;
overflow: hidden;
border: 1px solid var(--lt-border);
background: var(--lt-editor-bg);
}
.merge__editor :deep(.cm-editor) {
height: 100%;
}
.merge__footer {
display: flex;
justify-content: flex-end;
gap: var(--lt-space-s, 8px);
}
.merge__button {
padding: var(--lt-space-xs, 2px) var(--lt-space-m, 12px);
color: var(--lt-fg);
background: transparent;
border: 1px solid var(--lt-border);
border-radius: var(--lt-radius, 4px);
cursor: pointer;
}
.merge__button--primary {
background: color-mix(in srgb, var(--lt-accent) 18%, transparent);
border-color: var(--lt-accent);
}
.merge__button--danger {
border-color: var(--lt-error);
}
.merge__button:disabled {
opacity: 0.5;
cursor: default;
}
.merge__button:focus-visible,
.merge__filter:focus-visible {
outline: 2px solid var(--lt-accent);
outline-offset: 1px;
}
</style>

View file

@ -0,0 +1,276 @@
/**
* The three-way line merge of the resolve view (M4.8).
*
* - **Units:** texts are split into lines that keep their `\n`
* ({@link splitUnits}), so joining units gives the text back and a block
* inserted at a unit boundary carries its own line breaks. Line breaks
* are normalised to `\n` before (git returns blobs as stored).
* - **Line diff:** every distinct line becomes one character of the Basic
* Multilingual Plane outside the surrogates, and `@codemirror/merge`'s
* character `diff` (with a time limit) compares the two strings; so a
* change is a run of whole lines. Texts with more distinct lines than
* there are such characters fall back to one change covering both.
* - **Merge ({@link merge3}):** the changes of ours and of theirs against
* the base are grouped where they overlap or touch on the base (as git
* does). A group changed on one side takes that side; one changed alike
* on both takes it once; otherwise it is a conflict. Without a base (a
* file added on both sides) ours and theirs are compared directly, and
* every difference is a conflict ({@link merge2}).
* - **Result:** {@link initialResult} applies every non-conflicting change
* and keeps the base's lines in each conflict, so the result starts like
* git's merge without the markers.
*/
import { diff } from "@codemirror/merge";
/** What a block of the merge is. */
export type BlockKind = "stable" | "ours" | "theirs" | "both" | "conflict";
/** One block of a three-way merge, as units (lines with their `\n`). */
export interface MergeBlock {
/** What it is. */
kind: BlockKind;
/** The base's units. */
base: string[];
/** Our units (the current branch). */
ours: string[];
/** Their units (the merged branch). */
theirs: string[];
}
/** A change between two unit lists: `[fromA, toA)` became `[fromB, toB)`. */
export interface UnitChange {
/** Start in the first list. */
fromA: number;
/** End in the first list. */
toA: number;
/** Start in the second list. */
fromB: number;
/** End in the second list. */
toB: number;
}
/** Time limit of one line diff, in milliseconds. */
const DIFF_TIMEOUT = 2000;
/** First code unit used to encode lines (after the C0/C1 controls and Latin-1). */
const CODE_START = 0x100;
/** How many lines can be encoded: the BMP above {@link CODE_START} without the surrogates. */
const CODE_COUNT = 0xd800 - CODE_START + (0x10000 - 0xe000);
/**
* 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");
}
/**
* Splits a text into lines that keep their `\n`; the last one lacks it when
* the text does not end in a line break.
*
* @param text - text with `\n` breaks.
*/
export function splitUnits(text: string): string[] {
return text.match(/[^\n]*\n|[^\n]+$/g) ?? [];
}
/**
* The code unit of the `index`th distinct line.
*
* @param index - below {@link CODE_COUNT}.
*/
function codeOf(index: number): string {
const code = CODE_START + index;
return String.fromCharCode(code < 0xd800 ? code : code + (0xe000 - 0xd800));
}
/**
* The changes from one unit list to another.
*
* @param a - the first list.
* @param b - the second list.
* @returns changes in order, each a run of whole units.
*/
export function diffUnits(a: readonly string[], b: readonly string[]): UnitChange[] {
const codes = new Map<string, string>();
const encode = (units: readonly string[]): string | null => {
let out = "";
for (const unit of units) {
let code = codes.get(unit);
if (code === undefined) {
if (codes.size >= CODE_COUNT) {
return null;
}
code = codeOf(codes.size);
codes.set(unit, code);
}
out += code;
}
return out;
};
const left = encode(a);
const right = encode(b);
if (left === null || right === null) {
return a.length === 0 && b.length === 0 ? [] : [{ fromA: 0, toA: a.length, fromB: 0, toB: b.length }];
}
return diff(left, right, { timeout: DIFF_TIMEOUT }).map((c) => ({ fromA: c.fromA, toA: c.toA, fromB: c.fromB, toB: c.toB }));
}
/**
* Whether two unit lists are equal.
*
* @param a - one list.
* @param b - the other.
*/
function same(a: readonly string[], b: readonly string[]): boolean {
return a.length === b.length && a.every((unit, i) => unit === b[i]);
}
/**
* Pushes a block, merging stable runs.
*
* @param blocks - the blocks so far.
* @param block - the next block; empty stable blocks are dropped.
*/
function push(blocks: MergeBlock[], block: MergeBlock): void {
const last = blocks[blocks.length - 1];
if (block.kind === "stable") {
if (block.base.length === 0) {
return;
}
if (last?.kind === "stable") {
last.base.push(...block.base);
last.ours.push(...block.ours);
last.theirs.push(...block.theirs);
return;
}
}
blocks.push(block);
}
/**
* Merges ours and theirs without a base: equal runs are stable, every
* difference is a conflict with an empty base.
*
* @param ours - our units.
* @param theirs - their units.
*/
export function merge2(ours: readonly string[], theirs: readonly string[]): MergeBlock[] {
const blocks: MergeBlock[] = [];
let a = 0;
let b = 0;
for (const change of diffUnits(ours, theirs)) {
const stable = ours.slice(a, change.fromA);
push(blocks, { kind: "stable", base: stable, ours: [...stable], theirs: [...stable] });
push(blocks, {
kind: "conflict",
base: [],
ours: ours.slice(change.fromA, change.toA),
theirs: theirs.slice(change.fromB, change.toB),
});
a = change.toA;
b = change.toB;
}
const rest = ours.slice(a);
push(blocks, { kind: "stable", base: rest, ours: [...rest], theirs: theirs.slice(b) });
return blocks;
}
/** A change of one side against the base, tagged with its side. */
interface SideChange extends UnitChange {
/** 0 for ours, 1 for theirs. */
side: 0 | 1;
}
/**
* Merges ours and theirs against their common base.
*
* @param base - the base's units; null when there is none (added on both
* sides), see {@link merge2}.
* @param ours - our units.
* @param theirs - their units.
* @returns the blocks in order; joining one side's units of every block
* gives that side's text.
*/
export function merge3(base: readonly string[] | null, ours: readonly string[], theirs: readonly string[]): MergeBlock[] {
if (base === null) {
return merge2(ours, theirs);
}
const changes: SideChange[] = [
...diffUnits(base, ours).map((c) => ({ ...c, side: 0 as const })),
...diffUnits(base, theirs).map((c) => ({ ...c, side: 1 as const })),
].sort((x, y) => x.fromA - y.fromA || x.toA - y.toA);
const blocks: MergeBlock[] = [];
const sides = [ours, theirs] as const;
const delta = [0, 0];
let at = 0;
let i = 0;
while (i < changes.length) {
const first = changes[i];
if (!first) {
break;
}
const group: SideChange[] = [first];
let lo = first.fromA;
let hi = first.toA;
i += 1;
for (let next = changes[i]; next && next.fromA <= hi; next = changes[i]) {
group.push(next);
lo = Math.min(lo, next.fromA);
hi = Math.max(hi, next.toA);
i += 1;
}
const stable = base.slice(at, lo);
push(blocks, { kind: "stable", base: stable, ours: [...stable], theirs: [...stable] });
const ranges = ([0, 1] as const).map((side) => {
const own = group.filter((c) => c.side === side);
const firstOwn = own[0];
const lastOwn = own[own.length - 1];
const from = firstOwn ? firstOwn.fromB - (firstOwn.fromA - lo) : lo + (delta[side] ?? 0);
const to = lastOwn ? lastOwn.toB + (hi - lastOwn.toA) : hi + (delta[side] ?? 0);
delta[side] = to - hi;
return { changed: own.length > 0, units: sides[side].slice(from, to) };
});
const [mine, yours] = ranges;
if (!mine || !yours) {
break;
}
const kind: BlockKind =
mine.changed && yours.changed ? (same(mine.units, yours.units) ? "both" : "conflict") : mine.changed ? "ours" : "theirs";
blocks.push({ kind, base: base.slice(lo, hi), ours: mine.units, theirs: yours.units });
at = hi;
}
const rest = base.slice(at);
push(blocks, { kind: "stable", base: rest, ours: [...rest], theirs: [...rest] });
return blocks;
}
/**
* The units a block contributes to the initial result: the changed side,
* or the base for stable blocks and conflicts.
*
* @param block - the block.
*/
export function resultUnits(block: MergeBlock): string[] {
switch (block.kind) {
case "ours":
case "both":
return block.ours;
case "theirs":
return block.theirs;
default:
return block.base;
}
}
/**
* The result text before any conflict is resolved.
*
* @param blocks - the merge.
*/
export function initialResult(blocks: readonly MergeBlock[]): string {
return blocks.map((block) => resultUnits(block).join("")).join("");
}

View file

@ -0,0 +1,458 @@
/**
* The merge dialog's state (M4.8): merging a branch, the list of
* conflicted files, resolving one file and aborting the merge.
*
* - **Merge:** `git.merge {branch}` after `flushDirty()` (a failed save
* cancels it, as for checkout). A clean merge or "already up to date"
* toasts; a merge that stops on conflicts opens the conflicts list.
* - **Conflicts:** the files whose index or work tree state is
* `conflicted` in the shared status store (`stores/vcsStatus.ts`, the only
* caller of `git.status`). The list follows the store, so files resolved
* elsewhere leave it.
* - **Resolving a file:** `git.conflictVersions {path}` gives the base, ours
* and theirs; the view merges them (`diff3.ts`). Applying writes the result
* into the file's engine buffer (so its line endings, the journal and open
* tabs stay right), saves it and runs `git.markResolved {paths}`. A file
* deleted on one side offers to keep the other side's version; binary and
* too large files can only be marked resolved as they are on disk.
* - **Abort:** `git.mergeAbort` after a confirmation in the dialog.
* - **Untrusted input:** every result is checked field by field.
*/
import { defineStore } from "pinia";
import { computed, ref, shallowRef } from "vue";
import { t } from "../../../i18n";
import { runWaiting, type JsonValue } from "../../../ipc";
import { useAutosaveStore } from "../../../stores/autosave";
import { useEditorStore } from "../../../stores/editor";
import { useNotificationsStore } from "../../../stores/notifications";
import { useVcsStatusStore } from "../../../stores/vcsStatus";
import { normaliseEol } from "./diff3";
/** Command id that merges a branch into the current one. */
export const MERGE_COMMAND = "vcs.merge";
/** Command id that opens the conflicts (optionally one file's resolve view). */
export const RESOLVE_COMMAND = "vcs.resolveConflicts";
/** Command id that asks to abort the merge. */
export const ABORT_COMMAND = "vcs.abortMerge";
/** What the dialog shows. */
export type MergeMode = "closed" | "branches" | "conflicts" | "resolve" | "abort";
/** How `git.merge` ended. */
export type MergeResultKind = "merged" | "upToDate" | "conflicts";
/** A `git.merge` result, checked. */
export interface MergeAnswer {
/** How it ended. */
result: MergeResultKind;
/** Conflicted paths. */
conflicts: string[];
}
/** A `git.conflictVersions` result, checked; texts with `\n` breaks. */
export interface ConflictVersions {
/** The common ancestor; null when added on both sides. */
base: string | null;
/** Ours (the current branch); null when deleted there. */
ours: string | null;
/** Theirs (the merged branch); null when deleted there. */
theirs: string | null;
/** A version is binary. */
binary: boolean;
/** A version is too large. */
tooLarge: boolean;
}
/** What the resolve view of a file shows. */
export type ResolvePhase = "loading" | "text" | "deleted" | "binary" | "tooLarge" | "error";
/**
* Reads a `git.merge` result; null when malformed.
*
* @param raw - untrusted.
*/
export function toMergeAnswer(raw: unknown): MergeAnswer | null {
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
return null;
}
const r = raw as Record<string, unknown>;
if (r.result !== "merged" && r.result !== "upToDate" && r.result !== "conflicts") {
return null;
}
const conflicts = Array.isArray(r.conflicts) ? r.conflicts.filter((p): p is string => typeof p === "string" && p !== "") : [];
return { result: r.result, conflicts };
}
/**
* Reads a `git.conflictVersions` result; null when malformed. Line breaks
* become `\n`.
*
* @param raw - untrusted.
*/
export function toConflictVersions(raw: unknown): ConflictVersions | null {
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
return null;
}
const r = raw as Record<string, unknown>;
const text = (value: unknown): string | null | undefined =>
value === null || value === undefined ? null : typeof value === "string" ? normaliseEol(value) : undefined;
const base = text(r.base);
const ours = text(r.ours);
const theirs = text(r.theirs);
if (base === undefined || ours === undefined || theirs === undefined) {
return null;
}
return { base, ours, theirs, binary: r.binary === true, tooLarge: r.tooLarge === true };
}
/**
* The phase a file's versions call for.
*
* @param versions - the checked versions.
*/
export function phaseOf(versions: ConflictVersions): ResolvePhase {
if (versions.binary) {
return "binary";
}
if (versions.tooLarge) {
return "tooLarge";
}
return versions.ours === null || versions.theirs === null ? "deleted" : "text";
}
/**
* Reads the params of `vcs.resolveConflicts`; undefined when malformed.
*
* @param params - untrusted (`{}` from the palette).
* @returns the path, or null for the list.
*/
export function parseResolveParams(params: unknown): string | null | undefined {
const p = typeof params === "object" && params !== null && !Array.isArray(params) ? (params as Record<string, unknown>) : {};
if (p.path === undefined || p.path === null) {
return null;
}
return typeof p.path === "string" && p.path !== "" ? p.path : undefined;
}
/**
* A short reason for a toast: git's message, or `?` when empty.
*
* @param message - the error text.
*/
function reasonOf(message: string): string {
return message.trim() === "" ? "?" : message.trim();
}
/** The merge store. */
export const useMergeStore = defineStore("merge", () => {
const notifications = useNotificationsStore();
const status = useVcsStatusStore();
const editor = useEditorStore();
/** What the dialog shows. */
const mode = ref<MergeMode>("closed");
/** The branches offered for a merge (not the current one). */
const branches = ref<string[]>([]);
/** Why the branches could not be read; null if they could. */
const branchesError = ref<string | null>(null);
/** The file being resolved. */
const path = ref<string | null>(null);
/** What its view shows. */
const phase = ref<ResolvePhase>("loading");
/** Its versions, once loaded. */
const versions = shallowRef<ConflictVersions | null>(null);
/** Error text of the resolve view or the last action; null if none. */
const error = ref<string | null>(null);
/** A git call or save runs. */
const busy = ref(false);
/** Bumped on every load, so only the newest one lands. */
let generation = 0;
/** The conflicted files, sorted by path. */
const conflicts = computed(() =>
(status.snapshot?.files ?? [])
.filter((file) => file.index === "conflicted" || file.worktree === "conflicted")
.map((file) => file.path),
);
/** The current branch, null when detached or unknown. */
const currentBranch = computed(() => status.snapshot?.repo?.branch ?? null);
/** Closes the dialog. */
function close(): void {
mode.value = "closed";
error.value = null;
generation += 1;
}
/** Shows the branches to merge and reads them. */
async function showBranches(): Promise<void> {
mode.value = "branches";
error.value = null;
branchesError.value = null;
const result = await runWaiting("git.branches", {});
if (!result.ok) {
branchesError.value = reasonOf(result.error.message);
branches.value = [];
return;
}
const raw = result.value as Record<string, unknown> | null;
const current = typeof raw?.current === "string" ? raw.current : null;
const names = (list: unknown): string[] =>
Array.isArray(list)
? list
.map((entry: unknown) =>
typeof entry === "object" && entry !== null ? (entry as Record<string, unknown>).name : undefined,
)
.filter((name): name is string => typeof name === "string" && name !== "" && name !== current)
: [];
branches.value = [...names(raw?.local), ...names(raw?.remote)];
}
/** Shows the list of conflicted files. */
function showConflicts(): void {
mode.value = "conflicts";
path.value = null;
error.value = null;
generation += 1;
}
/** Shows the abort confirmation. */
function askAbort(): void {
mode.value = "abort";
error.value = null;
}
/**
* Merges a branch into the current one.
*
* @param branch - the branch name.
* @returns how it ended, or null when it did not run or git refused.
*/
async function merge(branch: string): Promise<MergeResultKind | null> {
if (busy.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.mergeNotSaved", params: { branch } });
return null;
}
const result = await runWaiting("git.merge", { branch });
if (!result.ok) {
const reason = reasonOf(result.error.message);
notifications.notify({ level: "error", messageKey: "notification.vcs.mergeFailed", message: reason, params: { branch, reason } });
return null;
}
const answer = toMergeAnswer(result.value);
if (!answer) {
notifications.notify({ level: "error", messageKey: "common.error.unexpectedResult", params: { command: "git.merge" } });
return null;
}
await status.refresh();
if (answer.result === "conflicts") {
notifications.notify({
level: "warning",
messageKey: "notification.vcs.mergeConflicts",
params: { branch, count: String(answer.conflicts.length) },
});
showConflicts();
} else {
notifications.notify({
level: "info",
messageKey: answer.result === "merged" ? "notification.vcs.merged" : "notification.vcs.mergeUpToDate",
params: { branch },
});
close();
}
return answer.result;
} finally {
busy.value = false;
}
}
/**
* Aborts the merge in progress.
*
* @returns whether git aborted it.
*/
async function abort(): Promise<boolean> {
if (busy.value) {
return false;
}
busy.value = true;
try {
const result = await runWaiting("git.mergeAbort", {});
if (!result.ok) {
error.value = reasonOf(result.error.message);
return false;
}
await status.refresh();
notifications.notify({ level: "info", messageKey: "notification.vcs.mergeAborted" });
close();
return true;
} finally {
busy.value = false;
}
}
/**
* Opens the resolve view of a file and reads its versions.
*
* @param file - project-relative path.
*/
async function openFile(file: string): Promise<void> {
generation += 1;
const mine = generation;
mode.value = "resolve";
path.value = file;
phase.value = "loading";
versions.value = null;
error.value = null;
const result = await runWaiting("git.conflictVersions", { path: file });
if (mine !== generation) {
return;
}
if (!result.ok) {
phase.value = "error";
error.value = reasonOf(result.error.message);
return;
}
const checked = toConflictVersions(result.value);
if (!checked) {
phase.value = "error";
error.value = t("common.error.unexpectedResult", { command: "git.conflictVersions" });
return;
}
versions.value = checked;
phase.value = phaseOf(checked);
}
/**
* Writes a text into a file through its engine buffer and saves it.
*
* @param file - project-relative path.
* @param text - the new text with `\n` breaks (the buffer keeps the
* file's line ending on save).
* @returns null when saved, else why not.
*/
async function write(file: string, text: string): Promise<string | null> {
const before = editor.lastError;
const id = await editor.openFile(file);
if (id === null) {
const reason = editor.lastError?.message ?? "?";
editor.lastError = before;
return reason;
}
const sync = editor.syncOf(id);
if (!sync) {
return "?";
}
await sync.idle();
const doc = sync.state.doc;
if (doc.toString() !== text) {
sync.dispatch({ changes: { from: 0, to: doc.length, insert: text } });
}
const saved = await editor.save(id);
return saved ? null : (editor.lastError?.message ?? "?");
}
/**
* Marks a file resolved, optionally writing its result first, then goes
* back to the list.
*
* @param file - project-relative path.
* @param text - the result to write; null to keep the file on disk as it is.
* @returns whether it was marked resolved.
*/
async function resolve(file: string, text: string | null): Promise<boolean> {
if (busy.value) {
return false;
}
busy.value = true;
try {
if (text !== null) {
const failed = await write(file, text);
if (failed !== null) {
error.value = t("vcs.merge.saveFailed", { reason: failed });
return false;
}
}
const result = await runWaiting("git.markResolved", { paths: [file] } satisfies JsonValue);
if (!result.ok) {
error.value = reasonOf(result.error.message);
return false;
}
await status.refresh();
notifications.notify({ level: "info", messageKey: "notification.vcs.resolved", params: { path: file } });
showConflicts();
return true;
} finally {
busy.value = false;
}
}
/**
* Runs `vcs.resolveConflicts {path?}`.
*
* @param params - untrusted params.
* @throws Error with a catalog message when the params are malformed.
*/
async function resolveCommand(params: JsonValue): Promise<void> {
const file = parseResolveParams(params);
if (file === undefined) {
throw new Error(t("vcs.merge.invalidParams"));
}
if (file === null) {
showConflicts();
return;
}
await openFile(file);
}
/**
* Runs `vcs.merge {branch?}`: merges the branch, or shows the branches.
*
* @param params - untrusted params.
* @throws Error with a catalog message when the params are malformed.
*/
async function mergeCommand(params: JsonValue): Promise<void> {
const p = typeof params === "object" && params !== null && !Array.isArray(params) ? params : {};
const branch = p.branch;
if (branch === undefined || branch === null) {
await showBranches();
return;
}
if (typeof branch !== "string" || branch.trim() === "") {
throw new Error(t("vcs.merge.invalidMergeParams"));
}
await merge(branch.trim());
}
return {
mode,
branches,
branchesError,
path,
phase,
versions,
error,
busy,
conflicts,
currentBranch,
close,
showBranches,
showConflicts,
askAbort,
merge,
abort,
openFile,
resolve,
resolveCommand,
mergeCommand,
};
});

View file

@ -0,0 +1,513 @@
/**
* The three editors of the resolve view (M4.8): ours (left, read-only),
* the result (middle, editable) and theirs (right, read-only).
*
* - **Blocks:** built by `merge3` (`diff3.ts`). Non-conflicting changes are
* in the result from the start; each conflict is a chunk whose range in
* the result starts as the base's lines.
* - **Chunks in the result:** a state field keeps each chunk's range,
* mapped through every edit (the start sticks before text inserted at it,
* the end after, so typing at a chunk's edge extends it). Its state comes
* from its text: open while it is the base's, taken from ours or theirs
* while it equals that side, edited by hand otherwise.
* - **Accepting:** {@link ResolveView.accept} replaces a chunk's range with
* that side's lines; it is one undoable change of the result, and undo
* opens the chunk again. The side
* panes show a button in the gutter at the first line of every open
* chunk ("»" left, "«" right); a click accepts it.
* - **Colours:** only `--lt-*` tokens: open conflicts tinted with
* `--lt-vcs-conflicted`, accepted chunks and non-conflicting changes with
* `--lt-vcs-modified`.
* - **Navigation:** {@link ResolveView.go} moves to the next or previous
* open chunk (wrapping), selects it in the result and scrolls all three
* editors to it.
*/
import { EditorState, RangeSetBuilder, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
import { Decoration, EditorView, GutterMarker, gutter, type DecorationSet } from "@codemirror/view";
import { basicSetup } from "codemirror";
import { lutraEditorTheme } from "../../editor/extensions";
import { languageExtensions } from "../../editor/language";
import { merge3, resultUnits, splitUnits, type MergeBlock } from "./diff3";
/** Which side a chunk was taken from, or how else it was settled. */
export type ChunkState = "open" | "ours" | "theirs" | "edited";
/** A conflict chunk: its text on each side and its place in each document. */
export interface Chunk {
/** Our text. */
ours: string;
/** Their text. */
theirs: string;
/** Range in the ours document. */
oursFrom: number;
/** End in the ours document. */
oursTo: number;
/** Range in the theirs document. */
theirsFrom: number;
/** End in the theirs document. */
theirsTo: number;
}
/** A chunk's live range in the result. */
interface Range {
/** Start in the result. */
from: number;
/** End in the result. */
to: number;
}
/** A chunk's live range and state in the result. */
export interface Live extends Range {
/** Its state, read from the text in its range. */
state: ChunkState;
}
/** A highlighted range of a side document. */
interface Marked {
/** Start. */
from: number;
/** End. */
to: number;
/** A conflict (else a non-conflicting change). */
conflict: boolean;
}
/** The laid-out merge: documents, chunks and highlights. */
export interface Layout {
/** The ours document. */
ours: string;
/** The theirs document. */
theirs: string;
/** The initial result. */
result: string;
/** The conflict chunks in order. */
chunks: Chunk[];
/** Initial result range of each chunk. */
resultRanges: { from: number; to: number }[];
/** Highlights of the ours document. */
oursMarks: Marked[];
/** Highlights of the theirs document. */
theirsMarks: Marked[];
}
/**
* Lays out a merge of the three texts.
*
* @param base - the base text, null when there is none.
* @param ours - our text.
* @param theirs - their text.
*/
export function layout(base: string | null, ours: string, theirs: string): Layout {
const blocks: MergeBlock[] = merge3(base === null ? null : splitUnits(base), splitUnits(ours), splitUnits(theirs));
const out: Layout = { ours: "", theirs: "", result: "", chunks: [], resultRanges: [], oursMarks: [], theirsMarks: [] };
for (const block of blocks) {
const oursText = block.ours.join("");
const theirsText = block.theirs.join("");
const resultText = resultUnits(block).join("");
const oursFrom = out.ours.length;
const theirsFrom = out.theirs.length;
const resultFrom = out.result.length;
out.ours += oursText;
out.theirs += theirsText;
out.result += resultText;
if (block.kind === "conflict") {
out.chunks.push({
ours: oursText,
theirs: theirsText,
oursFrom,
oursTo: out.ours.length,
theirsFrom,
theirsTo: out.theirs.length,
});
out.resultRanges.push({ from: resultFrom, to: out.result.length });
}
if (block.kind === "conflict" || block.kind === "ours" || block.kind === "both") {
out.oursMarks.push({ from: oursFrom, to: out.ours.length, conflict: block.kind === "conflict" });
}
if (block.kind === "conflict" || block.kind === "theirs" || block.kind === "both") {
out.theirsMarks.push({ from: theirsFrom, to: out.theirs.length, conflict: block.kind === "conflict" });
}
}
return out;
}
/** Marks the chunks resolved in a side pane (`true` = open). */
const setOpen = StateEffect.define<boolean[]>();
/** Line decorations by class. */
const lineDecos = {
conflict: Decoration.line({ class: "lt-merge-conflict" }),
change: Decoration.line({ class: "lt-merge-change" }),
resolved: Decoration.line({ class: "lt-merge-resolved" }),
};
/**
* Adds line decorations for the lines a range covers (one line for an
* empty range).
*
* @param doc - the document.
* @param from - start of the range.
* @param to - end of the range.
* @param add - receives each line start.
*/
function eachLine(doc: Text, from: number, to: number, add: (lineStart: number) => void): void {
const first = doc.lineAt(Math.min(from, doc.length));
const last = to > from ? doc.lineAt(Math.min(Math.max(to - 1, from), doc.length)) : first;
for (let n = first.number; n <= last.number; n += 1) {
add(doc.line(n).from);
}
}
/**
* Builds line decorations from ranges.
*
* @param doc - the document.
* @param ranges - ranges with their decoration, in document order.
*/
function lineSet(doc: Text, ranges: { from: number; to: number; deco: Decoration }[]): DecorationSet {
const builder = new RangeSetBuilder<Decoration>();
let last = -1;
for (const range of ranges) {
eachLine(doc, range.from, range.to, (start) => {
if (start > last) {
builder.add(start, start, range.deco);
last = start;
}
});
}
return builder.finish();
}
/** The accept button in a side pane's gutter. */
class AcceptMarker extends GutterMarker {
/**
* @param glyph - `»` or `«`.
* @param label - its accessible name.
*/
constructor(
readonly glyph: string,
readonly label: string,
) {
super();
}
/** @param other - another marker. */
override eq(other: GutterMarker): boolean {
return other instanceof AcceptMarker && other.glyph === this.glyph && other.label === this.label;
}
/** The button. */
override toDOM(): Node {
const button = document.createElement("button");
button.type = "button";
button.className = "lt-merge-accept";
button.textContent = this.glyph;
button.title = this.label;
button.setAttribute("aria-label", this.label);
button.tabIndex = -1;
return button;
}
}
/** Colours of the three editors, from tokens only. */
export const resolveTheme: Extension = EditorView.theme({
".lt-merge-conflict": { backgroundColor: "color-mix(in srgb, var(--lt-vcs-conflicted) 18%, var(--lt-editor-bg))" },
".lt-merge-change": { backgroundColor: "color-mix(in srgb, var(--lt-vcs-modified) 12%, var(--lt-editor-bg))" },
".lt-merge-resolved": { backgroundColor: "color-mix(in srgb, var(--lt-vcs-modified) 18%, var(--lt-editor-bg))" },
".lt-merge-accept": {
font: "inherit",
lineHeight: "1",
padding: "0 4px",
border: "1px solid var(--lt-border)",
borderRadius: "3px",
color: "var(--lt-fg)",
background: "var(--lt-bg)",
cursor: "pointer",
},
".lt-merge-accept:hover": { background: "color-mix(in srgb, var(--lt-accent) 25%, var(--lt-bg))" },
});
/** Labels of the gutter buttons. */
export interface ResolveLabels {
/** The ours pane's button. */
acceptOurs: string;
/** The theirs pane's button. */
acceptTheirs: string;
}
/** Where the three editors go and what they report. */
export interface ResolveOptions {
/** The file's path, for its language. */
path: string;
/** The base text, null when there is none. */
base: string | null;
/** Our text. */
ours: string;
/** Their text. */
theirs: string;
/** Element of the ours editor. */
oursHost: HTMLElement;
/** Element of the result editor. */
resultHost: HTMLElement;
/** Element of the theirs editor. */
theirsHost: HTMLElement;
/** Gutter button labels. */
labels: ResolveLabels;
/** Called after every change of a chunk's state, with the open count. */
onChange: (open: number) => void;
}
/** The three editors of one file. */
export class ResolveView {
/** The ours editor. */
readonly oursView: EditorView;
/** The result editor. */
readonly resultView: EditorView;
/** The theirs editor. */
readonly theirsView: EditorView;
/** The laid-out merge. */
readonly layout: Layout;
/** The chunk navigated to last; -1 before any. */
current = -1;
/** Reports changes. */
private readonly onChange: (open: number) => void;
/** The chunks' field in the result. */
private readonly field: StateField<Range[]>;
/** Each chunk's initial text in the result (the base's lines). */
private readonly bases: string[];
/** The open flags' field of the side panes. */
private readonly openField: StateField<boolean[]>;
/** @param options - hosts, texts and callbacks. */
constructor(options: ResolveOptions) {
this.onChange = options.onChange;
const lay = layout(options.base, options.ours, options.theirs);
this.layout = lay;
const base = lay.resultRanges.map((r) => lay.result.slice(r.from, r.to));
this.bases = base;
const field = StateField.define<Range[]>({
create: () => lay.resultRanges.map((r) => ({ ...r })),
update(ranges, tr) {
if (!tr.docChanged) {
return ranges;
}
return ranges.map((range) => {
const from = tr.changes.mapPos(range.from, -1);
return { from, to: Math.max(from, tr.changes.mapPos(range.to, 1)) };
});
},
provide: (f) =>
EditorView.decorations.from(f, (ranges) => (view: EditorView) =>
lineSet(
view.state.doc,
ranges.map((r, i) => ({
from: r.from,
to: r.to,
deco: view.state.doc.sliceString(r.from, r.to) === base[i] ? lineDecos.conflict : lineDecos.resolved,
})),
),
),
});
this.field = field;
const openField = StateField.define<boolean[]>({
create: () => lay.chunks.map(() => true),
update(flags, tr) {
for (const effect of tr.effects) {
if (effect.is(setOpen)) {
return effect.value;
}
}
return flags;
},
});
this.openField = openField;
const language = languageExtensions(options.path);
const readOnly = [EditorState.readOnly.of(true), EditorView.editable.of(false)];
const side = (which: "ours" | "theirs"): Extension => {
const marks = which === "ours" ? lay.oursMarks : lay.theirsMarks;
const marker = new AcceptMarker(which === "ours" ? "»" : "«", which === "ours" ? options.labels.acceptOurs : options.labels.acceptTheirs);
const starts = lay.chunks.map((c) => (which === "ours" ? c.oursFrom : c.theirsFrom));
return [
basicSetup,
lutraEditorTheme,
language,
resolveTheme,
readOnly,
openField,
StateField.define<DecorationSet>({
create: (state) =>
lineSet(
state.doc,
marks.map((m) => ({ from: m.from, to: m.to, deco: m.conflict ? lineDecos.conflict : lineDecos.change })),
),
update: (set) => set,
provide: (f) => EditorView.decorations.from(f),
}),
gutter({
class: "lt-merge-gutter",
lineMarker: (view, line) => {
const flags = view.state.field(openField);
const index = starts.findIndex(
(start, i) => flags[i] === true && view.state.doc.lineAt(Math.min(start, view.state.doc.length)).from === line.from,
);
return index >= 0 ? marker : null;
},
lineMarkerChange: (update) => update.transactions.some((tr) => tr.effects.some((e) => e.is(setOpen))),
domEventHandlers: {
mousedown: (view, line) => {
const flags = view.state.field(openField);
const index = starts.findIndex(
(start, i) => flags[i] === true && view.state.doc.lineAt(Math.min(start, view.state.doc.length)).from === line.from,
);
if (index < 0) {
return false;
}
this.accept(index, which);
return true;
},
},
}),
];
};
this.oursView = new EditorView({ parent: options.oursHost, state: EditorState.create({ doc: lay.ours, extensions: side("ours") }) });
this.theirsView = new EditorView({ parent: options.theirsHost, state: EditorState.create({ doc: lay.theirs, extensions: side("theirs") }) });
this.resultView = new EditorView({
parent: options.resultHost,
state: EditorState.create({
doc: lay.result,
extensions: [
basicSetup,
lutraEditorTheme,
language,
resolveTheme,
field,
EditorView.updateListener.of((update) => {
if (update.docChanged) {
this.report();
}
}),
],
}),
});
}
/**
* The chunks' live ranges and states. A chunk is open while its text is
* still the base's, taken from a side while it equals that side's, and
* edited otherwise; so undo and redo need no bookkeeping.
*/
get chunks(): readonly Live[] {
const state = this.resultView.state;
return state.field(this.field).map((range, i) => {
const text = state.doc.sliceString(range.from, range.to);
const chunk = this.layout.chunks[i];
const kind: ChunkState =
text === this.bases[i] ? "open" : text === chunk?.ours ? "ours" : text === chunk?.theirs ? "theirs" : "edited";
return { ...range, state: kind };
});
}
/** How many chunks are still open. */
get open(): number {
return this.chunks.filter((c) => c.state === "open").length;
}
/** The result text. */
get result(): string {
return this.resultView.state.doc.toString();
}
/** Tells the side panes which chunks are open and reports the count. */
private report(): void {
const flags = this.chunks.map((c) => c.state === "open");
for (const view of [this.oursView, this.theirsView]) {
const before = view.state.field(this.openField);
if (before.length !== flags.length || before.some((f, i) => f !== flags[i])) {
view.dispatch({ effects: setOpen.of(flags) });
}
}
this.onChange(this.open);
}
/**
* Takes one side's text for a chunk.
*
* @param index - the chunk.
* @param side - which side.
*/
accept(index: number, side: "ours" | "theirs"): void {
const live = this.chunks[index];
const chunk = this.layout.chunks[index];
if (!live || !chunk) {
return;
}
const insert = side === "ours" ? chunk.ours : chunk.theirs;
this.resultView.dispatch({
changes: { from: live.from, to: live.to, insert },
userEvent: "input.merge",
});
this.current = index;
}
/**
* Takes one side's text for every open chunk, last first so earlier
* ranges stay valid.
*
* @param side - which side.
*/
acceptAll(side: "ours" | "theirs"): void {
const open = this.chunks.map((c, i) => ({ c, i })).filter(({ c }) => c.state === "open");
for (const { i } of open.reverse()) {
this.accept(i, side);
}
}
/**
* Takes one side for the chunk navigated to last, else the first open one.
*
* @param side - which side.
*/
acceptCurrent(side: "ours" | "theirs"): void {
const chunks = this.chunks;
const index = chunks[this.current]?.state === "open" ? this.current : chunks.findIndex((c) => c.state === "open");
if (index >= 0) {
this.accept(index, side);
}
}
/**
* Moves to the next or previous open chunk, wrapping.
*
* @param direction - 1 or -1.
* @returns whether there was one.
*/
go(direction: 1 | -1): boolean {
const chunks = this.chunks;
const count = chunks.length;
for (let step = 1; step <= count; step += 1) {
const index = (((this.current < 0 && direction < 0 ? 0 : this.current) + direction * step) % count + count) % count;
const live = chunks[index];
const chunk = this.layout.chunks[index];
if (live?.state === "open" && chunk) {
this.current = index;
this.resultView.dispatch({
selection: { anchor: live.from, head: live.to },
effects: EditorView.scrollIntoView(live.from, { y: "center" }),
});
this.oursView.dispatch({ effects: EditorView.scrollIntoView(Math.min(chunk.oursFrom, this.oursView.state.doc.length), { y: "center" }) });
this.theirsView.dispatch({
effects: EditorView.scrollIntoView(Math.min(chunk.theirsFrom, this.theirsView.state.doc.length), { y: "center" }),
});
return true;
}
}
return false;
}
/** Destroys the three editors. */
destroy(): void {
this.oursView.destroy();
this.resultView.destroy();
this.theirsView.destroy();
}
}

View file

@ -19,12 +19,14 @@
"command.settings.open": "Settings…",
"command.terminal.open": "Terminal",
"command.unavailable": "{command} cannot run right now",
"command.vcs.abortMerge": "Abort Merge…",
"command.vcs.branches": "Branches…",
"command.vcs.checkout": "Check Out Branch",
"command.vcs.clone": "Clone Repository…",
"command.vcs.commit": "Commit…",
"command.vcs.fetch": "Fetch",
"command.vcs.manageRemotes": "Manage Remotes…",
"command.vcs.merge": "Merge…",
"command.vcs.newBranch": "New Branch…",
"command.vcs.nextChange": "Next Change",
"command.vcs.openChanges": "Changes",
@ -32,6 +34,7 @@
"command.vcs.pull": "Pull",
"command.vcs.push": "Push",
"command.vcs.refresh": "Refresh Changes",
"command.vcs.resolveConflicts": "Resolve Conflicts…",
"command.vcs.showDiff": "Show Diff",
"command.vcs.showHistory": "Show History",
"command.vcs.showLog": "Log",
@ -172,6 +175,12 @@
"notification.vcs.fetchFailed": "Fetch failed: {reason}",
"notification.vcs.fetched": "Fetched from every remote",
"notification.vcs.historyNoFile": "Open a file or pass a path to show its history",
"notification.vcs.mergeAborted": "Merge aborted",
"notification.vcs.mergeConflicts": "Merging {branch} stopped on conflicts (conflicted files: {count}). Resolve them, then commit.",
"notification.vcs.mergeFailed": "Git did not merge {branch}: {reason}",
"notification.vcs.mergeNotSaved": "Merge of {branch} cancelled: not every file could be saved first.",
"notification.vcs.mergeUpToDate": "Already up to date with {branch}",
"notification.vcs.merged": "Merged {branch}",
"notification.vcs.newBranchFailed": "Branch {branch} was not created: {reason}",
"notification.vcs.pullFailed": "Pull failed: {reason}",
"notification.vcs.pullNotSaved": "Pull cancelled: not every file could be saved first.",
@ -180,6 +189,7 @@
"notification.vcs.pushed": "Pushed {branch} to {remote}",
"notification.vcs.pushedUpstream": "Pushed {branch} to {remote} and set it as the upstream",
"notification.vcs.remoteCancelled": "Git operation cancelled",
"notification.vcs.resolved": "Marked {path} as resolved",
"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",
@ -388,6 +398,53 @@
"vcs.log.refresh": "Reload the history",
"vcs.log.toolWindow.title": "Log",
"vcs.log.truncated": "More files changed than are listed here.",
"vcs.merge.abort": "Abort merge…",
"vcs.merge.abortConfirm": "Abort merge",
"vcs.merge.abortQuestion": "Abort the merge? The files and the index return to how they were before it; resolutions made so far are lost.",
"vcs.merge.acceptLeft": "Accept left",
"vcs.merge.acceptRight": "Accept right",
"vcs.merge.allLeft": "Accept all left",
"vcs.merge.allResolved": "No open conflicts",
"vcs.merge.allRight": "Accept all right",
"vcs.merge.apply": "Apply and mark resolved",
"vcs.merge.applyHint": "Resolve every conflict first",
"vcs.merge.back": "Back",
"vcs.merge.binary": "Binary file: it cannot be merged here. Put the version you want on disk, then mark it resolved.",
"vcs.merge.branchesLabel": "Branches to merge",
"vcs.merge.close": "Close",
"vcs.merge.commit": "Commit…",
"vcs.merge.conflictsHint": "These files have conflicts. Resolve each one, then commit to finish the merge.",
"vcs.merge.conflictsLabel": "Conflicted files",
"vcs.merge.deletedOurs": "The current branch deleted this file and the merged branch changed it. Keep the merged branch's version, or delete the file and mark it resolved.",
"vcs.merge.deletedTheirs": "The merged branch deleted this file and the current branch changed it. Keep the current branch's version, or delete the file and mark it resolved.",
"vcs.merge.filter": "Filter branches",
"vcs.merge.invalidMergeParams": "vcs.merge takes {branch?: string}",
"vcs.merge.invalidParams": "vcs.resolveConflicts takes {path?: string}",
"vcs.merge.keep": "Keep merging",
"vcs.merge.keepOurs": "Keep the current branch's version",
"vcs.merge.keepTheirs": "Keep the merged branch's version",
"vcs.merge.loadFailed": "The conflict cannot be read: {reason}",
"vcs.merge.loading": "Reading the conflict from Git…",
"vcs.merge.markAsIs": "Mark resolved as on disk",
"vcs.merge.next": "Next conflict",
"vcs.merge.noBranches": "No other branch to merge",
"vcs.merge.noConflicts": "No conflicts left. Commit to finish the merge.",
"vcs.merge.openCount": "{open} of {total} conflicts open",
"vcs.merge.ours": "Current branch",
"vcs.merge.oursBranch": "Current branch ({branch})",
"vcs.merge.previous": "Previous conflict",
"vcs.merge.resolve": "Resolve…",
"vcs.merge.resolveFile": "Resolve {path}",
"vcs.merge.result": "Result",
"vcs.merge.saveFailed": "The result could not be saved: {reason}",
"vcs.merge.theirs": "Merged branch",
"vcs.merge.titleAbort": "Abort merge",
"vcs.merge.titleConflicts": "Merge conflicts",
"vcs.merge.titleMerge": "Merge a branch",
"vcs.merge.titleMergeInto": "Merge into {branch}",
"vcs.merge.titleResolve": "Resolve {path}",
"vcs.merge.tooLarge": "The file is too large to merge here. Put the version you want on disk, then mark it resolved.",
"vcs.merge.toolbar": "Conflict actions",
"vcs.remote.cancel": "Cancel the Git operation",
"vcs.remote.operation.clone": "Cloning",
"vcs.remote.operation.fetch": "Fetching",

View file

@ -45,8 +45,8 @@ const usedKeys = sourceFiles(SRC).flatMap((file) =>
* `settings.list`, the `messageKey` of
* `notification` events (engine and desktop host), the keys the
* notifications store passes through a constant, and the Changes
* window's commit toasts (M4.2), the branch toasts (M4.5) and the remote
* toasts (M4.10), passed as
* window's commit toasts (M4.2), the branch toasts (M4.5), the merge
* toasts (M4.8) and the remote toasts (M4.10), passed as
* `messageKey`.
*/
const RUNTIME_KEYS = new Set([
@ -68,6 +68,12 @@ const RUNTIME_KEYS = new Set([
"notification.vcs.historyNoFile",
"notification.vcs.commitNotSaved",
"notification.vcs.committed",
"notification.vcs.mergeAborted",
"notification.vcs.mergeConflicts",
"notification.vcs.mergeFailed",
"notification.vcs.mergeNotSaved",
"notification.vcs.mergeUpToDate",
"notification.vcs.merged",
"notification.vcs.newBranchFailed",
"notification.vcs.cloned",
"notification.vcs.fetchFailed",
@ -79,6 +85,7 @@ const RUNTIME_KEYS = new Set([
"notification.vcs.pushed",
"notification.vcs.pushedUpstream",
"notification.vcs.remoteCancelled",
"notification.vcs.resolved",
"notification.settings.corrupt",
"notification.settings.corruptNotMoved",
"notification.settings.unavailable",

View file

@ -275,6 +275,7 @@ describe("AppMenu", () => {
"goto.fileOpen",
"goto.classOpen",
"goto.symbolOpen",
"vcs.abortMerge",
"vcs.branches",
"vcs.openChanges",
"vcs.clone",
@ -282,12 +283,14 @@ describe("AppMenu", () => {
"vcs.fetch",
"vcs.showLog",
"vcs.manageRemotes",
"vcs.merge",
"vcs.newBranch",
"vcs.nextChange",
"vcs.previousChange",
"vcs.pull",
"vcs.push",
"vcs.refresh",
"vcs.resolveConflicts",
"vcs.showDiff",
"vcs.showHistory",
"app.about",

View file

@ -258,6 +258,7 @@ describe("CommandPalette", () => {
expect(wrapper.find("[data-test=palette]").exists()).toBe(true);
expect(document.activeElement).toBe(wrapper.find("[data-test=palette-input]").element);
expect(rows(wrapper)).toEqual([
"vcs.abortMerge",
"vcs.branches",
"vcs.openChanges",
"vcs.checkout",
@ -273,6 +274,7 @@ describe("CommandPalette", () => {
"goto.symbolOpen",
"vcs.showLog",
"vcs.manageRemotes",
"vcs.merge",
"vcs.newBranch",
"vcs.nextChange",
"project.openDialog",
@ -285,6 +287,7 @@ describe("CommandPalette", () => {
"editor.quickDocumentation",
"app.quit",
"vcs.refresh",
"vcs.resolveConflicts",
"editor.reveal",
"settings.open",
"vcs.showDiff",
@ -325,7 +328,7 @@ describe("CommandPalette", () => {
await press({ key: "ArrowUp" });
expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("terminal.open");
await press({ key: "ArrowDown" });
expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("vcs.branches");
expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("vcs.abortMerge");
});
it("dims disabled commands, which Enter and clicks do not run", async () => {

577
ui/tests/vcs/Merge.test.ts Normal file
View file

@ -0,0 +1,577 @@
/**
* Tests of merge conflicts (M4.8): the three-way line merge (one-sided,
* identical and conflicting changes, touching changes, no base, missing
* final line breaks, the initial result), the layout of the three
* documents, reading untrusted `git.merge` and `git.conflictVersions`
* results and the command params, merging with `flushDirty` first (clean,
* up to date, conflicts, refusal, cancelled by a failed save), the dialog
* (branches, the conflicts list from the shared status store, the resolve
* view's three editors with accept left/right per chunk, accept all, a
* chunk opening again when its base text is back, Apply writing the result through the file's buffer
* then `git.markResolved`, deleted and binary files, abort with its
* confirmation and git's refusal), the Changes window opening a
* conflicted file in the resolve view, and the registration of the
* commands. The engine is a fake behind the mocked Tauri `invoke` and
* `listen`.
*/
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { createPinia, setActivePinia, type Pinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorView } from "@codemirror/view";
const invoke = vi.hoisted(() => vi.fn());
const listen = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
vi.mock("@tauri-apps/api/event", () => ({ listen }));
import { useModalsStore } from "../../src/commands/modals";
import { useCommandsStore } from "../../src/commands/store";
import { UI_COMMANDS } from "../../src/commands/uiCommands";
import ChangesToolWindow from "../../src/components/vcs/changes/ChangesToolWindow.vue";
import { useChangesStore } from "../../src/components/vcs/changes/changes";
import { initialResult, merge3, splitUnits, type MergeBlock } from "../../src/components/vcs/merge/diff3";
import MergeDialog from "../../src/components/vcs/merge/MergeDialog.vue";
import {
parseResolveParams,
phaseOf,
toConflictVersions,
toMergeAnswer,
useMergeStore,
} from "../../src/components/vcs/merge/merge";
import { layout } from "../../src/components/vcs/merge/resolveView";
import { useNotificationsStore } from "../../src/stores/notifications";
import { useProjectStore } from "../../src/stores/project";
import { useVcsStatusStore } from "../../src/stores/vcsStatus";
/** A buffer of the fake engine. */
interface FakeBuffer {
path: string;
text: string;
version: number;
saved: string;
}
/** A recorded engine call. */
interface Call {
/** Command id. */
command: string;
/** Its params. */
params: Record<string, unknown>;
}
/** Every engine call, in order. */
let calls: Call[];
/** Fake engine buffers by id. */
let buffers: Map<number, FakeBuffer>;
/** Files on disk. */
let disk: Record<string, string>;
/** Next buffer id. */
let nextId: number;
/** What `git.status` answers. */
let gitStatus: { available: boolean; repo: unknown; files: unknown[] };
/** What `git.merge` answers. */
let mergeAnswer: unknown;
/** What `git.conflictVersions` answers, by path. */
let versions: Record<string, unknown>;
/** What `file.saveAll` answers. */
let saveAll: unknown;
/** Errors to throw, by command id. */
let failures: Record<string, { code: string; message: string }>;
/** Pinia of the current test. */
let pinia: Pinia;
/** Mounted components. */
let mounted: VueWrapper[];
/** The conflicted status entry of a path. */
function conflicted(path: string): unknown {
return { path, index: "conflicted", worktree: "conflicted" };
}
/**
* The calls of a command.
*
* @param command - the command id.
*/
function callsOf(command: string): Call[] {
return calls.filter((c) => c.command === command);
}
/**
* Describes a buffer as `file.open` does.
*
* @param id - its id.
*/
function describeBuffer(id: number): unknown {
const b = buffers.get(id);
return b ? { id, path: b.path, text: b.text, version: b.version, dirty: b.text !== b.saved, lineEnding: "lf" } : null;
}
/**
* The fake engine.
*
* @param command - command id.
* @param p - params.
*/
function execute(command: string, p: Record<string, unknown>): Promise<unknown> {
const failure = failures[command];
if (failure) {
return Promise.reject(Object.assign(new Error(failure.message), failure));
}
const id = typeof p.id === "number" ? p.id : -1;
const b = buffers.get(id);
switch (command) {
case "git.status":
return Promise.resolve(gitStatus);
case "git.branches":
return Promise.resolve({
current: "main",
local: [{ name: "main", head: "1" }, { name: "feature", head: "2" }],
remote: [{ name: "origin/release", head: "3" }],
});
case "git.merge":
return Promise.resolve(mergeAnswer);
case "git.conflictVersions":
return Promise.resolve(versions[String(p.path)] ?? null);
case "git.markResolved": {
const paths = p.paths as string[];
gitStatus = { ...gitStatus, files: gitStatus.files.filter((f) => !paths.includes((f as { path: string }).path)) };
return Promise.resolve({});
}
case "file.saveAll":
return Promise.resolve(saveAll);
case "file.open": {
const path = String(p.path);
for (const [existing, buffer] of buffers) {
if (buffer.path === path) {
return Promise.resolve(describeBuffer(existing));
}
}
const text = disk[path];
if (text === undefined) {
return Promise.reject(Object.assign(new Error(`${path}: not found`), { code: "failed", message: `${path}: not found` }));
}
const newId = nextId++;
buffers.set(newId, { path, text, version: 1, saved: text });
return Promise.resolve(describeBuffer(newId));
}
case "buffer.get":
return Promise.resolve(describeBuffer(id));
case "buffer.edit": {
if (!b || p.baseVersion !== b.version) {
return Promise.reject(Object.assign(new Error("stale"), { code: "stale_version", message: "stale" }));
}
let out = "";
let pos = 0;
for (const e of p.edits as { from: number; to: number; insert: string }[]) {
out += b.text.slice(pos, e.from) + e.insert;
pos = e.to;
}
b.text = out + b.text.slice(pos);
b.version += 1;
return Promise.resolve({ id, version: b.version, dirty: true });
}
case "file.save":
if (b) {
b.saved = b.text;
disk[b.path] = b.text;
}
return Promise.resolve({ id, version: b?.version ?? 0, dirty: false });
default:
return Promise.resolve({});
}
}
/** jsdom has no layout; CodeMirror measures text ranges, so give ranges empty rectangles. */
function stubRangeGeometry(): void {
const empty = (): DOMRectList => Object.assign([] as DOMRect[], { item: () => null });
Range.prototype.getClientRects = empty;
Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0);
}
/** Mounts the dialog with the status store, commands and a project. */
async function mountDialog(): Promise<VueWrapper> {
useProjectStore(pinia).root = { path: "/p", name: "p" };
useVcsStatusStore(pinia).start();
const wrapper = mount(MergeDialog, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(wrapper);
await useCommandsStore(pinia).start();
await flushPromises();
return wrapper;
}
/**
* Runs a command through the command store and waits.
*
* @param id - command id.
* @param params - its params.
*/
async function runCommand(id: string, params: Record<string, unknown> = {}): Promise<void> {
await useCommandsStore(pinia).execute(id, params as never);
await flushPromises();
}
/** Kinds of the blocks of a merge. */
function kinds(blocks: MergeBlock[]): string[] {
return blocks.map((b) => b.kind);
}
/** Lines of a text. */
function lines(...items: string[]): string {
return items.map((l) => `${l}\n`).join("");
}
beforeEach(() => {
stubRangeGeometry();
Element.prototype.scrollIntoView = () => undefined;
pinia = createPinia();
setActivePinia(pinia);
calls = [];
buffers = new Map();
nextId = 1;
mounted = [];
failures = {};
saveAll = { saved: [], failed: [], skipped: [] };
mergeAnswer = { result: "conflicts", conflicts: ["a.php"] };
gitStatus = {
available: true,
repo: { root: "C:/p", branch: "main", detached: false, head: "0123456789" },
files: [conflicted("a.php"), { path: "b.php", index: "modified", worktree: "unmodified" }],
};
disk = { "a.php": "<<<<<<< markers\n" };
versions = {
"a.php": {
base: lines("<?php", "one", "two", "three", "four", "five"),
ours: lines("<?php", "ONE", "two", "three", "four (main)", "five"),
theirs: "<?php\r\none\r\ntwo\r\nthree (feature)\r\nfour (feature)\r\nfive\r\n",
binary: false,
tooLarge: false,
},
};
invoke.mockReset();
listen.mockReset();
listen.mockImplementation(() => Promise.resolve(() => undefined));
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (cmd === "engine_list_commands") {
return Promise.resolve([{ id: "git.status", label: "Git Status", enabled: true }]);
}
if ((cmd === "engine_execute" || cmd === "engine_execute_waiting") && args) {
calls.push({ command: args.command, params: args.params });
return execute(args.command, args.params);
}
return Promise.resolve(null);
});
});
afterEach(async () => {
await flushPromises();
for (const wrapper of mounted) {
wrapper.unmount();
}
useCommandsStore(pinia).stop();
useVcsStatusStore(pinia).stop();
document.body.innerHTML = "";
});
describe("the three-way merge", () => {
it("takes one-sided and identical changes and conflicts on different ones", () => {
const base = splitUnits(lines("a", "b", "c", "d", "e", "f", "g"));
const ours = splitUnits(lines("A", "b", "c", "D", "e", "f", "g", "h"));
const theirs = splitUnits(lines("a", "b", "C", "d2", "e", "F", "g", "h"));
const blocks = merge3(base, ours, theirs);
expect(kinds(blocks)).toEqual(["ours", "stable", "conflict", "stable", "theirs", "stable", "both"]);
expect(blocks[2]).toMatchObject({ base: ["c\n", "d\n"], ours: ["c\n", "D\n"], theirs: ["C\n", "d2\n"] });
expect(initialResult(blocks)).toBe(lines("A", "b", "c", "d", "e", "F", "g", "h"));
});
it("joins every side's units back to its text", () => {
const base = lines("1", "2", "3", "4");
const ours = lines("1", "x", "3", "4", "5");
const theirs = lines("0", "1", "2", "3", "4");
const blocks = merge3(splitUnits(base), splitUnits(ours), splitUnits(theirs));
expect(blocks.map((b) => b.base.join("")).join("")).toBe(base);
expect(blocks.map((b) => b.ours.join("")).join("")).toBe(ours);
expect(blocks.map((b) => b.theirs.join("")).join("")).toBe(theirs);
expect(blocks.some((b) => b.kind === "conflict")).toBe(false);
expect(initialResult(blocks)).toBe(lines("0", "1", "x", "3", "4", "5"));
});
it("gives every side back for random texts, and equals a side changed alone", () => {
let seed = 7;
const next = (n: number): number => {
seed = (seed * 1103515245 + 12345) % 2147483648;
return seed % n;
};
const mutate = (units: string[]): string[] => {
const out = [...units];
for (let k = next(4); k > 0; k -= 1) {
const at = next(out.length + 1);
if (next(2) === 0) {
out.splice(at, 1);
} else {
out.splice(at, 0, `${String(next(5))}\n`);
}
}
return out;
};
for (let round = 0; round < 300; round += 1) {
const base = Array.from({ length: next(8) }, () => `${String(next(5))}\n`);
const ours = mutate(base);
const theirs = mutate(base);
const blocks = merge3(base, ours, theirs);
expect(blocks.map((b) => b.base.join("")).join("")).toBe(base.join(""));
expect(blocks.map((b) => b.ours.join("")).join("")).toBe(ours.join(""));
expect(blocks.map((b) => b.theirs.join("")).join("")).toBe(theirs.join(""));
expect(initialResult(merge3(base, ours, base))).toBe(ours.join(""));
expect(initialResult(merge3(base, base, theirs))).toBe(theirs.join(""));
}
});
it("treats touching changes as a conflict, as git does", () => {
const blocks = merge3(splitUnits(lines("a", "b", "c")), splitUnits(lines("a", "B", "c")), splitUnits(lines("a", "b", "C")));
expect(kinds(blocks)).toEqual(["stable", "conflict"]);
});
it("compares ours and theirs directly without a base", () => {
const blocks = merge3(null, splitUnits(lines("<?php", "main", "end")), splitUnits(lines("<?php", "feature", "end")));
expect(kinds(blocks)).toEqual(["stable", "conflict", "stable"]);
expect(blocks[1]).toMatchObject({ base: [], ours: ["main\n"], theirs: ["feature\n"] });
expect(initialResult(blocks)).toBe(lines("<?php", "end"));
});
it("keeps a missing final line break as a difference", () => {
expect(splitUnits("a\nb")).toEqual(["a\n", "b"]);
expect(splitUnits("")).toEqual([]);
const blocks = merge3(splitUnits("a\nb"), splitUnits("a\nb\n"), splitUnits("a\nb"));
expect(initialResult(blocks)).toBe("a\nb\n");
});
it("lays out the documents with the chunks' places", () => {
const lay = layout("x\nbase\ny\n", "x\nours\ny\n", "x\ntheirs\ny\n");
expect(lay.result).toBe("x\nbase\ny\n");
expect(lay.chunks).toEqual([{ ours: "ours\n", theirs: "theirs\n", oursFrom: 2, oursTo: 7, theirsFrom: 2, theirsTo: 9 }]);
expect(lay.resultRanges).toEqual([{ from: 2, to: 7 }]);
expect(lay.oursMarks).toEqual([{ from: 2, to: 7, conflict: true }]);
});
});
describe("reading results and params", () => {
it("checks git.merge and git.conflictVersions", () => {
expect(toMergeAnswer({ result: "conflicts", conflicts: ["a", 3, ""] })).toEqual({ result: "conflicts", conflicts: ["a"] });
expect(toMergeAnswer({ result: "upToDate" })).toEqual({ result: "upToDate", conflicts: [] });
expect(toMergeAnswer({ result: "weird" })).toBeNull();
expect(toMergeAnswer([1])).toBeNull();
const v = toConflictVersions({ ours: "a\r\nb", theirs: null, binary: false });
expect(v).toEqual({ base: null, ours: "a\nb", theirs: null, binary: false, tooLarge: false });
expect(v && phaseOf(v)).toBe("deleted");
expect(toConflictVersions({ ours: 3, theirs: "x" })).toBeNull();
expect(toConflictVersions(null)).toBeNull();
expect(phaseOf({ base: null, ours: null, theirs: null, binary: true, tooLarge: false })).toBe("binary");
expect(phaseOf({ base: null, ours: "", theirs: "", binary: false, tooLarge: false })).toBe("text");
});
it("checks the params of vcs.resolveConflicts", () => {
expect(parseResolveParams({})).toBeNull();
expect(parseResolveParams(null)).toBeNull();
expect(parseResolveParams({ path: "a.php" })).toBe("a.php");
expect(parseResolveParams({ path: 3 })).toBeUndefined();
expect(parseResolveParams({ path: "" })).toBeUndefined();
});
});
describe("merging", () => {
it("saves first, merges and opens the conflicts list", async () => {
const wrapper = await mountDialog();
await runCommand("vcs.merge", { branch: "feature" });
const order = calls.map((c) => c.command);
expect(order.indexOf("file.saveAll")).toBeLessThan(order.indexOf("git.merge"));
expect(callsOf("git.merge")[0]?.params).toEqual({ branch: "feature" });
const merge = useMergeStore(pinia);
expect(merge.mode).toBe("conflicts");
expect(wrapper.findAll("[data-test=merge-conflict]").map((r) => r.attributes("data-path"))).toEqual(["a.php"]);
expect(useNotificationsStore(pinia).toasts.at(-1)?.level).toBe("warning");
expect(useModalsStore(pinia).current).toBe("merge");
});
it("toasts a clean merge and an up-to-date one, and closes", async () => {
await mountDialog();
mergeAnswer = { result: "merged", conflicts: [] };
await runCommand("vcs.merge", { branch: "feature" });
expect(useMergeStore(pinia).mode).toBe("closed");
expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toContain("Merged feature");
mergeAnswer = { result: "upToDate", conflicts: [] };
await runCommand("vcs.merge", { branch: "feature" });
expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toContain("up to date");
});
it("toasts git's refusal and a failed save cancels the merge", async () => {
await mountDialog();
failures["git.merge"] = { code: "failed", message: "Your local changes would be overwritten" };
await runCommand("vcs.merge", { branch: "feature" });
expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toContain("Your local changes would be overwritten");
delete failures["git.merge"];
calls = [];
saveAll = { saved: [], failed: [{ id: 1, path: "x.php", message: "denied" }], skipped: [] };
await runCommand("vcs.merge", { branch: "feature" });
expect(callsOf("git.merge")).toHaveLength(0);
expect(useNotificationsStore(pinia).toasts.some((n) => n.text.includes("cancelled"))).toBe(true);
});
it("lists the other branches and merges the one chosen", async () => {
const wrapper = await mountDialog();
await runCommand("vcs.merge");
expect(wrapper.get("[data-test=merge-title]").text()).toBe("Merge into main");
expect(wrapper.findAll("[data-test=merge-branch]").map((b) => b.text())).toEqual(["feature", "origin/release"]);
await wrapper.get("[data-test=merge-filter]").setValue("rel");
expect(wrapper.findAll("[data-test=merge-branch]").map((b) => b.text())).toEqual(["origin/release"]);
await wrapper.get("[data-test=merge-filter]").trigger("keydown", { key: "Enter" });
await flushPromises();
expect(callsOf("git.merge")[0]?.params).toEqual({ branch: "origin/release" });
});
});
describe("resolving a file", () => {
/** Opens the resolve view of a.php. */
async function openResolve(): Promise<VueWrapper> {
const wrapper = await mountDialog();
await runCommand("vcs.resolveConflicts", { path: "a.php" });
await flushPromises();
return wrapper;
}
/**
* The text of one of the three editors.
*
* @param wrapper - the dialog.
* @param pane - ours, result or theirs.
*/
function paneText(wrapper: VueWrapper, pane: "ours" | "result" | "theirs"): string {
return [...wrapper.get(`[data-test=merge-${pane}]`).element.querySelectorAll(".cm-line")].map((l) => l.textContent).join("\n");
}
it("shows ours, the merged result and theirs with the conflict open", async () => {
const wrapper = await openResolve();
expect(callsOf("git.conflictVersions")[0]?.params).toEqual({ path: "a.php" });
expect(paneText(wrapper, "ours")).toContain("four (main)");
expect(paneText(wrapper, "theirs")).toContain("three (feature)");
expect(paneText(wrapper, "result")).toContain("ONE");
expect(paneText(wrapper, "result")).toContain("three");
expect(wrapper.get("[data-test=merge-counter]").text()).toBe("1 of 1 conflicts open");
expect(wrapper.get("[data-test=merge-apply]").attributes("disabled")).toBeDefined();
expect(wrapper.findAll(".lt-merge-accept")).toHaveLength(2);
});
it("accepts right per chunk, undo reopens it, and Apply writes and marks resolved", async () => {
const wrapper = await openResolve();
await wrapper.get("[data-test=merge-accept-right]").trigger("click");
await flushPromises();
expect(paneText(wrapper, "result")).toContain("three (feature)");
expect(wrapper.get("[data-test=merge-counter]").text()).toBe("No open conflicts");
expect(wrapper.findAll(".lt-merge-accept")).toHaveLength(0);
await wrapper.get("[data-test=merge-accept-left]").trigger("click");
await wrapper.get("[data-test=merge-apply]").trigger("click");
await flushPromises();
expect(disk["a.php"]).toBe(lines("<?php", "ONE", "two", "three (feature)", "four (feature)", "five"));
const order = calls.map((c) => c.command);
expect(order.lastIndexOf("file.save")).toBeLessThan(order.indexOf("git.markResolved"));
expect(callsOf("git.markResolved")[0]?.params).toEqual({ paths: ["a.php"] });
expect(useMergeStore(pinia).mode).toBe("conflicts");
expect(wrapper.find("[data-test=merge-none]").exists()).toBe(true);
expect(wrapper.find("[data-test=merge-commit]").exists()).toBe(true);
});
it("accepts all left, and restoring the base's text opens the chunk again", async () => {
const wrapper = await openResolve();
await wrapper.get("[data-test=merge-all-left]").trigger("click");
await flushPromises();
expect(paneText(wrapper, "result")).toContain("four (main)");
expect(wrapper.get("[data-test=merge-counter]").text()).toBe("No open conflicts");
const dom = wrapper.get("[data-test=merge-result]").element.querySelector(".cm-editor");
const view = dom ? EditorView.findFromDOM(dom as HTMLElement) : null;
expect(view).not.toBeNull();
if (view) {
const text = view.state.doc.toString();
const taken = "three\nfour (main)\n";
const from = text.indexOf(taken);
view.dispatch({ changes: { from, to: from + taken.length, insert: "three\nfour\n" } });
}
await flushPromises();
expect(wrapper.get("[data-test=merge-counter]").text()).toBe("1 of 1 conflicts open");
expect(wrapper.findAll(".lt-merge-accept")).toHaveLength(2);
});
it("keeps the side that was not deleted, and marks binary files resolved as they are", async () => {
versions["a.php"] = { base: "x\n", ours: null, theirs: "y\n", binary: false, tooLarge: false };
const wrapper = await openResolve();
expect(wrapper.find("[data-test=merge-deleted]").exists()).toBe(true);
expect(wrapper.find("[data-test=merge-keep-ours]").exists()).toBe(false);
await wrapper.get("[data-test=merge-keep-theirs]").trigger("click");
await flushPromises();
expect(disk["a.php"]).toBe("y\n");
gitStatus = { ...gitStatus, files: [conflicted("img.png")] };
versions["img.png"] = { ours: null, theirs: null, binary: true, tooLarge: false };
await useVcsStatusStore(pinia).refresh();
await runCommand("vcs.resolveConflicts", { path: "img.png" });
expect(wrapper.find("[data-test=merge-binary]").exists()).toBe(true);
await wrapper.get("[data-test=merge-mark-as-is]").trigger("click");
await flushPromises();
expect(callsOf("git.markResolved").at(-1)?.params).toEqual({ paths: ["img.png"] });
expect(callsOf("file.open").filter((c) => c.params.path === "img.png")).toHaveLength(0);
});
it("shows git's error for a file that is not in conflict", async () => {
failures["git.conflictVersions"] = { code: "failed", message: "a.php is not in conflict" };
const wrapper = await openResolve();
expect(wrapper.get("[data-test=merge-error]").text()).toContain("a.php is not in conflict");
});
});
describe("aborting", () => {
it("asks first, then aborts; git's refusal stays in the dialog", async () => {
const wrapper = await mountDialog();
await runCommand("vcs.abortMerge");
expect(callsOf("git.mergeAbort")).toHaveLength(0);
failures["git.mergeAbort"] = { code: "failed", message: "There is no merge to abort (MERGE_HEAD missing)." };
await wrapper.get("[data-test=merge-abort]").trigger("click");
await flushPromises();
expect(wrapper.get("[data-test=merge-error]").text()).toContain("MERGE_HEAD missing");
delete failures["git.mergeAbort"];
await wrapper.get("[data-test=merge-abort]").trigger("click");
await flushPromises();
expect(callsOf("git.mergeAbort")).toHaveLength(2);
expect(useMergeStore(pinia).mode).toBe("closed");
expect(wrapper.find("[data-test=merge]").exists()).toBe(false);
});
it("Escape closes the list", async () => {
const wrapper = await mountDialog();
await runCommand("vcs.resolveConflicts");
await wrapper.get("[data-test=merge-dialog]").trigger("keydown", { key: "Escape" });
expect(useMergeStore(pinia).mode).toBe("closed");
expect(useModalsStore(pinia).current).toBeNull();
});
});
describe("entry points", () => {
it("registers the merge commands without default shortcuts", () => {
for (const id of ["vcs.merge", "vcs.resolveConflicts", "vcs.abortMerge"]) {
const spec = UI_COMMANDS.find((c) => c.id === id);
expect(spec?.menuPath?.startsWith("Git/")).toBe(true);
expect(spec?.defaultShortcut).toBeUndefined();
}
});
it("opens a conflicted file from the Changes window in the resolve view", async () => {
await mountDialog();
useChangesStore(pinia).start();
const changes = mount(ChangesToolWindow, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(changes);
await flushPromises();
const row = changes.findAll("[data-test=changes-row]").find((r) => r.text().includes("a.php"));
expect(row).toBeDefined();
await row?.trigger("dblclick");
await flushPromises();
expect(useMergeStore(pinia).mode).toBe("resolve");
expect(useMergeStore(pinia).path).toBe("a.php");
useChangesStore(pinia).stop();
});
});