Skip to content
Source
Sign inSign up
Open History to see the last commit

pullRequestDiff.logic.ts

54 lines1.9 KB

1import type { FileDiffMetadata } from "@pierre/diffs";
2import type { PullRequestDiffSide } from "@t3tools/contracts";
3​
4/** Only rendered hunks can anchor comments; list others off-diff. */
5export function isLineInFileDiff(
6 file: FileDiffMetadata,
7 side: PullRequestDiffSide,
8 line: number,
9): boolean {
10 return file.hunks.some((hunk) =>
11 side === "left"
12 ? line >= hunk.deletionStart && line < hunk.deletionStart + hunk.deletionCount
13 : line >= hunk.additionStart && line < hunk.additionStart + hunk.additionCount,
14 );
16​
17export type DiffFoldOverride = "expanded" | "folded" | null;
18​
19/** The reader's own fold choice per file. It is absolute, so a Viewed mark loading later keeps it. */
20export type FileDiffFoldChoices = ReadonlyMap<string, boolean>;
21​
22/**
23 * A reader's own choice wins. Otherwise the toolbar decides, and a file still marked Viewed
24 * starts folded. Fold all and Expand all clear the choices, so later pages follow the toolbar.
25 */
26export function isFileDiffCollapsed(
27 fileKey: string,
28 foldOverride: DiffFoldOverride,
29 choices: FileDiffFoldChoices,
30 viewed = false,
31): boolean {
32 return choices.get(fileKey) ?? (foldOverride === "folded" || viewed);
34​
35export function withFileDiffFold(
36 choices: FileDiffFoldChoices,
37 fileKey: string,
38 collapsed: boolean,
39): FileDiffFoldChoices {
40 if (choices.get(fileKey) === collapsed) return choices;
41 return new Map(choices).set(fileKey, collapsed);
43​
44export function getFileViewedRange<T extends { readonly fileKey: string }>(
45 files: ReadonlyArray<T>,
46 fileKey: string,
47 anchorFileKey: string | null,
48): ReadonlyArray<T> {
49 const index = files.findIndex((file) => file.fileKey === fileKey);
50 if (index === -1) return [];
51 const anchorIndex = files.findIndex((file) => file.fileKey === anchorFileKey);
52 if (anchorIndex === -1) return files.slice(index, index + 1);
53 return files.slice(Math.min(index, anchorIndex), Math.max(index, anchorIndex) + 1);