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:
parent
74c674ed12
commit
d82e57b3ac
26 changed files with 3872 additions and 16 deletions
|
|
@ -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 });
|
||||
|
|
|
|||
917
ui/src/components/vcs/merge/MergeDialog.vue
Normal file
917
ui/src/components/vcs/merge/MergeDialog.vue
Normal 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>
|
||||
276
ui/src/components/vcs/merge/diff3.ts
Normal file
276
ui/src/components/vcs/merge/diff3.ts
Normal 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("");
|
||||
}
|
||||
458
ui/src/components/vcs/merge/merge.ts
Normal file
458
ui/src/components/vcs/merge/merge.ts
Normal 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,
|
||||
};
|
||||
});
|
||||
513
ui/src/components/vcs/merge/resolveView.ts
Normal file
513
ui/src/components/vcs/merge/resolveView.ts
Normal 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();
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue