PM: merge C3 chunk staging, unstaging and revert
Some checks are pending
ci / ci (macos-15) (push) Waiting to run
ci / ci (ubuntu-24.04) (push) Waiting to run
ci / ci (windows-2025) (push) Waiting to run

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-11-01 12:50:59 +01:00
commit 30de747ad6
28 changed files with 3159 additions and 101 deletions

View file

@ -55,6 +55,7 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [
{ id: "vcs.showStashes", labelKey: "command.vcs.showStashes", menuPath: "Git/Stashes…" },
{ id: "vcs.showCommit", labelKey: "command.vcs.showCommit" },
{ id: "vcs.toggleBlame", labelKey: "command.vcs.toggleBlame", menuPath: "Git/Annotate with Git Blame" },
{ id: "vcs.showChunk", labelKey: "command.vcs.showChunk", menuPath: "Git/Show Changed Chunk" },
{ 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+[" },

View file

@ -0,0 +1,692 @@
/**
* The chunk popup (C8 C3): a click on a Git change marker in the gutter
* (or `vcs.showChunk` at the caret) shows that chunk's diff with the
* actions Stage, Unstage, Revert, Previous and Next.
*
* - **Source:** `git.chunks {id}` (a pending outcome, so through
* `runWaiting`) after the buffer sync is idle. It lists the unstaged
* chunks (index → buffer) and the staged ones (HEAD → index, placed on
* the buffer lines they map to) with a token of the texts compared.
* - **Sections:** the popup shows the unstaged chunk at the line (Stage,
* Revert) and the staged chunk at the line (Unstage), whichever exist.
* - **Actions** pass the chunk's position and the token back
* (`git.stageChunk`, `git.unstageChunk`, `git.revertChunk`); the engine
* refuses when the buffer, index or HEAD changed since, and the popup
* shows the refusal. After Stage or Unstage the popup re-reads the chunks
* and stays on the line, so a stage can be undone at once. Revert edits
* the buffer; the edit enters the editor's undo history
* ({@link ChunkTransport.undoable}) and the popup closes.
* - **Previous / Next** move the caret to the start of the previous or
* next chunk (unstaged and staged, in line order, wrapping) and show it.
* - **Closing:** Escape, the close button, an edit of the document, or a
* click elsewhere in the editor.
* - **Untrusted input:** results are checked field by field.
*
* Colours come from `--lt-*` tokens only.
*/
import { EditorSelection, Prec, StateEffect, StateField, type Extension } from "@codemirror/state";
import { EditorView, ViewPlugin, keymap, showTooltip, type Tooltip } from "@codemirror/view";
import { t } from "../../i18n";
import { runWaiting, type JsonValue } from "../../ipc";
import { useEditorStore } from "../../stores/editor";
import type { AssistBuffer } from "./assist";
/** UI command that opens the popup at the caret line. */
export const SHOW_CHUNK_COMMAND = "vcs.showChunk";
/** What a chunk changed. */
export type ChunkKind = "added" | "modified" | "deleted";
/** One chunk of `git.chunks`, checked. */
export interface ChunkInfo {
/** Its position in its list (what the actions take). */
index: number;
/** What it changed. */
kind: ChunkKind;
/** First buffer line (0-based). */
startLine: number;
/** Line after the last; equal to `startLine` for a deletion point. */
endLine: number;
/** Removed lines. */
removed: string[];
/** Added lines. */
added: string[];
/** Whether the lines were cut. */
truncated: boolean;
}
/** A `git.chunks` result, checked. */
export interface ChunkList {
/** The token of the texts compared. */
token: string;
/** Index → buffer. */
unstaged: ChunkInfo[];
/** HEAD → index. */
staged: ChunkInfo[];
}
/** The chunks at one line. */
export interface ChunksAt {
/** The unstaged chunk, if any. */
unstaged: ChunkInfo | null;
/** The staged chunk, if any. */
staged: ChunkInfo | null;
}
/** A command's outcome as the popup sees it. */
export type ChunkResult = { ok: true; value: unknown } | { ok: false; error?: { message: string } };
/** How the popup reaches the engine; replaced in tests. */
export interface ChunkTransport {
/** Runs a command and resolves with its untrusted result. */
query(command: string, params: JsonValue): Promise<ChunkResult>;
/**
* Makes the engine's next edits of a buffer undoable in its editor;
* null when the buffer has no sync.
*
* @param id - the buffer.
*/
undoable?(id: number): { end(version: number | null): void } | null;
}
/** The transport through the engine IPC and the editor store's syncs. */
export const engineChunkTransport: ChunkTransport = {
query: (command, params) => runWaiting<unknown>(command, params),
undoable: (id) => {
const sync = useEditorStore().syncOf(id);
if (!sync) {
return null;
}
sync.beginUndoableRemote();
return {
end: (version) => {
sync.endUndoableRemote(version);
},
};
},
};
/** Whether a value is a non-negative integer. */
function isLine(value: unknown): value is number {
return typeof value === "number" && Number.isInteger(value) && value >= 0;
}
/** Most lines of each side shown in the popup. */
export const POPUP_LINES = 200;
/**
* Reads one list of `git.chunks`; malformed chunks are skipped but keep
* their positions.
*
* @param raw - untrusted.
*/
function readList(raw: unknown): ChunkInfo[] {
if (!Array.isArray(raw)) {
return [];
}
const out: ChunkInfo[] = [];
(raw as unknown[]).forEach((item, index) => {
if (typeof item !== "object" || item === null) {
return;
}
const c = item as Record<string, unknown>;
const kind = c.kind;
if ((kind !== "added" && kind !== "modified" && kind !== "deleted") || !isLine(c.startLine) || !isLine(c.endLine) || c.endLine < c.startLine) {
return;
}
const lines = (value: unknown): string[] =>
Array.isArray(value) ? (value as unknown[]).filter((l): l is string => typeof l === "string").slice(0, POPUP_LINES) : [];
out.push({
index,
kind,
startLine: c.startLine,
endLine: c.endLine,
removed: lines(c.removed),
added: lines(c.added),
truncated: c.truncated === true,
});
});
return out;
}
/**
* Reads a `git.chunks` result.
*
* @param value - untrusted.
* @returns the lists, or null without a token.
*/
export function readChunks(value: unknown): ChunkList | null {
if (typeof value !== "object" || value === null) {
return null;
}
const v = value as Record<string, unknown>;
if (typeof v.token !== "string") {
return null;
}
return { token: v.token, unstaged: readList(v.unstaged), staged: readList(v.staged) };
}
/**
* Whether a chunk covers a line: a line of its range, or for a deletion
* point the line after it (the last line when it is at the end), where
* the gutter draws its marker.
*
* @param chunk - the chunk.
* @param line - 0-based line.
* @param lineCount - the document's line count.
*/
export function covers(chunk: ChunkInfo, line: number, lineCount: number): boolean {
if (chunk.startLine === chunk.endLine) {
const marked = chunk.startLine >= lineCount ? lineCount - 1 : chunk.startLine;
return line === marked;
}
return line >= chunk.startLine && line < chunk.endLine;
}
/**
* The chunks at a line.
*
* @param list - the chunks.
* @param line - 0-based line.
* @param lineCount - the document's line count.
*/
export function chunksAt(list: ChunkList, line: number, lineCount: number): ChunksAt {
return {
unstaged: list.unstaged.find((c) => covers(c, line, lineCount)) ?? null,
staged: list.staged.find((c) => covers(c, line, lineCount)) ?? null,
};
}
/**
* The line of the next or previous chunk start after or before `line`,
* wrapping around; null without chunks.
*
* @param list - the chunks.
* @param line - 0-based line.
* @param direction - 1 for the next chunk, -1 for the previous one.
* @param lineCount - the document's line count.
*/
export function neighbourLine(list: ChunkList, line: number, direction: 1 | -1, lineCount: number): number | null {
const starts = [...new Set([...list.unstaged, ...list.staged].map((c) => Math.min(c.startLine, Math.max(lineCount - 1, 0))))].sort(
(a, b) => a - b,
);
if (starts.length === 0) {
return null;
}
if (direction > 0) {
return starts.find((s) => s > line) ?? starts[0] ?? null;
}
return [...starts].reverse().find((s) => s < line) ?? starts[starts.length - 1] ?? null;
}
/** What the popup shows. */
interface Popup {
/** 0-based line it is for. */
line: number;
/** Document position it is shown at (the line's start). */
pos: number;
/** The chunks read, null while loading. */
list: ChunkList | null;
/** An error to show, null if none. */
error: string | null;
/** Whether an action runs. */
busy: boolean;
}
/** Replaces the popup; null closes it. */
const setPopup = StateEffect.define<Popup | null>();
/** How each view reaches the engine, and its buffer. */
const owners = new WeakMap<EditorView, { buffer: AssistBuffer; transport: ChunkTransport }>();
/**
* Builds a line of the diff.
*
* @param sign - `-` or `+`.
* @param text - the line.
*/
function diffLine(sign: "-" | "+", text: string): HTMLElement {
const row = document.createElement("div");
row.className = `lt-chunk-popup__line lt-chunk-popup__line--${sign === "-" ? "removed" : "added"}`;
row.dataset.test = sign === "-" ? "chunk-removed" : "chunk-added";
row.textContent = `${sign} ${text}`;
return row;
}
/**
* A button of the popup.
*
* @param label - its text.
* @param test - its `data-test` value.
* @param disabled - whether it is disabled.
* @param run - what a click does.
*/
function button(label: string, test: string, disabled: boolean, run: () => void): HTMLButtonElement {
const element = document.createElement("button");
element.type = "button";
element.className = "lt-chunk-popup__button";
element.textContent = label;
element.dataset.test = test;
element.disabled = disabled;
element.addEventListener("mousedown", (event) => {
event.preventDefault();
});
element.addEventListener("click", (event) => {
event.preventDefault();
run();
});
return element;
}
/**
* One section: the chunk's diff and its actions.
*
* @param view - the editor.
* @param popup - the popup state.
* @param chunk - the chunk.
* @param staged - whether it is a staged chunk.
*/
function section(view: EditorView, popup: Popup, chunk: ChunkInfo, staged: boolean): HTMLElement {
const box = document.createElement("div");
box.className = "lt-chunk-popup__section";
box.dataset.test = staged ? "chunk-staged" : "chunk-unstaged";
const title = document.createElement("div");
title.className = "lt-chunk-popup__title";
title.textContent = staged ? t("editor.chunk.staged") : t("editor.chunk.unstaged");
const lines = document.createElement("div");
lines.className = "lt-chunk-popup__diff";
for (const text of chunk.removed) {
lines.append(diffLine("-", text));
}
for (const text of chunk.added) {
lines.append(diffLine("+", text));
}
if (chunk.truncated) {
const more = document.createElement("div");
more.className = "lt-chunk-popup__more";
more.textContent = t("editor.chunk.truncated");
lines.append(more);
}
const actions = document.createElement("div");
actions.className = "lt-chunk-popup__actions";
if (staged) {
actions.append(
button(t("editor.chunk.unstage"), "chunk-unstage", popup.busy, () => {
void act(view, "git.unstageChunk", chunk);
}),
);
} else {
actions.append(
button(t("editor.chunk.stage"), "chunk-stage", popup.busy, () => {
void act(view, "git.stageChunk", chunk);
}),
button(t("editor.chunk.revert"), "chunk-revert", popup.busy, () => {
void act(view, "git.revertChunk", chunk);
}),
);
}
box.append(title, lines, actions);
return box;
}
/**
* The popup's DOM.
*
* @param view - the editor.
* @param popup - what it shows.
*/
function popupDom(view: EditorView, popup: Popup): HTMLElement {
const dom = document.createElement("div");
dom.className = "lt-chunk-popup";
dom.dataset.test = "chunk-popup";
dom.setAttribute("role", "dialog");
dom.setAttribute("aria-label", t("editor.chunk.title"));
const head = document.createElement("div");
head.className = "lt-chunk-popup__head";
const nav = (direction: 1 | -1): void => {
move(view, direction);
};
head.append(
button(t("editor.chunk.previous"), "chunk-previous", popup.list === null, () => {
nav(-1);
}),
button(t("editor.chunk.next"), "chunk-next", popup.list === null, () => {
nav(1);
}),
button("×", "chunk-close", false, () => {
closeChunkPopup(view);
}),
);
head.lastElementChild?.setAttribute("aria-label", t("editor.chunk.close"));
dom.append(head);
if (popup.list === null && popup.error === null) {
const loading = document.createElement("div");
loading.className = "lt-chunk-popup__status";
loading.textContent = t("editor.chunk.loading");
dom.append(loading);
}
if (popup.list !== null) {
const at = chunksAt(popup.list, popup.line, view.state.doc.lines);
if (at.unstaged) {
dom.append(section(view, popup, at.unstaged, false));
}
if (at.staged) {
dom.append(section(view, popup, at.staged, true));
}
if (!at.unstaged && !at.staged) {
const none = document.createElement("div");
none.className = "lt-chunk-popup__status";
none.dataset.test = "chunk-none";
none.textContent = t("editor.chunk.none");
dom.append(none);
}
}
if (popup.error !== null) {
const error = document.createElement("div");
error.className = "lt-chunk-popup__error";
error.dataset.test = "chunk-error";
error.setAttribute("role", "alert");
error.textContent = popup.error;
dom.append(error);
}
return dom;
}
/** The popup of a state. */
const popupState = StateField.define<Popup | null>({
create: () => null,
update(value, tr) {
let next = value;
if (next !== null && tr.docChanged) {
next = null;
}
for (const effect of tr.effects) {
if (effect.is(setPopup)) {
next = effect.value;
}
}
return next;
},
provide: (field) =>
showTooltip.from(field, (popup): Tooltip | null => {
if (popup === null) {
return null;
}
return {
pos: popup.pos,
above: false,
create: (view) => ({ dom: popupDom(view, popup) }),
};
}),
});
/**
* Replaces the popup of a view that has an owner.
*
* @param view - the editor.
* @param popup - the new state; null closes it.
*/
function setPopupAt(view: EditorView, popup: Popup | null): void {
if (!owners.has(view)) {
return;
}
view.dispatch({ effects: setPopup.of(popup) });
}
/**
* The start of a 0-based line, clamped to the document.
*
* @param view - the editor.
* @param line - 0-based line.
*/
function lineStart(view: EditorView, line: number): number {
const doc = view.state.doc;
return doc.line(Math.min(Math.max(line + 1, 1), doc.lines)).from;
}
/**
* The popup a view shows, for tests and inspection.
*
* @param view - the editor.
* @returns its 0-based line, or null when closed.
*/
export function chunkPopupLine(view: EditorView): number | null {
return view.state.field(popupState, false)?.line ?? null;
}
/**
* Closes the popup.
*
* @param view - the editor.
*/
export function closeChunkPopup(view: EditorView): void {
if ((view.state.field(popupState, false) ?? null) !== null) {
view.dispatch({ effects: setPopup.of(null) });
}
}
/**
* Reads the chunks of a view's buffer.
*
* @param view - the editor.
* @returns the chunks, or an error text.
*/
async function load(view: EditorView): Promise<ChunkList | string> {
const owner = owners.get(view);
if (!owner) {
return t("editor.chunk.failed", { reason: "" });
}
await owner.buffer.idle();
const result = await owner.transport.query("git.chunks", { id: owner.buffer.id });
if (!result.ok) {
return t("editor.chunk.failed", { reason: result.error?.message ?? "" });
}
return readChunks(result.value) ?? t("editor.chunk.failed", { reason: "" });
}
/**
* Shows the popup for a line: loading first, then the chunks there.
*
* @param view - an editor built with {@link chunkPopupExtensions}.
* @param line - 0-based line.
* @param error - an error to keep showing, if any.
*/
export async function openChunkPopup(view: EditorView, line: number, error: string | null = null): Promise<void> {
if (!owners.has(view)) {
return;
}
const doc = view.state.doc;
const pos = lineStart(view, line);
setPopupAt(view, { line, pos, list: null, error: null, busy: false });
const loaded = await load(view);
if (view.state.doc !== doc || chunkPopupLine(view) !== line) {
return;
}
setPopupAt(view, typeof loaded === "string" ? { line, pos, list: null, error: loaded, busy: false } : { line, pos, list: loaded, error, busy: false });
}
/**
* Moves the caret to the previous or next chunk and shows it.
*
* @param view - the editor.
* @param direction - 1 for the next chunk, -1 for the previous one.
*/
function move(view: EditorView, direction: 1 | -1): void {
const popup = view.state.field(popupState, false);
if (!popup?.list) {
return;
}
const target = neighbourLine(popup.list, popup.line, direction, view.state.doc.lines);
if (target === null) {
return;
}
const pos = lineStart(view, target);
view.dispatch({
selection: EditorSelection.cursor(pos),
effects: [EditorView.scrollIntoView(pos, { y: "center" }), setPopup.of({ ...popup, line: target, pos, error: null })],
});
}
/**
* Runs a chunk action and updates the popup.
*
* @param view - the editor.
* @param command - `git.stageChunk`, `git.unstageChunk` or `git.revertChunk`.
* @param chunk - the chunk.
*/
async function act(view: EditorView, command: string, chunk: ChunkInfo): Promise<void> {
const owner = owners.get(view);
const popup = view.state.field(popupState, false);
if (!owner || !popup?.list) {
return;
}
const { line } = popup;
setPopupAt(view, { ...popup, busy: true, error: null });
const revert = command === "git.revertChunk";
const undo = revert ? (owner.transport.undoable?.(owner.buffer.id) ?? null) : null;
const result = await owner.transport.query(command, { id: owner.buffer.id, index: chunk.index, token: popup.list.token });
if (undo) {
const version = result.ok && typeof result.value === "object" && result.value !== null ? (result.value as Record<string, unknown>).version : null;
undo.end(typeof version === "number" ? version : null);
}
if (!result.ok) {
if (chunkPopupLine(view) === line) {
await openChunkPopup(view, line, t("editor.chunk.failed", { reason: result.error?.message ?? "" }));
}
return;
}
if (revert) {
closeChunkPopup(view);
return;
}
if (chunkPopupLine(view) === line) {
await openChunkPopup(view, line);
}
}
/** Popup styles from the theme tokens. */
const popupTheme: Extension = EditorView.theme({
".lt-chunk-popup": {
minWidth: "320px",
maxWidth: "640px",
fontSize: "var(--lt-font-size-ui)",
color: "var(--lt-fg)",
background: "var(--lt-bg)",
},
".lt-chunk-popup__head": {
display: "flex",
justifyContent: "flex-end",
gap: "4px",
padding: "4px",
borderBottom: "1px solid var(--lt-border)",
},
".lt-chunk-popup__section + .lt-chunk-popup__section": {
borderTop: "1px solid var(--lt-border)",
},
".lt-chunk-popup__title": {
padding: "4px 8px 2px",
color: "var(--lt-fg-muted)",
},
".lt-chunk-popup__diff": {
maxHeight: "240px",
overflow: "auto",
fontFamily: "var(--lt-font-mono)",
fontSize: "var(--lt-font-size-editor)",
whiteSpace: "pre",
background: "var(--lt-editor-bg)",
},
".lt-chunk-popup__line": {
padding: "0 8px",
},
".lt-chunk-popup__line--removed": {
background: "color-mix(in srgb, var(--lt-vcs-deleted) 18%, var(--lt-editor-bg))",
},
".lt-chunk-popup__line--added": {
background: "color-mix(in srgb, var(--lt-vcs-added) 18%, var(--lt-editor-bg))",
},
".lt-chunk-popup__more, .lt-chunk-popup__status": {
padding: "4px 8px",
color: "var(--lt-fg-muted)",
},
".lt-chunk-popup__error": {
padding: "4px 8px",
color: "var(--lt-error)",
whiteSpace: "pre-wrap",
},
".lt-chunk-popup__actions": {
display: "flex",
gap: "4px",
padding: "4px 8px 6px",
},
".lt-chunk-popup__button": {
color: "var(--lt-fg)",
background: "var(--lt-bg)",
border: "1px solid var(--lt-border)",
borderRadius: "3px",
padding: "1px 8px",
cursor: "pointer",
font: "inherit",
},
".lt-chunk-popup__button:hover:not(:disabled)": {
background: "color-mix(in srgb, var(--lt-fg) 8%, var(--lt-bg))",
},
".lt-chunk-popup__button:disabled": {
color: "var(--lt-fg-muted)",
cursor: "default",
},
});
/**
* Remembers a view's buffer and transport while the view lives.
*
* @param buffer - the buffer the view shows.
* @param transport - how to reach the engine.
*/
function ownerPlugin(buffer: AssistBuffer, transport: ChunkTransport): Extension {
return ViewPlugin.define((view) => {
owners.set(view, { buffer, transport });
return {
destroy(): void {
owners.delete(view);
},
};
});
}
/**
* The chunk popup's extensions.
*
* @param buffer - the buffer the state shows.
* @param transport - how to reach the engine.
*/
export function chunkPopupExtensions(buffer: AssistBuffer, transport: ChunkTransport): Extension {
return [
popupState,
popupTheme,
ownerPlugin(buffer, transport),
EditorView.domEventHandlers({
mousedown: (event, view) => {
const target = event.target;
if (target instanceof Element && (target.closest(".lt-chunk-popup") || target.closest(".lt-git-gutter"))) {
return false;
}
closeChunkPopup(view);
return false;
},
}),
Prec.highest(
keymap.of([
{
key: "Escape",
run: (view) => {
if ((view.state.field(popupState, false) ?? null) === null) {
return false;
}
closeChunkPopup(view);
return true;
},
},
]),
),
];
}

View file

@ -18,15 +18,22 @@
* (lines removed at the end) marks the bottom of the last line.
* - Failures leave the markers as they are: markers are best effort while
* typing, and the Changes window reports git problems.
* - **Staged changes (C8 C3):** when the view shows the state and on every
* refresh (not while typing), `git.chunks {id}` is read too; lines of a
* staged chunk without an unstaged marker get a hollow `staged` marker,
* mapped through edits like the others.
* - **Click:** a click on a marker opens the chunk popup
* (`chunkPopup.ts`) for that line: the chunk's diff with Stage,
* Unstage, Revert, Previous and Next.
*
* Colours come from `--lt-vcs-added`, `--lt-vcs-modified` and
* `--lt-vcs-deleted`.
*/
import { RangeSet, RangeSetBuilder, StateEffect, StateField, type EditorState, type Extension, type Text } from "@codemirror/state";
import { EditorView, GutterMarker, ViewPlugin, gutter, type PluginValue, type ViewUpdate } from "@codemirror/view";
import { runWaiting, type JsonValue } from "../../ipc";
import { t } from "../../i18n";
import type { AssistBuffer } from "./assist";
import { chunkPopupExtensions, covers, engineChunkTransport, openChunkPopup, readChunks, type ChunkList, type ChunkTransport } from "./chunkPopup";
/** Delay between the last edit and the query. */
export const GIT_GUTTER_DEBOUNCE_MS = 150;
@ -44,16 +51,11 @@ export interface LineChange {
endLine: number;
}
/** How the gutter reaches the engine; replaced in tests. */
export interface GitGutterTransport {
/** Runs a command and resolves with its untrusted result. */
query(command: string, params: JsonValue): Promise<{ ok: true; value: unknown } | { ok: false }>;
}
/** How the gutter and its chunk popup reach the engine; replaced in tests. */
export type GitGutterTransport = ChunkTransport;
/** The transport through the engine IPC, off the shell's main thread. */
export const engineGitGutterTransport: GitGutterTransport = {
query: (command, params) => runWaiting<unknown>(command, params),
};
export const engineGitGutterTransport: GitGutterTransport = engineChunkTransport;
/** Whether a value is a non-negative integer. */
function isLine(value: unknown): value is number {
@ -88,8 +90,8 @@ export function readLineChanges(value: unknown): LineChange[] | null {
return out;
}
/** A marker class: the three kinds, plus deleted lines below the last line. */
type MarkerClass = LineChangeKind | "deleted-end";
/** A marker class: the three kinds, deleted lines below the last line, and staged lines. */
type MarkerClass = LineChangeKind | "deleted-end" | "staged";
/** The tooltip of each marker class, from the catalog. */
const TITLES: Record<MarkerClass, () => string> = {
@ -97,6 +99,7 @@ const TITLES: Record<MarkerClass, () => string> = {
modified: () => t("editor.gitGutter.modified"),
deleted: () => t("editor.gitGutter.deleted"),
"deleted-end": () => t("editor.gitGutter.deleted"),
staged: () => t("editor.gitGutter.staged"),
};
/** One gutter marker; equal markers share their DOM. */
@ -134,6 +137,7 @@ const MARKERS: Record<MarkerClass, GitMarker> = {
modified: new GitMarker("modified"),
deleted: new GitMarker("deleted"),
"deleted-end": new GitMarker("deleted-end"),
staged: new GitMarker("staged"),
};
/**
@ -170,9 +174,53 @@ export function buildMarkers(doc: Text, ranges: readonly LineChange[]): RangeSet
return builder.finish();
}
/**
* Builds the staged markers: every line of a staged chunk (the line after a
* deletion point) that no unstaged chunk covers.
*
* @param doc - the document the chunks were computed for.
* @param list - the chunks.
*/
export function buildStagedMarkers(doc: Text, list: ChunkList): RangeSet<GutterMarker> {
const lines = new Set<number>();
for (const chunk of list.staged) {
const point = chunk.startLine === chunk.endLine;
const first = point ? Math.min(chunk.startLine, doc.lines - 1) : chunk.startLine;
const last = point ? first + 1 : Math.min(chunk.endLine, doc.lines);
for (let line = Math.max(first, 0); line < last; line += 1) {
if (!list.unstaged.some((c) => covers(c, line, doc.lines))) {
lines.add(line);
}
}
}
const builder = new RangeSetBuilder<GutterMarker>();
for (const line of [...lines].sort((a, b) => a - b)) {
const from = doc.line(line + 1).from;
builder.add(from, from, MARKERS.staged);
}
return builder.finish();
}
/** Replaces the markers of a state. */
const setGitMarkers = StateEffect.define<RangeSet<GutterMarker>>();
/** Replaces the staged markers of a state. */
const setStagedMarkers = StateEffect.define<RangeSet<GutterMarker>>();
/** The staged markers of a state, mapped through edits between answers. */
const stagedMarkers = StateField.define<RangeSet<GutterMarker>>({
create: () => RangeSet.empty,
update(value, tr) {
let next = value.map(tr.changes);
for (const effect of tr.effects) {
if (effect.is(setStagedMarkers)) {
next = effect.value;
}
}
return next;
},
});
/** The markers of a state, mapped through edits between answers. */
const gitMarkers = StateField.define<RangeSet<GutterMarker>>({
create: () => RangeSet.empty,
@ -196,22 +244,23 @@ const gitMarkers = StateField.define<RangeSet<GutterMarker>>({
*/
export function gitMarkerLines(state: EditorState): Record<number, string> {
const out: Record<number, string> = {};
const set = state.field(gitMarkers, false);
if (set === undefined) {
return out;
}
const cursor = set.iter();
while (cursor.value !== null) {
if (cursor.value instanceof GitMarker) {
out[state.doc.lineAt(cursor.from).number] = cursor.value.kind;
for (const set of [state.field(stagedMarkers, false), state.field(gitMarkers, false)]) {
if (set === undefined) {
continue;
}
const cursor = set.iter();
while (cursor.value !== null) {
if (cursor.value instanceof GitMarker) {
out[state.doc.lineAt(cursor.from).number] = cursor.value.kind;
}
cursor.next();
}
cursor.next();
}
return out;
}
/** Live plugins, refreshed by {@link refreshGitGutters}. */
const live = new Set<{ schedule(delay: number): void }>();
const live = new Set<{ schedule(delay: number, staged?: boolean): void }>();
/** Asks every editor shown now to query its markers again (`gitChanged`). */
export function refreshGitGutters(): void {
@ -231,6 +280,7 @@ function gitGutterPlugin(buffer: AssistBuffer, transport: GitGutterTransport): E
const life = { alive: true };
let timer: ReturnType<typeof setTimeout> | null = null;
let asked = 0;
let withStaged = true;
/**
* Whether the plugin still lives and the view still shows `doc`.
@ -244,27 +294,43 @@ function gitGutterPlugin(buffer: AssistBuffer, transport: GitGutterTransport): E
/** Queries the markers for the current document and applies them. */
async function run(): Promise<void> {
const doc = view.state.doc;
const staged = withStaged;
withStaged = false;
await buffer.idle();
if (!current(doc)) {
withStaged ||= staged;
return;
}
asked += 1;
const mine = asked;
const result = await transport.query("git.lineChanges", { id: buffer.id });
if (!current(doc) || mine !== asked || !result.ok) {
const [result, chunks] = await Promise.all([
transport.query("git.lineChanges", { id: buffer.id }),
staged ? transport.query("git.chunks", { id: buffer.id }) : Promise.resolve(null),
]);
if (!current(doc) || mine !== asked) {
withStaged ||= staged;
return;
}
const ranges = readLineChanges(result.value);
const effects: StateEffect<RangeSet<GutterMarker>>[] = [];
const ranges = result.ok ? readLineChanges(result.value) : null;
if (ranges !== null) {
view.dispatch({ effects: setGitMarkers.of(buildMarkers(doc, ranges)) });
effects.push(setGitMarkers.of(buildMarkers(doc, ranges)));
}
if (chunks !== null) {
const list = chunks.ok ? readChunks(chunks.value) : null;
effects.push(setStagedMarkers.of(list === null ? RangeSet.of<GutterMarker>([]) : buildStagedMarkers(doc, list)));
}
if (effects.length > 0) {
view.dispatch({ effects });
}
}
const handle = {
schedule(delay: number): void {
schedule(delay: number, staged = true): void {
if (!life.alive) {
return;
}
withStaged ||= staged;
if (timer !== null) {
clearTimeout(timer);
}
@ -279,7 +345,7 @@ function gitGutterPlugin(buffer: AssistBuffer, transport: GitGutterTransport): E
return {
update(update: ViewUpdate): void {
if (update.docChanged) {
handle.schedule(GIT_GUTTER_DEBOUNCE_MS);
handle.schedule(GIT_GUTTER_DEBOUNCE_MS, false);
}
},
destroy(): void {
@ -315,6 +381,13 @@ const gitGutterTheme: Extension = EditorView.theme({
".lt-git-marker--deleted-end": {
background: "linear-gradient(to top, var(--lt-vcs-deleted) 0 3px, transparent 3px)",
},
".lt-git-marker--staged": {
boxSizing: "border-box",
border: "1px solid var(--lt-vcs-modified)",
},
".lt-git-gutter .cm-gutterElement:has(.lt-git-marker)": {
cursor: "pointer",
},
});
/**
@ -333,12 +406,24 @@ export function gitGutterExtensions(
}
return [
gitMarkers,
stagedMarkers,
gutter({
class: "lt-git-gutter",
markers: (view) => view.state.field(gitMarkers),
markers: (view) => [view.state.field(stagedMarkers), view.state.field(gitMarkers)],
initialSpacer: () => MARKERS.added,
domEventHandlers: {
click: (view, block) => {
const line = view.state.doc.lineAt(block.from).number;
if (gitMarkerLines(view.state)[line] === undefined) {
return false;
}
void openChunkPopup(view, line - 1);
return true;
},
},
}),
gitGutterTheme,
gitGutterPlugin(buffer, transport),
chunkPopupExtensions(buffer, transport),
];
}

View file

@ -36,7 +36,8 @@
* `vcs.showCommit {hash}` (M4.7) shows the Log with that commit selected
* (a click on a blame annotation); `vcs.toggleBlame {path?}` shows or
* hides the blame annotations of a file (default: the active tab's, once
* tabs for buffers just opened are adopted). No
* tabs for buffers just opened are adopted). `vcs.showChunk` (C8 C3)
* opens the chunk popup at the caret line of the editor shown last. No
* default shortcuts.
*
* A slim header bar along the top (M3.9) holds the app menu
@ -60,6 +61,8 @@ import LogToolWindow from "../vcs/log/LogToolWindow.vue";
import { SHOW_HISTORY_COMMAND, SHOW_LOG_COMMAND, useLogStore } from "../vcs/log/log";
import StashDialog from "../vcs/stash/StashDialog.vue";
import { SHOW_COMMIT_COMMAND, TOGGLE_BLAME_COMMAND, setCommitOpener, toggleBlame } from "../editor/blame";
import { SHOW_CHUNK_COMMAND, openChunkPopup } from "../editor/chunkPopup";
import { activeView } from "../editor/nav/navExtension";
import { useEditorStore } from "../../stores/editor";
import { useProjectStore } from "../../stores/project";
import ProjectToolWindow from "../project/ProjectToolWindow.vue";
@ -261,6 +264,15 @@ onMounted(() => {
},
enabled: () => project.root !== null,
}),
commands.provide(SHOW_CHUNK_COMMAND, {
run: async () => {
const view = activeView();
if (view) {
await openChunkPopup(view, view.state.doc.lineAt(view.state.selection.main.head).number - 1);
}
},
enabled: () => project.root !== null && activeView() !== null,
}),
commands.provide("view.toggleStructure", {
run: () => {
toggleLeft("structure");

View file

@ -446,6 +446,12 @@ watch(
:class="`changes__name--${stateColor(row.state)}`"
>{{ baseName(row.file.path) }}</span>
<span class="changes__dir">{{ detail(row) }}</span>
<span
v-if="row.partial"
class="changes__partial"
:title="t('vcs.changes.partlyStaged')"
data-test="changes-row-partial"
>{{ t("vcs.changes.partly") }}</span>
<span class="changes__state">{{ stateLabel(row.state) }}</span>
</div>
</div>
@ -637,6 +643,20 @@ watch(
color: var(--lt-fg-muted);
}
.changes__partial {
flex: none;
margin-left: auto;
padding: 0 4px;
color: var(--lt-fg-muted);
border: 1px solid var(--lt-border);
border-radius: 3px;
font-size: var(--lt-font-size-small);
}
.changes__partial + .changes__state {
margin-left: 6px;
}
.changes__row--selected .changes__dir,
.changes__row--selected .changes__state {
color: var(--lt-fg);

View file

@ -10,7 +10,8 @@
* - **Groups:** a file is Staged when its index side changed, in Changes
* when its work tree side changed or it is conflicted, and Untracked when
* git does not track it. A partly staged file is in both Staged and
* Changes. Ignored files are not listed by the backend.
* Changes, and both rows say so (`partial`, C8 C3: chunks staged from
* the gutter or the diff). Ignored files are not listed by the backend.
* - **Ignoring (C7 A3):** `git.ignore {paths}` for untracked rows adds a
* literal pattern per file to the root `.gitignore`, then re-reads.
* - **Staging:** `git.stage` / `git.unstage` per file or per group.
@ -69,6 +70,8 @@ export interface ChangeRow {
file: ChangedFile;
/** The state shown: the index side in Staged, the work tree side otherwise. */
state: FileState;
/** Whether the file is partly staged, so it has a row in Staged and in Changes too. */
partial: boolean;
}
/** What the window shows above the groups. */
@ -92,7 +95,8 @@ function changed(state: FileState): boolean {
export function groupFiles(files: ChangedFile[]): Record<GroupId, ChangeRow[]> {
const out: Record<GroupId, ChangeRow[]> = { staged: [], changes: [], untracked: [] };
const add = (group: GroupId, file: ChangedFile, state: FileState): void => {
out[group].push({ key: `${group}:${file.path}`, group, file, state });
const partial = state !== "untracked" && state !== "conflicted" && changed(file.index) && changed(file.worktree);
out[group].push({ key: `${group}:${file.path}`, group, file, state, partial });
};
for (const file of files) {
if (file.index === "untracked" || file.worktree === "untracked") {

View file

@ -18,6 +18,10 @@
* (`gitChanged` after staging).
* - **Colours:** only `--lt-*` tokens; changed lines are tinted with
* `--lt-vcs-deleted` (left) and `--lt-vcs-added` (right).
* - **Chunk actions (C8 C3):** the right side is an ordinary editor of the
* buffer, so its Git gutter shows unstaged and staged markers; a click
* opens the chunk popup with Stage, Unstage and Revert. A hint line says
* so.
* - **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.
@ -270,6 +274,13 @@ onBeforeUnmount(() => {
>
{{ caption }}
</div>
<div
v-if="diff.activeTab && !diff.activeTab.commit && diff.activeContent?.phase === 'ready' && diff.activeContent.bufferId !== null"
class="diff-view__hint"
data-test="diff-chunk-hint"
>
{{ t("vcs.diff.chunkHint") }}
</div>
<div
v-if="notice"
class="diff-view__notice"
@ -314,6 +325,15 @@ onBeforeUnmount(() => {
text-overflow: ellipsis;
}
.diff-view__hint {
flex-shrink: 0;
padding: 2px 12px;
color: var(--lt-fg-muted);
background: var(--lt-bg);
border-bottom: 1px solid var(--lt-border);
font-size: var(--lt-font-size-small);
}
.diff-view__notice {
flex-shrink: 0;
padding: 4px 12px;

View file

@ -35,6 +35,7 @@
"command.vcs.push": "Push",
"command.vcs.refresh": "Refresh Changes",
"command.vcs.resolveConflicts": "Resolve Conflicts…",
"command.vcs.showChunk": "Show Changed Chunk at Caret",
"command.vcs.showCommit": "Show Commit in Log",
"command.vcs.showDiff": "Show Diff",
"command.vcs.showHistory": "Show History",
@ -87,10 +88,24 @@
"editor.blame.clickHint": "Click to show this commit in the Log",
"editor.blame.notCommitted": "Not committed yet",
"editor.blame.notCommittedHint": "This line has changes that are not committed.",
"editor.chunk.close": "Close",
"editor.chunk.failed": "That did not work: {reason}",
"editor.chunk.loading": "Reading the change…",
"editor.chunk.next": "Next",
"editor.chunk.none": "No change on this line any more.",
"editor.chunk.previous": "Previous",
"editor.chunk.revert": "Revert",
"editor.chunk.stage": "Stage",
"editor.chunk.staged": "Staged",
"editor.chunk.title": "Changed chunk",
"editor.chunk.truncated": "More lines are not shown.",
"editor.chunk.unstage": "Unstage",
"editor.chunk.unstaged": "Not staged",
"editor.closePrompt.question": "Save changes to {name} before closing?",
"editor.gitGutter.added": "Added since the staged version",
"editor.gitGutter.deleted": "Lines deleted here since the staged version",
"editor.gitGutter.modified": "Changed since the staged version",
"editor.gitGutter.staged": "Staged change (click for the chunk)",
"editor.notice.changedOnDisk": "{name} changed on disk. Your unsaved changes are kept; saving overwrites the file.",
"editor.notice.removedOnDisk": "{name} was deleted on disk. Your text is kept; saving writes it again.",
"editor.reveal.invalidParams": "editor.reveal needs a path (string), line and column (numbers)",
@ -362,6 +377,8 @@
"vcs.changes.noCommits": "no commits yet",
"vcs.changes.noProject": "Open a project to see its changes",
"vcs.changes.noRepo": "This project is not in a Git repository",
"vcs.changes.partly": "partly staged",
"vcs.changes.partlyStaged": "Partly staged: some changes of this file are staged, others are not",
"vcs.changes.renamedFrom": "from {path}",
"vcs.changes.repoError": "The Git repository cannot be read: {reason}",
"vcs.changes.stageFile": "Stage {path}",
@ -393,6 +410,7 @@
"vcs.diff.captionCommit": "{path}: before (left) and after (right) commit {hash}",
"vcs.diff.captionHead": "{path}: last commit (left) and working copy (right)",
"vcs.diff.captionIndex": "{path}: staged version (left) and working copy (right)",
"vcs.diff.chunkHint": "Click a change marker in the gutter to stage, unstage or revert that chunk.",
"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}",

View file

@ -0,0 +1,297 @@
/**
* Tests of chunk staging in the editor (C8 C3, `chunkPopup.ts` and the
* staged markers of `gitGutter.ts`): reading `git.chunks`, which chunk a
* line belongs to, previous/next, staged markers (read on show and refresh,
* not while typing), and the popup: opening from a marker click, its
* sections, Stage and Unstage with the token, Revert as an undoable edit,
* refusals shown in place, Next, Escape and closing on an edit.
*/
import { EditorState, Text } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
chunkPopupLine,
chunksAt,
closeChunkPopup,
covers,
neighbourLine,
openChunkPopup,
readChunks,
type ChunkList,
type ChunkResult,
type ChunkTransport,
} from "../../src/components/editor/chunkPopup";
import { buildStagedMarkers, gitGutterExtensions, gitMarkerLines, refreshGitGutters } from "../../src/components/editor/gitGutter";
import type { JsonValue } from "../../src/ipc";
/** Views created by a test, destroyed after it. */
let views: EditorView[] = [];
/** A raw chunk of `git.chunks`. */
function raw(kind: string, startLine: number, endLine: number, removed: string[] = [], added: string[] = []): Record<string, unknown> {
return { kind, startLine, endLine, oldStart: 0, oldEnd: 0, newStart: 0, newEnd: 0, removed, added, truncated: false };
}
/** A fake engine for the gutter and the popup. */
class FakeEngine implements ChunkTransport {
/** Every command with its params, in order. */
readonly calls: { command: string; params: JsonValue }[] = [];
/** What `git.chunks` answers. */
chunks: unknown = { token: "t1", unstaged: [], staged: [] };
/** Commands that fail, with their message. */
failing = new Map<string, string>();
/** What `git.lineChanges` answers. */
ranges: unknown[] = [];
/** Undo windows opened and how they ended. */
readonly undo: (number | null)[] = [];
query(command: string, params: JsonValue): Promise<ChunkResult> {
this.calls.push({ command, params });
const message = this.failing.get(command);
if (message !== undefined) {
return Promise.resolve({ ok: false, error: { message } });
}
if (command === "git.lineChanges") {
return Promise.resolve({ ok: true, value: { ranges: this.ranges, version: 1 } });
}
if (command === "git.chunks") {
return Promise.resolve({ ok: true, value: this.chunks });
}
if (command === "git.revertChunk") {
return Promise.resolve({ ok: true, value: { id: 7, version: 9, dirty: true } });
}
return Promise.resolve({ ok: true, value: {} });
}
undoable(): { end(version: number | null): void } {
return {
end: (version) => {
this.undo.push(version);
},
};
}
/** The commands run, without the gutter's queries. */
actions(): string[] {
return this.calls.map((c) => c.command).filter((c) => c !== "git.lineChanges");
}
}
/**
* A view of buffer 7 showing `doc`.
*
* @param doc - the text.
* @param engine - the fake engine.
*/
function viewOf(doc: string, engine: FakeEngine): EditorView {
const view = new EditorView({
state: EditorState.create({ doc, extensions: gitGutterExtensions({ id: 7, idle: () => Promise.resolve() }, engine) }),
parent: document.body,
});
views.push(view);
return view;
}
/** Lets timers and promises run. */
async function flush(ms = 0): Promise<void> {
await vi.advanceTimersByTimeAsync(ms);
for (let i = 0; i < 8; i += 1) {
await Promise.resolve();
}
}
/** The popup element, if shown. */
function popup(view: EditorView): HTMLElement | null {
return view.dom.querySelector<HTMLElement>("[data-test=chunk-popup]");
}
/**
* Clicks a popup button.
*
* @param view - the editor.
* @param test - the button's `data-test`.
*/
function click(view: EditorView, test: string): void {
const element = view.dom.querySelector<HTMLButtonElement>(`[data-test=${test}]`);
expect(element, test).not.toBeNull();
element?.click();
}
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
for (const view of views) {
view.destroy();
}
views = [];
vi.useRealTimers();
});
describe("reading and finding chunks", () => {
it("checks every field and keeps positions", () => {
const list = readChunks({
token: "abc",
unstaged: [raw("moved", 0, 1), raw("added", 2, 4, [], ["x", 3 as unknown as string]), null],
staged: [raw("deleted", 5, 5, ["gone"])],
});
expect(list?.token).toBe("abc");
expect(list?.unstaged).toEqual([{ index: 1, kind: "added", startLine: 2, endLine: 4, removed: [], added: ["x"], truncated: false }]);
expect(list?.staged[0]?.index).toBe(0);
expect(readChunks({ unstaged: [] })).toBeNull();
expect(readChunks(null)).toBeNull();
});
it("matches lines, deletion points and the end", () => {
const list = readChunks({ token: "t", unstaged: [raw("modified", 1, 3), raw("deleted", 5, 5), raw("deleted", 8, 8)], staged: [] }) as ChunkList;
const [first, point, end] = list.unstaged;
expect(first && covers(first, 1, 8)).toBe(true);
expect(first && covers(first, 3, 8)).toBe(false);
expect(point && covers(point, 5, 8)).toBe(true);
expect(point && covers(point, 4, 8)).toBe(false);
expect(end && covers(end, 7, 8)).toBe(true);
expect(chunksAt(list, 2, 8).unstaged).toBe(first);
expect(chunksAt(list, 0, 8)).toEqual({ unstaged: null, staged: null });
});
it("finds the previous and next chunk, wrapping", () => {
const list = readChunks({ token: "t", unstaged: [raw("added", 2, 3), raw("modified", 6, 7)], staged: [raw("modified", 4, 5)] }) as ChunkList;
expect(neighbourLine(list, 2, 1, 10)).toBe(4);
expect(neighbourLine(list, 6, 1, 10)).toBe(2);
expect(neighbourLine(list, 2, -1, 10)).toBe(6);
expect(neighbourLine({ token: "t", unstaged: [], staged: [] }, 0, 1, 10)).toBeNull();
});
});
describe("staged markers", () => {
it("marks staged lines no unstaged chunk covers", () => {
const doc = Text.of(["a", "b", "c", "d"]);
const list = readChunks({ token: "t", unstaged: [raw("modified", 1, 2)], staged: [raw("modified", 0, 3), raw("deleted", 4, 4)] }) as ChunkList;
const set = buildStagedMarkers(doc, list);
const lines: number[] = [];
const cursor = set.iter();
while (cursor.value !== null) {
lines.push(doc.lineAt(cursor.from).number);
cursor.next();
}
expect(lines).toEqual([1, 3, 4]);
});
it("are read when shown and on refresh, not while typing", async () => {
const engine = new FakeEngine();
engine.chunks = { token: "t", unstaged: [], staged: [raw("modified", 1, 2)] };
const view = viewOf("a\nb\nc\n", engine);
await flush();
expect(gitMarkerLines(view.state)).toEqual({ 2: "staged" });
const asked = () => engine.calls.filter((c) => c.command === "git.chunks").length;
expect(asked()).toBe(1);
view.dispatch({ changes: { from: 0, insert: "x\n" } });
await flush(500);
expect(asked()).toBe(1);
expect(gitMarkerLines(view.state)).toEqual({ 3: "staged" });
refreshGitGutters();
await flush();
expect(asked()).toBe(2);
});
});
describe("the chunk popup", () => {
it("opens from a marker click and shows both sections", async () => {
const engine = new FakeEngine();
engine.chunks = {
token: "t1",
unstaged: [raw("modified", 0, 1, ["b"], ["B"])],
staged: [raw("modified", 0, 1, ["old"], ["b"])],
};
engine.ranges = [{ kind: "modified", startLine: 0, endLine: 1 }];
const view = viewOf("B\nc\n", engine);
await flush();
const marker = view.dom.querySelector<HTMLElement>(".lt-git-gutter .lt-git-marker");
expect(marker).not.toBeNull();
marker?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await flush();
expect(chunkPopupLine(view)).toBe(0);
const dom = popup(view);
expect(dom?.querySelector("[data-test=chunk-unstaged]")?.textContent).toContain("- b");
expect(dom?.querySelector("[data-test=chunk-unstaged]")?.textContent).toContain("+ B");
expect(dom?.querySelector("[data-test=chunk-staged]")?.textContent).toContain("- old");
});
it("stages with the token, re-reads and stays open", async () => {
const engine = new FakeEngine();
engine.chunks = { token: "t1", unstaged: [raw("added", 0, 1), raw("modified", 2, 3, ["c"], ["C"])], staged: [] };
const view = viewOf("x\nb\nC\n", engine);
await flush();
await openChunkPopup(view, 2);
await flush();
engine.chunks = { token: "t2", unstaged: [raw("added", 0, 1)], staged: [raw("modified", 2, 3, ["c"], ["C"])] };
click(view, "chunk-stage");
await flush();
expect(engine.calls.find((c) => c.command === "git.stageChunk")?.params).toEqual({ id: 7, index: 1, token: "t1" });
expect(chunkPopupLine(view)).toBe(2);
expect(popup(view)?.querySelector("[data-test=chunk-staged]")).not.toBeNull();
click(view, "chunk-unstage");
await flush();
expect(engine.calls.find((c) => c.command === "git.unstageChunk")?.params).toEqual({ id: 7, index: 0, token: "t2" });
});
it("reverts inside an undo window and closes", async () => {
const engine = new FakeEngine();
engine.chunks = { token: "t1", unstaged: [raw("modified", 0, 1, ["a"], ["A"])], staged: [] };
const view = viewOf("A\n", engine);
await flush();
await openChunkPopup(view, 0);
await flush();
click(view, "chunk-revert");
await flush();
expect(engine.calls.find((c) => c.command === "git.revertChunk")?.params).toEqual({ id: 7, index: 0, token: "t1" });
expect(engine.undo).toEqual([9]);
expect(chunkPopupLine(view)).toBeNull();
});
it("shows a refusal in place", async () => {
const engine = new FakeEngine();
engine.chunks = { token: "t1", unstaged: [raw("modified", 0, 1, ["a"], ["A"])], staged: [] };
engine.failing.set("git.stageChunk", "the file or the index changed since the chunk was shown; look at it again");
const view = viewOf("A\n", engine);
await flush();
await openChunkPopup(view, 0);
await flush();
click(view, "chunk-stage");
await flush();
expect(popup(view)?.querySelector("[data-test=chunk-error]")?.textContent).toContain("changed since");
expect(popup(view)?.querySelector("[data-test=chunk-unstaged]")).not.toBeNull();
});
it("shows why chunks cannot be read", async () => {
const engine = new FakeEngine();
engine.failing.set("git.chunks", "x.bin: the staged version is binary; stage the whole file");
const view = viewOf("a\n", engine);
await flush();
await openChunkPopup(view, 0);
await flush();
expect(popup(view)?.querySelector("[data-test=chunk-error]")?.textContent).toContain("binary");
});
it("moves to the next chunk, closes on Escape and on an edit", async () => {
const engine = new FakeEngine();
engine.chunks = { token: "t1", unstaged: [raw("added", 0, 1), raw("modified", 3, 4)], staged: [] };
const view = viewOf("a\nb\nc\nd\ne\n", engine);
await flush();
await openChunkPopup(view, 0);
await flush();
click(view, "chunk-next");
await flush();
expect(chunkPopupLine(view)).toBe(3);
expect(view.state.doc.lineAt(view.state.selection.main.head).number).toBe(4);
view.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
expect(chunkPopupLine(view)).toBeNull();
await openChunkPopup(view, 0);
await flush();
view.dispatch({ changes: { from: 0, insert: "z" } });
expect(chunkPopupLine(view)).toBeNull();
closeChunkPopup(view);
expect(engine.actions().every((c) => c === "git.chunks")).toBe(true);
});
});

View file

@ -38,7 +38,16 @@ class FakeEngine implements GitGutterTransport {
/** Whether to hold answers until released. */
hold = false;
/** The params of every `git.chunks` query, in order. */
readonly chunkCalls: JsonValue[] = [];
/** What `git.chunks` answers; null fails it. */
chunks: unknown = null;
query(command: string, params: JsonValue): Promise<{ ok: true; value: unknown } | { ok: false }> {
if (command === "git.chunks") {
this.chunkCalls.push(params);
return Promise.resolve(this.chunks === null ? { ok: false } : { ok: true, value: this.chunks });
}
expect(command).toBe("git.lineChanges");
this.calls.push(params);
const answer = this.answer;

View file

@ -209,6 +209,8 @@ describe("reading git.status", () => {
expect(groups.staged.map((r) => `${r.file.path}:${r.state}`)).toEqual(["a:modified", "b:added"]);
expect(groups.changes.map((r) => `${r.file.path}:${r.state}`)).toEqual(["a:modified", "c:deleted", "d:conflicted"]);
expect(groups.untracked.map((r) => r.file.path)).toEqual(["e"]);
expect(groups.staged.map((r) => `${r.file.path}:${String(r.partial)}`)).toEqual(["a:true", "b:false"]);
expect(groups.changes.map((r) => `${r.file.path}:${String(r.partial)}`)).toEqual(["a:true", "c:false", "d:false"]);
});
it("unstages a staged rename with both paths", () => {