Files
openidea/src/features/vcs/GitMergeDiff.tsx
T
Bert Verhelstandbertyhell 03ee687353 fix(vcs): diffs pick a file's language as its editor does (#3811)
Code shown outside an editor tab (diffs, merge editor, revision browser, previews of closed files) picked its language on the frontend from the file extension, while the editor uses the backend's detection, which also checks overrides, File Types patterns and the first line. A single resolver, languageDescriptionFor, now uses the open editor's mode when the file is open and otherwise asks the backend (doc_language, replacing doc_ui_mode) to detect it from the shown text's first line, or the open buffer / file on disk, falling back to the extension only when that fails.

Closes #3799

Co-authored-by: bertyhell <1710840+bertyhell@users.noreply.github.com>
2026-11-17 02:06:23 +08:00

98 lines
3.9 KiB
TypeScript

import { useEffect, useRef, useState } from "react";
import { EditorState, Text } from "@codemirror/state";
import { Decoration, EditorView } from "@codemirror/view";
import { Chunk } from "@codemirror/merge";
import { call, commands } from "@/platform/ipc";
import type { EditorInput } from "@/workbench/contributions";
import { firstLineOf, languageFor, viewerBase } from "./cm";
import { repositoryPath } from "./repositoryPaths";
import styles from "./GitLog.module.css";
import { syncMergeScroll } from "./mergeScroll";
/** Read-only parent / merge result / parent comparison, independent of the worktree. */
export function GitMergeDiff({ input }: { input: EditorInput }) {
const data = input.data as {
repo: string;
revision: string;
path: string;
parents: Array<{ rev: string; path: string }>;
};
const host = useRef<HTMLDivElement>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let alive = true;
const views: EditorView[] = [];
let stopScroll: (() => void) | undefined;
const sides = [data.parents[0]!, { rev: data.revision, path: data.path }, data.parents[1]!];
const path = repositoryPath(data.repo, data.path);
void Promise.all(sides.map((s) => call(commands.vcsFileAt(repositoryPath(data.repo, s.path), s.rev))))
.then(async (texts) => [texts, await languageFor(path, texts[1] == null ? null : firstLineOf(texts[1]))] as const)
.then(([texts, language]) => {
if (!alive || !host.current) return;
const docs = texts.map((text) => Text.of((text ?? "").split("\n")));
const marks = docs.map(() => new Map<number, string>());
for (const parent of [0, 2])
for (const chunk of Chunk.build(docs[parent]!, docs[1]!)) {
for (const [pane, from, to] of [
[parent, chunk.fromA, chunk.toA],
[1, chunk.fromB, chunk.toB],
]) {
const doc = docs[pane!]!;
for (let line = doc.lineAt(Math.min(from!, doc.length)); line.from < to!;) {
marks[pane!]!.set(
line.from,
chunk.fromA === chunk.toA ? "inserted" : chunk.fromB === chunk.toB ? "deleted" : "modified",
);
if (line.number === doc.lines) break;
line = doc.line(line.number + 1);
}
}
}
for (const [i, text] of texts.entries()) {
const pane = document.createElement("div");
pane.className = styles.mergeDiffPane!;
host.current.append(pane);
const view = new EditorView({
parent: pane,
state: EditorState.create({
doc: text ?? "",
extensions: [
viewerBase({ readOnly: true }),
...(language ? [language] : []),
EditorView.decorations.of(
Decoration.set(
[...marks[i]!]
.sort((a, b) => a[0] - b[0])
.map(([from, kind]) => Decoration.line({ class: `cm-diffLine-${kind}` }).range(from)),
),
),
],
}),
});
views.push(view);
}
stopScroll = syncMergeScroll({ ours: views[0]!, result: views[1]!, theirs: views[2]! });
})
.catch((e) => alive && setError(String(e)));
const element = host.current;
return () => {
alive = false;
stopScroll?.();
views.forEach((v) => v.destroy());
element?.replaceChildren();
};
}, [data]);
const labels = [data.parents[0]!, { rev: data.revision, path: data.path }, data.parents[1]!];
return (
<div className={styles.mergeDiff}>
{error && <div role="alert">{error}</div>}
<div className={styles.mergeDiffLabels}>
{labels.map((side, i) => (
<span key={i}>{`${side.rev.slice(0, 8)} · ${side.path}`}</span>
))}
</div>
<div className={styles.mergeDiffPanes} ref={host} />
</div>
);
}