-
Notifications
You must be signed in to change notification settings - Fork 736
Expand file tree
/
Copy pathissueOverview.ts
More file actions
886 lines (786 loc) · 29.7 KB
/
issueOverview.ts
File metadata and controls
886 lines (786 loc) · 29.7 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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as vscode from 'vscode';
import { CloseResult, OpenLocalFileArgs } from '../../common/views';
import { openPullRequestOnGitHub } from '../commands';
import { FolderRepositoryManager } from './folderRepositoryManager';
import { GithubItemStateEnum, IAccount, IMilestone, IProject, IProjectItem, RepoAccessAndMergeMethods } from './interface';
import { IssueModel } from './issueModel';
import { getAssigneesQuickPickItems, getLabelOptions, getMilestoneFromQuickPick, getProjectFromQuickPick } from './quickPicks';
import { isInCodespaces, processPermalinks, vscodeDevPrLink } from './utils';
import { ChangeAssigneesReply, DisplayLabel, Issue, ProjectItemsReply, SubmitReviewReply, UnresolvedIdentity } from './views';
import { COPILOT_ACCOUNTS, IComment } from '../common/comment';
import { emojify, ensureEmojis } from '../common/emoji';
import Logger from '../common/logger';
import { PR_SETTINGS_NAMESPACE, WEBVIEW_REFRESH_INTERVAL } from '../common/settingKeys';
import { ITelemetry } from '../common/telemetry';
import { CommentEvent, EventType, ReviewStateValue, TimelineEvent } from '../common/timelineEvent';
import { asPromise, formatError } from '../common/utils';
import { generateUuid } from '../common/uuid';
import { IRequestMessage, WebviewBase } from '../common/webview';
export function panelKey(owner: string, repo: string, number: number): string {
return `${owner}/${repo}#${number}`;
}
export class IssueOverviewPanel<TItem extends IssueModel = IssueModel> extends WebviewBase {
public static ID: string = 'IssueOverviewPanel';
/**
* All open panels, keyed by "owner/repo#number".
*/
protected static _panels: Map<string, IssueOverviewPanel> = new Map();
public static readonly viewType: string = 'IssueOverview';
protected readonly _panel: vscode.WebviewPanel;
protected _item: TItem;
protected _identity: UnresolvedIdentity;
protected _folderRepositoryManager: FolderRepositoryManager;
protected _scrollPosition = { x: 0, y: 0 };
protected static _getViewColumn(toTheSide: boolean, panel?: IssueOverviewPanel): number | undefined {
const tabViewColumn = vscode.window.tabGroups.activeTabGroup.viewColumn;
const activeColumn = toTheSide
? vscode.ViewColumn.Beside
: (panel ? undefined : tabViewColumn);
return activeColumn;
}
public static async createOrShow(
telemetry: ITelemetry,
extensionUri: vscode.Uri,
folderRepositoryManager: FolderRepositoryManager,
identity: UnresolvedIdentity,
issue?: IssueModel,
toTheSide: boolean = false,
_preserveFocus: boolean = true,
existingPanel?: vscode.WebviewPanel
) {
await ensureEmojis(folderRepositoryManager.context);
const key = panelKey(identity.owner, identity.repo, identity.number);
let panel = this._panels.get(key);
const activeColumn = IssueOverviewPanel._getViewColumn(toTheSide, panel);
if (panel) {
panel._panel.reveal(activeColumn, true);
} else {
const title = `#${identity.number.toString()}`;
panel = new IssueOverviewPanel(
telemetry,
extensionUri,
activeColumn || vscode.ViewColumn.Active,
title,
folderRepositoryManager,
undefined,
existingPanel,
undefined
);
this._panels.set(key, panel);
}
await panel.updateWithIdentity(folderRepositoryManager, identity, issue);
}
public static refresh(owner: string, repo: string, number: number): void {
const panel = this.findPanel(owner, repo, number);
if (panel) {
panel.refreshPanel();
}
}
/**
* Return the panel whose webview is currently active (focused),
* or `undefined` when no issue/PR panel is active.
*/
public static getActivePanel(): IssueOverviewPanel | undefined {
for (const panel of this._panels.values()) {
if (panel._panel.active) {
return panel;
}
}
return undefined;
}
/**
* Find the panel showing a specific issue.
*/
public static findPanel(owner: string, repo: string, number: number): IssueOverviewPanel | undefined {
return this._panels.get(panelKey(owner, repo, number));
}
/**
* Build a short panel title: `#<number> <truncated title>`.
* The item title is truncated to approximately `maxLength` characters on a
* word boundary and suffixed with "..." when it doesn't fit in full.
*/
protected buildPanelTitle(itemNumber: number, itemTitle: string, maxLength: number = 20): string {
let truncated = itemTitle;
if (itemTitle.length > maxLength) {
const lastSpace = itemTitle.lastIndexOf(' ', maxLength);
const cutOff = lastSpace > 0 ? lastSpace : maxLength;
truncated = itemTitle.substring(0, cutOff) + '...';
}
return `#${itemNumber} ${truncated}`;
}
protected setPanelTitle(title: string): void {
try {
this._panel.title = title;
} catch (e) {
// The webview can be disposed at the time that we try to set the title if the user has closed
// it while it's still loading.
}
}
protected constructor(
protected readonly _telemetry: ITelemetry,
protected readonly _extensionUri: vscode.Uri,
column: vscode.ViewColumn,
title: string,
folderRepositoryManager: FolderRepositoryManager,
private readonly type: string = IssueOverviewPanel.viewType,
existingPanel?: vscode.WebviewPanel,
iconSubpath: {
light: string,
dark: string,
} = {
light: 'resources/icons/issue_webview.svg',
dark: 'resources/icons/dark/issue_webview.svg',
}
) {
super();
this._folderRepositoryManager = folderRepositoryManager;
// Create and show a new webview panel
this._panel = existingPanel ?? this._register(vscode.window.createWebviewPanel(type, title, column, {
// Enable javascript in the webview
enableScripts: true,
retainContextWhenHidden: true,
// And restrict the webview to only loading content from our extension's `dist` directory.
localResourceRoots: [vscode.Uri.joinPath(_extensionUri, 'dist')],
enableFindWidget: true
}));
this._panel.iconPath = {
dark: vscode.Uri.joinPath(_extensionUri, iconSubpath.dark),
light: vscode.Uri.joinPath(_extensionUri, iconSubpath.light)
};
this._webview = this._panel.webview;
super.initialize();
// Listen for when the panel is disposed
// This happens when the user closes the panel or when the panel is closed programmatically
this._register(this._panel.onDidDispose(() => this.dispose()));
this._register(this._folderRepositoryManager.onDidChangeActiveIssue(
_ => {
if (this._folderRepositoryManager && this._item) {
const isCurrentlyCheckedOut = this._item.equals(this._folderRepositoryManager.activeIssue);
this._postMessage({
command: 'pr.update-checkout-status',
isCurrentlyCheckedOut: isCurrentlyCheckedOut,
});
}
}));
this._register(folderRepositoryManager.credentialStore.onDidUpgradeSession(() => {
this.updateItem(this._item);
}));
this._register(this._panel.onDidChangeViewState(e => this.onDidChangeViewState(e)));
this.lastRefreshTime = new Date();
this.pollForUpdates(true);
this._register(vscode.workspace.onDidChangeConfiguration(e => {
if (e.affectsConfiguration(`${PR_SETTINGS_NAMESPACE}.${WEBVIEW_REFRESH_INTERVAL}`)) {
this.pollForUpdates(this._panel.visible, true);
}
}));
this._register({ dispose: () => clearTimeout(this.timeout) });
}
private getRefreshInterval(): number {
return vscode.workspace.getConfiguration().get<number>(`${PR_SETTINGS_NAMESPACE}.${WEBVIEW_REFRESH_INTERVAL}`) || 60;
}
protected onDidChangeViewState(e: vscode.WebviewPanelOnDidChangeViewStateEvent): void {
if (e.webviewPanel.visible) {
this.pollForUpdates(!!this._item, true);
}
}
private timeout: NodeJS.Timeout | undefined = undefined;
private lastRefreshTime: Date;
private pollForUpdates(isVisible: boolean, refreshImmediately: boolean = false): void {
clearTimeout(this.timeout);
const refresh = async () => {
const previousRefreshTime = this.lastRefreshTime;
this.lastRefreshTime = await this._item.getLastUpdateTime(previousRefreshTime);
if (this.lastRefreshTime.getTime() > previousRefreshTime.getTime()) {
return this.refreshPanel();
}
};
if (refreshImmediately) {
refresh();
}
const webview = isVisible || vscode.window.tabGroups.all.find(group => group.activeTab?.input instanceof vscode.TabInputWebview && group.activeTab.input.viewType.endsWith(this.type));
const timeoutDuration = 1000 * (webview ? this.getRefreshInterval() : (5 * 60));
this.timeout = setTimeout(async () => {
await refresh();
this.pollForUpdates(this._panel.visible);
}, timeoutDuration);
}
public async refreshPanel(): Promise<void> {
if (this._panel && this._panel.visible) {
await this.updateItem(this._item);
}
}
protected continueOnGitHub() {
return isInCodespaces();
}
protected async getInitializeContext(currentUser: IAccount, issue: IssueModel, timelineEvents: TimelineEvent[], repositoryAccess: RepoAccessAndMergeMethods, viewerCanEdit: boolean, assignableUsers: IAccount[]): Promise<Issue> {
const hasWritePermission = repositoryAccess.hasWritePermission;
const canEdit = hasWritePermission || viewerCanEdit;
const labels = issue.item.labels.map(label => ({
...label,
displayName: emojify(label.name)
}));
const context: Issue = {
owner: issue.remote.owner,
repo: issue.remote.repositoryName,
number: issue.number,
title: issue.title,
titleHTML: issue.titleHTML,
url: issue.html_url,
createdAt: issue.createdAt,
body: issue.body,
bodyHTML: await this.processLinksInBodyHtml(issue.bodyHTML),
labels: labels,
author: issue.author,
state: issue.state,
stateReason: issue.stateReason,
events: await this.processTimelineEvents(timelineEvents),
continueOnGitHub: this.continueOnGitHub(),
canEdit,
hasWritePermission,
isIssue: true,
projectItems: issue.item.projectItems,
milestone: issue.milestone,
assignees: issue.assignees ?? [],
isEnterprise: issue.githubRepository.remote.isEnterprise,
isDarkTheme: vscode.window.activeColorTheme.kind === vscode.ColorThemeKind.Dark,
canAssignCopilot: assignableUsers.find(user => COPILOT_ACCOUNTS[user.login]) !== undefined,
canRequestCopilotReview: false,
reactions: issue.item.reactions,
isAuthor: issue.author.login === currentUser.login,
};
return context;
}
protected async updateItem(issueModel: TItem): Promise<void> {
try {
const [
issue,
timelineEvents,
repositoryAccess,
viewerCanEdit,
assignableUsers,
currentUser
] = await Promise.all([
this._folderRepositoryManager.resolveIssue(
issueModel.remote.owner,
issueModel.remote.repositoryName,
issueModel.number,
),
issueModel.getIssueTimelineEvents(),
this._folderRepositoryManager.getPullRequestRepositoryAccessAndMergeMethods(issueModel),
issueModel.canEdit(),
this._folderRepositoryManager.getAssignableUsers(),
this._folderRepositoryManager.getCurrentUser(),
]);
if (!issue) {
throw new Error(
`Fail to resolve issue #${issueModel.number} in ${issueModel.remote.owner}/${issueModel.remote.repositoryName}`,
);
}
this._item = issue as TItem;
this.setPanelTitle(this.buildPanelTitle(issueModel.number, issueModel.title));
// Process permalinks in bodyHTML before sending to webview
const context = await this.getInitializeContext(currentUser, issue, timelineEvents, repositoryAccess, viewerCanEdit, assignableUsers[this._item.remote.remoteName] ?? []);
Logger.debug('pr.initialize', IssueOverviewPanel.ID);
this._postMessage({
command: 'pr.initialize',
pullrequest: context,
});
} catch (e) {
vscode.window.showErrorMessage(`Error updating issue description: ${formatError(e)}`);
}
}
protected registerPrListeners() {
// none for issues
}
/**
* Resolve a model from an unresolved identity.
* Subclasses can override to resolve different types (e.g., pull requests vs issues).
*/
protected async resolveModel(identity: UnresolvedIdentity): Promise<TItem | undefined> {
return this._folderRepositoryManager.resolveIssue(
identity.owner,
identity.repo,
identity.number
) as Promise<TItem | undefined>;
}
/**
* Get the display name for the item type (for error messages).
*/
protected getItemTypeName(): string {
return 'issue';
}
/**
* Update the panel with an unresolved identity and optional model.
* If no model is provided, it will be resolved from the identity.
*/
public async updateWithIdentity(foldersManager: FolderRepositoryManager, identity: UnresolvedIdentity, issueModel?: TItem, progressLocation?: string): Promise<void> {
this._identity = identity;
this._folderRepositoryManager = foldersManager;
this._postMessage({
command: 'set-scroll',
scrollPosition: this._scrollPosition,
});
if (!this._panel.webview.html) {
this._panel.webview.html = this.getHtmlForWebview();
if (this._item) {
this._postMessage({ command: 'pr.clear' });
}
}
// If no model provided, resolve it from the identity
if (!issueModel) {
const resolvedModel = await this.resolveModel(identity);
if (!resolvedModel) {
throw new Error(
`Failed to resolve ${this.getItemTypeName()} #${identity.number} in ${identity.owner}/${identity.repo}`,
);
}
issueModel = resolvedModel;
}
if (progressLocation) {
return vscode.window.withProgress({ location: { viewId: progressLocation } }, () => this.updateItem(issueModel!));
} else {
return this.updateItem(issueModel);
}
}
protected override async _onDidReceiveMessage(message: IRequestMessage<any>) {
const result = await super._onDidReceiveMessage(message);
if (result !== this.MESSAGE_UNHANDLED) {
return;
}
switch (message.command) {
case 'alert':
vscode.window.showErrorMessage(message.args);
return;
case 'pr.close':
return this.close(message);
case 'pr.submit':
return this.submitReviewMessage(message);
case 'scroll':
this._scrollPosition = message.args.scrollPosition;
return;
case 'pr.edit-comment':
return this.editComment(message);
case 'pr.delete-comment':
return this.deleteComment(message);
case 'pr.edit-description':
return this.editDescription(message);
case 'pr.edit-title':
return this.editTitle(message);
case 'pr.refresh':
this.refreshPanel();
return;
case 'pr.add-labels':
return this.addLabels(message);
case 'pr.remove-label':
return this.removeLabel(message);
case 'pr.change-assignees':
return this.changeAssignees(message);
case 'pr.remove-milestone':
return this.removeMilestone(message);
case 'pr.add-milestone':
return this.addMilestone(message);
case 'pr.change-projects':
return this.changeProjects(message);
case 'pr.remove-project':
return this.removeProject(message);
case 'pr.add-assignee-yourself':
return this.addAssigneeYourself(message);
case 'pr.add-assignee-copilot':
return this.addAssigneeCopilot(message);
case 'pr.copy-prlink':
return this.copyItemLink();
case 'pr.copy-vscodedevlink':
return this.copyVscodeDevLink();
case 'pr.openOnGitHub':
return openPullRequestOnGitHub(this._item, this._telemetry);
case 'pr.open-local-file':
return this.openLocalFile(message);
case 'pr.debug':
return this.webviewDebug(message);
default:
return this.MESSAGE_UNHANDLED;
}
}
protected async submitReviewMessage(message: IRequestMessage<string>) {
const comment = await this._item.createIssueComment(message.args);
const commentedEvent: CommentEvent = {
...comment,
event: EventType.Commented
};
const allEvents = await this._getTimeline();
const reply: SubmitReviewReply = {
events: allEvents,
reviewedEvent: commentedEvent,
};
this.tryScheduleCopilotRefresh(comment.body);
return this._replyMessage(message, reply);
}
private _scheduledRefresh: Promise<void> | undefined;
protected async tryScheduleCopilotRefresh(commentBody: string, reviewType?: ReviewStateValue) {
if (!this._scheduledRefresh) {
this._scheduledRefresh = this.doScheduleCopilotRefresh(commentBody, reviewType)
.finally(() => {
this._scheduledRefresh = undefined;
});
}
}
private async doScheduleCopilotRefresh(commentBody: string, reviewType?: ReviewStateValue) {
if (!COPILOT_ACCOUNTS[this._item.author.login]) {
return;
}
if (!commentBody.includes('@copilot') && !commentBody.includes('@Copilot') && reviewType !== 'CHANGES_REQUESTED') {
return;
}
const initialTimeline = await this._getTimeline();
const delays = [250, 500, 1000, 2000];
for (const delay of delays) {
await new Promise(resolve => setTimeout(resolve, delay));
if (this._isDisposed) {
return;
}
try {
const currentTimeline = await this._getTimeline();
// Check if we have any new CopilotStarted events
if (currentTimeline.length > initialTimeline.length) {
// Found a new CopilotStarted event, refresh and stop
this.refreshPanel();
return;
}
} catch (error) {
// If timeline fetch fails, continue with the next retry
Logger.warn(`Failed to fetch timeline during Copilot refresh retry: ${error}`, IssueOverviewPanel.ID);
}
}
// If no new CopilotStarted events were found after all retries, still refresh once
if (!this._isDisposed) {
this.refreshPanel();
}
}
private async addLabels(message: IRequestMessage<void>): Promise<void> {
const quickPick = vscode.window.createQuickPick<(vscode.QuickPickItem & { name: string })>();
try {
let newLabels: DisplayLabel[] = [];
quickPick.busy = true;
quickPick.canSelectMany = true;
quickPick.show();
quickPick.items = await (getLabelOptions(this._folderRepositoryManager, this._item.item.labels, this._item.remote.owner, this._item.remote.repositoryName).then(options => {
newLabels = options.newLabels;
return options.labelPicks;
}));
quickPick.selectedItems = quickPick.items.filter(item => item.picked);
quickPick.busy = false;
const acceptPromise = asPromise<void>(quickPick.onDidAccept).then(() => {
return quickPick.selectedItems;
});
const hidePromise = asPromise<void>(quickPick.onDidHide);
const labelsToAdd = await Promise.race<readonly (vscode.QuickPickItem & { name: string })[] | void>([acceptPromise, hidePromise]);
quickPick.busy = true;
quickPick.enabled = false;
if (labelsToAdd) {
await this._item.setLabels(labelsToAdd.map(r => r.name));
const addedLabels: DisplayLabel[] = labelsToAdd.map(label => newLabels.find(l => l.name === label.name)!);
await this._replyMessage(message, {
added: addedLabels,
});
}
} catch (e) {
vscode.window.showErrorMessage(formatError(e));
} finally {
quickPick.hide();
quickPick.dispose();
}
}
private async removeLabel(message: IRequestMessage<string>): Promise<void> {
try {
await this._item.removeLabel(message.args);
this._replyMessage(message, {});
} catch (e) {
vscode.window.showErrorMessage(formatError(e));
}
}
private webviewDebug(message: IRequestMessage<string>): void {
Logger.debug(message.args, IssueOverviewPanel.ID);
}
/**
* Process code reference links in bodyHTML. Can be overridden by subclasses (e.g., PullRequestOverviewPanel)
* to provide custom processing logic for different item types.
* Returns undefined if bodyHTML is undefined.
*/
protected async processLinksInBodyHtml(bodyHTML: string | undefined): Promise<string | undefined> {
if (!bodyHTML) {
return bodyHTML;
}
return processPermalinks(
bodyHTML,
this._item.githubRepository,
this._item.githubRepository.rootUri
);
}
/**
* Process code reference links in timeline events (comments, reviews, commits).
* Updates bodyHTML fields for all events that contain them.
*/
protected async processTimelineEvents(events: TimelineEvent[]): Promise<TimelineEvent[]> {
return Promise.all(events.map(async (event) => {
// Create a shallow copy to avoid mutating the original
const processedEvent = { ...event };
if (processedEvent.event === EventType.Commented || processedEvent.event === EventType.Reviewed || processedEvent.event === EventType.Committed) {
processedEvent.bodyHTML = await this.processLinksInBodyHtml(processedEvent.bodyHTML);
// ReviewEvent also has comments array
if (processedEvent.event === EventType.Reviewed && processedEvent.comments) {
processedEvent.comments = await Promise.all(processedEvent.comments.map(async (comment: IComment) => ({
...comment,
bodyHTML: await this.processLinksInBodyHtml(comment.bodyHTML)
})));
}
}
return processedEvent;
}));
}
private async editDescription(message: IRequestMessage<{ text: string }>) {
try {
const result = await this._item.edit({ body: message.args.text });
const bodyHTML = await this.processLinksInBodyHtml(result.bodyHTML);
this._replyMessage(message, { body: result.body, bodyHTML });
} catch (e) {
this._throwError(message, e);
vscode.window.showErrorMessage(`Editing description failed: ${formatError(e)}`);
}
}
private editTitle(message: IRequestMessage<{ text: string }>) {
return this._item
.edit({ title: message.args.text })
.then(result => {
return this._replyMessage(message, { titleHTML: result.titleHTML });
})
.catch(e => {
this._throwError(message, e);
vscode.window.showErrorMessage(`Editing title failed: ${formatError(e)}`);
});
}
protected async _getTimeline(): Promise<TimelineEvent[]> {
const events = await this._item.getIssueTimelineEvents();
return this.processTimelineEvents(events);
}
private async changeAssignees(message: IRequestMessage<void>): Promise<void> {
const quickPick = vscode.window.createQuickPick<vscode.QuickPickItem & { user?: IAccount }>();
try {
quickPick.busy = true;
quickPick.canSelectMany = true;
quickPick.matchOnDescription = true;
quickPick.show();
quickPick.items = await getAssigneesQuickPickItems(this._folderRepositoryManager, undefined, this._item.remote.remoteName, this._item.assignees ?? [], this._item);
quickPick.selectedItems = quickPick.items.filter(item => item.picked);
quickPick.busy = false;
const acceptPromise = asPromise<void>(quickPick.onDidAccept).then(() => {
return quickPick.selectedItems.filter(item => item.user) as (vscode.QuickPickItem & { user: IAccount })[] | undefined;
});
const hidePromise = asPromise<void>(quickPick.onDidHide);
const allAssignees = await Promise.race<(vscode.QuickPickItem & { user: IAccount })[] | void>([acceptPromise, hidePromise]);
quickPick.busy = true;
quickPick.enabled = false;
if (allAssignees) {
const newAssignees: IAccount[] = allAssignees.map(item => item.user);
await this._item.replaceAssignees(newAssignees);
const events = await this._getTimeline();
const reply: ChangeAssigneesReply = {
assignees: newAssignees,
events
};
await this._replyMessage(message, reply);
}
} catch (e) {
vscode.window.showErrorMessage(formatError(e));
} finally {
quickPick.hide();
quickPick.dispose();
}
}
private async addMilestone(message: IRequestMessage<void>): Promise<void> {
return getMilestoneFromQuickPick(this._folderRepositoryManager, this._item.githubRepository, this._item.milestone, (milestone) => this.updateMilestone(milestone, message));
}
private async updateMilestone(milestone: IMilestone | undefined, message: IRequestMessage<void>) {
if (!milestone) {
return this.removeMilestone(message);
}
await this._item.updateMilestone(milestone.id);
this._replyMessage(message, {
added: milestone,
});
}
private async removeMilestone(message: IRequestMessage<void>): Promise<void> {
try {
await this._item.updateMilestone('null');
this._replyMessage(message, {});
} catch (e) {
vscode.window.showErrorMessage(formatError(e));
}
}
private async changeProjects(message: IRequestMessage<void>): Promise<void> {
return getProjectFromQuickPick(this._folderRepositoryManager, this._item.githubRepository, this._item.item.projectItems?.map(item => item.project), (project) => this.updateProjects(project, message));
}
private async updateProjects(projects: IProject[] | undefined, message: IRequestMessage<void>) {
let newProjects: IProjectItem[] = [];
if (projects) {
newProjects = (await this._item.updateProjects(projects)) ?? [];
}
const projectItemsReply: ProjectItemsReply = {
projectItems: newProjects,
};
return this._replyMessage(message, projectItemsReply);
}
private async removeProject(message: IRequestMessage<IProjectItem>): Promise<void> {
await this._item.removeProjects([message.args]);
return this._replyMessage(message, {});
}
private async addAssigneeYourself(message: IRequestMessage<void>): Promise<void> {
try {
const currentUser = await this._folderRepositoryManager.getCurrentUser();
const alreadyAssigned = this._item.assignees?.find(user => user.login === currentUser.login);
if (!alreadyAssigned) {
const newAssignees = (this._item.assignees ?? []).concat(currentUser);
await this._item.replaceAssignees(newAssignees);
}
const events = await this._getTimeline();
const reply: ChangeAssigneesReply = {
assignees: this._item.assignees ?? [],
events
};
this._replyMessage(message, reply);
} catch (e) {
vscode.window.showErrorMessage(formatError(e));
}
}
private async addAssigneeCopilot(message: IRequestMessage<void>): Promise<void> {
try {
const copilotUser = (await this._folderRepositoryManager.getAssignableUsers())[this._item.remote.remoteName].find(user => COPILOT_ACCOUNTS[user.login]);
if (copilotUser) {
const newAssignees = (this._item.assignees ?? []).concat(copilotUser);
await this._item.replaceAssignees(newAssignees);
}
const events = await this._getTimeline();
const reply: ChangeAssigneesReply = {
assignees: this._item.assignees ?? [],
events
};
this._replyMessage(message, reply);
} catch (e) {
vscode.window.showErrorMessage(formatError(e));
}
}
private async copyItemLink(): Promise<void> {
return vscode.env.clipboard.writeText(this._item.html_url);
}
private async copyVscodeDevLink(): Promise<void> {
return vscode.env.clipboard.writeText(vscodeDevPrLink(this._item));
}
protected editCommentPromise(comment: IComment, text: string): Promise<IComment> {
return this._item.editIssueComment(comment, text);
}
private async editComment(message: IRequestMessage<{ comment: IComment; text: string }>) {
try {
const result = await this.editCommentPromise(message.args.comment, message.args.text);
const bodyHTML = await this.processLinksInBodyHtml(result.bodyHTML);
this._replyMessage(message, { body: result.body, bodyHTML });
} catch (e) {
this._throwError(message, e);
vscode.window.showErrorMessage(formatError(e));
}
}
protected deleteCommentPromise(comment: IComment): Promise<void> {
return this._item.deleteIssueComment(comment.id.toString());
}
private deleteComment(message: IRequestMessage<IComment>) {
vscode.window
.showWarningMessage(vscode.l10n.t('Are you sure you want to delete this comment?'), { modal: true }, 'Delete')
.then(value => {
if (value === 'Delete') {
this.deleteCommentPromise(message.args)
.then(_ => {
this._replyMessage(message, {});
})
.catch(e => {
this._throwError(message, e);
vscode.window.showErrorMessage(formatError(e));
});
}
});
}
protected async openLocalFile(message: IRequestMessage<OpenLocalFileArgs>): Promise<void> {
try {
const { file, startLine, endLine } = message.args;
// Resolve relative path to absolute using repository root
const fileUri = vscode.Uri.joinPath(
this._item.githubRepository.rootUri,
file
);
const selection = new vscode.Range(
new vscode.Position(startLine - 1, 0),
new vscode.Position(endLine - 1, Number.MAX_SAFE_INTEGER)
);
await vscode.window.showTextDocument(fileUri, {
selection,
viewColumn: vscode.ViewColumn.One
});
} catch (e) {
Logger.error(`Open local file failed: ${formatError(e)}`, IssueOverviewPanel.ID);
// Fallback to opening external URL
await vscode.env.openExternal(vscode.Uri.parse(message.args.href));
}
}
protected async close(message: IRequestMessage<string>) {
let comment: IComment | undefined;
if (message.args) {
comment = await this._item.createIssueComment(message.args);
}
const closeUpdate = await this._item.close();
const result: CloseResult = {
state: closeUpdate.item.state.toUpperCase() as GithubItemStateEnum,
commentEvent: comment ? {
...comment,
event: EventType.Commented
} : undefined,
closeEvent: closeUpdate.closedEvent
};
this._replyMessage(message, result);
}
protected _removeFromPanels(): void {
if (this._identity) {
const key = panelKey(this._identity.owner, this._identity.repo, this._identity.number);
// Use the subclass's own static _panels map via this.constructor
(this.constructor as unknown as typeof IssueOverviewPanel)._panels.delete(key);
}
}
public override dispose() {
super.dispose();
this._removeFromPanels();
this._webview = undefined;
}
protected getHtmlForWebview() {
const nonce = generateUuid();
const uri = vscode.Uri.joinPath(this._extensionUri, 'dist', 'webview-pr-description.js');
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src vscode-resource: https:; media-src https:; script-src 'nonce-${nonce}'; style-src vscode-resource: 'unsafe-inline' http: https: data:;">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body class="${process.platform}">
<div id=app></div>
<script nonce="${nonce}" src="${this._webview!.asWebviewUri(uri).toString()}"></script>
</body>
</html>`;
}
public getCurrentTitle(): string {
return this._panel.title;
}
public getCurrentItem(): TItem | undefined {
return this._item;
}
}