-
Notifications
You must be signed in to change notification settings - Fork 31.3k
/
Copy pathsettingsEditor2.ts
1770 lines (1498 loc) · 71.1 KB
/
settingsEditor2.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 * as DOM from 'vs/base/browser/dom';
import * as aria from 'vs/base/browser/ui/aria/aria';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
import { Button } from 'vs/base/browser/ui/button/button';
import { ITreeElement } from 'vs/base/browser/ui/tree/tree';
import { Action } from 'vs/base/common/actions';
import { Delayer, IntervalTimer, ThrottledDelayer, timeout } from 'vs/base/common/async';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import * as collections from 'vs/base/common/collections';
import { fromNow } from 'vs/base/common/date';
import { isCancellationError } from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
import { Iterable } from 'vs/base/common/iterator';
import { KeyCode } from 'vs/base/common/keyCodes';
import { Disposable, DisposableStore, dispose } from 'vs/base/common/lifecycle';
import * as platform from 'vs/base/common/platform';
import { withNullAsUndefined, withUndefinedAsNull } from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import 'vs/css!./media/settingsEditor2';
import { localize } from 'vs/nls';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { ConfigurationTarget, IConfigurationUpdateOverrides } from 'vs/platform/configuration/common/configuration';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ILogService } from 'vs/platform/log/common/log';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { asCssVariable, badgeBackground, badgeForeground, contrastBorder, editorForeground } from 'vs/platform/theme/common/colorRegistry';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { ThemeIcon } from 'vs/base/common/themables';
import { IUserDataSyncEnablementService, IUserDataSyncService, SyncStatus } from 'vs/platform/userDataSync/common/userDataSync';
import { EditorPane } from 'vs/workbench/browser/parts/editor/editorPane';
import { IEditorMemento, IEditorOpenContext, IEditorPane } from 'vs/workbench/common/editor';
import { SuggestEnabledInput } from 'vs/workbench/contrib/codeEditor/browser/suggestEnabledInput/suggestEnabledInput';
import { SettingsTarget, SettingsTargetsWidget } from 'vs/workbench/contrib/preferences/browser/preferencesWidgets';
import { commonlyUsedData, tocData } from 'vs/workbench/contrib/preferences/browser/settingsLayout';
import { AbstractSettingRenderer, HeightChangeParams, ISettingLinkClickEvent, resolveConfiguredUntrustedSettings, createTocTreeForExtensionSettings, resolveSettingsTree, SettingsTree, SettingTreeRenderers } from 'vs/workbench/contrib/preferences/browser/settingsTree';
import { ISettingsEditorViewState, parseQuery, SearchResultIdx, SearchResultModel, SettingsTreeElement, SettingsTreeGroupChild, SettingsTreeGroupElement, SettingsTreeModel, SettingsTreeSettingElement } from 'vs/workbench/contrib/preferences/browser/settingsTreeModels';
import { createTOCIterator, TOCTree, TOCTreeModel } from 'vs/workbench/contrib/preferences/browser/tocTree';
import { CONTEXT_SETTINGS_EDITOR, CONTEXT_SETTINGS_ROW_FOCUS, CONTEXT_SETTINGS_SEARCH_FOCUS, CONTEXT_TOC_ROW_FOCUS, ENABLE_LANGUAGE_FILTER, EXTENSION_SETTING_TAG, FEATURE_SETTING_TAG, ID_SETTING_TAG, IPreferencesSearchService, ISearchProvider, LANGUAGE_SETTING_TAG, MODIFIED_SETTING_TAG, POLICY_SETTING_TAG, REQUIRE_TRUSTED_WORKSPACE_SETTING_TAG, SETTINGS_EDITOR_COMMAND_CLEAR_SEARCH_RESULTS, SETTINGS_EDITOR_COMMAND_SUGGEST_FILTERS, WORKSPACE_TRUST_SETTING_TAG } from 'vs/workbench/contrib/preferences/common/preferences';
import { settingsHeaderBorder, settingsSashBorder, settingsTextInputBorder } from 'vs/workbench/contrib/preferences/common/settingsEditorColorRegistry';
import { IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IOpenSettingsOptions, IPreferencesService, ISearchResult, ISettingsEditorModel, ISettingsEditorOptions, SettingMatchType, SettingValueType, validateSettingsEditorOptions } from 'vs/workbench/services/preferences/common/preferences';
import { SettingsEditor2Input } from 'vs/workbench/services/preferences/common/preferencesEditorInput';
import { Settings2EditorModel } from 'vs/workbench/services/preferences/common/preferencesModels';
import { IUserDataSyncWorkbenchService } from 'vs/workbench/services/userDataSync/common/userDataSync';
import { preferencesClearInputIcon, preferencesFilterIcon } from 'vs/workbench/contrib/preferences/browser/preferencesIcons';
import { IWorkspaceTrustManagementService } from 'vs/platform/workspace/common/workspaceTrust';
import { IWorkbenchConfigurationService } from 'vs/workbench/services/configuration/common/configuration';
import { ITextResourceConfigurationService } from 'vs/editor/common/services/textResourceConfiguration';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { Orientation, Sizing, SplitView } from 'vs/base/browser/ui/splitview/splitview';
import { Color } from 'vs/base/common/color';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { SettingsSearchFilterDropdownMenuActionViewItem } from 'vs/workbench/contrib/preferences/browser/settingsSearchMenu';
import { IExtensionManagementService } from 'vs/platform/extensionManagement/common/extensionManagement';
import { ISettingOverrideClickEvent } from 'vs/workbench/contrib/preferences/browser/settingsEditorSettingIndicators';
import { ConfigurationScope, Extensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry';
import { Registry } from 'vs/platform/registry/common/platform';
import { defaultButtonStyles } from 'vs/platform/theme/browser/defaultStyles';
export const enum SettingsFocusContext {
Search,
TableOfContents,
SettingTree,
SettingControl
}
export function createGroupIterator(group: SettingsTreeGroupElement): Iterable<ITreeElement<SettingsTreeGroupChild>> {
return Iterable.map(group.children, g => {
return {
element: g,
children: g instanceof SettingsTreeGroupElement ?
createGroupIterator(g) :
undefined
};
});
}
const $ = DOM.$;
interface IFocusEventFromScroll extends KeyboardEvent {
fromScroll: true;
}
const searchBoxLabel = localize('SearchSettings.AriaLabel', "Search settings");
const SETTINGS_EDITOR_STATE_KEY = 'settingsEditorState';
export class SettingsEditor2 extends EditorPane {
static readonly ID: string = 'workbench.editor.settings2';
private static NUM_INSTANCES: number = 0;
private static SEARCH_DEBOUNCE: number = 200;
private static SETTING_UPDATE_FAST_DEBOUNCE: number = 200;
private static SETTING_UPDATE_SLOW_DEBOUNCE: number = 1000;
private static CONFIG_SCHEMA_UPDATE_DELAYER = 500;
private static TOC_MIN_WIDTH: number = 100;
private static TOC_RESET_WIDTH: number = 200;
private static EDITOR_MIN_WIDTH: number = 500;
// Below NARROW_TOTAL_WIDTH, we only render the editor rather than the ToC.
private static NARROW_TOTAL_WIDTH: number = SettingsEditor2.TOC_RESET_WIDTH + SettingsEditor2.EDITOR_MIN_WIDTH;
private static SUGGESTIONS: string[] = [
`@${MODIFIED_SETTING_TAG}`,
'@tag:notebookLayout',
'@tag:notebookOutputLayout',
`@tag:${REQUIRE_TRUSTED_WORKSPACE_SETTING_TAG}`,
`@tag:${WORKSPACE_TRUST_SETTING_TAG}`,
'@tag:sync',
'@tag:usesOnlineServices',
'@tag:telemetry',
'@tag:accessibility',
`@${ID_SETTING_TAG}`,
`@${EXTENSION_SETTING_TAG}`,
`@${FEATURE_SETTING_TAG}scm`,
`@${FEATURE_SETTING_TAG}explorer`,
`@${FEATURE_SETTING_TAG}search`,
`@${FEATURE_SETTING_TAG}debug`,
`@${FEATURE_SETTING_TAG}extensions`,
`@${FEATURE_SETTING_TAG}terminal`,
`@${FEATURE_SETTING_TAG}task`,
`@${FEATURE_SETTING_TAG}problems`,
`@${FEATURE_SETTING_TAG}output`,
`@${FEATURE_SETTING_TAG}comments`,
`@${FEATURE_SETTING_TAG}remote`,
`@${FEATURE_SETTING_TAG}timeline`,
`@${FEATURE_SETTING_TAG}notebook`,
`@${POLICY_SETTING_TAG}`
];
private static shouldSettingUpdateFast(type: SettingValueType | SettingValueType[]): boolean {
if (Array.isArray(type)) {
// nullable integer/number or complex
return false;
}
return type === SettingValueType.Enum ||
type === SettingValueType.Array ||
type === SettingValueType.BooleanObject ||
type === SettingValueType.Object ||
type === SettingValueType.Complex ||
type === SettingValueType.Boolean ||
type === SettingValueType.Exclude;
}
// (!) Lots of props that are set once on the first render
private defaultSettingsEditorModel!: Settings2EditorModel;
private modelDisposables: DisposableStore;
private rootElement!: HTMLElement;
private headerContainer!: HTMLElement;
private bodyContainer!: HTMLElement;
private searchWidget!: SuggestEnabledInput;
private countElement!: HTMLElement;
private controlsElement!: HTMLElement;
private settingsTargetsWidget!: SettingsTargetsWidget;
private splitView!: SplitView<number>;
private settingsTreeContainer!: HTMLElement;
private settingsTree!: SettingsTree;
private settingRenderers!: SettingTreeRenderers;
private tocTreeModel!: TOCTreeModel;
private settingsTreeModel!: SettingsTreeModel;
private noResultsMessage!: HTMLElement;
private clearFilterLinkContainer!: HTMLElement;
private tocTreeContainer!: HTMLElement;
private tocTree!: TOCTree;
private delayedFilterLogging: Delayer<void>;
private localSearchDelayer: Delayer<void>;
private remoteSearchThrottle: ThrottledDelayer<void>;
private searchInProgress: CancellationTokenSource | null = null;
private searchInputDelayer: Delayer<void>;
private updatedConfigSchemaDelayer: Delayer<void>;
private settingFastUpdateDelayer: Delayer<void>;
private settingSlowUpdateDelayer: Delayer<void>;
private pendingSettingUpdate: { key: string; value: any; languageFilter: string | undefined } | null = null;
private readonly viewState: ISettingsEditorViewState;
private _searchResultModel: SearchResultModel | null = null;
private searchResultLabel: string | null = null;
private lastSyncedLabel: string | null = null;
private tocRowFocused: IContextKey<boolean>;
private settingRowFocused: IContextKey<boolean>;
private inSettingsEditorContextKey: IContextKey<boolean>;
private searchFocusContextKey: IContextKey<boolean>;
private scheduledRefreshes: Map<string, DOM.IFocusTracker>;
private _currentFocusContext: SettingsFocusContext = SettingsFocusContext.Search;
/** Don't spam warnings */
private hasWarnedMissingSettings = false;
/** Persist the search query upon reloads */
private editorMemento: IEditorMemento<ISettingsEditor2State>;
private tocFocusedElement: SettingsTreeGroupElement | null = null;
private treeFocusedElement: SettingsTreeElement | null = null;
private settingsTreeScrollTop = 0;
private dimension!: DOM.Dimension;
private installedExtensionIds: string[] = [];
constructor(
@ITelemetryService telemetryService: ITelemetryService,
@IWorkbenchConfigurationService private readonly configurationService: IWorkbenchConfigurationService,
@ITextResourceConfigurationService textResourceConfigurationService: ITextResourceConfigurationService,
@IThemeService themeService: IThemeService,
@IPreferencesService private readonly preferencesService: IPreferencesService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IPreferencesSearchService private readonly preferencesSearchService: IPreferencesSearchService,
@ILogService private readonly logService: ILogService,
@IContextKeyService contextKeyService: IContextKeyService,
@IStorageService private readonly storageService: IStorageService,
@IEditorGroupsService protected editorGroupService: IEditorGroupsService,
@IUserDataSyncWorkbenchService private readonly userDataSyncWorkbenchService: IUserDataSyncWorkbenchService,
@IUserDataSyncEnablementService private readonly userDataSyncEnablementService: IUserDataSyncEnablementService,
@IWorkspaceTrustManagementService private readonly workspaceTrustManagementService: IWorkspaceTrustManagementService,
@IExtensionService private readonly extensionService: IExtensionService,
@ILanguageService private readonly languageService: ILanguageService,
@IExtensionManagementService extensionManagementService: IExtensionManagementService
) {
super(SettingsEditor2.ID, telemetryService, themeService, storageService);
this.delayedFilterLogging = new Delayer<void>(1000);
this.localSearchDelayer = new Delayer(300);
this.remoteSearchThrottle = new ThrottledDelayer(200);
this.viewState = { settingsTarget: ConfigurationTarget.USER_LOCAL };
this.settingFastUpdateDelayer = new Delayer<void>(SettingsEditor2.SETTING_UPDATE_FAST_DEBOUNCE);
this.settingSlowUpdateDelayer = new Delayer<void>(SettingsEditor2.SETTING_UPDATE_SLOW_DEBOUNCE);
this.searchInputDelayer = new Delayer<void>(SettingsEditor2.SEARCH_DEBOUNCE);
this.updatedConfigSchemaDelayer = new Delayer<void>(SettingsEditor2.CONFIG_SCHEMA_UPDATE_DELAYER);
this.inSettingsEditorContextKey = CONTEXT_SETTINGS_EDITOR.bindTo(contextKeyService);
this.searchFocusContextKey = CONTEXT_SETTINGS_SEARCH_FOCUS.bindTo(contextKeyService);
this.tocRowFocused = CONTEXT_TOC_ROW_FOCUS.bindTo(contextKeyService);
this.settingRowFocused = CONTEXT_SETTINGS_ROW_FOCUS.bindTo(contextKeyService);
this.scheduledRefreshes = new Map<string, DOM.IFocusTracker>();
this.editorMemento = this.getEditorMemento<ISettingsEditor2State>(editorGroupService, textResourceConfigurationService, SETTINGS_EDITOR_STATE_KEY);
this._register(configurationService.onDidChangeConfiguration(e => {
if (e.source !== ConfigurationTarget.DEFAULT) {
this.onConfigUpdate(e.affectedKeys);
}
}));
this._register(workspaceTrustManagementService.onDidChangeTrust(() => {
this.searchResultModel?.updateWorkspaceTrust(workspaceTrustManagementService.isWorkspaceTrusted());
if (this.settingsTreeModel) {
this.settingsTreeModel.updateWorkspaceTrust(workspaceTrustManagementService.isWorkspaceTrusted());
this.renderTree();
}
}));
this._register(configurationService.onDidChangeRestrictedSettings(e => {
if (e.default.length && this.currentSettingsModel) {
this.updateElementsByKey(new Set(e.default));
}
}));
this.modelDisposables = this._register(new DisposableStore());
if (ENABLE_LANGUAGE_FILTER && !SettingsEditor2.SUGGESTIONS.includes(`@${LANGUAGE_SETTING_TAG}`)) {
SettingsEditor2.SUGGESTIONS.push(`@${LANGUAGE_SETTING_TAG}`);
}
extensionManagementService.getInstalled().then(extensions => {
this.installedExtensionIds = extensions
.filter(ext => ext.manifest && ext.manifest.contributes && ext.manifest.contributes.configuration)
.map(ext => ext.identifier.id);
});
}
override get minimumWidth(): number { return SettingsEditor2.EDITOR_MIN_WIDTH; }
override get maximumWidth(): number { return Number.POSITIVE_INFINITY; }
override get minimumHeight() { return 180; }
// these setters need to exist because this extends from EditorPane
override set minimumWidth(value: number) { /*noop*/ }
override set maximumWidth(value: number) { /*noop*/ }
private get currentSettingsModel() {
return this.searchResultModel || this.settingsTreeModel;
}
private get searchResultModel(): SearchResultModel | null {
return this._searchResultModel;
}
private set searchResultModel(value: SearchResultModel | null) {
this._searchResultModel = value;
this.rootElement.classList.toggle('search-mode', !!this._searchResultModel);
}
private get focusedSettingDOMElement(): HTMLElement | undefined {
const focused = this.settingsTree.getFocus()[0];
if (!(focused instanceof SettingsTreeSettingElement)) {
return;
}
return this.settingRenderers.getDOMElementsForSettingKey(this.settingsTree.getHTMLElement(), focused.setting.key)[0];
}
get currentFocusContext() {
return this._currentFocusContext;
}
protected createEditor(parent: HTMLElement): void {
parent.setAttribute('tabindex', '-1');
this.rootElement = DOM.append(parent, $('.settings-editor', { tabindex: '-1' }));
this.createHeader(this.rootElement);
this.createBody(this.rootElement);
this.addCtrlAInterceptor(this.rootElement);
this.updateStyles();
}
override async setInput(input: SettingsEditor2Input, options: ISettingsEditorOptions | undefined, context: IEditorOpenContext, token: CancellationToken): Promise<void> {
this.inSettingsEditorContextKey.set(true);
await super.setInput(input, options, context, token);
await timeout(0); // Force setInput to be async
if (!this.input) {
return;
}
const model = await this.input.resolve(options);
if (token.isCancellationRequested || !(model instanceof Settings2EditorModel)) {
return;
}
this.modelDisposables.clear();
this.modelDisposables.add(model.onDidChangeGroups(() => {
this.updatedConfigSchemaDelayer.trigger(() => {
this.onConfigUpdate(undefined, false, true);
});
}));
this.defaultSettingsEditorModel = model;
options = options || validateSettingsEditorOptions({});
if (!this.viewState.settingsTarget || !this.settingsTargetsWidget.settingsTarget) {
const optionsHasViewStateTarget = options.viewState && (options.viewState as ISettingsEditorViewState).settingsTarget;
if (!options.target && !optionsHasViewStateTarget) {
options.target = ConfigurationTarget.USER_LOCAL;
}
}
this._setOptions(options);
// Don't block setInput on render (which can trigger an async search)
this.onConfigUpdate(undefined, true).then(() => {
this._register(input.onWillDispose(() => {
this.searchWidget.setValue('');
}));
// Init TOC selection
this.updateTreeScrollSync();
});
}
private restoreCachedState(): ISettingsEditor2State | null {
const cachedState = this.group && this.input && this.editorMemento.loadEditorState(this.group, this.input);
if (cachedState && typeof cachedState.target === 'object') {
cachedState.target = URI.revive(cachedState.target);
}
if (cachedState) {
const settingsTarget = cachedState.target;
this.settingsTargetsWidget.settingsTarget = settingsTarget;
this.viewState.settingsTarget = settingsTarget;
this.searchWidget.setValue(cachedState.searchQuery);
}
if (this.input) {
this.editorMemento.clearEditorState(this.input, this.group);
}
return withUndefinedAsNull(cachedState);
}
override getViewState(): object | undefined {
return this.viewState;
}
override setOptions(options: ISettingsEditorOptions | undefined): void {
super.setOptions(options);
if (options) {
this._setOptions(options);
}
}
private _setOptions(options: ISettingsEditorOptions): void {
if (options.focusSearch && !platform.isIOS) {
// isIOS - #122044
this.focusSearch();
}
const recoveredViewState = options.viewState ?
options.viewState as ISettingsEditorViewState : undefined;
const query: string | undefined = recoveredViewState?.query ?? options.query;
if (query !== undefined) {
this.searchWidget.setValue(query);
this.viewState.query = query;
}
const target: SettingsTarget | undefined = options.folderUri ?? recoveredViewState?.settingsTarget ?? <SettingsTarget | undefined>options.target;
if (target) {
this.settingsTargetsWidget.settingsTarget = target;
this.viewState.settingsTarget = target;
}
}
override clearInput(): void {
this.inSettingsEditorContextKey.set(false);
super.clearInput();
}
layout(dimension: DOM.Dimension): void {
this.dimension = dimension;
if (!this.isVisible()) {
return;
}
this.layoutSplitView(dimension);
const innerWidth = Math.min(1000, dimension.width) - 24 * 2; // 24px padding on left and right;
// minus padding inside inputbox, countElement width, controls width, extra padding before countElement
const monacoWidth = innerWidth - 10 - this.countElement.clientWidth - this.controlsElement.clientWidth - 12;
this.searchWidget.layout(new DOM.Dimension(monacoWidth, 20));
this.rootElement.classList.toggle('narrow-width', dimension.width < SettingsEditor2.NARROW_TOTAL_WIDTH);
}
override focus(): void {
if (this._currentFocusContext === SettingsFocusContext.Search) {
if (!platform.isIOS) {
// #122044
this.focusSearch();
}
} else if (this._currentFocusContext === SettingsFocusContext.SettingControl) {
const element = this.focusedSettingDOMElement;
if (element) {
const control = element.querySelector(AbstractSettingRenderer.CONTROL_SELECTOR);
if (control) {
(<HTMLElement>control).focus();
return;
}
}
} else if (this._currentFocusContext === SettingsFocusContext.SettingTree) {
this.settingsTree.domFocus();
} else if (this._currentFocusContext === SettingsFocusContext.TableOfContents) {
this.tocTree.domFocus();
}
}
protected override setEditorVisible(visible: boolean, group: IEditorGroup | undefined): void {
super.setEditorVisible(visible, group);
if (!visible) {
// Wait for editor to be removed from DOM #106303
setTimeout(() => {
this.searchWidget.onHide();
}, 0);
}
}
focusSettings(focusSettingInput = false): void {
const focused = this.settingsTree.getFocus();
if (!focused.length) {
this.settingsTree.focusFirst();
}
this.settingsTree.domFocus();
if (focusSettingInput) {
const controlInFocusedRow = this.settingsTree.getHTMLElement().querySelector(`.focused ${AbstractSettingRenderer.CONTROL_SELECTOR}`);
if (controlInFocusedRow) {
(<HTMLElement>controlInFocusedRow).focus();
}
}
}
focusTOC(): void {
this.tocTree.domFocus();
}
showContextMenu(): void {
const focused = this.settingsTree.getFocus()[0];
const rowElement = this.focusedSettingDOMElement;
if (rowElement && focused instanceof SettingsTreeSettingElement) {
this.settingRenderers.showContextMenu(focused, rowElement);
}
}
focusSearch(filter?: string, selectAll = true): void {
if (filter && this.searchWidget) {
this.searchWidget.setValue(filter);
}
this.searchWidget.focus(selectAll);
}
clearSearchResults(): void {
this.searchWidget.setValue('');
this.focusSearch();
}
clearSearchFilters(): void {
const query = this.searchWidget.getValue();
const splitQuery = query.split(' ').filter(word => {
return word.length && !SettingsEditor2.SUGGESTIONS.some(suggestion => word.startsWith(suggestion));
});
this.searchWidget.setValue(splitQuery.join(' '));
}
private updateInputAriaLabel() {
let label = searchBoxLabel;
if (this.searchResultLabel) {
label += `. ${this.searchResultLabel}`;
}
if (this.lastSyncedLabel) {
label += `. ${this.lastSyncedLabel}`;
}
this.searchWidget.updateAriaLabel(label);
}
private createHeader(parent: HTMLElement): void {
this.headerContainer = DOM.append(parent, $('.settings-header'));
const searchContainer = DOM.append(this.headerContainer, $('.search-container'));
const clearInputAction = new Action(SETTINGS_EDITOR_COMMAND_CLEAR_SEARCH_RESULTS, localize('clearInput', "Clear Settings Search Input"), ThemeIcon.asClassName(preferencesClearInputIcon), false, async () => this.clearSearchResults());
const filterAction = new Action(SETTINGS_EDITOR_COMMAND_SUGGEST_FILTERS, localize('filterInput', "Filter Settings"), ThemeIcon.asClassName(preferencesFilterIcon));
this.searchWidget = this._register(this.instantiationService.createInstance(SuggestEnabledInput, `${SettingsEditor2.ID}.searchbox`, searchContainer, {
triggerCharacters: ['@', ':'],
provideResults: (query: string) => {
// Based on testing, the trigger character is always at the end of the query.
// for the ':' trigger, only return suggestions if there was a '@' before it in the same word.
const queryParts = query.split(/\s/g);
if (queryParts[queryParts.length - 1].startsWith(`@${LANGUAGE_SETTING_TAG}`)) {
const sortedLanguages = this.languageService.getRegisteredLanguageIds().map(languageId => {
return `@${LANGUAGE_SETTING_TAG}${languageId} `;
}).sort();
return sortedLanguages.filter(langFilter => !query.includes(langFilter));
} else if (queryParts[queryParts.length - 1].startsWith(`@${EXTENSION_SETTING_TAG}`)) {
const installedExtensionsTags = this.installedExtensionIds.map(extensionId => {
return `@${EXTENSION_SETTING_TAG}${extensionId} `;
}).sort();
return installedExtensionsTags.filter(extFilter => !query.includes(extFilter));
} else if (queryParts[queryParts.length - 1].startsWith('@')) {
return SettingsEditor2.SUGGESTIONS.filter(tag => !query.includes(tag)).map(tag => tag.endsWith(':') ? tag : tag + ' ');
}
return [];
}
}, searchBoxLabel, 'settingseditor:searchinput' + SettingsEditor2.NUM_INSTANCES++, {
placeholderText: searchBoxLabel,
focusContextKey: this.searchFocusContextKey,
styleOverrides: {
inputBorder: settingsTextInputBorder
}
// TODO: Aria-live
}));
this._register(this.searchWidget.onDidFocus(() => {
this._currentFocusContext = SettingsFocusContext.Search;
}));
this.countElement = DOM.append(searchContainer, DOM.$('.settings-count-widget.monaco-count-badge.long'));
this.countElement.style.backgroundColor = asCssVariable(badgeBackground);
this.countElement.style.color = asCssVariable(badgeForeground);
this.countElement.style.border = `1px solid ${asCssVariable(contrastBorder)}`;
this._register(this.searchWidget.onInputDidChange(() => {
const searchVal = this.searchWidget.getValue();
clearInputAction.enabled = !!searchVal;
this.searchInputDelayer.trigger(() => this.onSearchInputChanged());
}));
const headerControlsContainer = DOM.append(this.headerContainer, $('.settings-header-controls'));
headerControlsContainer.style.borderColor = asCssVariable(settingsHeaderBorder);
const targetWidgetContainer = DOM.append(headerControlsContainer, $('.settings-target-container'));
this.settingsTargetsWidget = this._register(this.instantiationService.createInstance(SettingsTargetsWidget, targetWidgetContainer, { enableRemoteSettings: true }));
this.settingsTargetsWidget.settingsTarget = ConfigurationTarget.USER_LOCAL;
this.settingsTargetsWidget.onDidTargetChange(target => this.onDidSettingsTargetChange(target));
this._register(DOM.addDisposableListener(targetWidgetContainer, DOM.EventType.KEY_DOWN, e => {
const event = new StandardKeyboardEvent(e);
if (event.keyCode === KeyCode.DownArrow) {
this.focusSettings();
}
}));
if (this.userDataSyncWorkbenchService.enabled && this.userDataSyncEnablementService.canToggleEnablement()) {
const syncControls = this._register(this.instantiationService.createInstance(SyncControls, headerControlsContainer));
this._register(syncControls.onDidChangeLastSyncedLabel(lastSyncedLabel => {
this.lastSyncedLabel = lastSyncedLabel;
this.updateInputAriaLabel();
}));
}
this.controlsElement = DOM.append(searchContainer, DOM.$('.settings-clear-widget'));
const actionBar = this._register(new ActionBar(this.controlsElement, {
animated: false,
actionViewItemProvider: (action) => {
if (action.id === filterAction.id) {
return this.instantiationService.createInstance(SettingsSearchFilterDropdownMenuActionViewItem, action, this.actionRunner, this.searchWidget);
}
return undefined;
}
}));
actionBar.push([clearInputAction, filterAction], { label: false, icon: true });
}
private onDidSettingsTargetChange(target: SettingsTarget): void {
this.viewState.settingsTarget = target;
// TODO Instead of rebuilding the whole model, refresh and uncache the inspected setting value
this.onConfigUpdate(undefined, true);
}
private onDidClickSetting(evt: ISettingLinkClickEvent, recursed?: boolean): void {
const targetElement = this.currentSettingsModel.getElementsByName(evt.targetKey)?.[0];
let revealFailed = false;
if (targetElement) {
let sourceTop = 0.5;
try {
const _sourceTop = this.settingsTree.getRelativeTop(evt.source);
if (_sourceTop !== null) {
sourceTop = _sourceTop;
}
} catch {
// e.g. clicked a searched element, now the search has been cleared
}
// If we search for something and focus on a category, the settings tree
// only renders settings in that category.
// If the target display category is different than the source's, unfocus the category
// so that we can render all found settings again.
// Then, the reveal call will correctly find the target setting.
if (this.viewState.filterToCategory && evt.source.displayCategory !== targetElement.displayCategory) {
this.tocTree.setFocus([]);
}
try {
this.settingsTree.reveal(targetElement, sourceTop);
} catch (_) {
// The listwidget couldn't find the setting to reveal,
// even though it's in the model, meaning there might be a filter
// preventing it from showing up.
revealFailed = true;
}
if (!revealFailed) {
// We need to shift focus from the setting that contains the link to the setting that's
// linked. Clicking on the link sets focus on the setting that contains the link,
// which is why we need the setTimeout.
setTimeout(() => {
this.settingsTree.setFocus([targetElement]);
}, 50);
const domElements = this.settingRenderers.getDOMElementsForSettingKey(this.settingsTree.getHTMLElement(), evt.targetKey);
if (domElements && domElements[0]) {
const control = domElements[0].querySelector(AbstractSettingRenderer.CONTROL_SELECTOR);
if (control) {
(<HTMLElement>control).focus();
}
}
}
}
if (!recursed && (!targetElement || revealFailed)) {
// We'll call this event handler again after clearing the search query,
// so that more settings show up in the list.
const p = this.triggerSearch('');
p.then(() => {
this.searchWidget.setValue('');
this.onDidClickSetting(evt, true);
});
}
}
switchToApplicationSettingsFile(): Promise<IEditorPane | undefined> {
const query = parseQuery(this.searchWidget.getValue()).query;
return this.openSettingsFile({ query }, true);
}
switchToSettingsFile(): Promise<IEditorPane | undefined> {
const query = parseQuery(this.searchWidget.getValue()).query;
return this.openSettingsFile({ query });
}
private async openSettingsFile(options?: ISettingsEditorOptions, forceOpenApplicationSettings?: boolean): Promise<IEditorPane | undefined> {
const currentSettingsTarget = this.settingsTargetsWidget.settingsTarget;
const openOptions: IOpenSettingsOptions = { jsonEditor: true, ...options };
if (currentSettingsTarget === ConfigurationTarget.USER_LOCAL) {
if (options?.revealSetting) {
const configurationProperties = Registry.as<IConfigurationRegistry>(Extensions.Configuration).getConfigurationProperties();
const configurationScope = configurationProperties[options?.revealSetting.key]?.scope;
if (configurationScope === ConfigurationScope.APPLICATION) {
return this.preferencesService.openApplicationSettings(openOptions);
}
}
if (forceOpenApplicationSettings) {
return this.preferencesService.openApplicationSettings(openOptions);
}
return this.preferencesService.openUserSettings(openOptions);
} else if (currentSettingsTarget === ConfigurationTarget.USER_REMOTE) {
return this.preferencesService.openRemoteSettings(openOptions);
} else if (currentSettingsTarget === ConfigurationTarget.WORKSPACE) {
return this.preferencesService.openWorkspaceSettings(openOptions);
} else if (URI.isUri(currentSettingsTarget)) {
return this.preferencesService.openFolderSettings({ folderUri: currentSettingsTarget, ...openOptions });
}
return undefined;
}
private createBody(parent: HTMLElement): void {
this.bodyContainer = DOM.append(parent, $('.settings-body'));
this.noResultsMessage = DOM.append(this.bodyContainer, $('.no-results-message'));
this.noResultsMessage.innerText = localize('noResults', "No Settings Found");
this.clearFilterLinkContainer = $('span.clear-search-filters');
this.clearFilterLinkContainer.textContent = ' - ';
const clearFilterLink = DOM.append(this.clearFilterLinkContainer, $('a.pointer.prominent', { tabindex: 0 }, localize('clearSearchFilters', 'Clear Filters')));
this._register(DOM.addDisposableListener(clearFilterLink, DOM.EventType.CLICK, (e: MouseEvent) => {
DOM.EventHelper.stop(e, false);
this.clearSearchFilters();
}));
DOM.append(this.noResultsMessage, this.clearFilterLinkContainer);
this.noResultsMessage.style.color = asCssVariable(editorForeground);
this.tocTreeContainer = $('.settings-toc-container');
this.settingsTreeContainer = $('.settings-tree-container');
this.createTOC(this.tocTreeContainer);
this.createSettingsTree(this.settingsTreeContainer);
this.splitView = new SplitView(this.bodyContainer, {
orientation: Orientation.HORIZONTAL,
proportionalLayout: true
});
const startingWidth = this.storageService.getNumber('settingsEditor2.splitViewWidth', StorageScope.PROFILE, SettingsEditor2.TOC_RESET_WIDTH);
this.splitView.addView({
onDidChange: Event.None,
element: this.tocTreeContainer,
minimumSize: SettingsEditor2.TOC_MIN_WIDTH,
maximumSize: Number.POSITIVE_INFINITY,
layout: (width, _, height) => {
this.tocTreeContainer.style.width = `${width}px`;
this.tocTree.layout(height, width);
}
}, startingWidth, undefined, true);
this.splitView.addView({
onDidChange: Event.None,
element: this.settingsTreeContainer,
minimumSize: SettingsEditor2.EDITOR_MIN_WIDTH,
maximumSize: Number.POSITIVE_INFINITY,
layout: (width, _, height) => {
this.settingsTreeContainer.style.width = `${width}px`;
this.settingsTree.layout(height, width);
}
}, Sizing.Distribute, undefined, true);
this._register(this.splitView.onDidSashReset(() => {
const totalSize = this.splitView.getViewSize(0) + this.splitView.getViewSize(1);
this.splitView.resizeView(0, SettingsEditor2.TOC_RESET_WIDTH);
this.splitView.resizeView(1, totalSize - SettingsEditor2.TOC_RESET_WIDTH);
}));
this._register(this.splitView.onDidSashChange(() => {
const width = this.splitView.getViewSize(0);
this.storageService.store('settingsEditor2.splitViewWidth', width, StorageScope.PROFILE, StorageTarget.USER);
}));
const borderColor = this.theme.getColor(settingsSashBorder)!;
this.splitView.style({ separatorBorder: borderColor });
}
private addCtrlAInterceptor(container: HTMLElement): void {
this._register(DOM.addStandardDisposableListener(container, DOM.EventType.KEY_DOWN, (e: StandardKeyboardEvent) => {
if (
e.keyCode === KeyCode.KeyA &&
(platform.isMacintosh ? e.metaKey : e.ctrlKey) &&
e.target.tagName !== 'TEXTAREA' &&
e.target.tagName !== 'INPUT'
) {
// Avoid browser ctrl+a
e.browserEvent.stopPropagation();
e.browserEvent.preventDefault();
}
}));
}
private createTOC(container: HTMLElement): void {
this.tocTreeModel = this.instantiationService.createInstance(TOCTreeModel, this.viewState);
this.tocTree = this._register(this.instantiationService.createInstance(TOCTree,
DOM.append(container, $('.settings-toc-wrapper', {
'role': 'navigation',
'aria-label': localize('settings', "Settings"),
})),
this.viewState));
this._register(this.tocTree.onDidFocus(() => {
this._currentFocusContext = SettingsFocusContext.TableOfContents;
}));
this._register(this.tocTree.onDidChangeFocus(e => {
const element: SettingsTreeGroupElement | null = withUndefinedAsNull(e.elements?.[0]);
if (this.tocFocusedElement === element) {
return;
}
this.tocFocusedElement = element;
this.tocTree.setSelection(element ? [element] : []);
if (this.searchResultModel) {
if (this.viewState.filterToCategory !== element) {
this.viewState.filterToCategory = withNullAsUndefined(element);
// Force render in this case, because
// onDidClickSetting relies on the updated view.
this.renderTree(undefined, true);
this.settingsTree.scrollTop = 0;
}
} else if (element && (!e.browserEvent || !(<IFocusEventFromScroll>e.browserEvent).fromScroll)) {
this.settingsTree.reveal(element, 0);
this.settingsTree.setFocus([element]);
}
}));
this._register(this.tocTree.onDidFocus(() => {
this.tocRowFocused.set(true);
}));
this._register(this.tocTree.onDidBlur(() => {
this.tocRowFocused.set(false);
}));
}
private applyFilter(filter: string) {
if (this.searchWidget && !this.searchWidget.getValue().includes(filter)) {
// Prepend the filter to the query.
const newQuery = `${filter} ${this.searchWidget.getValue().trimStart()}`;
this.focusSearch(newQuery, false);
}
}
private removeLanguageFilters() {
if (this.searchWidget && this.searchWidget.getValue().includes(`@${LANGUAGE_SETTING_TAG}`)) {
const query = this.searchWidget.getValue().split(' ');
const newQuery = query.filter(word => !word.startsWith(`@${LANGUAGE_SETTING_TAG}`)).join(' ');
this.focusSearch(newQuery, false);
}
}
private createSettingsTree(container: HTMLElement): void {
this.settingRenderers = this.instantiationService.createInstance(SettingTreeRenderers);
this._register(this.settingRenderers.onDidChangeSetting(e => this.onDidChangeSetting(e.key, e.value, e.type, e.manualReset, e.scope)));
this._register(this.settingRenderers.onDidOpenSettings(settingKey => {
this.openSettingsFile({ revealSetting: { key: settingKey, edit: true } });
}));
this._register(this.settingRenderers.onDidClickSettingLink(settingName => this.onDidClickSetting(settingName)));
this._register(this.settingRenderers.onDidFocusSetting(element => {
this.settingsTree.setFocus([element]);
this._currentFocusContext = SettingsFocusContext.SettingControl;
this.settingRowFocused.set(false);
}));
this._register(this.settingRenderers.onDidChangeSettingHeight((params: HeightChangeParams) => {
const { element, height } = params;
try {
this.settingsTree.updateElementHeight(element, height);
} catch (e) {
// the element was not found
}
}));
this._register(this.settingRenderers.onApplyFilter((filter) => this.applyFilter(filter)));
this._register(this.settingRenderers.onDidClickOverrideElement((element: ISettingOverrideClickEvent) => {
this.removeLanguageFilters();
if (element.language) {
this.applyFilter(`@${LANGUAGE_SETTING_TAG}${element.language}`);
}
if (element.scope === 'workspace') {
this.settingsTargetsWidget.updateTarget(ConfigurationTarget.WORKSPACE);
} else if (element.scope === 'user') {
this.settingsTargetsWidget.updateTarget(ConfigurationTarget.USER_LOCAL);
} else if (element.scope === 'remote') {
this.settingsTargetsWidget.updateTarget(ConfigurationTarget.USER_REMOTE);
}
this.applyFilter(`@${ID_SETTING_TAG}${element.settingKey}`);
}));
this.settingsTree = this._register(this.instantiationService.createInstance(SettingsTree,
container,
this.viewState,
this.settingRenderers.allRenderers));
this._register(this.settingsTree.onDidScroll(() => {
if (this.settingsTree.scrollTop === this.settingsTreeScrollTop) {
return;
}
this.settingsTreeScrollTop = this.settingsTree.scrollTop;
// setTimeout because calling setChildren on the settingsTree can trigger onDidScroll, so it fires when
// setChildren has called on the settings tree but not the toc tree yet, so their rendered elements are out of sync
setTimeout(() => {
this.updateTreeScrollSync();
}, 0);
}));
this._register(this.settingsTree.onDidFocus(() => {
const classList = document.activeElement?.classList;
if (classList && classList.contains('monaco-list') && classList.contains('settings-editor-tree')) {
this._currentFocusContext = SettingsFocusContext.SettingTree;
this.settingRowFocused.set(true);
this.treeFocusedElement ??= withUndefinedAsNull(this.settingsTree.firstVisibleElement);
if (this.treeFocusedElement) {
this.treeFocusedElement.tabbable = true;
}
}
}));
this._register(this.settingsTree.onDidBlur(() => {
this.settingRowFocused.set(false);
// Clear out the focused element, otherwise it could be
// out of date during the next onDidFocus event.
this.treeFocusedElement = null;
}));
// There is no different select state in the settings tree
this._register(this.settingsTree.onDidChangeFocus(e => {
const element = e.elements[0];
if (this.treeFocusedElement === element) {
return;
}
if (this.treeFocusedElement) {
this.treeFocusedElement.tabbable = false;
}
this.treeFocusedElement = element;
if (this.treeFocusedElement) {
this.treeFocusedElement.tabbable = true;
}
this.settingsTree.setSelection(element ? [element] : []);
}));
}
private onDidChangeSetting(key: string, value: any, type: SettingValueType | SettingValueType[], manualReset: boolean, scope: ConfigurationScope | undefined): void {
const parsedQuery = parseQuery(this.searchWidget.getValue());
const languageFilter = parsedQuery.languageFilter;
if (manualReset || (this.pendingSettingUpdate && this.pendingSettingUpdate.key !== key)) {
this.updateChangedSetting(key, value, manualReset, languageFilter, scope);
}
this.pendingSettingUpdate = { key, value, languageFilter };
if (SettingsEditor2.shouldSettingUpdateFast(type)) {
this.settingFastUpdateDelayer.trigger(() => this.updateChangedSetting(key, value, manualReset, languageFilter, scope));
} else {
this.settingSlowUpdateDelayer.trigger(() => this.updateChangedSetting(key, value, manualReset, languageFilter, scope));
}
}
private updateTreeScrollSync(): void {
this.settingRenderers.cancelSuggesters();
if (this.searchResultModel) {
return;
}
if (!this.tocTreeModel) {
return;
}