forked from microsoft/vscode-pull-request-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathissueOverview.ts
More file actions
401 lines (353 loc) · 11.9 KB
/
issueOverview.ts
File metadata and controls
401 lines (353 loc) · 11.9 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
/*---------------------------------------------------------------------------------------------
* 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 { IComment } from '../common/comment';
import Logger from '../common/logger';
import { formatError } from '../common/utils';
import { getNonce, IRequestMessage, WebviewBase } from '../common/webview';
import { DescriptionNode } from '../view/treeNodes/descriptionNode';
import { OctokitCommon } from './common';
import { FolderRepositoryManager } from './folderRepositoryManager';
import { ILabel } from './interface';
import { IssueModel } from './issueModel';
export class IssueOverviewPanel<TItem extends IssueModel = IssueModel> extends WebviewBase {
public static ID: string = 'PullRequestOverviewPanel';
/**
* Track the currently panel. Only allow a single panel to exist at a time.
*/
public static currentPanel?: IssueOverviewPanel;
protected static readonly _viewType: string = 'IssueOverview';
protected readonly _panel: vscode.WebviewPanel;
protected _disposables: vscode.Disposable[] = [];
protected _descriptionNode: DescriptionNode;
protected _item: TItem;
protected _folderRepositoryManager: FolderRepositoryManager;
protected _scrollPosition = { x: 0, y: 0 };
public static async createOrShow(
extensionUri: vscode.Uri,
folderRepositoryManager: FolderRepositoryManager,
issue: IssueModel,
toTheSide: Boolean = false,
) {
const activeColumn = toTheSide
? vscode.ViewColumn.Beside
: vscode.window.activeTextEditor
? vscode.window.activeTextEditor.viewColumn
: vscode.ViewColumn.One;
// If we already have a panel, show it.
// Otherwise, create a new panel.
if (IssueOverviewPanel.currentPanel) {
IssueOverviewPanel.currentPanel._panel.reveal(activeColumn, true);
} else {
const title = `Issue #${issue.number.toString()}`;
IssueOverviewPanel.currentPanel = new IssueOverviewPanel(
extensionUri,
activeColumn || vscode.ViewColumn.Active,
title,
folderRepositoryManager,
);
}
await IssueOverviewPanel.currentPanel!.update(folderRepositoryManager, issue);
}
public static refresh(): void {
if (this.currentPanel) {
this.currentPanel.refreshPanel();
}
}
protected constructor(
private readonly _extensionUri: vscode.Uri,
column: vscode.ViewColumn,
title: string,
folderRepositoryManager: FolderRepositoryManager,
type: string = IssueOverviewPanel._viewType,
) {
super();
this._folderRepositoryManager = folderRepositoryManager;
// Create and show a new webview panel
this._panel = 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')],
});
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._panel.onDidDispose(() => this.dispose(), null, this._disposables);
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,
});
}
},
null,
this._disposables,
);
}
public async refreshPanel(): Promise<void> {
if (this._panel && this._panel.visible) {
this.update(this._folderRepositoryManager, this._item);
}
}
public async updateIssue(issueModel: IssueModel): Promise<void> {
return Promise.all([
this._folderRepositoryManager.resolveIssue(
issueModel.remote.owner,
issueModel.remote.repositoryName,
issueModel.number,
),
issueModel.getIssueTimelineEvents(),
this._folderRepositoryManager.getPullRequestRepositoryDefaultBranch(issueModel),
])
.then(result => {
const [issue, timelineEvents, defaultBranch] = result;
if (!issue) {
throw new Error(
`Fail to resolve issue #${issueModel.number} in ${issueModel.remote.owner}/${issueModel.remote.repositoryName}`,
);
}
this._item = issue as TItem;
this._panel.title = `Pull Request #${issueModel.number.toString()}`;
Logger.debug('pr.initialize', IssueOverviewPanel.ID);
this._postMessage({
command: 'pr.initialize',
pullrequest: {
number: this._item.number,
title: this._item.title,
url: this._item.html_url,
createdAt: this._item.createdAt,
body: this._item.body,
bodyHTML: this._item.bodyHTML,
labels: this._item.item.labels,
author: {
login: this._item.author.login,
name: this._item.author.name,
avatarUrl: this._item.userAvatar,
url: this._item.author.url,
},
state: this._item.state,
events: timelineEvents,
repositoryDefaultBranch: defaultBranch,
canEdit: true,
// TODO@eamodio What is status?
status: /*status ? status :*/ { statuses: [] },
isIssue: true,
},
});
})
.catch(e => {
vscode.window.showErrorMessage(formatError(e));
});
}
public async update(foldersManager: FolderRepositoryManager, issueModel: IssueModel): Promise<void> {
this._folderRepositoryManager = foldersManager;
this._postMessage({
command: 'set-scroll',
scrollPosition: this._scrollPosition,
});
this._panel.webview.html = this.getHtmlForWebview(issueModel.number.toString());
return this.updateIssue(issueModel);
}
protected 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.comment':
return this.createComment(message);
case 'scroll':
this._scrollPosition = message.args;
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.debug':
return this.webviewDebug(message);
default:
return this.MESSAGE_UNHANDLED;
}
}
private async addLabels(message: IRequestMessage<void>): Promise<void> {
try {
let newLabels: ILabel[] = [];
async function getLabelOptions(
folderRepoManager: FolderRepositoryManager,
issue: IssueModel,
): Promise<vscode.QuickPickItem[]> {
const allLabels = await folderRepoManager.getLabels(issue);
newLabels = allLabels.filter(l => !issue.item.labels.some(label => label.name === l.name));
return newLabels.map(label => {
return {
label: label.name,
};
});
}
const labelsToAdd = await vscode.window.showQuickPick(
getLabelOptions(this._folderRepositoryManager, this._item),
{ canPickMany: true },
);
if (labelsToAdd && labelsToAdd.length) {
await this._item.addLabels(labelsToAdd.map(r => r.label));
const addedLabels: ILabel[] = labelsToAdd.map(label => newLabels.find(l => l.name === label.label)!);
this._item.item.labels = this._item.item.labels.concat(...addedLabels);
this._replyMessage(message, {
added: addedLabels,
});
}
} catch (e) {
vscode.window.showErrorMessage(formatError(e));
}
}
private async removeLabel(message: IRequestMessage<string>): Promise<void> {
try {
await this._item.removeLabel(message.args);
const index = this._item.item.labels.findIndex(label => label.name === message.args);
this._item.item.labels.splice(index, 1);
this._replyMessage(message, {});
} catch (e) {
vscode.window.showErrorMessage(formatError(e));
}
}
private webviewDebug(message: IRequestMessage<string>): void {
Logger.debug(message.args, IssueOverviewPanel.ID);
}
private editDescription(message: IRequestMessage<{ text: string }>) {
this._item
.edit({ body: message.args.text })
.then(result => {
this._replyMessage(message, { body: result.body, bodyHTML: result.bodyHTML });
})
.catch(e => {
this._throwError(message, e);
vscode.window.showErrorMessage(`Editing description failed: ${formatError(e)}`);
});
}
private editTitle(message: IRequestMessage<{ text: string }>) {
this._item
.edit({ title: message.args.text })
.then(result => {
this._replyMessage(message, { text: result.title });
})
.catch(e => {
this._throwError(message, e);
vscode.window.showErrorMessage(`Editing title failed: ${formatError(e)}`);
});
}
protected editCommentPromise(comment: IComment, text: string): Promise<IComment> {
return this._item.editIssueComment(comment, text);
}
private editComment(message: IRequestMessage<{ comment: IComment; text: string }>) {
this.editCommentPromise(message.args.comment, message.args.text)
.then(result => {
this._replyMessage(message, {
body: result.body,
bodyHTML: result.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('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));
});
}
});
}
private close(message: IRequestMessage<string>): void {
vscode.commands
.executeCommand<OctokitCommon.PullsGetResponseData>('pr.close', this._item, message.args)
.then(comment => {
if (comment) {
this._replyMessage(message, {
value: comment,
});
} else {
this._throwError(message, 'Close cancelled');
}
});
}
private createComment(message: IRequestMessage<string>) {
this._item.createIssueComment(message.args).then(comment => {
this._replyMessage(message, {
value: comment,
});
});
}
protected set _currentPanel(panel: IssueOverviewPanel | undefined) {
IssueOverviewPanel.currentPanel = panel;
}
public dispose() {
this._currentPanel = undefined;
// Clean up our resources
this._panel.dispose();
this._webview = undefined;
while (this._disposables.length) {
const x = this._disposables.pop();
if (x) {
x.dispose();
}
}
}
protected getHtmlForWebview(number: string) {
const nonce = getNonce();
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:; script-src 'nonce-${nonce}'; style-src vscode-resource: 'unsafe-inline' http: https: data:;">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pull Request #${number}</title>
</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;
}
}