forked from microsoft/vscode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
issueReporterService.ts
1402 lines (1197 loc) · 49.7 KB
/
issueReporterService.ts
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
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { $, createStyleSheet, reset, windowOpenNoOpener } from 'vs/base/browser/dom';
import { Button, unthemedButtonStyles } from 'vs/base/browser/ui/button/button';
import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';
import { mainWindow } from 'vs/base/browser/window';
import { Delayer, RunOnceScheduler } from 'vs/base/common/async';
import { Codicon } from 'vs/base/common/codicons';
import { groupBy } from 'vs/base/common/collections';
import { debounce } from 'vs/base/common/decorators';
import { CancellationError } from 'vs/base/common/errors';
import { Disposable } from 'vs/base/common/lifecycle';
import { isLinuxSnap, isMacintosh } from 'vs/base/common/platform';
import { escape } from 'vs/base/common/strings';
import { ThemeIcon } from 'vs/base/common/themables';
import { IssueReporterModel, IssueReporterData as IssueReporterModelData } from 'vs/code/electron-sandbox/issue/issueReporterModel';
import { localize } from 'vs/nls';
import { isRemoteDiagnosticError } from 'vs/platform/diagnostics/common/diagnostics';
import { IIssueMainService, IssueReporterData, IssueReporterExtensionData, IssueReporterStyles, IssueReporterWindowConfiguration, IssueType } from 'vs/platform/issue/common/issue';
import { normalizeGitHubUrl } from 'vs/platform/issue/common/issueReporterUtil';
import { INativeHostService } from 'vs/platform/native/common/native';
import { getIconsStyleSheet } from 'vs/platform/theme/browser/iconsStyleSheet';
import { applyZoom, zoomIn, zoomOut } from 'vs/platform/window/electron-sandbox/window';
// GitHub has let us know that we could up our limit here to 8k. We chose 7500 to play it safe.
// ref https://github.com/microsoft/vscode/issues/159191
const MAX_URL_LENGTH = 7500;
interface SearchResult {
html_url: string;
title: string;
state?: string;
}
enum IssueSource {
VSCode = 'vscode',
Extension = 'extension',
Marketplace = 'marketplace'
}
export class IssueReporter extends Disposable {
private readonly issueReporterModel: IssueReporterModel;
private numberOfSearchResultsDisplayed = 0;
private receivedSystemInfo = false;
private receivedExtensionData = false;
private receivedPerformanceInfo = false;
private shouldQueueSearch = false;
private hasBeenSubmitted = false;
private delayedSubmit = new Delayer<void>(300);
private readonly previewButton!: Button;
constructor(
private readonly configuration: IssueReporterWindowConfiguration,
@INativeHostService private readonly nativeHostService: INativeHostService,
@IIssueMainService private readonly issueMainService: IIssueMainService
) {
super();
const targetExtension = configuration.data.extensionId ? configuration.data.enabledExtensions.find(extension => extension.id.toLocaleLowerCase() === configuration.data.extensionId?.toLocaleLowerCase()) : undefined;
this.issueReporterModel = new IssueReporterModel({
...configuration.data,
issueType: configuration.data.issueType || IssueType.Bug,
versionInfo: {
vscodeVersion: `${configuration.product.nameShort} ${!!configuration.product.darwinUniversalAssetId ? `${configuration.product.version} (Universal)` : configuration.product.version} (${configuration.product.commit || 'Commit unknown'}, ${configuration.product.date || 'Date unknown'})`,
os: `${this.configuration.os.type} ${this.configuration.os.arch} ${this.configuration.os.release}${isLinuxSnap ? ' snap' : ''}`
},
extensionsDisabled: !!configuration.disableExtensions,
fileOnExtension: configuration.data.extensionId ? !targetExtension?.isBuiltin : undefined,
selectedExtension: targetExtension
});
//TODO: Handle case where extension is not activated
const issueReporterElement = this.getElementById('issue-reporter');
if (issueReporterElement) {
this.previewButton = new Button(issueReporterElement, unthemedButtonStyles);
this.updatePreviewButtonState();
}
const issueTitle = configuration.data.issueTitle;
if (issueTitle) {
const issueTitleElement = this.getElementById<HTMLInputElement>('issue-title');
if (issueTitleElement) {
issueTitleElement.value = issueTitle;
}
}
const issueBody = configuration.data.issueBody;
if (issueBody) {
const description = this.getElementById<HTMLTextAreaElement>('description');
if (description) {
description.value = issueBody;
this.issueReporterModel.update({ issueDescription: issueBody });
}
}
this.issueMainService.$getSystemInfo().then(info => {
this.issueReporterModel.update({ systemInfo: info });
this.receivedSystemInfo = true;
this.updateSystemInfo(this.issueReporterModel.getData());
this.updatePreviewButtonState();
});
if (configuration.data.issueType === IssueType.PerformanceIssue) {
this.issueMainService.$getPerformanceInfo().then(info => {
this.updatePerformanceInfo(info as Partial<IssueReporterData>);
});
}
if (mainWindow.document.documentElement.lang !== 'en') {
show(this.getElementById('english'));
}
const codiconStyleSheet = createStyleSheet();
codiconStyleSheet.id = 'codiconStyles';
// TODO: Is there a way to use the IThemeService here instead
const iconsStyleSheet = getIconsStyleSheet(undefined);
function updateAll() {
codiconStyleSheet.textContent = iconsStyleSheet.getCSS();
}
const delayer = new RunOnceScheduler(updateAll, 0);
iconsStyleSheet.onDidChange(() => delayer.schedule());
delayer.schedule();
this.setUpTypes();
this.setEventHandlers();
applyZoom(configuration.data.zoomLevel);
this.applyStyles(configuration.data.styles);
this.handleExtensionData(configuration.data.enabledExtensions);
this.updateExperimentsInfo(configuration.data.experiments);
this.updateRestrictedMode(configuration.data.restrictedMode);
this.updateUnsupportedMode(configuration.data.isUnsupported);
// Handle case where extension is pre-selected through the command
if (configuration.data.command && targetExtension) {
this.updateExtensionStatus(targetExtension);
}
}
render(): void {
this.renderBlocks();
}
setInitialFocus() {
const { fileOnExtension } = this.issueReporterModel.getData();
if (fileOnExtension) {
const issueTitle = mainWindow.document.getElementById('issue-title');
issueTitle?.focus();
} else {
const issueType = mainWindow.document.getElementById('issue-type');
issueType?.focus();
}
}
private applyStyles(styles: IssueReporterStyles) {
const styleTag = document.createElement('style');
const content: string[] = [];
if (styles.inputBackground) {
content.push(`input[type="text"], textarea, select, .issues-container > .issue > .issue-state, .block-info { background-color: ${styles.inputBackground}; }`);
}
if (styles.inputBorder) {
content.push(`input[type="text"], textarea, select { border: 1px solid ${styles.inputBorder}; }`);
} else {
content.push(`input[type="text"], textarea, select { border: 1px solid transparent; }`);
}
if (styles.inputForeground) {
content.push(`input[type="text"], textarea, select, .issues-container > .issue > .issue-state, .block-info { color: ${styles.inputForeground}; }`);
}
if (styles.inputErrorBorder) {
content.push(`.invalid-input, .invalid-input:focus, .validation-error { border: 1px solid ${styles.inputErrorBorder} !important; }`);
content.push(`.required-input { color: ${styles.inputErrorBorder}; }`);
}
if (styles.inputErrorBackground) {
content.push(`.validation-error { background: ${styles.inputErrorBackground}; }`);
}
if (styles.inputErrorForeground) {
content.push(`.validation-error { color: ${styles.inputErrorForeground}; }`);
}
if (styles.inputActiveBorder) {
content.push(`input[type='text']:focus, textarea:focus, select:focus, summary:focus, button:focus, a:focus, .workbenchCommand:focus { border: 1px solid ${styles.inputActiveBorder}; outline-style: none; }`);
}
if (styles.textLinkColor) {
content.push(`a, .workbenchCommand { color: ${styles.textLinkColor}; }`);
}
if (styles.textLinkColor) {
content.push(`a { color: ${styles.textLinkColor}; }`);
}
if (styles.textLinkActiveForeground) {
content.push(`a:hover, .workbenchCommand:hover { color: ${styles.textLinkActiveForeground}; }`);
}
if (styles.sliderBackgroundColor) {
content.push(`::-webkit-scrollbar-thumb { background-color: ${styles.sliderBackgroundColor}; }`);
}
if (styles.sliderActiveColor) {
content.push(`::-webkit-scrollbar-thumb:active { background-color: ${styles.sliderActiveColor}; }`);
}
if (styles.sliderHoverColor) {
content.push(`::--webkit-scrollbar-thumb:hover { background-color: ${styles.sliderHoverColor}; }`);
}
if (styles.buttonBackground) {
content.push(`.monaco-text-button { background-color: ${styles.buttonBackground} !important; }`);
}
if (styles.buttonForeground) {
content.push(`.monaco-text-button { color: ${styles.buttonForeground} !important; }`);
}
if (styles.buttonHoverBackground) {
content.push(`.monaco-text-button:not(.disabled):hover, .monaco-text-button:focus { background-color: ${styles.buttonHoverBackground} !important; }`);
}
styleTag.textContent = content.join('\n');
mainWindow.document.head.appendChild(styleTag);
mainWindow.document.body.style.color = styles.color || '';
}
private handleExtensionData(extensions: IssueReporterExtensionData[]) {
const installedExtensions = extensions.filter(x => !x.isBuiltin);
const { nonThemes, themes } = groupBy(installedExtensions, ext => {
return ext.isTheme ? 'themes' : 'nonThemes';
});
const numberOfThemeExtesions = themes && themes.length;
this.issueReporterModel.update({ numberOfThemeExtesions, enabledNonThemeExtesions: nonThemes, allExtensions: installedExtensions });
this.updateExtensionTable(nonThemes, numberOfThemeExtesions);
if (this.configuration.disableExtensions || installedExtensions.length === 0) {
(<HTMLButtonElement>this.getElementById('disableExtensions')).disabled = true;
}
this.updateExtensionSelector(installedExtensions);
}
private async updateIssueReporterUri(extension: IssueReporterExtensionData): Promise<void> {
try {
const uri = await this.issueMainService.$getIssueReporterUri(extension.id);
extension.bugsUrl = uri.toString(true);
} catch (e) {
extension.hasIssueUriRequestHandler = false;
// The issue handler failed so fall back to old issue reporter experience.
this.renderBlocks();
}
}
private async getIssueDataFromExtension(extension: IssueReporterExtensionData): Promise<string> {
try {
const data = await this.issueMainService.$getIssueReporterData(extension.id);
extension.extensionData = data;
this.receivedExtensionData = true;
this.issueReporterModel.update({ extensionData: data });
return data;
} catch (e) {
extension.hasIssueDataProviders = false;
// The issue handler failed so fall back to old issue reporter experience.
this.renderBlocks();
throw e;
}
}
private async getIssueTemplateFromExtension(extension: IssueReporterExtensionData): Promise<string> {
try {
const data = await this.issueMainService.$getIssueReporterTemplate(extension.id);
extension.extensionTemplate = data;
return data;
} catch (e) {
throw e;
}
}
private async getReporterStatus(extension: IssueReporterExtensionData): Promise<boolean[]> {
try {
const data = await this.issueMainService.$getReporterStatus(extension.id, extension.name);
return data;
} catch (e) {
console.error(e);
return [false, false];
}
}
private setEventHandlers(): void {
this.addEventListener('issue-type', 'change', (event: Event) => {
const issueType = parseInt((<HTMLInputElement>event.target).value);
this.issueReporterModel.update({ issueType: issueType });
if (issueType === IssueType.PerformanceIssue && !this.receivedPerformanceInfo) {
this.issueMainService.$getPerformanceInfo().then(info => {
this.updatePerformanceInfo(info as Partial<IssueReporterData>);
});
}
this.updatePreviewButtonState();
this.setSourceOptions();
this.render();
});
(['includeSystemInfo', 'includeProcessInfo', 'includeWorkspaceInfo', 'includeExtensions', 'includeExperiments', 'includeExtensionData'] as const).forEach(elementId => {
this.addEventListener(elementId, 'click', (event: Event) => {
event.stopPropagation();
this.issueReporterModel.update({ [elementId]: !this.issueReporterModel.getData()[elementId] });
});
});
const showInfoElements = mainWindow.document.getElementsByClassName('showInfo');
for (let i = 0; i < showInfoElements.length; i++) {
const showInfo = showInfoElements.item(i)!;
(showInfo as HTMLAnchorElement).addEventListener('click', (e: MouseEvent) => {
e.preventDefault();
const label = (<HTMLDivElement>e.target);
if (label) {
const containingElement = label.parentElement && label.parentElement.parentElement;
const info = containingElement && containingElement.lastElementChild;
if (info && info.classList.contains('hidden')) {
show(info);
label.textContent = localize('hide', "hide");
} else {
hide(info);
label.textContent = localize('show', "show");
}
}
});
}
this.addEventListener('issue-source', 'change', (e: Event) => {
const value = (<HTMLInputElement>e.target).value;
const problemSourceHelpText = this.getElementById('problem-source-help-text')!;
if (value === '') {
this.issueReporterModel.update({ fileOnExtension: undefined });
show(problemSourceHelpText);
this.clearSearchResults();
this.render();
return;
} else {
hide(problemSourceHelpText);
}
let fileOnExtension, fileOnMarketplace = false;
if (value === IssueSource.Extension) {
fileOnExtension = true;
} else if (value === IssueSource.Marketplace) {
fileOnMarketplace = true;
}
this.issueReporterModel.update({ fileOnExtension, fileOnMarketplace });
this.render();
const title = (<HTMLInputElement>this.getElementById('issue-title')).value;
this.searchIssues(title, fileOnExtension, fileOnMarketplace);
});
this.addEventListener('description', 'input', (e: Event) => {
const issueDescription = (<HTMLInputElement>e.target).value;
this.issueReporterModel.update({ issueDescription });
// Only search for extension issues on title change
if (this.issueReporterModel.fileOnExtension() === false) {
const title = (<HTMLInputElement>this.getElementById('issue-title')).value;
this.searchVSCodeIssues(title, issueDescription);
}
});
this.addEventListener('issue-title', 'input', (e: Event) => {
const title = (<HTMLInputElement>e.target).value;
const lengthValidationMessage = this.getElementById('issue-title-length-validation-error');
const issueUrl = this.getIssueUrl();
if (title && this.getIssueUrlWithTitle(title, issueUrl).length > MAX_URL_LENGTH) {
show(lengthValidationMessage);
} else {
hide(lengthValidationMessage);
}
const issueSource = this.getElementById<HTMLSelectElement>('issue-source');
if (!issueSource || issueSource.value === '') {
return;
}
const { fileOnExtension, fileOnMarketplace } = this.issueReporterModel.getData();
this.searchIssues(title, fileOnExtension, fileOnMarketplace);
});
this.previewButton.onDidClick(async () => {
this.delayedSubmit.trigger(async () => {
this.createIssue();
});
});
this.addEventListener('disableExtensions', 'click', () => {
this.issueMainService.$reloadWithExtensionsDisabled();
});
this.addEventListener('extensionBugsLink', 'click', (e: Event) => {
const url = (<HTMLElement>e.target).innerText;
windowOpenNoOpener(url);
});
this.addEventListener('disableExtensions', 'keydown', (e: Event) => {
e.stopPropagation();
if ((e as KeyboardEvent).keyCode === 13 || (e as KeyboardEvent).keyCode === 32) {
this.issueMainService.$reloadWithExtensionsDisabled();
}
});
mainWindow.document.onkeydown = async (e: KeyboardEvent) => {
const cmdOrCtrlKey = isMacintosh ? e.metaKey : e.ctrlKey;
// Cmd/Ctrl+Enter previews issue and closes window
if (cmdOrCtrlKey && e.keyCode === 13) {
this.delayedSubmit.trigger(async () => {
if (await this.createIssue()) {
this.close();
}
});
}
// Cmd/Ctrl + w closes issue window
if (cmdOrCtrlKey && e.keyCode === 87) {
e.stopPropagation();
e.preventDefault();
const issueTitle = (<HTMLInputElement>this.getElementById('issue-title'))!.value;
const { issueDescription } = this.issueReporterModel.getData();
if (!this.hasBeenSubmitted && (issueTitle || issueDescription)) {
// fire and forget
this.issueMainService.$showConfirmCloseDialog();
} else {
this.close();
}
}
// Cmd/Ctrl + zooms in
if (cmdOrCtrlKey && e.keyCode === 187) {
zoomIn();
}
// Cmd/Ctrl - zooms out
if (cmdOrCtrlKey && e.keyCode === 189) {
zoomOut();
}
// With latest electron upgrade, cmd+a is no longer propagating correctly for inputs in this window on mac
// Manually perform the selection
if (isMacintosh) {
if (cmdOrCtrlKey && e.keyCode === 65 && e.target) {
if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
(<HTMLInputElement>e.target).select();
}
}
}
};
}
private updatePerformanceInfo(info: Partial<IssueReporterData>) {
this.issueReporterModel.update(info);
this.receivedPerformanceInfo = true;
const state = this.issueReporterModel.getData();
this.updateProcessInfo(state);
this.updateWorkspaceInfo(state);
this.updatePreviewButtonState();
}
private updatePreviewButtonState() {
if (this.isPreviewEnabled()) {
if (this.configuration.data.githubAccessToken) {
this.previewButton.label = localize('createOnGitHub', "Create on GitHub");
} else {
this.previewButton.label = localize('previewOnGitHub', "Preview on GitHub");
}
this.previewButton.enabled = true;
} else {
this.previewButton.enabled = false;
this.previewButton.label = localize('loadingData', "Loading data...");
}
}
private isPreviewEnabled() {
const issueType = this.issueReporterModel.getData().issueType;
if (this.issueReporterModel.getData().selectedExtension?.hasIssueDataProviders && !this.receivedExtensionData) {
return false;
}
if (issueType === IssueType.Bug && this.receivedSystemInfo) {
return true;
}
if (issueType === IssueType.PerformanceIssue && this.receivedSystemInfo && this.receivedPerformanceInfo) {
return true;
}
if (issueType === IssueType.FeatureRequest) {
return true;
}
return false;
}
private getExtensionRepositoryUrl(): string | undefined {
const selectedExtension = this.issueReporterModel.getData().selectedExtension;
return selectedExtension && selectedExtension.repositoryUrl;
}
private getExtensionBugsUrl(): string | undefined {
const selectedExtension = this.issueReporterModel.getData().selectedExtension;
return selectedExtension && selectedExtension.bugsUrl;
}
private getExtensionData(): string | undefined {
return this.issueReporterModel.getData().selectedExtension?.extensionData;
}
private searchVSCodeIssues(title: string, issueDescription?: string): void {
if (title) {
this.searchDuplicates(title, issueDescription);
} else {
this.clearSearchResults();
}
}
private searchIssues(title: string, fileOnExtension: boolean | undefined, fileOnMarketplace: boolean | undefined): void {
if (fileOnExtension) {
return this.searchExtensionIssues(title);
}
if (fileOnMarketplace) {
return this.searchMarketplaceIssues(title);
}
const description = this.issueReporterModel.getData().issueDescription;
this.searchVSCodeIssues(title, description);
}
private searchExtensionIssues(title: string): void {
const url = this.getExtensionGitHubUrl();
if (title) {
const matches = /^https?:\/\/github\.com\/(.*)/.exec(url);
if (matches && matches.length) {
const repo = matches[1];
return this.searchGitHub(repo, title);
}
// If the extension has no repository, display empty search results
if (this.issueReporterModel.getData().selectedExtension) {
this.clearSearchResults();
return this.displaySearchResults([]);
}
}
this.clearSearchResults();
}
private searchMarketplaceIssues(title: string): void {
if (title) {
const gitHubInfo = this.parseGitHubUrl(this.configuration.product.reportMarketplaceIssueUrl!);
if (gitHubInfo) {
return this.searchGitHub(`${gitHubInfo.owner}/${gitHubInfo.repositoryName}`, title);
}
}
}
private async close(): Promise<void> {
await this.issueMainService.$closeReporter();
}
private clearSearchResults(): void {
const similarIssues = this.getElementById('similar-issues')!;
similarIssues.innerText = '';
this.numberOfSearchResultsDisplayed = 0;
}
@debounce(300)
private searchGitHub(repo: string, title: string): void {
const query = `is:issue+repo:${repo}+${title}`;
const similarIssues = this.getElementById('similar-issues')!;
fetch(`https://api.github.com/search/issues?q=${query}`).then((response) => {
response.json().then(result => {
similarIssues.innerText = '';
if (result && result.items) {
this.displaySearchResults(result.items);
} else {
// If the items property isn't present, the rate limit has been hit
const message = $('div.list-title');
message.textContent = localize('rateLimited', "GitHub query limit exceeded. Please wait.");
similarIssues.appendChild(message);
const resetTime = response.headers.get('X-RateLimit-Reset');
const timeToWait = resetTime ? parseInt(resetTime) - Math.floor(Date.now() / 1000) : 1;
if (this.shouldQueueSearch) {
this.shouldQueueSearch = false;
setTimeout(() => {
this.searchGitHub(repo, title);
this.shouldQueueSearch = true;
}, timeToWait * 1000);
}
}
}).catch(_ => {
// Ignore
});
}).catch(_ => {
// Ignore
});
}
@debounce(300)
private searchDuplicates(title: string, body?: string): void {
const url = 'https://vscode-probot.westus.cloudapp.azure.com:7890/duplicate_candidates';
const init = {
method: 'POST',
body: JSON.stringify({
title,
body
}),
headers: new Headers({
'Content-Type': 'application/json'
})
};
fetch(url, init).then((response) => {
response.json().then(result => {
this.clearSearchResults();
if (result && result.candidates) {
this.displaySearchResults(result.candidates);
} else {
throw new Error('Unexpected response, no candidates property');
}
}).catch(_ => {
// Ignore
});
}).catch(_ => {
// Ignore
});
}
private displaySearchResults(results: SearchResult[]) {
const similarIssues = this.getElementById('similar-issues')!;
if (results.length) {
const issues = $('div.issues-container');
const issuesText = $('div.list-title');
issuesText.textContent = localize('similarIssues', "Similar issues");
this.numberOfSearchResultsDisplayed = results.length < 5 ? results.length : 5;
for (let i = 0; i < this.numberOfSearchResultsDisplayed; i++) {
const issue = results[i];
const link = $('a.issue-link', { href: issue.html_url });
link.textContent = issue.title;
link.title = issue.title;
link.addEventListener('click', (e) => this.openLink(e));
link.addEventListener('auxclick', (e) => this.openLink(<MouseEvent>e));
let issueState: HTMLElement;
let item: HTMLElement;
if (issue.state) {
issueState = $('span.issue-state');
const issueIcon = $('span.issue-icon');
issueIcon.appendChild(renderIcon(issue.state === 'open' ? Codicon.issueOpened : Codicon.issueClosed));
const issueStateLabel = $('span.issue-state.label');
issueStateLabel.textContent = issue.state === 'open' ? localize('open', "Open") : localize('closed', "Closed");
issueState.title = issue.state === 'open' ? localize('open', "Open") : localize('closed', "Closed");
issueState.appendChild(issueIcon);
issueState.appendChild(issueStateLabel);
item = $('div.issue', undefined, issueState, link);
} else {
item = $('div.issue', undefined, link);
}
issues.appendChild(item);
}
similarIssues.appendChild(issuesText);
similarIssues.appendChild(issues);
} else {
const message = $('div.list-title');
message.textContent = localize('noSimilarIssues', "No similar issues found");
similarIssues.appendChild(message);
}
}
private setUpTypes(): void {
const makeOption = (issueType: IssueType, description: string) => $('option', { 'value': issueType.valueOf() }, escape(description));
const typeSelect = this.getElementById('issue-type')! as HTMLSelectElement;
const { issueType } = this.issueReporterModel.getData();
reset(typeSelect,
makeOption(IssueType.Bug, localize('bugReporter', "Bug Report")),
makeOption(IssueType.FeatureRequest, localize('featureRequest', "Feature Request")),
makeOption(IssueType.PerformanceIssue, localize('performanceIssue', "Performance Issue"))
);
typeSelect.value = issueType.toString();
this.setSourceOptions();
}
private makeOption(value: string, description: string, disabled: boolean): HTMLOptionElement {
const option: HTMLOptionElement = document.createElement('option');
option.disabled = disabled;
option.value = value;
option.textContent = description;
return option;
}
private setSourceOptions(): void {
const sourceSelect = this.getElementById('issue-source')! as HTMLSelectElement;
const { issueType, fileOnExtension, selectedExtension } = this.issueReporterModel.getData();
let selected = sourceSelect.selectedIndex;
if (selected === -1) {
if (fileOnExtension !== undefined) {
selected = fileOnExtension ? 2 : 1;
} else if (selectedExtension?.isBuiltin) {
selected = 1;
}
}
sourceSelect.innerText = '';
sourceSelect.append(this.makeOption('', localize('selectSource', "Select source"), true));
sourceSelect.append(this.makeOption('vscode', localize('vscode', "Visual Studio Code"), false));
sourceSelect.append(this.makeOption('extension', localize('extension', "An extension"), false));
if (this.configuration.product.reportMarketplaceIssueUrl) {
sourceSelect.append(this.makeOption('marketplace', localize('marketplace', "Extensions marketplace"), false));
}
if (issueType !== IssueType.FeatureRequest) {
sourceSelect.append(this.makeOption('unknown', localize('unknown', "Don't know"), false));
}
if (selected !== -1 && selected < sourceSelect.options.length) {
sourceSelect.selectedIndex = selected;
} else {
sourceSelect.selectedIndex = 0;
hide(this.getElementById('problem-source-help-text'));
}
}
private renderBlocks(): void {
// Depending on Issue Type, we render different blocks and text
const { issueType, fileOnExtension, fileOnMarketplace, selectedExtension } = this.issueReporterModel.getData();
const blockContainer = this.getElementById('block-container');
const systemBlock = mainWindow.document.querySelector('.block-system');
const processBlock = mainWindow.document.querySelector('.block-process');
const workspaceBlock = mainWindow.document.querySelector('.block-workspace');
const extensionsBlock = mainWindow.document.querySelector('.block-extensions');
const experimentsBlock = mainWindow.document.querySelector('.block-experiments');
const extensionDataBlock = mainWindow.document.querySelector('.block-extension-data');
const problemSource = this.getElementById('problem-source')!;
const descriptionTitle = this.getElementById('issue-description-label')!;
const descriptionSubtitle = this.getElementById('issue-description-subtitle')!;
const extensionSelector = this.getElementById('extension-selection')!;
const titleTextArea = this.getElementById('issue-title-container')!;
const descriptionTextArea = this.getElementById('description')!;
const extensionDataTextArea = this.getElementById('extension-data')!;
// Hide all by default
hide(blockContainer);
hide(systemBlock);
hide(processBlock);
hide(workspaceBlock);
hide(extensionsBlock);
hide(experimentsBlock);
hide(extensionSelector);
hide(extensionDataTextArea);
hide(extensionDataBlock);
show(problemSource);
show(titleTextArea);
show(descriptionTextArea);
if (fileOnExtension) {
show(extensionSelector);
}
if (fileOnExtension && selectedExtension?.hasIssueUriRequestHandler && !selectedExtension.hasIssueDataProviders) {
hide(titleTextArea);
hide(descriptionTextArea);
reset(descriptionTitle, localize('handlesIssuesElsewhere', "This extension handles issues outside of VS Code"));
reset(descriptionSubtitle, localize('elsewhereDescription', "The '{0}' extension prefers to use an external issue reporter. To be taken to that issue reporting experience, click the button below.", selectedExtension.displayName));
this.previewButton.label = localize('openIssueReporter', "Open External Issue Reporter");
return;
}
if (fileOnExtension && selectedExtension?.hasIssueDataProviders) {
const data = this.getExtensionData();
if (data) {
(extensionDataTextArea as HTMLElement).innerText = data.toString();
}
(extensionDataTextArea as HTMLTextAreaElement).readOnly = true;
show(extensionDataBlock);
}
if (issueType === IssueType.Bug) {
if (!fileOnMarketplace) {
show(blockContainer);
show(systemBlock);
show(experimentsBlock);
if (!fileOnExtension) {
show(extensionsBlock);
}
}
reset(descriptionTitle, localize('stepsToReproduce', "Steps to Reproduce") + ' ', $('span.required-input', undefined, '*'));
reset(descriptionSubtitle, localize('bugDescription', "Share the steps needed to reliably reproduce the problem. Please include actual and expected results. We support GitHub-flavored Markdown. You will be able to edit your issue and add screenshots when we preview it on GitHub."));
} else if (issueType === IssueType.PerformanceIssue) {
if (!fileOnMarketplace) {
show(blockContainer);
show(systemBlock);
show(processBlock);
show(workspaceBlock);
show(experimentsBlock);
}
if (fileOnExtension) {
show(extensionSelector);
} else if (!fileOnMarketplace) {
show(extensionsBlock);
}
reset(descriptionTitle, localize('stepsToReproduce', "Steps to Reproduce") + ' ', $('span.required-input', undefined, '*'));
reset(descriptionSubtitle, localize('performanceIssueDesciption', "When did this performance issue happen? Does it occur on startup or after a specific series of actions? We support GitHub-flavored Markdown. You will be able to edit your issue and add screenshots when we preview it on GitHub."));
} else if (issueType === IssueType.FeatureRequest) {
reset(descriptionTitle, localize('description', "Description") + ' ', $('span.required-input', undefined, '*'));
reset(descriptionSubtitle, localize('featureRequestDescription', "Please describe the feature you would like to see. We support GitHub-flavored Markdown. You will be able to edit your issue and add screenshots when we preview it on GitHub."));
}
}
private validateInput(inputId: string): boolean {
const inputElement = (<HTMLInputElement>this.getElementById(inputId));
const inputValidationMessage = this.getElementById(`${inputId}-empty-error`);
if (!inputElement.value) {
inputElement.classList.add('invalid-input');
inputValidationMessage?.classList.remove('hidden');
return false;
} else {
inputElement.classList.remove('invalid-input');
inputValidationMessage?.classList.add('hidden');
return true;
}
}
private validateInputs(): boolean {
let isValid = true;
['issue-title', 'description', 'issue-source'].forEach(elementId => {
isValid = this.validateInput(elementId) && isValid;
});
if (this.issueReporterModel.fileOnExtension()) {
isValid = this.validateInput('extension-selector') && isValid;
}
return isValid;
}
private async submitToGitHub(issueTitle: string, issueBody: string, gitHubDetails: { owner: string; repositoryName: string }): Promise<boolean> {
const url = `https://api.github.com/repos/${gitHubDetails.owner}/${gitHubDetails.repositoryName}/issues`;
const init = {
method: 'POST',
body: JSON.stringify({
title: issueTitle,
body: issueBody
}),
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.configuration.data.githubAccessToken}`
})
};
const response = await fetch(url, init);
if (!response.ok) {
return false;
}
const result = await response.json();
await this.nativeHostService.openExternal(result.html_url);
this.close();
return true;
}
private async createIssue(): Promise<boolean> {
const hasUri = this.issueReporterModel.getData().selectedExtension?.hasIssueUriRequestHandler;
const hasData = this.issueReporterModel.getData().selectedExtension?.hasIssueDataProviders;
// Short circuit if the extension provides a custom issue handler
if (hasUri && !hasData) {
const url = this.getExtensionBugsUrl();
if (url) {
this.hasBeenSubmitted = true;
await this.nativeHostService.openExternal(url);
return true;
}
}
if (!this.validateInputs()) {
// If inputs are invalid, set focus to the first one and add listeners on them
// to detect further changes
const invalidInput = mainWindow.document.getElementsByClassName('invalid-input');
if (invalidInput.length) {
(<HTMLInputElement>invalidInput[0]).focus();
}
this.addEventListener('issue-title', 'input', _ => {
this.validateInput('issue-title');
});
this.addEventListener('description', 'input', _ => {
this.validateInput('description');
});
this.addEventListener('issue-source', 'change', _ => {
this.validateInput('issue-source');
});
if (this.issueReporterModel.fileOnExtension()) {
this.addEventListener('extension-selector', 'change', _ => {
this.validateInput('extension-selector');
});
}
return false;
}
this.hasBeenSubmitted = true;
const issueTitle = (<HTMLInputElement>this.getElementById('issue-title')).value;
const issueBody = this.issueReporterModel.serialize();
const issueUrl = hasUri ? this.getExtensionBugsUrl() : this.getIssueUrl();
if (!issueUrl) {
return false;
}
const gitHubDetails = this.parseGitHubUrl(issueUrl);
if (this.configuration.data.githubAccessToken && gitHubDetails) {
return this.submitToGitHub(issueTitle, issueBody, gitHubDetails);
}
const baseUrl = this.getIssueUrlWithTitle((<HTMLInputElement>this.getElementById('issue-title')).value, issueUrl);
let url = baseUrl + `&body=${encodeURIComponent(issueBody)}`;
if (url.length > MAX_URL_LENGTH) {
try {
url = await this.writeToClipboard(baseUrl, issueBody);
} catch (_) {
return false;
}
}
await this.nativeHostService.openExternal(url);
return true;
}
private async writeToClipboard(baseUrl: string, issueBody: string): Promise<string> {
const shouldWrite = await this.issueMainService.$showClipboardDialog();
if (!shouldWrite) {
throw new CancellationError();
}
await this.nativeHostService.writeClipboardText(issueBody);
return baseUrl + `&body=${encodeURIComponent(localize('pasteData', "We have written the needed data into your clipboard because it was too large to send. Please paste."))}`;
}
private getIssueUrl(): string {
return this.issueReporterModel.fileOnExtension()
? this.getExtensionGitHubUrl()
: this.issueReporterModel.getData().fileOnMarketplace
? this.configuration.product.reportMarketplaceIssueUrl!
: this.configuration.product.reportIssueUrl!;
}
private parseGitHubUrl(url: string): undefined | { repositoryName: string; owner: string } {
// Assumes a GitHub url to a particular repo, https://github.com/repositoryName/owner.
// Repository name and owner cannot contain '/'
const match = /^https?:\/\/github\.com\/([^\/]*)\/([^\/]*).*/.exec(url);
if (match && match.length) {
return {
owner: match[1],
repositoryName: match[2]
};
}
return undefined;
}
private getExtensionGitHubUrl(): string {
let repositoryUrl = '';