-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathdiff-viewer-multi-file.svelte.ts
More file actions
763 lines (669 loc) · 25.3 KB
/
Copy pathdiff-viewer-multi-file.svelte.ts
File metadata and controls
763 lines (669 loc) · 25.3 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
import {
fetchGithubCommitDiff,
fetchGithubComparison,
fetchGithubPRComparison,
type FileStatus,
getGithubToken,
type GithubDiff,
type GithubDiffResult,
parseMultiFilePatchGithub,
} from "./github.svelte";
import { type StructuredPatch } from "diff";
import {
ConciseDiffViewCachedState,
DEFAULT_THEME_DARK,
DEFAULT_THEME_LIGHT,
isNoNewlineAtEofLine,
parseSinglePatch,
patchHeaderDiffOnly,
} from "$lib/components/diff/concise-diff-view.svelte";
import type { BundledTheme } from "shiki";
import { browser } from "$app/environment";
import { getEffectiveGlobalTheme } from "$lib/theme.svelte";
import {
countOccurrences,
type FileTreeNodeData,
makeFileTree,
type LazyPromise,
lazyPromise,
watchLocalStorage,
animationFramePromise,
yieldToBrowser,
} from "$lib/util";
import { onDestroy, tick } from "svelte";
import { type TreeNode, TreeState } from "$lib/components/tree/index.svelte";
import { VList } from "virtua/svelte";
import { Context, Debounced, watch } from "runed";
import { MediaQuery } from "svelte/reactivity";
import { ProgressBarState } from "$lib/components/progress-bar/index.svelte";
export type SidebarLocation = "left" | "right";
export class GlobalOptions {
static readonly key = "diff-viewer-global-options";
private static readonly context = new Context<GlobalOptions>(GlobalOptions.key);
static init(cookie?: string) {
const opts = new GlobalOptions();
if (!browser) {
GlobalOptions.context.set(opts);
if (cookie) {
opts.deserialize(cookie);
}
return opts;
}
const serialized = localStorage.getItem(GlobalOptions.key);
if (serialized !== null) {
opts.deserialize(serialized);
}
GlobalOptions.context.set(opts);
return opts;
}
static get() {
return GlobalOptions.context.get();
}
syntaxHighlighting = $state(true);
syntaxHighlightingThemeLight: BundledTheme = $state(DEFAULT_THEME_LIGHT);
syntaxHighlightingThemeDark: BundledTheme = $state(DEFAULT_THEME_DARK);
wordDiffs = $state(true);
lineWrap = $state(true);
omitPatchHeaderOnlyHunks = $state(true);
sidebarLocation: SidebarLocation = $state("left");
private constructor() {
$effect(() => {
this.save();
});
watchLocalStorage(GlobalOptions.key, (newValue) => {
if (newValue) {
this.deserialize(newValue);
}
});
}
get syntaxHighlightingTheme() {
switch (getEffectiveGlobalTheme()) {
case "dark":
return this.syntaxHighlightingThemeDark;
case "light":
return this.syntaxHighlightingThemeLight;
}
}
private save() {
if (!browser) {
return;
}
localStorage.setItem(GlobalOptions.key, this.serialize());
document.cookie = `${GlobalOptions.key}=${encodeURIComponent(this.serializeCookie())}; path=/; max-age=31536000; SameSite=Lax`;
}
private serialize() {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const cereal: any = {
syntaxHighlighting: this.syntaxHighlighting,
omitPatchHeaderOnlyHunks: this.omitPatchHeaderOnlyHunks,
wordDiff: this.wordDiffs,
lineWrap: this.lineWrap,
sidebarLocation: this.sidebarLocation,
};
if (this.syntaxHighlightingThemeLight !== DEFAULT_THEME_LIGHT) {
cereal.syntaxHighlightingThemeLight = this.syntaxHighlightingThemeLight;
}
if (this.syntaxHighlightingThemeDark !== DEFAULT_THEME_DARK) {
cereal.syntaxHighlightingThemeDark = this.syntaxHighlightingThemeDark;
}
return JSON.stringify(cereal);
}
private serializeCookie() {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const cereal: any = {
sidebarLocation: this.sidebarLocation,
};
return JSON.stringify(cereal);
}
private deserialize(serialized: string) {
const jsonObject = JSON.parse(serialized);
if (jsonObject.syntaxHighlighting !== undefined) {
this.syntaxHighlighting = jsonObject.syntaxHighlighting;
}
if (jsonObject.syntaxHighlightingThemeLight !== undefined) {
this.syntaxHighlightingThemeLight = jsonObject.syntaxHighlightingThemeLight as BundledTheme;
} else {
this.syntaxHighlightingThemeLight = DEFAULT_THEME_LIGHT;
}
if (jsonObject.syntaxHighlightingThemeDark !== undefined) {
this.syntaxHighlightingThemeDark = jsonObject.syntaxHighlightingThemeDark as BundledTheme;
} else {
this.syntaxHighlightingThemeDark = DEFAULT_THEME_DARK;
}
if (jsonObject.omitPatchHeaderOnlyHunks !== undefined) {
this.omitPatchHeaderOnlyHunks = jsonObject.omitPatchHeaderOnlyHunks;
}
if (jsonObject.wordDiff !== undefined) {
this.wordDiffs = jsonObject.wordDiff;
}
if (jsonObject.lineWrap !== undefined) {
this.lineWrap = jsonObject.lineWrap;
}
if (jsonObject.sidebarLocation !== undefined) {
this.sidebarLocation = jsonObject.sidebarLocation;
}
}
}
export const staticSidebar = new MediaQuery("(width >= 64rem)");
export type AddOrRemove = "add" | "remove";
export type CommonFileDetails = {
fromFile: string;
toFile: string;
status: FileStatus;
};
export type TextFileDetails = CommonFileDetails & {
type: "text";
structuredPatch: StructuredPatch;
patchHeaderDiffOnly: boolean;
};
export type ImageFileDetails = CommonFileDetails & {
type: "image";
image: ImageDiffDetails;
};
export function makeTextDetails(fromFile: string, toFile: string, status: FileStatus, patchText: string): TextFileDetails {
const patch = parseSinglePatch(patchText);
return {
type: "text",
fromFile,
toFile,
status,
structuredPatch: patch,
patchHeaderDiffOnly: patchHeaderDiffOnly(patch),
};
}
export function makeImageDetails(
fromFile: string,
toFile: string,
status: FileStatus,
fromBlob?: Promise<Blob> | Blob,
toBlob?: Promise<Blob> | Blob,
): ImageFileDetails {
return {
type: "image",
fromFile,
toFile,
status,
image: {
fileA: fromBlob !== undefined ? lazyPromise(async () => URL.createObjectURL(await fromBlob)) : null,
fileB: toBlob !== undefined ? lazyPromise(async () => URL.createObjectURL(await toBlob)) : null,
load: false,
},
};
}
export type FileDetails = TextFileDetails | ImageFileDetails;
export type ImageDiffDetails = {
fileA: LazyPromise<string> | null;
fileB: LazyPromise<string> | null;
load: boolean;
};
export function requireEitherImage(details: ImageDiffDetails) {
if (details.fileA) return details.fileA;
if (details.fileB) return details.fileB;
throw new Error("Neither image is available");
}
// Sort such that when displayed as a file tree, directories come before files and each level is sorted by name
function compareFileDetails(a: FileDetails, b: FileDetails): number {
const aName = a.toFile;
const bName = b.toFile;
// Split paths into components
const aParts = aName.split("/");
const bParts = bName.split("/");
// Compare component by component
const minLength = Math.min(aParts.length, bParts.length);
for (let i = 0; i < minLength; i++) {
// If we're not at the last component of both paths
if (i < aParts.length - 1 && i < bParts.length - 1) {
const comparison = aParts[i].localeCompare(bParts[i]);
if (comparison !== 0) {
return comparison;
}
continue;
}
// If one path is longer at this position (has subdirectories)
if (i === bParts.length - 1 && i < aParts.length - 1) {
// a has subdirectories, so it should come first
return -1;
}
if (i === aParts.length - 1 && i < bParts.length - 1) {
// b has subdirectories, so it should come first
return 1;
}
// Both are at their final component, compare them
return aParts[i].localeCompare(bParts[i]);
}
// If one path is a prefix of the other, shorter path comes first
return aParts.length - bParts.length;
}
export type FileStatusProps = {
iconClasses: string;
title: string;
};
const addStatusProps: FileStatusProps = {
iconClasses: "iconify octicon--file-added-16 text-green-600",
title: "Added",
};
const removeStatusProps: FileStatusProps = {
iconClasses: "iconify octicon--file-removed-16 text-red-600",
title: "Removed",
};
const modifyStatusProps: FileStatusProps = {
iconClasses: "iconify octicon--file-diff-16 text-yellow-600",
title: "Modified",
};
const renamedStatusProps: FileStatusProps = {
iconClasses: "iconify octicon--file-moved-16 text-gray-600",
title: "Renamed",
};
const renamedModifiedStatusProps: FileStatusProps = {
iconClasses: "iconify octicon--file-moved-16 text-yellow-600",
title: "Renamed and Modified",
};
export function getFileStatusProps(status: FileStatus): FileStatusProps {
switch (status) {
case "added":
return addStatusProps;
case "removed":
return removeStatusProps;
case "renamed":
return renamedStatusProps;
case "renamed_modified":
return renamedModifiedStatusProps;
default:
return modifyStatusProps;
}
}
export type ViewerStatistics = {
addedLines: number;
removedLines: number;
fileAddedLines: number[];
fileRemovedLines: number[];
};
export type GithubDiffMetadata = {
type: "github";
details: GithubDiff;
};
export type FileDiffMetadata = {
type: "file";
fileName: string;
};
export type DiffMetadata = GithubDiffMetadata | FileDiffMetadata;
export class MultiFileDiffViewerState {
private static readonly context = new Context<MultiFileDiffViewerState>("MultiFileDiffViewerState");
static init() {
return MultiFileDiffViewerState.context.set(new MultiFileDiffViewerState());
}
static get() {
return MultiFileDiffViewerState.context.get();
}
fileTreeFilter: string = $state("");
searchQuery: string = $state("");
// TODO remove parallel arrays to fix order-dependency issues
collapsed: boolean[] = $state([]);
checked: boolean[] = $state([]);
fileDetails: FileDetails[] = $state([]);
diffViewCache: Map<FileDetails, ConciseDiffViewCachedState> = new Map();
vlist: VList<FileDetails> | undefined = $state();
tree: TreeState<FileTreeNodeData> | undefined = $state();
activeSearchResult: ActiveSearchResult | null = $state(null);
sidebarCollapsed = $state(false);
diffMetadata: DiffMetadata | null = $state(null);
readonly loadingState: LoadingState = $state(new LoadingState());
readonly fileTreeFilterDebounced = new Debounced(() => this.fileTreeFilter, 500);
readonly searchQueryDebounced = new Debounced(() => this.searchQuery, 500);
readonly stats: ViewerStatistics = $derived(this.countStats());
readonly fileTreeRoots: TreeNode<FileTreeNodeData>[] = $derived(makeFileTree(this.fileDetails));
readonly filteredFileDetails: FileDetails[] = $derived(
this.fileTreeFilterDebounced.current ? this.fileDetails.filter((f) => this.filterFile(f)) : this.fileDetails,
);
readonly searchResults: Promise<SearchResults> = $derived(this.findSearchResults());
private constructor() {
// Auto-check all patch header diff only diffs
$effect(() => {
for (let i = 0; i < this.fileDetails.length; i++) {
const details = this.fileDetails[i];
if (details.type !== "text") {
continue;
}
if (details.patchHeaderDiffOnly && this.checked[i] === undefined) {
this.checked[i] = true;
}
}
});
// Make sure to revoke object URLs when the component is destroyed
onDestroy(() => this.clearImages());
}
getIndex(details: FileDetails): number {
return this.fileDetails.findIndex((f) => f.fromFile === details.fromFile && f.toFile === details.toFile);
}
filterFile(file: FileDetails): boolean {
const queryLower = this.fileTreeFilterDebounced.current.toLowerCase();
return file.toFile.toLowerCase().includes(queryLower) || file.fromFile.toLowerCase().includes(queryLower);
}
clearSearch() {
this.fileTreeFilter = "";
}
toggleCollapse(index: number) {
this.collapsed[index] = !(this.collapsed[index] || false);
}
expandAll() {
this.collapsed = [];
}
collapseAll() {
this.collapsed = this.fileDetails.map(() => true);
}
toggleChecked(index: number) {
this.checked[index] = !this.checked[index];
if (this.checked[index]) {
// Auto-collapse on check
this.collapsed[index] = true;
}
}
scrollToFile(index: number, options: { autoExpand?: boolean; smooth?: boolean; focus?: boolean } = {}) {
if (!this.vlist) return;
const autoExpand = options.autoExpand ?? true;
const smooth = options.smooth ?? false;
const focus = options.focus ?? false;
if (autoExpand && !this.checked[index]) {
// Auto-expand on jump when not checked
this.collapsed[index] = false;
}
this.vlist.scrollToIndex(index, { align: "start", smooth });
if (focus) {
requestAnimationFrame(() => {
const headerElement = document.getElementById(`file-header-${index}`);
headerElement?.focus();
});
}
}
// https://github.com/inokawa/virtua/issues/621
// https://github.com/inokawa/virtua/discussions/542#discussioncomment-11214618
async scrollToMatch(file: FileDetails, idx: number) {
if (!this.vlist) return;
const fileIdx = this.getIndex(file);
this.collapsed[fileIdx] = false;
const startIdx = this.vlist.findStartIndex();
const endIdx = this.vlist.findEndIndex();
if (fileIdx < startIdx || fileIdx > endIdx) {
this.vlist.scrollToIndex(fileIdx, { align: "start" });
}
requestAnimationFrame(() => {
const fileElement = document.getElementById(`file-${fileIdx}`);
const resultElement = fileElement?.querySelector(`[data-match-id='${idx}']`) as HTMLElement | null | undefined;
if (!resultElement) return;
resultElement.scrollIntoView({ block: "center", inline: "center" });
});
}
clearImages() {
for (let i = 0; i < this.fileDetails.length; i++) {
const details = this.fileDetails[i];
if (details.type !== "image") {
continue;
}
const image = details.image;
image.load = false;
const fileA = image.fileA;
if (fileA?.hasValue()) {
(async () => {
const a = await fileA.getValue();
URL.revokeObjectURL(a);
})();
}
const fileB = image.fileB;
if (fileB?.hasValue()) {
(async () => {
const b = await fileB.getValue();
URL.revokeObjectURL(b);
})();
}
}
}
private clear(clearMeta: boolean = true) {
// Reset state
this.collapsed = [];
this.checked = [];
if (clearMeta) {
this.diffMetadata = null;
}
this.fileDetails = [];
this.clearImages();
this.vlist?.scrollToIndex(0, { align: "start" });
}
async loadPatches(meta: () => Promise<DiffMetadata>, patches: () => Promise<AsyncGenerator<FileDetails, void>>) {
if (this.loadingState.loading) {
alert("Already loading patches, please wait.");
return false;
}
try {
// Show progress bar
this.loadingState.start();
await tick();
await animationFramePromise();
// Start potential multiple web requests in parallel
const metaPromise = meta();
const generatorPromise = patches();
// Update metadata
this.diffMetadata = await metaPromise;
await tick();
await animationFramePromise();
// Clear previous state
this.clear(false);
await tick();
await animationFramePromise();
// Setup generator
const generator = await generatorPromise;
await tick();
await animationFramePromise();
// Load patches
const tempDetails: FileDetails[] = [];
let lastYield = performance.now();
let i = 0;
for await (const details of generator) {
i++;
this.loadingState.loadedCount++;
// Pushing directly to the main array causes too many signals to update (lag)
tempDetails.push(details);
if (performance.now() - lastYield > 50 || i % 100 === 0) {
await tick();
await yieldToBrowser();
lastYield = performance.now();
}
}
if (tempDetails.length === 0) {
throw new Error("No valid patches found in the provided data.");
}
tempDetails.sort(compareFileDetails);
this.fileDetails.push(...tempDetails);
return true;
} catch (e) {
this.clear(); // Clear any partially loaded state
console.error("Failed to load patches:", e);
alert("Failed to load patches: " + e);
return false;
} finally {
// Let the last progress update render before closing the loading state
await tick();
await animationFramePromise();
this.loadingState.done();
}
}
private async loadPatchesGithub(resultOrPromise: Promise<GithubDiffResult> | GithubDiffResult) {
return await this.loadPatches(
async () => {
const result = resultOrPromise instanceof Promise ? await resultOrPromise : resultOrPromise;
return { type: "github", details: await result.info };
},
async () => {
const result = resultOrPromise instanceof Promise ? await resultOrPromise : resultOrPromise;
return parseMultiFilePatchGithub(await result.info, await result.response, this.loadingState);
},
);
}
// TODO fails for initial commit?
// handle matched github url
async loadFromGithubApi(match: Array<string>): Promise<boolean> {
const [url, owner, repo, type, id] = match;
const token = getGithubToken();
try {
if (type === "commit") {
return await this.loadPatchesGithub(fetchGithubCommitDiff(token, owner, repo, id.split("/")[0]));
} else if (type === "pull") {
return await this.loadPatchesGithub(fetchGithubPRComparison(token, owner, repo, id.split("/")[0]));
} else if (type === "compare") {
let refs = id.split("...");
if (refs.length !== 2) {
refs = id.split("..");
if (refs.length !== 2) {
alert(`Invalid comparison URL. '${id}' does not match format 'ref_a...ref_b' or 'ref_a..ref_b'`);
return false;
}
}
const base = refs[0];
const head = refs[1];
return await this.loadPatchesGithub(fetchGithubComparison(token, owner, repo, base, head));
}
} catch (error) {
console.error(error);
alert(`Failed to load diff from GitHub: ${error}`);
return false;
}
alert("Unsupported URL type " + url);
return false;
}
private countStats(): ViewerStatistics {
let addedLines = 0;
let removedLines = 0;
const fileAddedLines: number[] = [];
const fileRemovedLines: number[] = [];
for (let i = 0; i < this.fileDetails.length; i++) {
const details = this.fileDetails[i];
if (details.type !== "text") {
continue;
}
const diff = details.structuredPatch;
for (let j = 0; j < diff.hunks.length; j++) {
const hunk = diff.hunks[j];
for (let k = 0; k < hunk.lines.length; k++) {
const line = hunk.lines[k];
if (line.startsWith("+")) {
addedLines++;
fileAddedLines[i] = (fileAddedLines[i] || 0) + 1;
} else if (line.startsWith("-")) {
removedLines++;
fileRemovedLines[i] = (fileRemovedLines[i] || 0) + 1;
}
}
}
}
return { addedLines, removedLines, fileAddedLines, fileRemovedLines };
}
private async findSearchResults(): Promise<SearchResults> {
let query = this.searchQueryDebounced.current;
if (!query) {
return SearchResults.EMPTY;
}
query = query.toLowerCase();
const diffPromises = this.fileDetails.map((details) => {
if (details.type !== "text") {
return undefined;
}
return details.structuredPatch;
});
const diffs = await Promise.all(diffPromises);
let total = 0;
const lines: Map<FileDetails, number[][]> = new Map();
const counts: Map<FileDetails, number> = new Map();
const mappings: Map<number, FileDetails> = new Map();
for (let i = 0; i < diffs.length; i++) {
const diff = diffs[i];
if (diff === undefined) {
continue;
}
const details = this.fileDetails[i];
const lineNumbers: number[][] = [];
let found = false;
for (let j = 0; j < diff.hunks.length; j++) {
const hunk = diff.hunks[j];
const hunkLineNumbers: number[] = [];
lineNumbers[j] = hunkLineNumbers;
let lineIdx = 0;
for (let k = 0; k < hunk.lines.length; k++) {
if (isNoNewlineAtEofLine(hunk.lines[k])) {
// These lines are 'merged' into the previous line
continue;
}
const count = countOccurrences(hunk.lines[k].slice(1).toLowerCase(), query);
if (count !== 0) {
counts.set(details, (counts.get(details) ?? 0) + count);
total += count;
if (!hunkLineNumbers.includes(lineIdx)) {
hunkLineNumbers.push(lineIdx);
}
found = true;
}
lineIdx++;
}
}
if (found) {
mappings.set(total, details);
lines.set(details, lineNumbers);
}
}
return new SearchResults(counts, total, mappings, lines);
}
}
export class LoadingState {
loading: boolean = $state(false);
loadedCount: number = $state(0);
totalCount: number | null = $state(0);
readonly progressBar = $state(new ProgressBarState(null, 100));
constructor() {
watch([() => this.loadedCount, () => this.totalCount], ([loadedCount, totalCount]) => {
if (totalCount === null || totalCount <= 0) {
this.progressBar.setSpinning();
} else {
this.progressBar.setProgress(loadedCount, totalCount);
}
});
}
start() {
this.loadedCount = 0;
this.totalCount = null;
this.progressBar.setSpinning();
this.loading = true;
}
done() {
this.loading = false;
}
}
export type ActiveSearchResult = {
file: FileDetails;
idx: number;
};
export class SearchResults {
static EMPTY = new SearchResults(new Map(), 0, new Map(), new Map());
counts: Map<FileDetails, number>;
mappings: Map<number, FileDetails> = new Map();
// FileDetails -> Hunk -> Line
lines: Map<FileDetails, number[][]> = new Map();
totalMatches: number;
constructor(counts: Map<FileDetails, number>, total: number, mappings: Map<number, FileDetails>, lines: Map<FileDetails, number[][]>) {
this.counts = counts;
this.totalMatches = total;
this.mappings = mappings;
this.lines = lines;
}
getLocation(index: number): ActiveSearchResult {
index++; // Mappings are 1-based
const originalIndex = index;
let file = this.mappings.get(index);
while (file === undefined && index < this.totalMatches) {
index++;
file = this.mappings.get(index);
}
if (file === undefined) {
throw new Error("No file found");
}
const matchCount = this.counts.get(file) || 0;
return { file, idx: matchCount - 1 - (index - originalIndex) };
}
}