~james/core

core/web/src/lib/components/repo/fileDiff.ts -rw-r--r-- 1.8 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 16 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import type { FileDiffMetadata, Hunk, SelectionSide } from "@pierre/diffs";

export type DiffEntry = FileDiffMetadata | { note: string };

export const reservedRows = (
	file: { lines?: number; stat: { insertions: number; deletions: number } },
	split: boolean
): number =>
	split
		? (file.lines ?? file.stat.insertions + file.stat.deletions)
		: (file.lines ?? file.stat.insertions + file.stat.deletions) +
			Math.min(file.stat.insertions, file.stat.deletions);

const sideStart = (start: number, count: number): number => (count === 0 ? start + 1 : start);

export const hiddenLine = (
	hunks: readonly Hunk[],
	line: number,
	side: SelectionSide
): number | undefined => {
	let shift = 0;
	for (const hunk of hunks) {
		const deletionFrom = sideStart(hunk.deletionStart, hunk.deletionCount);
		const additionFrom = sideStart(hunk.additionStart, hunk.additionCount);
		const from = side === "deletions" ? deletionFrom : additionFrom;
		const count = side === "deletions" ? hunk.deletionCount : hunk.additionCount;
		const delta = additionFrom - deletionFrom;
		if (line < from) return side === "deletions" ? line + delta : line;
		if (line < from + count) return undefined;
		shift = delta + hunk.additionCount - hunk.deletionCount;
	}
	return side === "deletions" ? line + shift : line;
};

export const newSideLine = (hunks: readonly Hunk[], line: number, side: SelectionSide): number => {
	if (side === "additions") return line;
	const hidden = hiddenLine(hunks, line, side);
	if (hidden !== undefined) return hidden;
	const hunk = hunks.find(
		(candidate) =>
			line >= sideStart(candidate.deletionStart, candidate.deletionCount) &&
			line <
				sideStart(candidate.deletionStart, candidate.deletionCount) +
					candidate.deletionCount
	);
	return hunk ? sideStart(hunk.additionStart, hunk.additionCount) : line;
};