-
Notifications
You must be signed in to change notification settings - Fork 28.1k
/
settingsTree.ts
2684 lines (2247 loc) · 103 KB
/
settingsTree.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 { BrowserFeatures } from 'vs/base/browser/canIUse';
import * as DOM from 'vs/base/browser/dom';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { renderMarkdownAsPlaintext } from 'vs/base/browser/markdownRenderer';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import * as aria from 'vs/base/browser/ui/aria/aria';
import { Button } from 'vs/base/browser/ui/button/button';
import { SimpleIconLabel } from 'vs/base/browser/ui/iconLabel/simpleIconLabel';
import { IInputOptions, InputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { CachedListVirtualDelegate } from 'vs/base/browser/ui/list/list';
import { DefaultStyleController, IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';
import { ISelectOptionItem, SelectBox } from 'vs/base/browser/ui/selectBox/selectBox';
import { Toggle, unthemedToggleStyles } from 'vs/base/browser/ui/toggle/toggle';
import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar';
import { RenderIndentGuides } from 'vs/base/browser/ui/tree/abstractTree';
import { IList } from 'vs/base/browser/ui/tree/indexTreeModel';
import { IObjectTreeOptions } from 'vs/base/browser/ui/tree/objectTree';
import { ObjectTreeModel } from 'vs/base/browser/ui/tree/objectTreeModel';
import { ITreeFilter, ITreeModel, ITreeNode, ITreeRenderer, TreeFilterResult, TreeVisibility } from 'vs/base/browser/ui/tree/tree';
import { Action, IAction, Separator } from 'vs/base/common/actions';
import { distinct } from 'vs/base/common/arrays';
import { Codicon } from 'vs/base/common/codicons';
import { onUnexpectedError } from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
import { IJSONSchema } from 'vs/base/common/jsonSchema';
import { KeyCode } from 'vs/base/common/keyCodes';
import { Disposable, DisposableStore, dispose, isDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { isIOS } from 'vs/base/common/platform';
import { escapeRegExpCharacters } from 'vs/base/common/strings';
import { isDefined, isUndefinedOrNull } from 'vs/base/common/types';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { MarkdownRenderer } from 'vs/editor/browser/widget/markdownRenderer/browser/markdownRenderer';
import { localize } from 'vs/nls';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { ConfigurationTarget, IConfigurationService, getLanguageTagSettingPlainKey } from 'vs/platform/configuration/common/configuration';
import { ConfigurationScope } from 'vs/platform/configuration/common/configurationRegistry';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IListService, WorkbenchObjectTree } from 'vs/platform/list/browser/listService';
import { ILogService } from 'vs/platform/log/common/log';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IProductService } from 'vs/platform/product/common/productService';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { defaultButtonStyles, getInputBoxStyle, getListStyles, getSelectBoxStyles } from 'vs/platform/theme/browser/defaultStyles';
import { editorBackground, foreground } from 'vs/platform/theme/common/colorRegistry';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IUserDataProfilesService } from 'vs/platform/userDataProfile/common/userDataProfile';
import { getIgnoredSettings } from 'vs/platform/userDataSync/common/settingsMerge';
import { IUserDataSyncEnablementService, getDefaultIgnoredSettings } from 'vs/platform/userDataSync/common/userDataSync';
import { IExtensionsWorkbenchService } from 'vs/workbench/contrib/extensions/common/extensions';
import { settingsMoreActionIcon } from 'vs/workbench/contrib/preferences/browser/preferencesIcons';
import { SettingsTarget } from 'vs/workbench/contrib/preferences/browser/preferencesWidgets';
import { ISettingOverrideClickEvent, SettingsTreeIndicatorsLabel, getIndicatorsLabelAriaLabel } from 'vs/workbench/contrib/preferences/browser/settingsEditorSettingIndicators';
import { ITOCEntry } from 'vs/workbench/contrib/preferences/browser/settingsLayout';
import { ISettingsEditorViewState, SettingsTreeElement, SettingsTreeGroupChild, SettingsTreeGroupElement, SettingsTreeNewExtensionsElement, SettingsTreeSettingElement, inspectSetting, objectSettingSupportsRemoveDefaultValue, settingKeyToDisplayFormat } from 'vs/workbench/contrib/preferences/browser/settingsTreeModels';
import { ExcludeSettingWidget, IBoolObjectDataItem, IIncludeExcludeDataItem, IListDataItem, IObjectDataItem, IObjectEnumOption, IObjectKeySuggester, IObjectValueSuggester, IncludeSettingWidget, ListSettingWidget, ObjectSettingCheckboxWidget, ObjectSettingDropdownWidget, ObjectValue, SettingListEvent } from 'vs/workbench/contrib/preferences/browser/settingsWidgets';
import { LANGUAGE_SETTING_TAG, SETTINGS_EDITOR_COMMAND_SHOW_CONTEXT_MENU, compareTwoNullableNumbers } from 'vs/workbench/contrib/preferences/common/preferences';
import { settingsNumberInputBackground, settingsNumberInputBorder, settingsNumberInputForeground, settingsSelectBackground, settingsSelectBorder, settingsSelectForeground, settingsSelectListBorder, settingsTextInputBackground, settingsTextInputBorder, settingsTextInputForeground } from 'vs/workbench/contrib/preferences/common/settingsEditorColorRegistry';
import { APPLY_ALL_PROFILES_SETTING, IWorkbenchConfigurationService } from 'vs/workbench/services/configuration/common/configuration';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { ISetting, ISettingsGroup, SettingValueType } from 'vs/workbench/services/preferences/common/preferences';
import { getInvalidTypeError } from 'vs/workbench/services/preferences/common/preferencesValidation';
import { getDefaultHoverDelegate } from 'vs/base/browser/ui/hover/hoverDelegateFactory';
import { IHoverService } from 'vs/platform/hover/browser/hover';
const $ = DOM.$;
function getIncludeExcludeDisplayValue(element: SettingsTreeSettingElement): IIncludeExcludeDataItem[] {
const elementDefaultValue: Record<string, unknown> = typeof element.defaultValue === 'object'
? element.defaultValue ?? {}
: {};
const data = element.isConfigured ?
{ ...elementDefaultValue, ...element.scopeValue } :
elementDefaultValue;
return Object.keys(data)
.filter(key => !!data[key])
.map(key => {
const defaultValue = elementDefaultValue[key];
// Get source if it's a default value
let source: string | undefined;
if (defaultValue === data[key] && element.setting.type === 'object' && element.defaultValueSource instanceof Map) {
const defaultSource = element.defaultValueSource.get(`${element.setting.key}.${key}`);
source = typeof defaultSource === 'string' ? defaultSource : defaultSource?.displayName;
}
const value = data[key];
const sibling = typeof value === 'boolean' ? undefined : value.when;
return {
value: {
type: 'string',
data: key
},
sibling,
elementType: element.valueType,
source
};
});
}
function areAllPropertiesDefined(properties: string[], itemsToDisplay: IObjectDataItem[]): boolean {
const staticProperties = new Set(properties);
itemsToDisplay.forEach(({ key }) => staticProperties.delete(key.data));
return staticProperties.size === 0;
}
function getEnumOptionsFromSchema(schema: IJSONSchema): IObjectEnumOption[] {
if (schema.anyOf) {
return schema.anyOf.map(getEnumOptionsFromSchema).flat();
}
const enumDescriptions = schema.enumDescriptions ?? [];
return (schema.enum ?? []).map((value, idx) => {
const description = idx < enumDescriptions.length
? enumDescriptions[idx]
: undefined;
return { value, description };
});
}
function getObjectValueType(schema: IJSONSchema): ObjectValue['type'] {
if (schema.anyOf) {
const subTypes = schema.anyOf.map(getObjectValueType);
if (subTypes.some(type => type === 'enum')) {
return 'enum';
}
return 'string';
}
if (schema.type === 'boolean') {
return 'boolean';
} else if (schema.type === 'string' && isDefined(schema.enum) && schema.enum.length > 0) {
return 'enum';
} else {
return 'string';
}
}
function getObjectEntryValueDisplayValue(type: ObjectValue['type'], data: unknown, options: IObjectEnumOption[]): ObjectValue {
if (type === 'boolean') {
return { type, data: !!data };
} else if (type === 'enum') {
return { type, data: '' + data, options };
} else {
return { type, data: '' + data };
}
}
function getObjectDisplayValue(element: SettingsTreeSettingElement): IObjectDataItem[] {
const elementDefaultValue: Record<string, unknown> = typeof element.defaultValue === 'object'
? element.defaultValue ?? {}
: {};
const elementScopeValue: Record<string, unknown> = typeof element.scopeValue === 'object'
? element.scopeValue ?? {}
: {};
const data = element.isConfigured ?
{ ...elementDefaultValue, ...elementScopeValue } :
elementDefaultValue;
const { objectProperties, objectPatternProperties, objectAdditionalProperties } = element.setting;
const patternsAndSchemas = Object
.entries(objectPatternProperties ?? {})
.map(([pattern, schema]) => ({
pattern: new RegExp(pattern),
schema
}));
const wellDefinedKeyEnumOptions = Object.entries(objectProperties ?? {}).map(
([key, schema]) => ({ value: key, description: schema.description })
);
return Object.keys(data).map(key => {
const defaultValue = elementDefaultValue[key];
// Get source if it's a default value
let source: string | undefined;
if (defaultValue === data[key] && element.setting.type === 'object' && element.defaultValueSource instanceof Map) {
const defaultSource = element.defaultValueSource.get(`${element.setting.key}.${key}`);
source = typeof defaultSource === 'string' ? defaultSource : defaultSource?.displayName;
}
if (isDefined(objectProperties) && key in objectProperties) {
const valueEnumOptions = getEnumOptionsFromSchema(objectProperties[key]);
return {
key: {
type: 'enum',
data: key,
options: wellDefinedKeyEnumOptions,
},
value: getObjectEntryValueDisplayValue(getObjectValueType(objectProperties[key]), data[key], valueEnumOptions),
keyDescription: objectProperties[key].description,
removable: isUndefinedOrNull(defaultValue),
resetable: !isUndefinedOrNull(defaultValue),
source
} satisfies IObjectDataItem;
}
// The row is removable if it doesn't have a default value assigned or the setting supports removing the default value.
// If a default value is assigned and the user modified the default, it can be reset back to the default.
const removable = defaultValue === undefined || objectSettingSupportsRemoveDefaultValue(element.setting.key);
const resetable = !!defaultValue && defaultValue !== data[key];
const schema = patternsAndSchemas.find(({ pattern }) => pattern.test(key))?.schema;
if (schema) {
const valueEnumOptions = getEnumOptionsFromSchema(schema);
return {
key: { type: 'string', data: key },
value: getObjectEntryValueDisplayValue(getObjectValueType(schema), data[key], valueEnumOptions),
keyDescription: schema.description,
removable,
resetable,
source
} satisfies IObjectDataItem;
}
const additionalValueEnums = getEnumOptionsFromSchema(
typeof objectAdditionalProperties === 'boolean'
? {}
: objectAdditionalProperties ?? {}
);
return {
key: { type: 'string', data: key },
value: getObjectEntryValueDisplayValue(
typeof objectAdditionalProperties === 'object' ? getObjectValueType(objectAdditionalProperties) : 'string',
data[key],
additionalValueEnums,
),
keyDescription: typeof objectAdditionalProperties === 'object' ? objectAdditionalProperties.description : undefined,
removable,
resetable,
source
} satisfies IObjectDataItem;
}).filter(item => !isUndefinedOrNull(item.value.data));
}
function getBoolObjectDisplayValue(element: SettingsTreeSettingElement): IBoolObjectDataItem[] {
const elementDefaultValue: Record<string, unknown> = typeof element.defaultValue === 'object'
? element.defaultValue ?? {}
: {};
const elementScopeValue: Record<string, unknown> = typeof element.scopeValue === 'object'
? element.scopeValue ?? {}
: {};
const data = element.isConfigured ?
{ ...elementDefaultValue, ...elementScopeValue } :
elementDefaultValue;
const { objectProperties } = element.setting;
const displayValues: IBoolObjectDataItem[] = [];
for (const key in objectProperties) {
const defaultValue = elementDefaultValue[key];
// Get source if it's a default value
let source: string | undefined;
if (defaultValue === data[key] && element.setting.type === 'object' && element.defaultValueSource instanceof Map) {
const defaultSource = element.defaultValueSource.get(key);
source = typeof defaultSource === 'string' ? defaultSource : defaultSource?.displayName;
}
displayValues.push({
key: {
type: 'string',
data: key
},
value: {
type: 'boolean',
data: !!data[key]
},
keyDescription: objectProperties[key].description,
removable: false,
resetable: true,
source
});
}
return displayValues;
}
function createArraySuggester(element: SettingsTreeSettingElement): IObjectKeySuggester {
return (keys, idx) => {
const enumOptions: IObjectEnumOption[] = [];
if (element.setting.enum) {
element.setting.enum.forEach((key, i) => {
// include the currently selected value, even if uniqueItems is true
if (!element.setting.uniqueItems || (idx !== undefined && key === keys[idx]) || !keys.includes(key)) {
const description = element.setting.enumDescriptions?.[i];
enumOptions.push({ value: key, description });
}
});
}
return enumOptions.length > 0
? { type: 'enum', data: enumOptions[0].value, options: enumOptions }
: undefined;
};
}
function createObjectKeySuggester(element: SettingsTreeSettingElement): IObjectKeySuggester {
const { objectProperties } = element.setting;
const allStaticKeys = Object.keys(objectProperties ?? {});
return keys => {
const existingKeys = new Set(keys);
const enumOptions: IObjectEnumOption[] = [];
allStaticKeys.forEach(staticKey => {
if (!existingKeys.has(staticKey)) {
enumOptions.push({ value: staticKey, description: objectProperties![staticKey].description });
}
});
return enumOptions.length > 0
? { type: 'enum', data: enumOptions[0].value, options: enumOptions }
: undefined;
};
}
function createObjectValueSuggester(element: SettingsTreeSettingElement): IObjectValueSuggester {
const { objectProperties, objectPatternProperties, objectAdditionalProperties } = element.setting;
const patternsAndSchemas = Object
.entries(objectPatternProperties ?? {})
.map(([pattern, schema]) => ({
pattern: new RegExp(pattern),
schema
}));
return (key: string) => {
let suggestedSchema: IJSONSchema | undefined;
if (isDefined(objectProperties) && key in objectProperties) {
suggestedSchema = objectProperties[key];
}
const patternSchema = suggestedSchema ?? patternsAndSchemas.find(({ pattern }) => pattern.test(key))?.schema;
if (isDefined(patternSchema)) {
suggestedSchema = patternSchema;
} else if (isDefined(objectAdditionalProperties) && typeof objectAdditionalProperties === 'object') {
suggestedSchema = objectAdditionalProperties;
}
if (isDefined(suggestedSchema)) {
const type = getObjectValueType(suggestedSchema);
if (type === 'boolean') {
return { type, data: suggestedSchema.default ?? true };
} else if (type === 'enum') {
const options = getEnumOptionsFromSchema(suggestedSchema);
return { type, data: suggestedSchema.default ?? options[0].value, options };
} else {
return { type, data: suggestedSchema.default ?? '' };
}
}
return;
};
}
function isNonNullableNumericType(type: unknown): type is 'number' | 'integer' {
return type === 'number' || type === 'integer';
}
function parseNumericObjectValues(dataElement: SettingsTreeSettingElement, v: Record<string, unknown>): Record<string, unknown> {
const newRecord: Record<string, unknown> = {};
for (const key in v) {
// Set to true/false once we're sure of the answer
let keyMatchesNumericProperty: boolean | undefined;
const patternProperties = dataElement.setting.objectPatternProperties;
const properties = dataElement.setting.objectProperties;
const additionalProperties = dataElement.setting.objectAdditionalProperties;
// Match the current record key against the properties of the object
if (properties) {
for (const propKey in properties) {
if (propKey === key) {
keyMatchesNumericProperty = isNonNullableNumericType(properties[propKey].type);
break;
}
}
}
if (keyMatchesNumericProperty === undefined && patternProperties) {
for (const patternKey in patternProperties) {
if (key.match(patternKey)) {
keyMatchesNumericProperty = isNonNullableNumericType(patternProperties[patternKey].type);
break;
}
}
}
if (keyMatchesNumericProperty === undefined && additionalProperties && typeof additionalProperties !== 'boolean') {
if (isNonNullableNumericType(additionalProperties.type)) {
keyMatchesNumericProperty = true;
}
}
newRecord[key] = keyMatchesNumericProperty ? Number(v[key]) : v[key];
}
return newRecord;
}
function getListDisplayValue(element: SettingsTreeSettingElement): IListDataItem[] {
if (!element.value || !Array.isArray(element.value)) {
return [];
}
if (element.setting.arrayItemType === 'enum') {
let enumOptions: IObjectEnumOption[] = [];
if (element.setting.enum) {
enumOptions = element.setting.enum.map((setting, i) => {
return {
value: setting,
description: element.setting.enumDescriptions?.[i]
};
});
}
return element.value.map((key: string) => {
return {
value: {
type: 'enum',
data: key,
options: enumOptions
}
};
});
} else {
return element.value.map((key: string) => {
return {
value: {
type: 'string',
data: key
}
};
});
}
}
function getShowAddButtonList(dataElement: SettingsTreeSettingElement, listDisplayValue: IListDataItem[]): boolean {
if (dataElement.setting.enum && dataElement.setting.uniqueItems) {
return dataElement.setting.enum.length - listDisplayValue.length > 0;
} else {
return true;
}
}
export function resolveSettingsTree(tocData: ITOCEntry<string>, coreSettingsGroups: ISettingsGroup[], logService: ILogService): { tree: ITOCEntry<ISetting>; leftoverSettings: Set<ISetting> } {
const allSettings = getFlatSettings(coreSettingsGroups);
return {
tree: _resolveSettingsTree(tocData, allSettings, logService),
leftoverSettings: allSettings
};
}
export function resolveConfiguredUntrustedSettings(groups: ISettingsGroup[], target: SettingsTarget, languageFilter: string | undefined, configurationService: IWorkbenchConfigurationService): ISetting[] {
const allSettings = getFlatSettings(groups);
return [...allSettings].filter(setting => setting.restricted && inspectSetting(setting.key, target, languageFilter, configurationService).isConfigured);
}
export async function createTocTreeForExtensionSettings(extensionService: IExtensionService, groups: ISettingsGroup[]): Promise<ITOCEntry<ISetting>> {
const extGroupTree = new Map<string, ITOCEntry<ISetting>>();
const addEntryToTree = (extensionId: string, extensionName: string, childEntry: ITOCEntry<ISetting>) => {
if (!extGroupTree.has(extensionId)) {
const rootEntry = {
id: extensionId,
label: extensionName,
children: []
};
extGroupTree.set(extensionId, rootEntry);
}
extGroupTree.get(extensionId)!.children!.push(childEntry);
};
const processGroupEntry = async (group: ISettingsGroup) => {
const flatSettings = group.sections.map(section => section.settings).flat();
const extensionId = group.extensionInfo!.id;
const extension = await extensionService.getExtension(extensionId);
const extensionName = extension?.displayName ?? extension?.name ?? extensionId;
// Each group represents a single category of settings.
// If the extension author forgets to specify an id for the group,
// fall back to the title given to the group.
const childEntry: ITOCEntry<ISetting> = {
id: group.id || group.title,
label: group.title,
order: group.order,
settings: flatSettings
};
addEntryToTree(extensionId, extensionName, childEntry);
};
const processPromises = groups.map(g => processGroupEntry(g));
return Promise.all(processPromises).then(() => {
const extGroups: ITOCEntry<ISetting>[] = [];
for (const extensionRootEntry of extGroupTree.values()) {
for (const child of extensionRootEntry.children!) {
// Sort the individual settings of the child by order.
// Leave the undefined order settings untouched.
child.settings?.sort((a, b) => {
return compareTwoNullableNumbers(a.order, b.order);
});
}
if (extensionRootEntry.children!.length === 1) {
// There is a single category for this extension.
// Push a flattened setting.
extGroups.push({
id: extensionRootEntry.id,
label: extensionRootEntry.children![0].label,
settings: extensionRootEntry.children![0].settings
});
} else {
// Sort the categories.
// Leave the undefined order categories untouched.
extensionRootEntry.children!.sort((a, b) => {
return compareTwoNullableNumbers(a.order, b.order);
});
// If there is a category that matches the setting name,
// add the settings in manually as "ungrouped" settings.
// https://github.com/microsoft/vscode/issues/137259
const ungroupedChild = extensionRootEntry.children!.find(child => child.label === extensionRootEntry.label);
if (ungroupedChild && !ungroupedChild.children) {
const groupedChildren = extensionRootEntry.children!.filter(child => child !== ungroupedChild);
extGroups.push({
id: extensionRootEntry.id,
label: extensionRootEntry.label,
settings: ungroupedChild.settings,
children: groupedChildren
});
} else {
// Push all the groups as-is.
extGroups.push(extensionRootEntry);
}
}
}
// Sort the outermost settings.
extGroups.sort((a, b) => a.label.localeCompare(b.label));
return {
id: 'extensions',
label: localize('extensions', "Extensions"),
children: extGroups
};
});
}
function _resolveSettingsTree(tocData: ITOCEntry<string>, allSettings: Set<ISetting>, logService: ILogService): ITOCEntry<ISetting> {
let children: ITOCEntry<ISetting>[] | undefined;
if (tocData.children) {
children = tocData.children
.map(child => _resolveSettingsTree(child, allSettings, logService))
.filter(child => child.children?.length || child.settings?.length);
}
let settings: ISetting[] | undefined;
if (tocData.settings) {
settings = tocData.settings.map(pattern => getMatchingSettings(allSettings, pattern, logService)).flat();
}
if (!children && !settings) {
throw new Error(`TOC node has no child groups or settings: ${tocData.id}`);
}
return {
id: tocData.id,
label: tocData.label,
children,
settings
};
}
const knownDynamicSettingGroups = [
/^settingsSync\..*/,
/^sync\..*/,
/^workbench.fontAliasing$/,
];
function getMatchingSettings(allSettings: Set<ISetting>, pattern: string, logService: ILogService): ISetting[] {
const result: ISetting[] = [];
allSettings.forEach(s => {
if (settingMatches(s, pattern)) {
result.push(s);
allSettings.delete(s);
}
});
if (!result.length && !knownDynamicSettingGroups.some(r => r.test(pattern))) {
logService.warn(`Settings pattern "${pattern}" doesn't match any settings`);
}
return result.sort((a, b) => a.key.localeCompare(b.key));
}
const settingPatternCache = new Map<string, RegExp>();
export function createSettingMatchRegExp(pattern: string): RegExp {
pattern = escapeRegExpCharacters(pattern)
.replace(/\\\*/g, '.*');
return new RegExp(`^${pattern}$`, 'i');
}
function settingMatches(s: ISetting, pattern: string): boolean {
let regExp = settingPatternCache.get(pattern);
if (!regExp) {
regExp = createSettingMatchRegExp(pattern);
settingPatternCache.set(pattern, regExp);
}
return regExp.test(s.key);
}
function getFlatSettings(settingsGroups: ISettingsGroup[]) {
const result: Set<ISetting> = new Set();
for (const group of settingsGroups) {
for (const section of group.sections) {
for (const s of section.settings) {
if (!s.overrides || !s.overrides.length) {
result.add(s);
}
}
}
}
return result;
}
interface IDisposableTemplate {
readonly toDispose: DisposableStore;
}
interface ISettingItemTemplate<T = any> extends IDisposableTemplate {
onChange?: (value: T) => void;
context?: SettingsTreeSettingElement;
containerElement: HTMLElement;
categoryElement: HTMLElement;
labelElement: SimpleIconLabel;
descriptionElement: HTMLElement;
controlElement: HTMLElement;
deprecationWarningElement: HTMLElement;
indicatorsLabel: SettingsTreeIndicatorsLabel;
toolbar: ToolBar;
readonly elementDisposables: DisposableStore;
}
interface ISettingBoolItemTemplate extends ISettingItemTemplate<boolean> {
checkbox: Toggle;
}
interface ISettingExtensionToggleItemTemplate extends ISettingItemTemplate<undefined> {
actionButton: Button;
dismissButton: Button;
}
interface ISettingTextItemTemplate extends ISettingItemTemplate<string> {
inputBox: InputBox;
validationErrorMessageElement: HTMLElement;
}
type ISettingNumberItemTemplate = ISettingTextItemTemplate;
interface ISettingEnumItemTemplate extends ISettingItemTemplate<number> {
selectBox: SelectBox;
selectElement: HTMLSelectElement | null;
enumDescriptionElement: HTMLElement;
}
interface ISettingComplexItemTemplate extends ISettingItemTemplate<void> {
button: HTMLElement;
validationErrorMessageElement: HTMLElement;
}
interface ISettingListItemTemplate extends ISettingItemTemplate<string[] | undefined> {
listWidget: ListSettingWidget<IListDataItem>;
validationErrorMessageElement: HTMLElement;
}
interface ISettingIncludeExcludeItemTemplate extends ISettingItemTemplate<void> {
includeExcludeWidget: ListSettingWidget<IIncludeExcludeDataItem>;
}
interface ISettingObjectItemTemplate extends ISettingItemTemplate<Record<string, unknown> | undefined> {
objectDropdownWidget?: ObjectSettingDropdownWidget;
objectCheckboxWidget?: ObjectSettingCheckboxWidget;
validationErrorMessageElement: HTMLElement;
}
interface ISettingNewExtensionsTemplate extends IDisposableTemplate {
button: Button;
context?: SettingsTreeNewExtensionsElement;
}
interface IGroupTitleTemplate extends IDisposableTemplate {
context?: SettingsTreeGroupElement;
parent: HTMLElement;
}
const SETTINGS_TEXT_TEMPLATE_ID = 'settings.text.template';
const SETTINGS_MULTILINE_TEXT_TEMPLATE_ID = 'settings.multilineText.template';
const SETTINGS_NUMBER_TEMPLATE_ID = 'settings.number.template';
const SETTINGS_ENUM_TEMPLATE_ID = 'settings.enum.template';
const SETTINGS_BOOL_TEMPLATE_ID = 'settings.bool.template';
const SETTINGS_ARRAY_TEMPLATE_ID = 'settings.array.template';
const SETTINGS_EXCLUDE_TEMPLATE_ID = 'settings.exclude.template';
const SETTINGS_INCLUDE_TEMPLATE_ID = 'settings.include.template';
const SETTINGS_OBJECT_TEMPLATE_ID = 'settings.object.template';
const SETTINGS_BOOL_OBJECT_TEMPLATE_ID = 'settings.boolObject.template';
const SETTINGS_COMPLEX_TEMPLATE_ID = 'settings.complex.template';
const SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID = 'settings.newExtensions.template';
const SETTINGS_ELEMENT_TEMPLATE_ID = 'settings.group.template';
const SETTINGS_EXTENSION_TOGGLE_TEMPLATE_ID = 'settings.extensionToggle.template';
export interface ISettingChangeEvent {
key: string;
value: any; // undefined => reset/unconfigure
type: SettingValueType | SettingValueType[];
manualReset: boolean;
scope: ConfigurationScope | undefined;
}
export interface ISettingLinkClickEvent {
source: SettingsTreeSettingElement;
targetKey: string;
}
function removeChildrenFromTabOrder(node: Element): void {
const focusableElements = node.querySelectorAll(`
[tabindex="0"],
input:not([tabindex="-1"]),
select:not([tabindex="-1"]),
textarea:not([tabindex="-1"]),
a:not([tabindex="-1"]),
button:not([tabindex="-1"]),
area:not([tabindex="-1"])
`);
focusableElements.forEach(element => {
element.setAttribute(AbstractSettingRenderer.ELEMENT_FOCUSABLE_ATTR, 'true');
element.setAttribute('tabindex', '-1');
});
}
function addChildrenToTabOrder(node: Element): void {
const focusableElements = node.querySelectorAll(
`[${AbstractSettingRenderer.ELEMENT_FOCUSABLE_ATTR}="true"]`
);
focusableElements.forEach(element => {
element.removeAttribute(AbstractSettingRenderer.ELEMENT_FOCUSABLE_ATTR);
element.setAttribute('tabindex', '0');
});
}
export interface HeightChangeParams {
element: SettingsTreeElement;
height: number;
}
export abstract class AbstractSettingRenderer extends Disposable implements ITreeRenderer<SettingsTreeElement, never, any> {
/** To override */
abstract get templateId(): string;
static readonly CONTROL_CLASS = 'setting-control-focus-target';
static readonly CONTROL_SELECTOR = '.' + this.CONTROL_CLASS;
static readonly CONTENTS_CLASS = 'setting-item-contents';
static readonly CONTENTS_SELECTOR = '.' + this.CONTENTS_CLASS;
static readonly ALL_ROWS_SELECTOR = '.monaco-list-row';
static readonly SETTING_KEY_ATTR = 'data-key';
static readonly SETTING_ID_ATTR = 'data-id';
static readonly ELEMENT_FOCUSABLE_ATTR = 'data-focusable';
private readonly _onDidClickOverrideElement = this._register(new Emitter<ISettingOverrideClickEvent>());
readonly onDidClickOverrideElement: Event<ISettingOverrideClickEvent> = this._onDidClickOverrideElement.event;
protected readonly _onDidChangeSetting = this._register(new Emitter<ISettingChangeEvent>());
readonly onDidChangeSetting: Event<ISettingChangeEvent> = this._onDidChangeSetting.event;
protected readonly _onDidOpenSettings = this._register(new Emitter<string>());
readonly onDidOpenSettings: Event<string> = this._onDidOpenSettings.event;
private readonly _onDidClickSettingLink = this._register(new Emitter<ISettingLinkClickEvent>());
readonly onDidClickSettingLink: Event<ISettingLinkClickEvent> = this._onDidClickSettingLink.event;
protected readonly _onDidFocusSetting = this._register(new Emitter<SettingsTreeSettingElement>());
readonly onDidFocusSetting: Event<SettingsTreeSettingElement> = this._onDidFocusSetting.event;
private ignoredSettings: string[];
private readonly _onDidChangeIgnoredSettings = this._register(new Emitter<void>());
readonly onDidChangeIgnoredSettings: Event<void> = this._onDidChangeIgnoredSettings.event;
protected readonly _onDidChangeSettingHeight = this._register(new Emitter<HeightChangeParams>());
readonly onDidChangeSettingHeight: Event<HeightChangeParams> = this._onDidChangeSettingHeight.event;
protected readonly _onApplyFilter = this._register(new Emitter<string>());
readonly onApplyFilter: Event<string> = this._onApplyFilter.event;
private readonly markdownRenderer: MarkdownRenderer;
constructor(
private readonly settingActions: IAction[],
private readonly disposableActionFactory: (setting: ISetting, settingTarget: SettingsTarget) => IAction[],
@IThemeService protected readonly _themeService: IThemeService,
@IContextViewService protected readonly _contextViewService: IContextViewService,
@IOpenerService protected readonly _openerService: IOpenerService,
@IInstantiationService protected readonly _instantiationService: IInstantiationService,
@ICommandService protected readonly _commandService: ICommandService,
@IContextMenuService protected readonly _contextMenuService: IContextMenuService,
@IKeybindingService protected readonly _keybindingService: IKeybindingService,
@IConfigurationService protected readonly _configService: IConfigurationService,
@IExtensionService protected readonly _extensionsService: IExtensionService,
@IExtensionsWorkbenchService protected readonly _extensionsWorkbenchService: IExtensionsWorkbenchService,
@IProductService protected readonly _productService: IProductService,
@ITelemetryService protected readonly _telemetryService: ITelemetryService,
@IHoverService protected readonly _hoverService: IHoverService,
) {
super();
this.markdownRenderer = this._register(_instantiationService.createInstance(MarkdownRenderer, {}));
this.ignoredSettings = getIgnoredSettings(getDefaultIgnoredSettings(), this._configService);
this._register(this._configService.onDidChangeConfiguration(e => {
this.ignoredSettings = getIgnoredSettings(getDefaultIgnoredSettings(), this._configService);
this._onDidChangeIgnoredSettings.fire();
}));
}
abstract renderTemplate(container: HTMLElement): any;
abstract renderElement(element: ITreeNode<SettingsTreeSettingElement, never>, index: number, templateData: any): void;
protected renderCommonTemplate(tree: any, _container: HTMLElement, typeClass: string): ISettingItemTemplate {
_container.classList.add('setting-item');
_container.classList.add('setting-item-' + typeClass);
const toDispose = new DisposableStore();
const container = DOM.append(_container, $(AbstractSettingRenderer.CONTENTS_SELECTOR));
container.classList.add('settings-row-inner-container');
const titleElement = DOM.append(container, $('.setting-item-title'));
const labelCategoryContainer = DOM.append(titleElement, $('.setting-item-cat-label-container'));
const categoryElement = DOM.append(labelCategoryContainer, $('span.setting-item-category'));
const labelElementContainer = DOM.append(labelCategoryContainer, $('span.setting-item-label'));
const labelElement = toDispose.add(new SimpleIconLabel(labelElementContainer));
const indicatorsLabel = this._instantiationService.createInstance(SettingsTreeIndicatorsLabel, titleElement);
toDispose.add(indicatorsLabel);
const descriptionElement = DOM.append(container, $('.setting-item-description'));
const modifiedIndicatorElement = DOM.append(container, $('.setting-item-modified-indicator'));
toDispose.add(this._hoverService.setupManagedHover(getDefaultHoverDelegate('mouse'), modifiedIndicatorElement, () => localize('modified', "The setting has been configured in the current scope.")));
const valueElement = DOM.append(container, $('.setting-item-value'));
const controlElement = DOM.append(valueElement, $('div.setting-item-control'));
const deprecationWarningElement = DOM.append(container, $('.setting-item-deprecation-message'));
const toolbarContainer = DOM.append(container, $('.setting-toolbar-container'));
const toolbar = this.renderSettingToolbar(toolbarContainer);
const template: ISettingItemTemplate = {
toDispose,
elementDisposables: toDispose.add(new DisposableStore()),
containerElement: container,
categoryElement,
labelElement,
descriptionElement,
controlElement,
deprecationWarningElement,
indicatorsLabel,
toolbar
};
// Prevent clicks from being handled by list
toDispose.add(DOM.addDisposableListener(controlElement, DOM.EventType.MOUSE_DOWN, e => e.stopPropagation()));
toDispose.add(DOM.addDisposableListener(titleElement, DOM.EventType.MOUSE_ENTER, e => container.classList.add('mouseover')));
toDispose.add(DOM.addDisposableListener(titleElement, DOM.EventType.MOUSE_LEAVE, e => container.classList.remove('mouseover')));
return template;
}
protected addSettingElementFocusHandler(template: ISettingItemTemplate): void {
const focusTracker = DOM.trackFocus(template.containerElement);
template.toDispose.add(focusTracker);
focusTracker.onDidBlur(() => {
if (template.containerElement.classList.contains('focused')) {
template.containerElement.classList.remove('focused');
}
});
focusTracker.onDidFocus(() => {
template.containerElement.classList.add('focused');
if (template.context) {
this._onDidFocusSetting.fire(template.context);
}
});
}
protected renderSettingToolbar(container: HTMLElement): ToolBar {
const toggleMenuKeybinding = this._keybindingService.lookupKeybinding(SETTINGS_EDITOR_COMMAND_SHOW_CONTEXT_MENU);
let toggleMenuTitle = localize('settingsContextMenuTitle', "More Actions... ");
if (toggleMenuKeybinding) {
toggleMenuTitle += ` (${toggleMenuKeybinding && toggleMenuKeybinding.getLabel()})`;
}
const toolbar = new ToolBar(container, this._contextMenuService, {
toggleMenuTitle,
renderDropdownAsChildElement: !isIOS,
moreIcon: settingsMoreActionIcon
});
return toolbar;
}
protected renderSettingElement(node: ITreeNode<SettingsTreeSettingElement, never>, index: number, template: ISettingItemTemplate | ISettingBoolItemTemplate): void {
const element = node.element;
// The element must inspect itself to get information for
// the modified indicator and the overridden Settings indicators.
element.inspectSelf();
template.context = element;
template.toolbar.context = element;
const actions = this.disposableActionFactory(element.setting, element.settingsTarget);
actions.forEach(a => isDisposable(a) && template.elementDisposables.add(a));
template.toolbar.setActions([], [...this.settingActions, ...actions]);
const setting = element.setting;
template.containerElement.classList.toggle('is-configured', element.isConfigured);
template.containerElement.setAttribute(AbstractSettingRenderer.SETTING_KEY_ATTR, element.setting.key);
template.containerElement.setAttribute(AbstractSettingRenderer.SETTING_ID_ATTR, element.id);
const titleTooltip = setting.key + (element.isConfigured ? ' - Modified' : '');
template.categoryElement.textContent = element.displayCategory ? (element.displayCategory + ': ') : '';
template.elementDisposables.add(this._hoverService.setupManagedHover(getDefaultHoverDelegate('mouse'), template.categoryElement, titleTooltip));
template.labelElement.text = element.displayLabel;
template.labelElement.title = titleTooltip;
template.descriptionElement.innerText = '';
if (element.setting.descriptionIsMarkdown) {
const renderedDescription = this.renderSettingMarkdown(element, template.containerElement, element.description, template.elementDisposables);
template.descriptionElement.appendChild(renderedDescription);
} else {
template.descriptionElement.innerText = element.description;
}
template.indicatorsLabel.updateScopeOverrides(element, this._onDidClickOverrideElement, this._onApplyFilter);
template.elementDisposables.add(this._configService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration(APPLY_ALL_PROFILES_SETTING)) {
template.indicatorsLabel.updateScopeOverrides(element, this._onDidClickOverrideElement, this._onApplyFilter);
}
}));
const onChange = (value: any) => this._onDidChangeSetting.fire({
key: element.setting.key,
value,
type: template.context!.valueType,
manualReset: false,
scope: element.setting.scope
});
const deprecationText = element.setting.deprecationMessage || '';
if (deprecationText && element.setting.deprecationMessageIsMarkdown) {
template.deprecationWarningElement.innerText = '';
template.deprecationWarningElement.appendChild(this.renderSettingMarkdown(element, template.containerElement, element.setting.deprecationMessage!, template.elementDisposables));
} else {
template.deprecationWarningElement.innerText = deprecationText;
}
template.deprecationWarningElement.prepend($('.codicon.codicon-error'));
template.containerElement.classList.toggle('is-deprecated', !!deprecationText);
this.renderValue(element, <ISettingItemTemplate>template, onChange);
template.indicatorsLabel.updateWorkspaceTrust(element);
template.indicatorsLabel.updateSyncIgnored(element, this.ignoredSettings);
template.indicatorsLabel.updateDefaultOverrideIndicator(element);
template.elementDisposables.add(this.onDidChangeIgnoredSettings(() => {
template.indicatorsLabel.updateSyncIgnored(element, this.ignoredSettings);
}));