M4.3: side-by-side diff viewer with next/previous change
vcs.showDiff {path?, staged?} (Mod+Alt+Shift+D) opens a "Diff: <name>"
tab in the editor area: @codemirror/merge (MIT, loaded lazily, 27 kB /
9.7 kB gzip), with the index (or HEAD for the staged view) read-only on
the left, line breaks normalised to LF, and the working copy on the right,
editable through its normal engine buffer. vcs.nextChange (Alt+Shift+])
and vcs.previousChange (Alt+Shift+[) move between chunks. Binary, too
large, failed and deleted files show a notice. Entry points: the Changes
window, a new project tree context menu (Open, Show Diff; right click or
Shift+F10) and the palette/menu. Colours come from the --lt-vcs-* tokens.
21 Vitest tests; parity docs updated (Git 6% -> 8%, est.).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
468b9928a7
commit
8360ffc2e2
23 changed files with 1836 additions and 24 deletions
|
|
@ -26,6 +26,7 @@
|
|||
"@codemirror/lang-yaml": "^6.1.3",
|
||||
"@codemirror/language": "^6.13.1",
|
||||
"@codemirror/lint": "^6.9.7",
|
||||
"@codemirror/merge": "^6.12.3",
|
||||
"@codemirror/state": "^6.7.6",
|
||||
"@codemirror/view": "^6.43.14",
|
||||
"@lezer/highlight": "^1.2.5",
|
||||
|
|
|
|||
14
ui/pnpm-lock.yaml
generated
14
ui/pnpm-lock.yaml
generated
|
|
@ -38,6 +38,9 @@ importers:
|
|||
'@codemirror/lint':
|
||||
specifier: ^6.9.7
|
||||
version: 6.9.7
|
||||
'@codemirror/merge':
|
||||
specifier: ^6.12.3
|
||||
version: 6.12.3
|
||||
'@codemirror/state':
|
||||
specifier: ^6.7.6
|
||||
version: 6.7.6
|
||||
|
|
@ -182,6 +185,9 @@ packages:
|
|||
'@codemirror/lint@6.9.7':
|
||||
resolution: {integrity: sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==}
|
||||
|
||||
'@codemirror/merge@6.12.3':
|
||||
resolution: {integrity: sha512-Wq9wXrp41cW/nIpi1CQPyNwD+36kg8KIX676ym0Hyfn3Dpr+XQHNAIsZYVNlaivuVB4SAASbreG3V0VXinbqZA==}
|
||||
|
||||
'@codemirror/search@6.7.2':
|
||||
resolution: {integrity: sha512-gUYkYhT2+n/+VGZ+8EzE5WFkYZUZYm1VOKDudIsNqh42uRVQJ0a6Yss9sdKT3MeOYfuL1N6AZA57oza0Oyr0LA==}
|
||||
|
||||
|
|
@ -1527,6 +1533,14 @@ snapshots:
|
|||
'@codemirror/view': 6.43.14
|
||||
crelt: 1.0.7
|
||||
|
||||
'@codemirror/merge@6.12.3':
|
||||
dependencies:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
'@lezer/highlight': 1.2.5
|
||||
style-mod: 4.1.4
|
||||
|
||||
'@codemirror/search@6.7.2':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
|
|
|
|||
|
|
@ -38,5 +38,8 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [
|
|||
{ id: "vcs.commit", labelKey: "command.vcs.commit", menuPath: "Git/Commit…", defaultShortcut: "Mod+Alt+Shift+M" },
|
||||
{ id: "vcs.openChanges", labelKey: "command.vcs.openChanges", menuPath: "Git/Changes", defaultShortcut: "Mod+Alt+Shift+G" },
|
||||
{ id: "vcs.refresh", labelKey: "command.vcs.refresh", menuPath: "Git/Refresh Changes" },
|
||||
{ id: "vcs.showDiff", labelKey: "command.vcs.showDiff", menuPath: "Git/Show Diff", defaultShortcut: "Mod+Alt+Shift+D" },
|
||||
{ id: "vcs.nextChange", labelKey: "command.vcs.nextChange", menuPath: "Git/Next Change", defaultShortcut: "Alt+Shift+]" },
|
||||
{ id: "vcs.previousChange", labelKey: "command.vcs.previousChange", menuPath: "Git/Previous Change", defaultShortcut: "Alt+Shift+[" },
|
||||
{ id: "view.toggleStructure", labelKey: "command.view.toggleStructure", menuPath: "View/Structure", defaultShortcut: "Mod+2" },
|
||||
];
|
||||
|
|
|
|||
|
|
@ -7,9 +7,11 @@
|
|||
* palette (`commands/store.ts`): the area supplies their behaviour with the
|
||||
* active buffer as context and says when they can run. It also supplies the
|
||||
* UI commands `editor.reveal` (`reveal.ts`) and the assist commands
|
||||
* (`assist/commands.ts`).
|
||||
* (`assist/commands.ts`). Diff tabs (M4.3, `vcs/diff/`) share the tab bar;
|
||||
* while one is active the diff view replaces the editor, and the area
|
||||
* supplies the diff commands.
|
||||
*/
|
||||
import { onBeforeUnmount, onMounted } from "vue";
|
||||
import { defineAsyncComponent, onBeforeUnmount, onMounted } from "vue";
|
||||
import { useCommandsStore } from "../../commands/store";
|
||||
import { t } from "../../i18n";
|
||||
import { useEditorStore } from "../../stores/editor";
|
||||
|
|
@ -18,9 +20,15 @@ import CodeEditor from "./CodeEditor.vue";
|
|||
import EditorTabs from "./EditorTabs.vue";
|
||||
import { reveal, REVEAL_COMMAND } from "./reveal";
|
||||
import * as assist from "./assist/commands";
|
||||
import { provideDiffCommands } from "../vcs/diff/commands";
|
||||
import { useDiffStore } from "../vcs/diff/diff";
|
||||
|
||||
/** The diff view, loaded on first use so `@codemirror/merge` stays out of the start bundle. */
|
||||
const DiffView = defineAsyncComponent(() => import("../vcs/diff/DiffView.vue"));
|
||||
|
||||
const editor = useEditorStore();
|
||||
const commands = useCommandsStore();
|
||||
const diff = useDiffStore();
|
||||
|
||||
/** Withdraws the command handlers; filled while mounted. */
|
||||
let withdraw: (() => void)[] = [];
|
||||
|
|
@ -36,6 +44,7 @@ onMounted(() => {
|
|||
commands.provide(assist.COMPLETE_COMMAND, { run: assist.completeAtCursor, enabled: assist.assistEnabled }),
|
||||
commands.provide(assist.QUICK_DOC_COMMAND, { run: assist.quickDocumentation, enabled: assist.assistEnabled }),
|
||||
commands.provide(assist.PARAMETER_INFO_COMMAND, { run: assist.parameterInfo, enabled: assist.assistEnabled }),
|
||||
...provideDiffCommands(commands),
|
||||
];
|
||||
});
|
||||
|
||||
|
|
@ -53,10 +62,10 @@ onBeforeUnmount(() => {
|
|||
class="editor-area"
|
||||
data-test="editor-area"
|
||||
>
|
||||
<template v-if="editor.tabs.length > 0">
|
||||
<template v-if="editor.tabs.length > 0 || diff.tabs.length > 0">
|
||||
<EditorTabs />
|
||||
<div
|
||||
v-if="editor.activeTab?.notice"
|
||||
v-if="!diff.visible && editor.activeTab?.notice"
|
||||
class="editor-area__notice"
|
||||
:class="{ 'editor-area__notice--error': editor.activeTab.notice.kind === 'error' }"
|
||||
role="status"
|
||||
|
|
@ -72,7 +81,8 @@ onBeforeUnmount(() => {
|
|||
{{ t("common.dismiss") }}
|
||||
</button>
|
||||
</div>
|
||||
<CodeEditor />
|
||||
<DiffView v-if="diff.visible" />
|
||||
<CodeEditor v-else-if="editor.activeTab" />
|
||||
</template>
|
||||
<div
|
||||
v-else
|
||||
|
|
|
|||
|
|
@ -5,15 +5,51 @@
|
|||
* A click activates a tab, a middle click or the close button closes it,
|
||||
* Left/Right move between tabs. A dot marks unsaved changes. Closing a
|
||||
* dirty tab asks first (see the editor store). Names are coloured by their
|
||||
* Git status (`--lt-vcs-*`, M4.4).
|
||||
* Git status (`--lt-vcs-*`, M4.4). Diff tabs (M4.3, `vcs/diff/diff.ts`)
|
||||
* follow the editor tabs; while one is active, no editor tab is marked
|
||||
* active.
|
||||
*/
|
||||
import { X } from "@lucide/vue";
|
||||
import { t } from "../../i18n";
|
||||
import { useEditorStore } from "../../stores/editor";
|
||||
import { useVcsStatusStore } from "../../stores/vcsStatus";
|
||||
import { useDiffStore } from "../vcs/diff/diff";
|
||||
|
||||
const editor = useEditorStore();
|
||||
const vcs = useVcsStatusStore();
|
||||
const diff = useDiffStore();
|
||||
|
||||
/**
|
||||
* Whether an editor tab is the active one.
|
||||
*
|
||||
* @param id - buffer id of the tab.
|
||||
*/
|
||||
function isActive(id: number): boolean {
|
||||
return id === editor.activeId && !diff.visible;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows an editor tab (and hides an active diff).
|
||||
*
|
||||
* @param id - buffer id of the tab.
|
||||
*/
|
||||
function activateTab(id: number): void {
|
||||
diff.deactivate();
|
||||
editor.activate(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes a diff tab on a middle click.
|
||||
*
|
||||
* @param event - the auxiliary click.
|
||||
* @param key - key of the diff tab.
|
||||
*/
|
||||
function onDiffAuxClick(event: MouseEvent, key: string): void {
|
||||
if (event.button === 1) {
|
||||
event.preventDefault();
|
||||
diff.close(key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes a tab on a middle click.
|
||||
|
|
@ -42,7 +78,7 @@ function onKeydown(event: KeyboardEvent): void {
|
|||
event.preventDefault();
|
||||
const next = editor.tabs[(index + step + editor.tabs.length) % editor.tabs.length];
|
||||
if (next) {
|
||||
editor.activate(next.id);
|
||||
activateTab(next.id);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
|
@ -59,14 +95,14 @@ function onKeydown(event: KeyboardEvent): void {
|
|||
v-for="tab in editor.tabs"
|
||||
:key="tab.id"
|
||||
class="tabs__tab"
|
||||
:class="{ 'tabs__tab--active': tab.id === editor.activeId }"
|
||||
:class="{ 'tabs__tab--active': isActive(tab.id) }"
|
||||
role="tab"
|
||||
:tabindex="tab.id === editor.activeId ? 0 : -1"
|
||||
:aria-selected="tab.id === editor.activeId"
|
||||
:tabindex="isActive(tab.id) ? 0 : -1"
|
||||
:aria-selected="isActive(tab.id)"
|
||||
:title="tab.path"
|
||||
:data-id="tab.id"
|
||||
data-test="editor-tab"
|
||||
@click="editor.activate(tab.id)"
|
||||
@click="activateTab(tab.id)"
|
||||
@mousedown.middle.prevent
|
||||
@auxclick="onAuxClick($event, tab.id)"
|
||||
>
|
||||
|
|
@ -92,6 +128,33 @@ function onKeydown(event: KeyboardEvent): void {
|
|||
<X :size="12" />
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
v-for="tab in diff.tabs"
|
||||
:key="tab.key"
|
||||
class="tabs__tab"
|
||||
:class="{ 'tabs__tab--active': tab.key === diff.activeKey }"
|
||||
role="tab"
|
||||
:tabindex="tab.key === diff.activeKey ? 0 : -1"
|
||||
:aria-selected="tab.key === diff.activeKey"
|
||||
:title="tab.path"
|
||||
:data-key="tab.key"
|
||||
data-test="diff-tab"
|
||||
@click="diff.activate(tab.key)"
|
||||
@mousedown.middle.prevent
|
||||
@auxclick="onDiffAuxClick($event, tab.key)"
|
||||
>
|
||||
<span class="tabs__name">{{ tab.staged ? t("vcs.diff.tabTitleStaged", { name: tab.name }) : t("vcs.diff.tabTitle", { name: tab.name }) }}</span>
|
||||
<button
|
||||
class="tabs__close"
|
||||
type="button"
|
||||
tabindex="-1"
|
||||
:aria-label="t('vcs.diff.closeTab', { name: tab.name })"
|
||||
data-test="diff-tab-close"
|
||||
@click.stop="diff.close(tab.key)"
|
||||
>
|
||||
<X :size="12" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@
|
|||
* the engine listed only partly ends with a "listing truncated" note.
|
||||
* File names are coloured by their Git status (`--lt-vcs-*`, M4.4); inside
|
||||
* a repository, ignored entries take the ignored colour.
|
||||
* A right click on a file, or Shift+F10 / the context-menu key on the
|
||||
* selected file, opens its context menu (`TreeContextMenu.vue`, M4.3).
|
||||
*/
|
||||
import { ChevronDown, ChevronRight, File, FileCode, Folder, FolderOpen } from "@lucide/vue";
|
||||
import { computed, nextTick, ref } from "vue";
|
||||
|
|
@ -18,6 +20,7 @@ import { parentOf, useProjectStore, type TreeRow } from "../../stores/project";
|
|||
import { useEditorStore } from "../../stores/editor";
|
||||
import { useVcsStatusStore, type VcsColour } from "../../stores/vcsStatus";
|
||||
import type { TreeEntry } from "./engineEvents";
|
||||
import TreeContextMenu from "./TreeContextMenu.vue";
|
||||
|
||||
const project = useProjectStore();
|
||||
const editor = useEditorStore();
|
||||
|
|
@ -89,6 +92,40 @@ function isPhp(name: string): boolean {
|
|||
return /\.(php|phtml|inc)$/i.test(name);
|
||||
}
|
||||
|
||||
/** The open context menu: the file and where it shows; null when closed. */
|
||||
const menu = ref<{ path: string; name: string; x: number; y: number } | null>(null);
|
||||
|
||||
/**
|
||||
* Opens the context menu of a file; folders have none yet.
|
||||
*
|
||||
* @param entry - the entry.
|
||||
* @param x - window x of the menu.
|
||||
* @param y - window y of the menu.
|
||||
*/
|
||||
function openMenu(entry: TreeEntry, x: number, y: number): void {
|
||||
if (entry.kind !== "file") {
|
||||
return;
|
||||
}
|
||||
project.select(entry.path);
|
||||
menu.value = { path: entry.path, name: entry.name, x, y };
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the context menu of the selected file from the keyboard, below its row.
|
||||
*
|
||||
* @param entry - the selected entry.
|
||||
*/
|
||||
function openMenuAtRow(entry: TreeEntry): void {
|
||||
const rect = document.getElementById(rowId(entry.path))?.getBoundingClientRect();
|
||||
openMenu(entry, rect ? rect.left + 24 : 0, rect ? rect.bottom : 0);
|
||||
}
|
||||
|
||||
/** Closes the context menu and gives the focus back to the tree. */
|
||||
function closeMenu(): void {
|
||||
menu.value = null;
|
||||
treeEl.value?.focus();
|
||||
}
|
||||
|
||||
/** Scrolls the selected row into view after the DOM updated. */
|
||||
async function revealSelected(): Promise<void> {
|
||||
await nextTick();
|
||||
|
|
@ -209,6 +246,13 @@ function onKeydown(event: KeyboardEvent): void {
|
|||
activate(row.entry);
|
||||
}
|
||||
break;
|
||||
case "ContextMenu":
|
||||
case "F10":
|
||||
if (!row || (event.key === "F10" && !event.shiftKey)) {
|
||||
return;
|
||||
}
|
||||
openMenuAtRow(row.entry);
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
|
|
@ -256,6 +300,7 @@ function onFocus(): void {
|
|||
data-test="tree-row"
|
||||
@click="onRowClick(row.entry, false)"
|
||||
@dblclick="activate(row.entry)"
|
||||
@contextmenu.prevent="openMenu(row.entry, $event.clientX, $event.clientY)"
|
||||
>
|
||||
<span
|
||||
class="tree__chevron"
|
||||
|
|
@ -325,6 +370,16 @@ function onFocus(): void {
|
|||
{{ row.error.message }}
|
||||
</div>
|
||||
</template>
|
||||
<Teleport to="body">
|
||||
<TreeContextMenu
|
||||
v-if="menu"
|
||||
:path="menu.path"
|
||||
:name="menu.name"
|
||||
:x="menu.x"
|
||||
:y="menu.y"
|
||||
@close="closeMenu"
|
||||
/>
|
||||
</Teleport>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
|
|
|||
201
ui/src/components/project/TreeContextMenu.vue
Normal file
201
ui/src/components/project/TreeContextMenu.vue
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* The project tree's context menu for a file (M4.3): Open and Show Diff
|
||||
* (`vcs.showDiff {path}`, dimmed while the command is disabled).
|
||||
*
|
||||
* Follows the WAI-ARIA menu pattern: it takes the focus when it opens,
|
||||
* Up/Down move between items (wrapping), Enter or Space runs one, Escape,
|
||||
* Tab or a press outside closes it. The position is clamped into the
|
||||
* window.
|
||||
*/
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import { useCommandsStore } from "../../commands/store";
|
||||
import { t } from "../../i18n";
|
||||
import { useEditorStore } from "../../stores/editor";
|
||||
import { SHOW_DIFF_COMMAND } from "../vcs/diff/diff";
|
||||
|
||||
const props = defineProps<{
|
||||
/** Project-relative path of the file. */
|
||||
path: string;
|
||||
/** File name, for the accessible label. */
|
||||
name: string;
|
||||
/** Window x of the pointer (or the row) in pixels. */
|
||||
x: number;
|
||||
/** Window y of the pointer (or the row) in pixels. */
|
||||
y: number;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
/** The menu should close (an item ran or the user dismissed it). */
|
||||
close: [];
|
||||
}>();
|
||||
|
||||
const editor = useEditorStore();
|
||||
const commands = useCommandsStore();
|
||||
|
||||
/** The menu element. */
|
||||
const menuEl = ref<HTMLElement | null>(null);
|
||||
/** Index of the focused item. */
|
||||
const focused = ref(0);
|
||||
|
||||
/** One item of the menu. */
|
||||
interface MenuItem {
|
||||
/** Stable id, also used by tests. */
|
||||
id: string;
|
||||
/** Text shown. */
|
||||
label: string;
|
||||
/** Whether it can run now. */
|
||||
enabled: boolean;
|
||||
/** Runs it. */
|
||||
run: () => Promise<void>;
|
||||
}
|
||||
|
||||
/** The items, in order. */
|
||||
const items = computed<MenuItem[]>(() => [
|
||||
{
|
||||
id: "open",
|
||||
label: t("project.tree.menu.open"),
|
||||
enabled: true,
|
||||
run: async () => {
|
||||
await editor.openFile(props.path);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "showDiff",
|
||||
label: t("project.tree.menu.showDiff"),
|
||||
enabled: commands.isEnabled(SHOW_DIFF_COMMAND),
|
||||
run: () => commands.execute(SHOW_DIFF_COMMAND, { path: props.path }),
|
||||
},
|
||||
]);
|
||||
|
||||
/** The menu's position, kept inside the window. */
|
||||
const position = computed(() => ({
|
||||
left: `${String(Math.max(0, Math.min(props.x, window.innerWidth - 200)))}px`,
|
||||
top: `${String(Math.max(0, Math.min(props.y, window.innerHeight - 80)))}px`,
|
||||
}));
|
||||
|
||||
/**
|
||||
* Runs an item and closes the menu.
|
||||
*
|
||||
* @param item - the item.
|
||||
*/
|
||||
async function choose(item: MenuItem): Promise<void> {
|
||||
if (!item.enabled) {
|
||||
return;
|
||||
}
|
||||
emit("close");
|
||||
await item.run();
|
||||
}
|
||||
|
||||
/**
|
||||
* Keyboard handling of the menu.
|
||||
*
|
||||
* @param event - the key event.
|
||||
*/
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
const count = items.value.length;
|
||||
switch (event.key) {
|
||||
case "ArrowDown":
|
||||
focused.value = (focused.value + 1) % count;
|
||||
break;
|
||||
case "ArrowUp":
|
||||
focused.value = (focused.value - 1 + count) % count;
|
||||
break;
|
||||
case "Enter":
|
||||
case " ": {
|
||||
const item = items.value[focused.value];
|
||||
if (item) {
|
||||
void choose(item);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "Escape":
|
||||
case "Tab":
|
||||
emit("close");
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the menu on a press outside it.
|
||||
*
|
||||
* @param event - the pointer event on the window.
|
||||
*/
|
||||
function onPointerDown(event: PointerEvent): void {
|
||||
if (menuEl.value && event.target instanceof Node && !menuEl.value.contains(event.target)) {
|
||||
emit("close");
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener("pointerdown", onPointerDown, true);
|
||||
void nextTick(() => menuEl.value?.focus());
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener("pointerdown", onPointerDown, true);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
ref="menuEl"
|
||||
class="tree-menu"
|
||||
role="menu"
|
||||
tabindex="-1"
|
||||
:aria-label="t('project.tree.menu.label', { name })"
|
||||
:aria-activedescendant="`lt-tree-menu-${items[focused]?.id ?? ''}`"
|
||||
:style="position"
|
||||
data-test="tree-menu"
|
||||
@keydown="onKeydown"
|
||||
@contextmenu.prevent
|
||||
>
|
||||
<div
|
||||
v-for="(item, index) in items"
|
||||
:id="`lt-tree-menu-${item.id}`"
|
||||
:key="item.id"
|
||||
class="tree-menu__item"
|
||||
:class="{ 'tree-menu__item--focused': index === focused, 'tree-menu__item--disabled': !item.enabled }"
|
||||
role="menuitem"
|
||||
:aria-disabled="!item.enabled"
|
||||
:data-item="item.id"
|
||||
data-test="tree-menu-item"
|
||||
@mouseenter="focused = index"
|
||||
@click="choose(item)"
|
||||
>
|
||||
{{ item.label }}
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.tree-menu {
|
||||
position: fixed;
|
||||
z-index: 50;
|
||||
min-width: 160px;
|
||||
padding: 4px 0;
|
||||
color: var(--lt-fg);
|
||||
background: var(--lt-bg);
|
||||
border: 1px solid var(--lt-border);
|
||||
border-radius: 4px;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.tree-menu__item {
|
||||
padding: 4px 16px;
|
||||
cursor: default;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.tree-menu__item--focused {
|
||||
background: var(--lt-editor-selection-bg);
|
||||
}
|
||||
|
||||
.tree-menu__item--disabled {
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
</style>
|
||||
338
ui/src/components/vcs/diff/DiffView.vue
Normal file
338
ui/src/components/vcs/diff/DiffView.vue
Normal file
|
|
@ -0,0 +1,338 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* The active diff tab (M4.3): a side-by-side `@codemirror/merge` view of
|
||||
* the ref (left, read-only) and the working copy (right, editable), or a
|
||||
* notice for binary, too large and failed diffs.
|
||||
*
|
||||
* - **Right side and the buffer:** the right editor starts from the
|
||||
* working copy's {@link BufferSync} state. Every local change of it is
|
||||
* handed to the sync, which sends it to the engine like typing in the
|
||||
* file's own tab (the file's tab is hidden while the diff shows, so the
|
||||
* sync has no view of its own). Engine changes to the buffer (a reload
|
||||
* from disk, an agent's edit) come back through `bufferChanged`: once the
|
||||
* sync has taken them over, the difference is applied to the right
|
||||
* editor outside its undo history.
|
||||
* - **Left side:** replaced in place when the store re-reads it
|
||||
* (`gitChanged` after staging).
|
||||
* - **Colours:** only `--lt-*` tokens; changed lines are tinted with
|
||||
* `--lt-vcs-deleted` (left) and `--lt-vcs-added` (right).
|
||||
* - **Navigation:** a navigator over the merge view is registered for
|
||||
* `vcs.nextChange` / `vcs.previousChange` (`navigation.ts`): the focused
|
||||
* side, else the working copy, moves to the next or previous chunk.
|
||||
*/
|
||||
import { getChunks, goToNextChunk, goToPreviousChunk, MergeView } from "@codemirror/merge";
|
||||
import { Annotation, EditorState, Transaction, type Extension } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { basicSetup } from "codemirror";
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
import { t } from "../../../i18n";
|
||||
import { onEngineEvent } from "../../../ipc";
|
||||
import { useEditorStore } from "../../../stores/editor";
|
||||
import type { BufferSync } from "../../editor/bufferSync";
|
||||
import { diffDocs } from "../../editor/engineText";
|
||||
import { editorExtensions, lutraEditorTheme } from "../../editor/extensions";
|
||||
import { languageExtensions } from "../../editor/language";
|
||||
import { refFor, useDiffStore } from "./diff";
|
||||
import { setNavigator } from "./navigation";
|
||||
|
||||
const diff = useDiffStore();
|
||||
const editor = useEditorStore();
|
||||
|
||||
/** Element the merge view is mounted in. */
|
||||
const host = ref<HTMLElement | null>(null);
|
||||
/** The merge view, null while none is built. */
|
||||
let merge: MergeView | null = null;
|
||||
/** The sync of the right side, null when the working copy is missing. */
|
||||
let sync: BufferSync | null = null;
|
||||
/** What the current merge view was built for, to rebuild only on a change. */
|
||||
let builtFor = "";
|
||||
/** Ends the engine event subscription. */
|
||||
let unsubscribe: (() => void) | null = null;
|
||||
|
||||
/** Marks right-side transactions that carry the buffer's changes, so they are not sent back. */
|
||||
const fromBuffer = Annotation.define<boolean>();
|
||||
|
||||
/** Colours of the diff, from tokens only. */
|
||||
const diffTheme: Extension = EditorView.theme({
|
||||
"&.cm-merge-a .cm-changedLine, .cm-deletedChunk": {
|
||||
backgroundColor: "color-mix(in srgb, var(--lt-vcs-deleted) 14%, var(--lt-editor-bg))",
|
||||
},
|
||||
"&.cm-merge-b .cm-changedLine, .cm-inlineChangedLine": {
|
||||
backgroundColor: "color-mix(in srgb, var(--lt-vcs-added) 14%, var(--lt-editor-bg))",
|
||||
},
|
||||
"&.cm-merge-a .cm-changedText, .cm-deletedChunk .cm-deletedText": {
|
||||
background: "color-mix(in srgb, var(--lt-vcs-deleted) 35%, transparent)",
|
||||
},
|
||||
"&.cm-merge-b .cm-changedText": {
|
||||
background: "color-mix(in srgb, var(--lt-vcs-added) 35%, transparent)",
|
||||
},
|
||||
"&.cm-merge-b .cm-deletedText": {
|
||||
background: "color-mix(in srgb, var(--lt-vcs-deleted) 35%, transparent)",
|
||||
},
|
||||
".cm-collapsedLines": {
|
||||
color: "var(--lt-fg-muted)",
|
||||
background: "var(--lt-bg)",
|
||||
borderTop: "1px solid var(--lt-border)",
|
||||
borderBottom: "1px solid var(--lt-border)",
|
||||
},
|
||||
"&.cm-merge-a .cm-changedLineGutter, .cm-deletedLineGutter": {
|
||||
background: "var(--lt-vcs-deleted)",
|
||||
},
|
||||
"&.cm-merge-b .cm-changedLineGutter": {
|
||||
background: "var(--lt-vcs-added)",
|
||||
},
|
||||
});
|
||||
|
||||
/** The header line: what is compared with what. */
|
||||
const caption = computed(() => {
|
||||
const tab = diff.activeTab;
|
||||
if (!tab) {
|
||||
return "";
|
||||
}
|
||||
return refFor(tab.staged) === "HEAD"
|
||||
? t("vcs.diff.captionHead", { path: tab.path })
|
||||
: t("vcs.diff.captionIndex", { path: tab.path });
|
||||
});
|
||||
|
||||
/** The notice shown instead of, or above, the diff; null if none. */
|
||||
const notice = computed(() => {
|
||||
const content = diff.activeContent;
|
||||
switch (content?.phase) {
|
||||
case "binary":
|
||||
return t("vcs.diff.binary");
|
||||
case "tooLarge":
|
||||
return t("vcs.diff.tooLarge");
|
||||
case "error":
|
||||
return t("vcs.diff.failed", { reason: content.message ?? "" });
|
||||
case "ready":
|
||||
return content.message;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Hands local changes of the right editor to the buffer's sync.
|
||||
*
|
||||
* @param transactions - transactions the right editor applied.
|
||||
*/
|
||||
function forward(transactions: readonly Transaction[]): void {
|
||||
if (!sync) {
|
||||
return;
|
||||
}
|
||||
for (const tr of transactions) {
|
||||
if (!tr.docChanged || tr.annotation(fromBuffer) === true) {
|
||||
continue;
|
||||
}
|
||||
const changes = sync.state.doc.eq(tr.startState.doc) ? tr.changes : diffDocs(sync.state.doc, tr.state.doc);
|
||||
const userEvent = tr.annotation(Transaction.userEvent);
|
||||
sync.dispatch(userEvent === undefined ? { changes } : { changes, userEvent });
|
||||
}
|
||||
}
|
||||
|
||||
/** Brings the right editor up to the buffer's text, outside its undo history. */
|
||||
function pullFromBuffer(): void {
|
||||
if (!merge || !sync) {
|
||||
return;
|
||||
}
|
||||
const from = merge.b.state.doc;
|
||||
const to = sync.state.doc;
|
||||
if (from.eq(to)) {
|
||||
return;
|
||||
}
|
||||
merge.b.dispatch({
|
||||
changes: diffDocs(from, to),
|
||||
annotations: [fromBuffer.of(true), Transaction.addToHistory.of(false)],
|
||||
});
|
||||
}
|
||||
|
||||
/** Destroys the merge view. */
|
||||
function destroy(): void {
|
||||
setNavigator(null);
|
||||
merge?.destroy();
|
||||
merge = null;
|
||||
sync = null;
|
||||
builtFor = "";
|
||||
}
|
||||
|
||||
/** Builds the merge view for the active tab, or rebuilds it when its inputs changed. */
|
||||
function build(): void {
|
||||
const tab = diff.activeTab;
|
||||
const content = diff.activeContent;
|
||||
const key = tab && content?.phase === "ready" ? `${tab.key}#${String(content.bufferId ?? "none")}` : "";
|
||||
if (key === builtFor && merge) {
|
||||
return;
|
||||
}
|
||||
destroy();
|
||||
if (!tab || !content || content.phase !== "ready" || !host.value) {
|
||||
return;
|
||||
}
|
||||
const bufferId = content.bufferId;
|
||||
sync = bufferId === null ? null : (editor.syncOf(bufferId) ?? null);
|
||||
const readOnly = [EditorState.readOnly.of(true), EditorView.editable.of(false)];
|
||||
const right: Extension = sync
|
||||
? [
|
||||
editorExtensions(tab.path, { id: sync.id, idle: () => sync?.idle() ?? Promise.resolve() }),
|
||||
diffTheme,
|
||||
EditorView.updateListener.of((update) => {
|
||||
forward(update.transactions);
|
||||
}),
|
||||
]
|
||||
: [basicSetup, lutraEditorTheme, languageExtensions(tab.path), diffTheme, readOnly];
|
||||
merge = new MergeView({
|
||||
a: { doc: content.left, extensions: [basicSetup, lutraEditorTheme, languageExtensions(tab.path), diffTheme, readOnly] },
|
||||
b: sync ? { doc: sync.state.doc, selection: sync.state.selection, extensions: right } : { doc: "", extensions: right },
|
||||
parent: host.value,
|
||||
gutter: true,
|
||||
highlightChanges: true,
|
||||
collapseUnchanged: { margin: 3, minSize: 8 },
|
||||
});
|
||||
builtFor = key;
|
||||
const view = merge;
|
||||
const side = (): EditorView => (view.a.hasFocus ? view.a : view.b);
|
||||
setNavigator({
|
||||
view,
|
||||
hasChanges: () => (getChunks(side().state)?.chunks.length ?? 0) > 0,
|
||||
go: (direction) => {
|
||||
const target = side();
|
||||
const moved = (direction > 0 ? goToNextChunk : goToPreviousChunk)(target);
|
||||
target.focus();
|
||||
return moved;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Replaces the left document with the store's text after a re-read. */
|
||||
function updateLeft(): void {
|
||||
const content = diff.activeContent;
|
||||
if (!merge || content?.phase !== "ready") {
|
||||
return;
|
||||
}
|
||||
const doc = merge.a.state.doc;
|
||||
if (doc.toString() !== content.left) {
|
||||
merge.a.dispatch({ changes: { from: 0, to: doc.length, insert: content.left } });
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [diff.activeKey, diff.activeContent] as const,
|
||||
() => {
|
||||
build();
|
||||
},
|
||||
);
|
||||
|
||||
watch(
|
||||
() => diff.leftRevision,
|
||||
() => {
|
||||
updateLeft();
|
||||
},
|
||||
);
|
||||
|
||||
onMounted(() => {
|
||||
build();
|
||||
unsubscribe = onEngineEvent((event) => {
|
||||
if (event.kind !== "bufferChanged" || !sync || event.id !== sync.id) {
|
||||
return;
|
||||
}
|
||||
const target = sync;
|
||||
void Promise.resolve()
|
||||
.then(() => target.idle())
|
||||
.then(() => {
|
||||
if (sync === target) {
|
||||
pullFromBuffer();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
unsubscribe?.();
|
||||
unsubscribe = null;
|
||||
destroy();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="diff-view"
|
||||
data-test="diff-view"
|
||||
:data-path="diff.activeTab?.path"
|
||||
>
|
||||
<div
|
||||
class="diff-view__caption"
|
||||
data-test="diff-caption"
|
||||
>
|
||||
{{ caption }}
|
||||
</div>
|
||||
<div
|
||||
v-if="notice"
|
||||
class="diff-view__notice"
|
||||
role="status"
|
||||
data-test="diff-notice"
|
||||
>
|
||||
{{ notice }}
|
||||
</div>
|
||||
<div
|
||||
v-if="diff.activeContent?.phase === 'loading'"
|
||||
class="diff-view__loading"
|
||||
data-test="diff-loading"
|
||||
>
|
||||
{{ t("vcs.diff.loading") }}
|
||||
</div>
|
||||
<div
|
||||
v-show="diff.activeContent?.phase === 'ready'"
|
||||
ref="host"
|
||||
class="diff-view__merge"
|
||||
data-test="diff-merge"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.diff-view {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
background: var(--lt-editor-bg);
|
||||
}
|
||||
|
||||
.diff-view__caption {
|
||||
flex-shrink: 0;
|
||||
padding: 3px 12px;
|
||||
color: var(--lt-fg-muted);
|
||||
background: var(--lt-bg);
|
||||
border-bottom: 1px solid var(--lt-border);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.diff-view__notice {
|
||||
flex-shrink: 0;
|
||||
padding: 4px 12px;
|
||||
color: var(--lt-fg);
|
||||
background: var(--lt-notice-bg);
|
||||
border-bottom: 1px solid var(--lt-border);
|
||||
}
|
||||
|
||||
.diff-view__loading {
|
||||
padding: 12px;
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.diff-view__merge {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
user-select: text;
|
||||
}
|
||||
|
||||
.diff-view__merge :deep(.cm-mergeView) {
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
.diff-view__merge :deep(.cm-mergeViewEditor + .cm-mergeViewEditor) {
|
||||
border-left: 1px solid var(--lt-border);
|
||||
}
|
||||
</style>
|
||||
43
ui/src/components/vcs/diff/commands.ts
Normal file
43
ui/src/components/vcs/diff/commands.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
/**
|
||||
* The diff viewer's UI commands, supplied by the editor area:
|
||||
*
|
||||
* - `vcs.showDiff {path?, staged?}`: opens the diff of a file; without a
|
||||
* path, of the active diff or editor tab (the palette). Enabled while a
|
||||
* project is open.
|
||||
* - `vcs.nextChange` / `vcs.previousChange`: move to the next or previous
|
||||
* change of the visible diff. Enabled while a diff with changes shows.
|
||||
*/
|
||||
import type { useCommandsStore } from "../../../commands/store";
|
||||
import { useProjectStore } from "../../../stores/project";
|
||||
import { NEXT_CHANGE_COMMAND, PREVIOUS_CHANGE_COMMAND, SHOW_DIFF_COMMAND, useDiffStore } from "./diff";
|
||||
import { goToChange, hasChanges } from "./navigation";
|
||||
|
||||
/**
|
||||
* Supplies the diff commands and starts the diff store.
|
||||
*
|
||||
* @param commands - the command store.
|
||||
* @returns functions that withdraw the handlers and stop the store.
|
||||
*/
|
||||
export function provideDiffCommands(commands: ReturnType<typeof useCommandsStore>): (() => void)[] {
|
||||
const diff = useDiffStore();
|
||||
const project = useProjectStore();
|
||||
diff.start();
|
||||
return [
|
||||
commands.provide(SHOW_DIFF_COMMAND, { run: (params) => diff.showDiff(params), enabled: () => project.root !== null }),
|
||||
commands.provide(NEXT_CHANGE_COMMAND, {
|
||||
run: () => {
|
||||
goToChange(1);
|
||||
},
|
||||
enabled: () => diff.activeContent?.phase === "ready" && hasChanges(),
|
||||
}),
|
||||
commands.provide(PREVIOUS_CHANGE_COMMAND, {
|
||||
run: () => {
|
||||
goToChange(-1);
|
||||
},
|
||||
enabled: () => diff.activeContent?.phase === "ready" && hasChanges(),
|
||||
}),
|
||||
() => {
|
||||
diff.stop();
|
||||
},
|
||||
];
|
||||
}
|
||||
475
ui/src/components/vcs/diff/diff.ts
Normal file
475
ui/src/components/vcs/diff/diff.ts
Normal file
|
|
@ -0,0 +1,475 @@
|
|||
/**
|
||||
* The diff viewer's state (M4.3): the "Diff: <name>" tabs of the editor
|
||||
* area and what each one compares.
|
||||
*
|
||||
* - **Opening:** the UI command `vcs.showDiff {path, staged?}` (Changes
|
||||
* window, the project tree's context menu, the palette). One tab per path
|
||||
* and side; opening it again activates and reloads it.
|
||||
* - **Left side:** `git.show {path, ref}` (a pending outcome, so through
|
||||
* `runWaiting`). `staged: true` compares with HEAD; otherwise with the
|
||||
* index, which equals HEAD for a file without staged changes, so a
|
||||
* partly staged file shows only what is not staged yet. A path missing at
|
||||
* that ref (a new or untracked file) gives an empty left side. Git
|
||||
* returns the blob as stored (LF when autocrlf normalised it), so line
|
||||
* breaks are normalised to `\n` ({@link normaliseEol}); CodeMirror keeps
|
||||
* lines, not break characters, so a CRLF working copy lines up.
|
||||
* - **Right side:** the working copy as an ordinary engine buffer, opened
|
||||
* through the editor store, so its edits, saves, autosave and the
|
||||
* recovery journal work as in any tab (the buffer also gets its normal
|
||||
* tab). A file missing from the working copy (deleted) shows an empty,
|
||||
* read-only right side and a notice.
|
||||
* - **Notices instead of a diff:** binary files and files over git's cap
|
||||
* (`binary` / `tooLarge` of `git.show`).
|
||||
* - **Active tab:** a diff tab is shown over the editor tab that was
|
||||
* active when it was activated (the anchor). Any other editor tab
|
||||
* becoming active hides the diff again; the editor tabs bar deactivates
|
||||
* it on a click.
|
||||
* - **Refresh:** `gitChanged` re-reads the left side of every text tab
|
||||
* (staging changes the index). A project open or close drops every tab;
|
||||
* closing the working copy's buffer closes its diff tabs.
|
||||
* - **Untrusted input:** `git.show` results are checked field by field.
|
||||
*/
|
||||
import { defineStore } from "pinia";
|
||||
import { computed, ref, shallowRef, watch } from "vue";
|
||||
import { t } from "../../../i18n";
|
||||
import { onEngineEvent, runWaiting, type EngineEventPayload, type JsonValue } from "../../../ipc";
|
||||
import { baseName, useEditorStore } from "../../../stores/editor";
|
||||
|
||||
/** Command id that opens a diff. */
|
||||
export const SHOW_DIFF_COMMAND = "vcs.showDiff";
|
||||
|
||||
/** Command id that moves to the next change of the active diff. */
|
||||
export const NEXT_CHANGE_COMMAND = "vcs.nextChange";
|
||||
|
||||
/** Command id that moves to the previous change of the active diff. */
|
||||
export const PREVIOUS_CHANGE_COMMAND = "vcs.previousChange";
|
||||
|
||||
/** The ref a diff compares the working copy with. */
|
||||
export type DiffRef = "HEAD" | "index";
|
||||
|
||||
/** Params of `vcs.showDiff`, checked. */
|
||||
export interface ShowDiffParams {
|
||||
/** Project-relative path; null for the active editor tab's file. */
|
||||
path: string | null;
|
||||
/** Whether to compare with HEAD (the staged view). */
|
||||
staged: boolean;
|
||||
}
|
||||
|
||||
/** One diff tab. */
|
||||
export interface DiffTab {
|
||||
/** Stable key: side and path. */
|
||||
key: string;
|
||||
/** Project-relative path with `/`. */
|
||||
path: string;
|
||||
/** Whether it compares with HEAD instead of the index. */
|
||||
staged: boolean;
|
||||
/** File name shown on the tab. */
|
||||
name: string;
|
||||
}
|
||||
|
||||
/** What a diff tab shows. */
|
||||
export type DiffPhase = "loading" | "ready" | "binary" | "tooLarge" | "error";
|
||||
|
||||
/** The loaded contents of a diff tab. */
|
||||
export interface DiffContent {
|
||||
/** What the tab shows. */
|
||||
phase: DiffPhase;
|
||||
/** The left text with `\n` breaks; empty when missing at the ref. */
|
||||
left: string;
|
||||
/** Whether the path does not exist at the ref (a new file). */
|
||||
leftMissing: boolean;
|
||||
/** Engine buffer of the working copy, null when it could not be opened. */
|
||||
bufferId: number | null;
|
||||
/** Error text, or why the working copy is missing; null if none. */
|
||||
message: string | null;
|
||||
}
|
||||
|
||||
/** A `git.show` result, checked. */
|
||||
export interface ShowResult {
|
||||
/** The text, null when the path does not exist at the ref. */
|
||||
text: string | null;
|
||||
/** Whether git sees the file as binary. */
|
||||
binary: boolean;
|
||||
/** Whether the file is over git's size cap. */
|
||||
tooLarge: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns every line break into `\n`.
|
||||
*
|
||||
* @param text - text with any mix of `\r\n`, `\r` and `\n`.
|
||||
*/
|
||||
export function normaliseEol(text: string): string {
|
||||
return text.replace(/\r\n?/g, "\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* The ref to compare with.
|
||||
*
|
||||
* @param staged - whether the staged view (HEAD) is asked for.
|
||||
*/
|
||||
export function refFor(staged: boolean): DiffRef {
|
||||
return staged ? "HEAD" : "index";
|
||||
}
|
||||
|
||||
/**
|
||||
* The key of a diff tab.
|
||||
*
|
||||
* @param path - project-relative path.
|
||||
* @param staged - the side.
|
||||
*/
|
||||
export function diffKey(path: string, staged: boolean): string {
|
||||
return `${staged ? "staged" : "work"}:${path}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the params of `vcs.showDiff`; null when malformed.
|
||||
*
|
||||
* @param params - untrusted (`{}` from the palette and the keyboard).
|
||||
*/
|
||||
export function parseShowDiff(params: unknown): ShowDiffParams | null {
|
||||
const p = typeof params === "object" && params !== null && !Array.isArray(params) ? (params as Record<string, unknown>) : {};
|
||||
const path = p.path === undefined || p.path === null ? null : typeof p.path === "string" && p.path !== "" ? p.path : undefined;
|
||||
const staged = p.staged === undefined || p.staged === null ? false : typeof p.staged === "boolean" ? p.staged : undefined;
|
||||
if (path === undefined || staged === undefined) {
|
||||
return null;
|
||||
}
|
||||
return { path, staged };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a `git.show` result; null when malformed.
|
||||
*
|
||||
* @param raw - untrusted.
|
||||
*/
|
||||
export function toShowResult(raw: unknown): ShowResult | null {
|
||||
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
||||
return null;
|
||||
}
|
||||
const r = raw as Record<string, unknown>;
|
||||
if (r.text !== null && typeof r.text !== "string") {
|
||||
return null;
|
||||
}
|
||||
return { text: r.text, binary: r.binary === true, tooLarge: r.tooLarge === true };
|
||||
}
|
||||
|
||||
/** A tab's content while it loads. */
|
||||
const LOADING: DiffContent = { phase: "loading", left: "", leftMissing: false, bufferId: null, message: null };
|
||||
|
||||
/** The diff store. */
|
||||
export const useDiffStore = defineStore("diff", () => {
|
||||
const editor = useEditorStore();
|
||||
|
||||
/** Open diff tabs in display order. */
|
||||
const tabs = ref<DiffTab[]>([]);
|
||||
/** Key of the active diff tab, null when an editor tab is shown. */
|
||||
const activeKey = ref<string | null>(null);
|
||||
/** Contents by tab key; replaced as a whole on every change. */
|
||||
const contents = shallowRef<Record<string, DiffContent>>({});
|
||||
/** Bumped whenever a tab's left text is re-read with a different result. */
|
||||
const leftRevision = ref(0);
|
||||
/** The editor tab shown under the active diff (see the module docs). */
|
||||
let anchor: number | null = null;
|
||||
/** Loads opening the working copy now; the editor tab they activate becomes the anchor. */
|
||||
let anchoring = 0;
|
||||
/** Load generation by tab key, so only the newest load of a tab lands. */
|
||||
const generations = new Map<string, number>();
|
||||
|
||||
/** The active diff tab, null when none is shown. */
|
||||
const activeTab = computed(() => tabs.value.find((tab) => tab.key === activeKey.value) ?? null);
|
||||
|
||||
/** Whether a diff tab covers the editor now. */
|
||||
const visible = computed(() => activeTab.value !== null);
|
||||
|
||||
/** The content of the active tab, null when none is shown. */
|
||||
const activeContent = computed(() => (activeTab.value ? (contents.value[activeTab.value.key] ?? LOADING) : null));
|
||||
|
||||
watch(
|
||||
() => editor.activeId,
|
||||
(id) => {
|
||||
if (anchoring > 0) {
|
||||
anchor = id;
|
||||
} else if (id !== anchor) {
|
||||
activeKey.value = null;
|
||||
}
|
||||
},
|
||||
{ flush: "sync" },
|
||||
);
|
||||
|
||||
watch(
|
||||
() => editor.tabs.map((tab) => tab.id),
|
||||
(ids) => {
|
||||
for (const tab of [...tabs.value]) {
|
||||
const bufferId = contents.value[tab.key]?.bufferId;
|
||||
if (bufferId !== undefined && bufferId !== null && !ids.includes(bufferId)) {
|
||||
close(tab.key);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* Stores the content of a tab.
|
||||
*
|
||||
* @param key - the tab key.
|
||||
* @param content - its content.
|
||||
*/
|
||||
function setContent(key: string, content: DiffContent): void {
|
||||
contents.value = { ...contents.value, [key]: content };
|
||||
}
|
||||
|
||||
/**
|
||||
* The content of a tab.
|
||||
*
|
||||
* @param key - the tab key.
|
||||
*/
|
||||
function contentOf(key: string): DiffContent | null {
|
||||
return contents.value[key] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a diff tab over the active editor tab.
|
||||
*
|
||||
* @param key - the tab key.
|
||||
*/
|
||||
function activate(key: string): void {
|
||||
if (tabs.value.some((tab) => tab.key === key)) {
|
||||
anchor = editor.activeId;
|
||||
activeKey.value = key;
|
||||
}
|
||||
}
|
||||
|
||||
/** Shows the editor tab again. */
|
||||
function deactivate(): void {
|
||||
activeKey.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the left side of a diff.
|
||||
*
|
||||
* @param tab - the tab.
|
||||
* @returns the checked result, or the error text.
|
||||
*/
|
||||
async function readLeft(tab: DiffTab): Promise<ShowResult | string> {
|
||||
const result = await runWaiting("git.show", { path: tab.path, ref: refFor(tab.staged) });
|
||||
if (!result.ok) {
|
||||
return result.error.message;
|
||||
}
|
||||
return toShowResult(result.value) ?? t("common.error.unexpectedResult", { command: "git.show" });
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the working copy of a tab as an engine buffer.
|
||||
*
|
||||
* @param tab - the tab.
|
||||
* @returns the buffer id, or the reason it could not be opened.
|
||||
*/
|
||||
async function openRight(tab: DiffTab): Promise<number | string> {
|
||||
const existing = editor.tabs.find((editorTab) => editorTab.path === tab.path);
|
||||
if (existing && editor.syncOf(existing.id)) {
|
||||
return existing.id;
|
||||
}
|
||||
const before = editor.lastError;
|
||||
const wasActive = activeKey.value === tab.key;
|
||||
if (wasActive) {
|
||||
anchoring += 1;
|
||||
}
|
||||
try {
|
||||
const id = await editor.openFile(tab.path);
|
||||
if (id !== null) {
|
||||
return id;
|
||||
}
|
||||
const reason = editor.lastError?.message ?? "";
|
||||
editor.lastError = before;
|
||||
return reason;
|
||||
} finally {
|
||||
if (wasActive) {
|
||||
anchoring -= 1;
|
||||
if (activeKey.value === tab.key) {
|
||||
anchor = editor.activeId;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads both sides of a tab.
|
||||
*
|
||||
* @param tab - the tab.
|
||||
*/
|
||||
async function load(tab: DiffTab): Promise<void> {
|
||||
const generation = (generations.get(tab.key) ?? 0) + 1;
|
||||
generations.set(tab.key, generation);
|
||||
const current = (): boolean => generations.get(tab.key) === generation && tabs.value.some((t) => t.key === tab.key);
|
||||
setContent(tab.key, LOADING);
|
||||
const left = await readLeft(tab);
|
||||
if (!current()) {
|
||||
return;
|
||||
}
|
||||
if (typeof left === "string") {
|
||||
setContent(tab.key, { ...LOADING, phase: "error", message: left });
|
||||
return;
|
||||
}
|
||||
if (left.binary || left.tooLarge) {
|
||||
setContent(tab.key, { ...LOADING, phase: left.binary ? "binary" : "tooLarge" });
|
||||
return;
|
||||
}
|
||||
const right = await openRight(tab);
|
||||
if (!current()) {
|
||||
return;
|
||||
}
|
||||
setContent(tab.key, {
|
||||
phase: "ready",
|
||||
left: normaliseEol(left.text ?? ""),
|
||||
leftMissing: left.text === null,
|
||||
bufferId: typeof right === "number" ? right : null,
|
||||
message: typeof right === "number" ? null : t("vcs.diff.workingCopyMissing", { reason: right }),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens (or activates and reloads) the diff of a file.
|
||||
*
|
||||
* @param path - project-relative path.
|
||||
* @param staged - compare with HEAD instead of the index.
|
||||
*/
|
||||
async function open(path: string, staged: boolean): Promise<void> {
|
||||
const key = diffKey(path, staged);
|
||||
let tab = tabs.value.find((t) => t.key === key);
|
||||
if (!tab) {
|
||||
tab = { key, path, staged, name: baseName(path) };
|
||||
tabs.value.push(tab);
|
||||
}
|
||||
activate(key);
|
||||
await load(tab);
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-reads the left side of every loaded text tab; a changed text
|
||||
* replaces the left document (`gitChanged`).
|
||||
*/
|
||||
async function refreshLeft(): Promise<void> {
|
||||
await Promise.all(
|
||||
tabs.value.map(async (tab) => {
|
||||
const before = contents.value[tab.key];
|
||||
if (before?.phase !== "ready") {
|
||||
return;
|
||||
}
|
||||
const generation = generations.get(tab.key);
|
||||
const left = await readLeft(tab);
|
||||
const now = contents.value[tab.key];
|
||||
if (generations.get(tab.key) !== generation || now?.phase !== "ready" || typeof left === "string") {
|
||||
return;
|
||||
}
|
||||
if (left.binary || left.tooLarge) {
|
||||
setContent(tab.key, { ...LOADING, phase: left.binary ? "binary" : "tooLarge" });
|
||||
return;
|
||||
}
|
||||
const text = normaliseEol(left.text ?? "");
|
||||
if (text !== now.left || (left.text === null) !== now.leftMissing) {
|
||||
setContent(tab.key, { ...now, left: text, leftMissing: left.text === null });
|
||||
leftRevision.value += 1;
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes a diff tab; the working copy's buffer stays open.
|
||||
*
|
||||
* @param key - the tab key.
|
||||
*/
|
||||
function close(key: string): void {
|
||||
const index = tabs.value.findIndex((tab) => tab.key === key);
|
||||
if (index < 0) {
|
||||
return;
|
||||
}
|
||||
tabs.value.splice(index, 1);
|
||||
generations.delete(key);
|
||||
contents.value = Object.fromEntries(Object.entries(contents.value).filter(([k]) => k !== key));
|
||||
if (activeKey.value === key) {
|
||||
activeKey.value = null;
|
||||
const next = tabs.value[Math.min(index, tabs.value.length - 1)];
|
||||
if (next && editor.tabs.length === 0) {
|
||||
activate(next.key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Drops every tab (project opened or closed). */
|
||||
function clear(): void {
|
||||
tabs.value = [];
|
||||
activeKey.value = null;
|
||||
contents.value = {};
|
||||
generations.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies one engine event.
|
||||
*
|
||||
* @param event - the event.
|
||||
*/
|
||||
function onEvent(event: EngineEventPayload): void {
|
||||
if (event.kind === "projectOpened" || event.kind === "projectClosed") {
|
||||
clear();
|
||||
} else if (event.kind === "gitChanged") {
|
||||
void refreshLeft();
|
||||
}
|
||||
}
|
||||
|
||||
/** Ends the event subscription; set while started. */
|
||||
let unsubscribe: (() => void) | null = null;
|
||||
|
||||
/** Subscribes to engine events; calling it again has no effect. */
|
||||
function start(): void {
|
||||
unsubscribe ??= onEngineEvent(onEvent);
|
||||
}
|
||||
|
||||
/** Ends the subscription. */
|
||||
function stop(): void {
|
||||
unsubscribe?.();
|
||||
unsubscribe = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `vcs.showDiff`: the given file, else the active diff's or editor
|
||||
* tab's file.
|
||||
*
|
||||
* @param params - untrusted params.
|
||||
* @throws Error with a catalog message when the params are malformed or
|
||||
* there is no file to compare.
|
||||
*/
|
||||
async function showDiff(params: JsonValue): Promise<void> {
|
||||
const parsed = parseShowDiff(params);
|
||||
if (!parsed) {
|
||||
throw new Error(t("vcs.diff.invalidParams"));
|
||||
}
|
||||
const path = parsed.path ?? activeTab.value?.path ?? editor.activeTab?.path ?? null;
|
||||
if (path === null) {
|
||||
throw new Error(t("vcs.diff.noFile"));
|
||||
}
|
||||
const staged = parsed.path === null && activeTab.value ? activeTab.value.staged : parsed.staged;
|
||||
await open(path, staged);
|
||||
}
|
||||
|
||||
return {
|
||||
tabs,
|
||||
activeKey,
|
||||
activeTab,
|
||||
activeContent,
|
||||
visible,
|
||||
contents,
|
||||
leftRevision,
|
||||
contentOf,
|
||||
activate,
|
||||
deactivate,
|
||||
open,
|
||||
showDiff,
|
||||
refreshLeft,
|
||||
close,
|
||||
clear,
|
||||
onEvent,
|
||||
start,
|
||||
stop,
|
||||
};
|
||||
});
|
||||
58
ui/src/components/vcs/diff/navigation.ts
Normal file
58
ui/src/components/vcs/diff/navigation.ts
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
/**
|
||||
* Next/previous change in the diff shown now (`vcs.nextChange`,
|
||||
* `vcs.previousChange`). The diff view registers a navigator here while it
|
||||
* shows a merge view; the commands move the cursor of the side that has
|
||||
* the focus (the working copy otherwise) to the next or previous changed
|
||||
* chunk, wrapping around, and scroll it into view.
|
||||
*
|
||||
* This module does not import `@codemirror/merge`, so the package stays in
|
||||
* the lazily loaded diff view's chunk.
|
||||
*/
|
||||
import type { MergeView } from "@codemirror/merge";
|
||||
|
||||
/** What the diff view offers the commands. */
|
||||
export interface DiffNavigator {
|
||||
/** The merge view (tests read it). */
|
||||
view: MergeView;
|
||||
/** Whether the diff has at least one change. */
|
||||
hasChanges(): boolean;
|
||||
/**
|
||||
* Moves to the next or previous change.
|
||||
*
|
||||
* @param direction - 1 for the next change, -1 for the previous one.
|
||||
* @returns whether the cursor moved.
|
||||
*/
|
||||
go(direction: 1 | -1): boolean;
|
||||
}
|
||||
|
||||
/** The navigator of the diff shown now, null when none is visible. */
|
||||
let current: DiffNavigator | null = null;
|
||||
|
||||
/**
|
||||
* Registers the navigator of the diff shown now.
|
||||
*
|
||||
* @param navigator - the navigator, or null when the merge view goes away.
|
||||
*/
|
||||
export function setNavigator(navigator: DiffNavigator | null): void {
|
||||
current = navigator;
|
||||
}
|
||||
|
||||
/** The merge view shown now, null when none. */
|
||||
export function currentMerge(): MergeView | null {
|
||||
return current?.view ?? null;
|
||||
}
|
||||
|
||||
/** Whether the visible diff has at least one change. */
|
||||
export function hasChanges(): boolean {
|
||||
return current?.hasChanges() ?? false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves to the next or previous change of the visible diff.
|
||||
*
|
||||
* @param direction - 1 for the next change, -1 for the previous one.
|
||||
* @returns whether the cursor moved.
|
||||
*/
|
||||
export function goToChange(direction: 1 | -1): boolean {
|
||||
return current?.go(direction) ?? false;
|
||||
}
|
||||
|
|
@ -20,8 +20,11 @@
|
|||
"command.terminal.open": "Terminal",
|
||||
"command.unavailable": "{command} cannot run right now",
|
||||
"command.vcs.commit": "Commit…",
|
||||
"command.vcs.nextChange": "Next Change",
|
||||
"command.vcs.openChanges": "Changes",
|
||||
"command.vcs.previousChange": "Previous Change",
|
||||
"command.vcs.refresh": "Refresh Changes",
|
||||
"command.vcs.showDiff": "Show Diff",
|
||||
"command.view.toggleProjectTree": "Show or Hide Project",
|
||||
"command.view.toggleStructure": "Show or Hide Structure",
|
||||
"common.cancel": "Cancel",
|
||||
|
|
@ -177,6 +180,9 @@
|
|||
"project.openFolder": "Open Folder…",
|
||||
"project.toolWindow.title": "Project",
|
||||
"project.tree.loading": "Loading…",
|
||||
"project.tree.menu.label": "Actions for {name}",
|
||||
"project.tree.menu.open": "Open",
|
||||
"project.tree.menu.showDiff": "Show Diff",
|
||||
"project.tree.truncated": "Listing truncated: more entries than can be shown",
|
||||
"recovery.dialog.changedOnDisk": "The file changed on disk since then",
|
||||
"recovery.dialog.discard": "Discard",
|
||||
|
|
@ -292,6 +298,18 @@
|
|||
"vcs.commit.hint": "Commit the staged changes ({keys})",
|
||||
"vcs.commit.messageLabel": "Commit message",
|
||||
"vcs.commit.placeholder": "Commit message",
|
||||
"vcs.diff.binary": "Binary file: no text diff to show.",
|
||||
"vcs.diff.captionHead": "{path}: last commit (left) and working copy (right)",
|
||||
"vcs.diff.captionIndex": "{path}: staged version (left) and working copy (right)",
|
||||
"vcs.diff.closeTab": "Close the diff of {name}",
|
||||
"vcs.diff.failed": "The diff cannot be shown: {reason}",
|
||||
"vcs.diff.invalidParams": "vcs.showDiff takes {path?: string, staged?: boolean}",
|
||||
"vcs.diff.loading": "Reading the file from Git…",
|
||||
"vcs.diff.noFile": "Open a file or pass a path to show its diff",
|
||||
"vcs.diff.tabTitle": "Diff: {name}",
|
||||
"vcs.diff.tabTitleStaged": "Diff: {name} (staged)",
|
||||
"vcs.diff.tooLarge": "The file is too large to compare.",
|
||||
"vcs.diff.workingCopyMissing": "The working copy cannot be opened ({reason}); it may have been deleted.",
|
||||
"vcs.state.added": "added",
|
||||
"vcs.state.conflicted": "conflicted",
|
||||
"vcs.state.copied": "copied",
|
||||
|
|
|
|||
|
|
@ -277,7 +277,10 @@ describe("AppMenu", () => {
|
|||
"goto.symbolOpen",
|
||||
"vcs.openChanges",
|
||||
"vcs.commit",
|
||||
"vcs.nextChange",
|
||||
"vcs.previousChange",
|
||||
"vcs.refresh",
|
||||
"vcs.showDiff",
|
||||
"app.about",
|
||||
]);
|
||||
const close = document.querySelector("[data-command='buffer.close']");
|
||||
|
|
|
|||
|
|
@ -267,15 +267,18 @@ describe("CommandPalette", () => {
|
|||
"goto.classOpen",
|
||||
"goto.fileOpen",
|
||||
"goto.symbolOpen",
|
||||
"vcs.nextChange",
|
||||
"project.openDialog",
|
||||
"menu.open",
|
||||
"editor.parameterInfo",
|
||||
"vcs.previousChange",
|
||||
"problems.open",
|
||||
"editor.quickDocumentation",
|
||||
"app.quit",
|
||||
"vcs.refresh",
|
||||
"editor.reveal",
|
||||
"settings.open",
|
||||
"vcs.showDiff",
|
||||
"view.toggleProjectTree",
|
||||
"view.toggleStructure",
|
||||
"terminal.open",
|
||||
|
|
|
|||
504
ui/tests/vcs/DiffView.test.ts
Normal file
504
ui/tests/vcs/DiffView.test.ts
Normal file
|
|
@ -0,0 +1,504 @@
|
|||
/**
|
||||
* Tests of the diff viewer (M4.3): reading the untrusted params and
|
||||
* `git.show` results, line-break normalisation, `vcs.showDiff` opening a
|
||||
* "Diff: <name>" tab with the index (or HEAD for the staged view) on the
|
||||
* left and the working copy's buffer on the right, edits on the right
|
||||
* reaching the engine through the buffer, engine changes reaching the right
|
||||
* side, left side refresh on `gitChanged`, notices for binary, too large,
|
||||
* failed and deleted files, switching between diff and editor tabs, the
|
||||
* next/previous change commands and the project tree's context menu. The
|
||||
* engine is a fake behind the mocked Tauri `invoke` and `listen`.
|
||||
*/
|
||||
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { createPinia, setActivePinia, type Pinia } from "pinia";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
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 { useCommandsStore } from "../../src/commands/store";
|
||||
import EditorArea from "../../src/components/editor/EditorArea.vue";
|
||||
import { emitEngineEvent } from "../../src/components/project/engineEvents";
|
||||
import ProjectToolWindow from "../../src/components/project/ProjectToolWindow.vue";
|
||||
import {
|
||||
diffKey,
|
||||
normaliseEol,
|
||||
parseShowDiff,
|
||||
refFor,
|
||||
toShowResult,
|
||||
useDiffStore,
|
||||
} from "../../src/components/vcs/diff/diff";
|
||||
import { currentMerge } from "../../src/components/vcs/diff/navigation";
|
||||
import { useEditorStore } from "../../src/stores/editor";
|
||||
import { useNotificationsStore } from "../../src/stores/notifications";
|
||||
import { useProjectStore } from "../../src/stores/project";
|
||||
|
||||
/** A buffer of the fake engine. */
|
||||
interface FakeBuffer {
|
||||
path: string;
|
||||
text: string;
|
||||
version: number;
|
||||
saved: number;
|
||||
}
|
||||
|
||||
/** Fake engine buffers by id. */
|
||||
let buffers: Map<number, FakeBuffer>;
|
||||
/** Files in the working copy. */
|
||||
let disk: Record<string, string>;
|
||||
/** What `git.show` answers, by `ref:path`; missing entries mean "not at that ref". */
|
||||
let blobs: Record<string, unknown>;
|
||||
/** Errors to throw, by command id. */
|
||||
let failures: Record<string, { code: string; message: string }>;
|
||||
/** Next buffer id. */
|
||||
let nextId: number;
|
||||
/** Every engine call, in order. */
|
||||
let calls: { via: string; command: string; params: Record<string, unknown> }[];
|
||||
/** Engine event callbacks of every subscription. */
|
||||
let listeners: ((event: { payload: unknown }) => void)[];
|
||||
/** Pinia of the current test. */
|
||||
let pinia: Pinia;
|
||||
/** Mounted components. */
|
||||
let mounted: VueWrapper[];
|
||||
|
||||
/**
|
||||
* Sends an engine event to every subscription.
|
||||
*
|
||||
* @param payload - the event.
|
||||
*/
|
||||
async function emit(payload: unknown): Promise<void> {
|
||||
for (const listener of [...listeners]) {
|
||||
listener({ payload });
|
||||
}
|
||||
await flushPromises();
|
||||
}
|
||||
|
||||
/**
|
||||
* Describes a buffer as `file.open` and `buffer.get` do.
|
||||
*
|
||||
* @param id - buffer 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.version !== b.saved, lineEnding: b.text.includes("\r\n") ? "crlf" : "lf" } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rejects like the shell does with an engine error.
|
||||
*
|
||||
* @param code - error code.
|
||||
* @param message - error text.
|
||||
*/
|
||||
function fail(code: string, message = code): Promise<never> {
|
||||
return Promise.reject(Object.assign(new Error(message), { code, message }));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 fail(failure.code, failure.message);
|
||||
}
|
||||
const id = typeof p.id === "number" ? p.id : -1;
|
||||
const b = buffers.get(id);
|
||||
switch (command) {
|
||||
case "git.show": {
|
||||
const blob = blobs[`${String(p.ref)}:${String(p.path)}`];
|
||||
return Promise.resolve(blob === undefined ? { text: null, binary: false, tooLarge: false } : blob);
|
||||
}
|
||||
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 fail("failed", `${path}: file not found`);
|
||||
}
|
||||
const newId = nextId++;
|
||||
buffers.set(newId, { path, text, version: 1, saved: 1 });
|
||||
return Promise.resolve(describeBuffer(newId));
|
||||
}
|
||||
case "buffer.get":
|
||||
return b ? Promise.resolve(describeBuffer(id)) : fail("failed");
|
||||
case "buffer.edit": {
|
||||
if (!b) {
|
||||
return fail("failed");
|
||||
}
|
||||
if (p.baseVersion !== b.version) {
|
||||
return fail("stale_version");
|
||||
}
|
||||
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 "project.children":
|
||||
return Promise.resolve({
|
||||
dir: "",
|
||||
entries: Object.keys(disk).map((path) => ({ name: path, path, kind: "file", ignored: false, role: null })),
|
||||
truncated: false,
|
||||
});
|
||||
default:
|
||||
return Promise.resolve({});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The calls of a command.
|
||||
*
|
||||
* @param command - the command id.
|
||||
*/
|
||||
function callsOf(command: string): { via: string; command: string; params: Record<string, unknown> }[] {
|
||||
return calls.filter((c) => c.command === command);
|
||||
}
|
||||
|
||||
/** 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 editor area with the keymap and an open project. */
|
||||
async function mountArea(): Promise<VueWrapper> {
|
||||
await useCommandsStore(pinia).start();
|
||||
useProjectStore(pinia).root = { path: "/p", name: "p" };
|
||||
const wrapper = mount(EditorArea, { attachTo: document.body, slots: { default: "empty" }, global: { plugins: [pinia] } });
|
||||
mounted.push(wrapper);
|
||||
await flushPromises();
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a command through the command store and waits for it.
|
||||
*
|
||||
* @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 vi.dynamicImportSettled();
|
||||
await flushPromises();
|
||||
}
|
||||
|
||||
/** Both sides of the merge view. */
|
||||
function sides(): { a: EditorView; b: EditorView } {
|
||||
const merge = currentMerge();
|
||||
if (!merge) {
|
||||
throw new Error("no merge view");
|
||||
}
|
||||
return { a: merge.a, b: merge.b };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
stubRangeGeometry();
|
||||
Element.prototype.scrollIntoView = () => undefined;
|
||||
pinia = createPinia();
|
||||
setActivePinia(pinia);
|
||||
buffers = new Map();
|
||||
disk = { "a.php": "<?php\necho 2;\nnew();\n", "b.txt": "bee\n" };
|
||||
blobs = {
|
||||
"index:a.php": { text: "<?php\r\necho 1;\r\n", binary: false, tooLarge: false },
|
||||
"HEAD:a.php": { text: "<?php\necho 0;\n", binary: false, tooLarge: false },
|
||||
};
|
||||
failures = {};
|
||||
nextId = 1;
|
||||
calls = [];
|
||||
listeners = [];
|
||||
mounted = [];
|
||||
invoke.mockReset();
|
||||
listen.mockReset();
|
||||
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
|
||||
listeners.push(callback);
|
||||
return Promise.resolve(() => {
|
||||
listeners = listeners.filter((l) => l !== callback);
|
||||
});
|
||||
});
|
||||
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
|
||||
if (cmd === "engine_list_commands") {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
if ((cmd === "engine_execute" || cmd === "engine_execute_waiting") && args) {
|
||||
calls.push({ via: cmd, command: args.command, params: args.params });
|
||||
return execute(args.command, args.params);
|
||||
}
|
||||
return Promise.resolve(null);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await flushPromises();
|
||||
useCommandsStore(pinia).stop();
|
||||
for (const wrapper of mounted) {
|
||||
wrapper.unmount();
|
||||
}
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
describe("helpers", () => {
|
||||
it("normalises every line break to LF", () => {
|
||||
expect(normaliseEol("a\r\nb\rc\nd")).toBe("a\nb\nc\nd");
|
||||
expect(normaliseEol("")).toBe("");
|
||||
});
|
||||
|
||||
it("reads the params of vcs.showDiff", () => {
|
||||
expect(parseShowDiff({})).toEqual({ path: null, staged: false });
|
||||
expect(parseShowDiff({ path: "a.php", staged: true })).toEqual({ path: "a.php", staged: true });
|
||||
expect(parseShowDiff(null)).toEqual({ path: null, staged: false });
|
||||
expect(parseShowDiff({ path: 3 })).toBeNull();
|
||||
expect(parseShowDiff({ path: "" })).toBeNull();
|
||||
expect(parseShowDiff({ path: "a", staged: "yes" })).toBeNull();
|
||||
});
|
||||
|
||||
it("reads git.show results and picks the ref", () => {
|
||||
expect(toShowResult({ text: "x", binary: false, tooLarge: false })).toEqual({ text: "x", binary: false, tooLarge: false });
|
||||
expect(toShowResult({ text: null, binary: true })).toEqual({ text: null, binary: true, tooLarge: false });
|
||||
expect(toShowResult({ text: 5 })).toBeNull();
|
||||
expect(toShowResult([])).toBeNull();
|
||||
expect(toShowResult("x")).toBeNull();
|
||||
expect(refFor(true)).toBe("HEAD");
|
||||
expect(refFor(false)).toBe("index");
|
||||
expect(diffKey("a", true)).not.toBe(diffKey("a", false));
|
||||
});
|
||||
});
|
||||
|
||||
describe("vcs.showDiff", () => {
|
||||
it("opens a diff tab: index on the left (CRLF normalised), the working copy's buffer on the right", async () => {
|
||||
const area = await mountArea();
|
||||
await runCommand("vcs.showDiff", { path: "a.php", staged: false });
|
||||
expect(callsOf("git.show")).toEqual([{ via: "engine_execute_waiting", command: "git.show", params: { path: "a.php", ref: "index" } }]);
|
||||
expect(area.findAll("[data-test=diff-tab]").map((t) => t.text())).toEqual(["Diff: a.php"]);
|
||||
expect(area.find("[data-test=diff-tab]").attributes("aria-selected")).toBe("true");
|
||||
expect(area.find("[data-test=editor-tab]").attributes("aria-selected")).toBe("false");
|
||||
expect(area.find("[data-test=code-editor]").exists()).toBe(false);
|
||||
expect(area.find("[data-test=diff-caption]").text()).toContain("staged version");
|
||||
const { a, b } = sides();
|
||||
expect(a.state.doc.toString()).toBe("<?php\necho 1;\n");
|
||||
expect(a.state.readOnly).toBe(true);
|
||||
expect(b.state.doc.toString()).toBe("<?php\necho 2;\nnew();\n");
|
||||
expect(b.state.readOnly).toBe(false);
|
||||
expect(currentMerge()?.chunks.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("compares with HEAD for the staged view and reuses one tab per path and side", async () => {
|
||||
const area = await mountArea();
|
||||
await runCommand("vcs.showDiff", { path: "a.php", staged: true });
|
||||
expect(callsOf("git.show")[0]?.params).toEqual({ path: "a.php", ref: "HEAD" });
|
||||
expect(sides().a.state.doc.toString()).toBe("<?php\necho 0;\n");
|
||||
expect(area.find("[data-test=diff-caption]").text()).toContain("last commit");
|
||||
expect(area.find("[data-test=diff-tab]").text()).toBe("Diff: a.php (staged)");
|
||||
await runCommand("vcs.showDiff", { path: "a.php", staged: true });
|
||||
expect(area.findAll("[data-test=diff-tab]")).toHaveLength(1);
|
||||
expect(callsOf("file.open")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("without a path, diffs the active editor tab's file", async () => {
|
||||
await mountArea();
|
||||
await useEditorStore(pinia).openFile("a.php");
|
||||
await runCommand("vcs.showDiff");
|
||||
expect(callsOf("git.show")[0]?.params).toEqual({ path: "a.php", ref: "index" });
|
||||
expect(useDiffStore(pinia).activeTab?.path).toBe("a.php");
|
||||
});
|
||||
|
||||
it("refuses bad params and a missing file with an error toast", async () => {
|
||||
await mountArea();
|
||||
await runCommand("vcs.showDiff", { path: 7 });
|
||||
await runCommand("vcs.showDiff");
|
||||
const texts = useNotificationsStore(pinia).toasts.map((toast) => toast.text);
|
||||
expect(texts.some((text) => text.includes("{path?: string"))).toBe(true);
|
||||
expect(texts.some((text) => text.includes("Open a file"))).toBe(true);
|
||||
expect(callsOf("git.show")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("is disabled without a project", async () => {
|
||||
await mountArea();
|
||||
useProjectStore(pinia).root = null;
|
||||
expect(useCommandsStore(pinia).isEnabled("vcs.showDiff")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("editing and refreshing", () => {
|
||||
it("sends edits on the right through the buffer", async () => {
|
||||
await mountArea();
|
||||
await runCommand("vcs.showDiff", { path: "a.php" });
|
||||
const { b } = sides();
|
||||
b.dispatch({ changes: { from: 0, insert: "// x\n" }, userEvent: "input.type" });
|
||||
await flushPromises();
|
||||
const edits = callsOf("buffer.edit");
|
||||
expect(edits).toHaveLength(1);
|
||||
expect(edits[0]?.params.edits).toEqual([{ from: 0, to: 0, insert: "// x\n" }]);
|
||||
expect(buffers.get(1)?.text).toBe("// x\n<?php\necho 2;\nnew();\n");
|
||||
expect(useEditorStore(pinia).syncOf(1)?.state.doc.toString()).toBe("// x\n<?php\necho 2;\nnew();\n");
|
||||
});
|
||||
|
||||
it("shows engine changes of the buffer on the right", async () => {
|
||||
await mountArea();
|
||||
await runCommand("vcs.showDiff", { path: "a.php" });
|
||||
const buffer = buffers.get(1);
|
||||
if (!buffer) {
|
||||
throw new Error("no buffer");
|
||||
}
|
||||
buffer.text = "<?php\necho 3;\n";
|
||||
buffer.version = 5;
|
||||
await emit({ kind: "bufferChanged", id: 1, version: 5 });
|
||||
await flushPromises();
|
||||
expect(sides().b.state.doc.toString()).toBe("<?php\necho 3;\n");
|
||||
expect(callsOf("buffer.edit")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("re-reads the left side on gitChanged", async () => {
|
||||
await mountArea();
|
||||
await runCommand("vcs.showDiff", { path: "a.php" });
|
||||
blobs["index:a.php"] = { text: "<?php\necho 2;\nnew();\n", binary: false, tooLarge: false };
|
||||
await emit({ kind: "gitChanged", available: true, repo: null, filesChanged: true });
|
||||
await flushPromises();
|
||||
expect(sides().a.state.doc.toString()).toBe("<?php\necho 2;\nnew();\n");
|
||||
expect(currentMerge()?.chunks).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("closes the diff when the working copy's buffer closes", async () => {
|
||||
const area = await mountArea();
|
||||
await runCommand("vcs.showDiff", { path: "a.php" });
|
||||
await emit({ kind: "bufferClosed", id: 1 });
|
||||
await flushPromises();
|
||||
expect(area.findAll("[data-test=diff-tab]")).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("notices", () => {
|
||||
it("shows a notice for binary and too large files without opening the file", async () => {
|
||||
blobs["index:img.png"] = { text: null, binary: true, tooLarge: false };
|
||||
blobs["index:big.sql"] = { text: null, binary: false, tooLarge: true };
|
||||
const area = await mountArea();
|
||||
await runCommand("vcs.showDiff", { path: "img.png" });
|
||||
expect(area.find("[data-test=diff-notice]").text()).toContain("Binary file");
|
||||
await runCommand("vcs.showDiff", { path: "big.sql" });
|
||||
expect(area.find("[data-test=diff-notice]").text()).toContain("too large");
|
||||
expect(callsOf("file.open")).toHaveLength(0);
|
||||
expect(currentMerge()).toBeNull();
|
||||
});
|
||||
|
||||
it("shows git's error", async () => {
|
||||
failures["git.show"] = { code: "failed", message: "fatal: bad object" };
|
||||
const area = await mountArea();
|
||||
await runCommand("vcs.showDiff", { path: "a.php" });
|
||||
expect(area.find("[data-test=diff-notice]").text()).toContain("fatal: bad object");
|
||||
});
|
||||
|
||||
it("shows a deleted working copy as an empty read-only side with a notice", async () => {
|
||||
blobs["index:gone.php"] = { text: "<?php\n", binary: false, tooLarge: false };
|
||||
const area = await mountArea();
|
||||
await runCommand("vcs.showDiff", { path: "gone.php" });
|
||||
expect(area.find("[data-test=diff-notice]").text()).toContain("may have been deleted");
|
||||
expect(area.find("[data-test=editor-error]").exists()).toBe(false);
|
||||
const { a, b } = sides();
|
||||
expect(a.state.doc.toString()).toBe("<?php\n");
|
||||
expect(b.state.doc.toString()).toBe("");
|
||||
expect(b.state.readOnly).toBe(true);
|
||||
});
|
||||
|
||||
it("shows a new file against an empty left side", async () => {
|
||||
await mountArea();
|
||||
await runCommand("vcs.showDiff", { path: "b.txt" });
|
||||
const { a, b } = sides();
|
||||
expect(a.state.doc.toString()).toBe("");
|
||||
expect(b.state.doc.toString()).toBe("bee\n");
|
||||
});
|
||||
});
|
||||
|
||||
describe("tabs and navigation", () => {
|
||||
it("switches between the diff and the editor tab, and closes the diff tab", async () => {
|
||||
const area = await mountArea();
|
||||
await runCommand("vcs.showDiff", { path: "a.php" });
|
||||
await area.find("[data-test=editor-tab]").trigger("click");
|
||||
expect(area.find("[data-test=diff-view]").exists()).toBe(false);
|
||||
expect(area.find("[data-test=code-editor]").exists()).toBe(true);
|
||||
await area.find("[data-test=diff-tab]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(area.find("[data-test=diff-view]").exists()).toBe(true);
|
||||
await area.find("[data-test=diff-tab-close]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(area.findAll("[data-test=diff-tab]")).toHaveLength(0);
|
||||
expect(area.find("[data-test=code-editor]").exists()).toBe(true);
|
||||
expect(area.findAll("[data-test=editor-tab]")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("moves to the next and previous change, wrapping around", async () => {
|
||||
blobs["index:a.php"] = { text: "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n", binary: false, tooLarge: false };
|
||||
disk["a.php"] = "1\nX\n3\n4\n5\n6\n7\n8\n9\n10\nY\n12\n";
|
||||
await mountArea();
|
||||
await runCommand("vcs.showDiff", { path: "a.php" });
|
||||
const { b } = sides();
|
||||
expect(currentMerge()?.chunks).toHaveLength(2);
|
||||
const lineOfCursor = (): number => b.state.doc.lineAt(b.state.selection.main.head).number;
|
||||
expect(useCommandsStore(pinia).isEnabled("vcs.nextChange")).toBe(true);
|
||||
await runCommand("vcs.nextChange");
|
||||
expect(lineOfCursor()).toBe(2);
|
||||
await runCommand("vcs.nextChange");
|
||||
expect(lineOfCursor()).toBe(11);
|
||||
await runCommand("vcs.nextChange");
|
||||
expect(lineOfCursor()).toBe(2);
|
||||
await runCommand("vcs.previousChange");
|
||||
expect(lineOfCursor()).toBe(11);
|
||||
});
|
||||
|
||||
it("disables next/previous change without a visible diff", async () => {
|
||||
await mountArea();
|
||||
expect(useCommandsStore(pinia).isEnabled("vcs.nextChange")).toBe(false);
|
||||
expect(useCommandsStore(pinia).isEnabled("vcs.previousChange")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("project tree context menu", () => {
|
||||
it("opens on a right click and runs Show Diff for the file", async () => {
|
||||
const area = await mountArea();
|
||||
const tree = mount(ProjectToolWindow, { attachTo: document.body, global: { plugins: [pinia] } });
|
||||
mounted.push(tree);
|
||||
emitEngineEvent({ kind: "projectOpened", root: "/p", name: "p" });
|
||||
await flushPromises();
|
||||
useProjectStore(pinia).root = { path: "/p", name: "p" };
|
||||
await tree.find("[data-path='a.php']").trigger("contextmenu", { clientX: 40, clientY: 50 });
|
||||
const menu = document.querySelector("[data-test=tree-menu]");
|
||||
expect(menu).not.toBeNull();
|
||||
expect([...document.querySelectorAll("[data-test=tree-menu-item]")].map((item) => item.textContent.trim())).toEqual(["Open", "Show Diff"]);
|
||||
(document.querySelector("[data-item=showDiff]") as HTMLElement).click();
|
||||
await flushPromises();
|
||||
await flushPromises();
|
||||
expect(document.querySelector("[data-test=tree-menu]")).toBeNull();
|
||||
expect(callsOf("git.show")[0]?.params).toEqual({ path: "a.php", ref: "index" });
|
||||
expect(area.findAll("[data-test=diff-tab]").map((t) => t.text())).toEqual(["Diff: a.php"]);
|
||||
});
|
||||
|
||||
it("opens from the keyboard with Shift+F10 and closes with Escape", async () => {
|
||||
await mountArea();
|
||||
const tree = mount(ProjectToolWindow, { attachTo: document.body, global: { plugins: [pinia] } });
|
||||
mounted.push(tree);
|
||||
emitEngineEvent({ kind: "projectOpened", root: "/p", name: "p" });
|
||||
await flushPromises();
|
||||
useProjectStore(pinia).select("a.php");
|
||||
await tree.find("[data-test=project-tree]").trigger("keydown", { key: "F10", shiftKey: true });
|
||||
await flushPromises();
|
||||
const menu = document.querySelector<HTMLElement>("[data-test=tree-menu]");
|
||||
expect(menu).not.toBeNull();
|
||||
expect(document.activeElement).toBe(menu);
|
||||
menu?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
|
||||
await flushPromises();
|
||||
expect(document.querySelector("[data-test=tree-menu]")).toBeNull();
|
||||
expect(callsOf("git.show")).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue