hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
listlengths 5
5
|
---|---|---|---|---|---|
{
"id": 2,
"code_window": [
"\tstatic readonly ID = 'toolbar.toggle.more';\n",
"\n",
"\tprivate _menuActions: IAction[];\n",
"\tprivate toggleDropdownMenu: () => void;\n",
"\n",
"\tconstructor(toggleDropdownMenu: () => void) {\n",
"\t\tsuper(ToggleMenuAction.ID, nls.localize('moreActions', \"More Actions...\"), null, true);\n",
"\n",
"\t\tthis.toggleDropdownMenu = toggleDropdownMenu;\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tconstructor(toggleDropdownMenu: () => void, title?: string) {\n",
"\t\ttitle = title || nls.localize('moreActions', \"More Actions...\");\n",
"\t\tsuper(ToggleMenuAction.ID, title, null, true);\n"
],
"file_path": "src/vs/base/browser/ui/toolbar/toolbar.ts",
"type": "replace",
"edit_start_line_idx": 172
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as path from 'path';
import * as fs from 'fs';
import * as cp from 'child_process';
import * as vscode from 'vscode';
import * as nls from 'vscode-nls';
const localize = nls.loadMessageBundle();
type AutoDetect = 'on' | 'off';
function exists(file: string): Promise<boolean> {
return new Promise<boolean>((resolve, _reject) => {
fs.exists(file, (value) => {
resolve(value);
});
});
}
function exec(command: string, options: cp.ExecOptions): Promise<{ stdout: string; stderr: string }> {
return new Promise<{ stdout: string; stderr: string }>((resolve, reject) => {
cp.exec(command, options, (error, stdout, stderr) => {
if (error) {
reject({ error, stdout, stderr });
}
resolve({ stdout, stderr });
});
});
}
const buildNames: string[] = ['build', 'compile', 'watch'];
function isBuildTask(name: string): boolean {
for (let buildName of buildNames) {
if (name.indexOf(buildName) !== -1) {
return true;
}
}
return false;
}
const testNames: string[] = ['test'];
function isTestTask(name: string): boolean {
for (let testName of testNames) {
if (name.indexOf(testName) !== -1) {
return true;
}
}
return false;
}
let _channel: vscode.OutputChannel;
function getOutputChannel(): vscode.OutputChannel {
if (!_channel) {
_channel = vscode.window.createOutputChannel('Gulp Auto Detection');
}
return _channel;
}
interface GulpTaskDefinition extends vscode.TaskDefinition {
task: string;
file?: string;
}
class FolderDetector {
private fileWatcher: vscode.FileSystemWatcher | undefined;
private promise: Thenable<vscode.Task[]> | undefined;
constructor(private _workspaceFolder: vscode.WorkspaceFolder) {
}
public get workspaceFolder(): vscode.WorkspaceFolder {
return this._workspaceFolder;
}
public isEnabled(): boolean {
return vscode.workspace.getConfiguration('gulp', this._workspaceFolder.uri).get<AutoDetect>('autoDetect') === 'on';
}
public start(): void {
let pattern = path.join(this._workspaceFolder.uri.fsPath, 'gulpfile{.babel.js,.js,.ts}');
this.fileWatcher = vscode.workspace.createFileSystemWatcher(pattern);
this.fileWatcher.onDidChange(() => this.promise = undefined);
this.fileWatcher.onDidCreate(() => this.promise = undefined);
this.fileWatcher.onDidDelete(() => this.promise = undefined);
}
public async getTasks(): Promise<vscode.Task[]> {
if (!this.promise) {
this.promise = this.computeTasks();
}
return this.promise;
}
private async computeTasks(): Promise<vscode.Task[]> {
let rootPath = this._workspaceFolder.uri.scheme === 'file' ? this._workspaceFolder.uri.fsPath : undefined;
let emptyTasks: vscode.Task[] = [];
if (!rootPath) {
return emptyTasks;
}
let gulpfile = path.join(rootPath, 'gulpfile.js');
if (!await exists(gulpfile)) {
gulpfile = path.join(rootPath, 'gulpfile.babel.js');
if (! await exists(gulpfile)) {
return emptyTasks;
}
}
let gulpCommand: string;
let platform = process.platform;
if (platform === 'win32' && await exists(path.join(rootPath!, 'node_modules', '.bin', 'gulp.cmd'))) {
gulpCommand = path.join('.', 'node_modules', '.bin', 'gulp.cmd');
} else if ((platform === 'linux' || platform === 'darwin') && await exists(path.join(rootPath!, 'node_modules', '.bin', 'gulp'))) {
gulpCommand = path.join('.', 'node_modules', '.bin', 'gulp');
} else {
gulpCommand = 'gulp';
}
let commandLine = `${gulpCommand} --tasks-simple --no-color`;
try {
let { stdout, stderr } = await exec(commandLine, { cwd: rootPath });
if (stderr && stderr.length > 0) {
getOutputChannel().appendLine(stderr);
getOutputChannel().show(true);
}
let result: vscode.Task[] = [];
if (stdout) {
let lines = stdout.split(/\r{0,1}\n/);
for (let line of lines) {
if (line.length === 0) {
continue;
}
let kind: GulpTaskDefinition = {
type: 'gulp',
task: line
};
let options: vscode.ShellExecutionOptions = { cwd: this.workspaceFolder.uri.fsPath };
let task = new vscode.Task(kind, this.workspaceFolder, line, 'gulp', new vscode.ShellExecution(`${gulpCommand} ${line}`, options));
result.push(task);
let lowerCaseLine = line.toLowerCase();
if (isBuildTask(lowerCaseLine)) {
task.group = vscode.TaskGroup.Build;
} else if (isTestTask(lowerCaseLine)) {
task.group = vscode.TaskGroup.Test;
}
}
}
return result;
} catch (err) {
let channel = getOutputChannel();
if (err.stderr) {
channel.appendLine(err.stderr);
}
if (err.stdout) {
channel.appendLine(err.stdout);
}
channel.appendLine(localize('execFailed', 'Auto detecting gulp for folder {0} failed with error: {1}', this.workspaceFolder.name, err.error ? err.error.toString() : 'unknown'));
channel.show(true);
return emptyTasks;
}
}
public dispose() {
this.promise = undefined;
if (this.fileWatcher) {
this.fileWatcher.dispose();
}
}
}
class TaskDetector {
private taskProvider: vscode.Disposable | undefined;
private detectors: Map<string, FolderDetector> = new Map();
constructor() {
}
public start(): void {
let folders = vscode.workspace.workspaceFolders;
if (folders) {
this.updateWorkspaceFolders(folders, []);
}
vscode.workspace.onDidChangeWorkspaceFolders((event) => this.updateWorkspaceFolders(event.added, event.removed));
vscode.workspace.onDidChangeConfiguration(this.updateConfiguration, this);
}
public dispose(): void {
if (this.taskProvider) {
this.taskProvider.dispose();
this.taskProvider = undefined;
}
this.detectors.clear();
}
private updateWorkspaceFolders(added: vscode.WorkspaceFolder[], removed: vscode.WorkspaceFolder[]): void {
for (let remove of removed) {
let detector = this.detectors.get(remove.uri.toString());
if (detector) {
detector.dispose();
this.detectors.delete(remove.uri.toString());
}
}
for (let add of added) {
let detector = new FolderDetector(add);
if (detector.isEnabled()) {
this.detectors.set(add.uri.toString(), detector);
detector.start();
}
}
this.updateProvider();
}
private updateConfiguration(): void {
for (let detector of this.detectors.values()) {
if (!detector.isEnabled()) {
detector.dispose();
this.detectors.delete(detector.workspaceFolder.uri.toString());
}
}
let folders = vscode.workspace.workspaceFolders;
if (folders) {
for (let folder of folders) {
if (!this.detectors.has(folder.uri.toString())) {
let detector = new FolderDetector(folder);
if (detector.isEnabled()) {
this.detectors.set(folder.uri.toString(), detector);
detector.start();
}
}
}
}
this.updateProvider();
}
private updateProvider(): void {
if (!this.taskProvider && this.detectors.size > 0) {
this.taskProvider = vscode.workspace.registerTaskProvider('gulp', {
provideTasks: () => {
return this.getTasks();
},
resolveTask(_task: vscode.Task): vscode.Task | undefined {
return undefined;
}
});
}
else if (this.taskProvider && this.detectors.size === 0) {
this.taskProvider.dispose();
this.taskProvider = undefined;
}
}
public getTasks(): Promise<vscode.Task[]> {
return this.computeTasks();
}
private computeTasks(): Promise<vscode.Task[]> {
if (this.detectors.size === 0) {
return Promise.resolve([]);
} else if (this.detectors.size === 1) {
return this.detectors.values().next().value.getTasks();
} else {
let promises: Promise<vscode.Task[]>[] = [];
for (let detector of this.detectors.values()) {
promises.push(detector.getTasks().then((value) => value, () => []));
}
return Promise.all(promises).then((values) => {
let result: vscode.Task[] = [];
for (let tasks of values) {
if (tasks && tasks.length > 0) {
result.push(...tasks);
}
}
return result;
});
}
}
}
let detector: TaskDetector;
export function activate(_context: vscode.ExtensionContext): void {
detector = new TaskDetector();
detector.start();
}
export function deactivate(): void {
detector.dispose();
} | extensions/gulp/src/main.ts | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.0013702489668503404,
0.00022251113841775805,
0.00016774212417658418,
0.00017356473836116493,
0.00021924420434515923
]
|
{
"id": 2,
"code_window": [
"\tstatic readonly ID = 'toolbar.toggle.more';\n",
"\n",
"\tprivate _menuActions: IAction[];\n",
"\tprivate toggleDropdownMenu: () => void;\n",
"\n",
"\tconstructor(toggleDropdownMenu: () => void) {\n",
"\t\tsuper(ToggleMenuAction.ID, nls.localize('moreActions', \"More Actions...\"), null, true);\n",
"\n",
"\t\tthis.toggleDropdownMenu = toggleDropdownMenu;\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tconstructor(toggleDropdownMenu: () => void, title?: string) {\n",
"\t\ttitle = title || nls.localize('moreActions', \"More Actions...\");\n",
"\t\tsuper(ToggleMenuAction.ID, title, null, true);\n"
],
"file_path": "src/vs/base/browser/ui/toolbar/toolbar.ts",
"type": "replace",
"edit_start_line_idx": 172
} | // ATTENTION - THIS DIRECTORY CONTAINS THIRD PARTY OPEN SOURCE MATERIALS:
[{
"name": "Colorsublime-Themes",
"version": "0.1.0",
"repositoryURL": "https://github.com/Colorsublime/Colorsublime-Themes",
"description": "The themes in this folders are copied from colorsublime.com. <<<TODO check the licenses, we can easily drop the themes>>>"
}]
| extensions/theme-monokai/OSSREADME.json | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.0001736219273880124,
0.0001736219273880124,
0.0001736219273880124,
0.0001736219273880124,
0
]
|
{
"id": 3,
"code_window": [
"import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';\n",
"import { ICommandService } from 'vs/platform/commands/common/commands';\n",
"import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n",
"import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';\n",
"import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';\n",
"import { WorkbenchTreeController } from 'vs/platform/list/browser/listService';\n",
"import { IOpenerService } from 'vs/platform/opener/common/opener';\n",
"import { editorBackground, errorForeground, focusBorder, foreground, inputValidationErrorBackground, inputValidationErrorForeground, inputValidationErrorBorder } from 'vs/platform/theme/common/colorRegistry';\n",
"import { attachButtonStyler, attachInputBoxStyler, attachSelectBoxStyler, attachStyler } from 'vs/platform/theme/common/styler';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "add",
"edit_start_line_idx": 35
} | /*---------------------------------------------------------------------------------------------
* 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 { renderMarkdown } from 'vs/base/browser/htmlContentRenderer';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { alert as ariaAlert } from 'vs/base/browser/ui/aria/aria';
import { Button } from 'vs/base/browser/ui/button/button';
import { Checkbox } from 'vs/base/browser/ui/checkbox/checkbox';
import { InputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { SelectBox } from 'vs/base/browser/ui/selectBox/selectBox';
import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar';
import { Action, IAction } from 'vs/base/common/actions';
import * as arrays from 'vs/base/common/arrays';
import { Color, RGBA } from 'vs/base/common/color';
import { onUnexpectedError } from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
import { KeyCode } from 'vs/base/common/keyCodes';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { escapeRegExpCharacters, startsWith } from 'vs/base/common/strings';
import { URI } from 'vs/base/common/uri';
import { TPromise } from 'vs/base/common/winjs.base';
import { IAccessibilityProvider, IDataSource, IFilter, IRenderer as ITreeRenderer, ITree, ITreeConfiguration } from 'vs/base/parts/tree/browser/tree';
import { DefaultTreestyler } from 'vs/base/parts/tree/browser/treeDefaults';
import { Tree } from 'vs/base/parts/tree/browser/treeImpl';
import { localize } from 'vs/nls';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { WorkbenchTreeController } from 'vs/platform/list/browser/listService';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { editorBackground, errorForeground, focusBorder, foreground, inputValidationErrorBackground, inputValidationErrorForeground, inputValidationErrorBorder } from 'vs/platform/theme/common/colorRegistry';
import { attachButtonStyler, attachInputBoxStyler, attachSelectBoxStyler, attachStyler } from 'vs/platform/theme/common/styler';
import { ICssStyleCollector, ITheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { ITOCEntry } from 'vs/workbench/parts/preferences/browser/settingsLayout';
import { ISettingsEditorViewState, isExcludeSetting, SettingsTreeElement, SettingsTreeGroupElement, SettingsTreeNewExtensionsElement, settingKeyToDisplayFormat, SettingsTreeSettingElement } from 'vs/workbench/parts/preferences/browser/settingsTreeModels';
import { ExcludeSettingWidget, IExcludeDataItem, settingsHeaderForeground, settingsNumberInputBackground, settingsNumberInputBorder, settingsNumberInputForeground, settingsSelectBackground, settingsSelectBorder, settingsSelectListBorder, settingsSelectForeground, settingsTextInputBackground, settingsTextInputBorder, settingsTextInputForeground } from 'vs/workbench/parts/preferences/browser/settingsWidgets';
import { ISetting, ISettingsGroup } from 'vs/workbench/services/preferences/common/preferences';
const $ = DOM.$;
function getExcludeDisplayValue(element: SettingsTreeSettingElement): IExcludeDataItem[] {
const data = element.isConfigured ?
{ ...element.defaultValue, ...element.scopeValue } :
element.defaultValue;
return Object.keys(data)
.filter(key => !!data[key])
.map(key => {
const value = data[key];
const sibling = typeof value === 'boolean' ? undefined : value.when;
return {
id: key,
pattern: key,
sibling
};
});
}
export function resolveSettingsTree(tocData: ITOCEntry, coreSettingsGroups: ISettingsGroup[]): { tree: ITOCEntry, leftoverSettings: Set<ISetting> } {
const allSettings = getFlatSettings(coreSettingsGroups);
return {
tree: _resolveSettingsTree(tocData, allSettings),
leftoverSettings: allSettings
};
}
export function resolveExtensionsSettings(groups: ISettingsGroup[]): ITOCEntry {
const settingsGroupToEntry = (group: ISettingsGroup) => {
const flatSettings = arrays.flatten(
group.sections.map(section => section.settings));
return {
id: group.id,
label: group.title,
settings: flatSettings
};
};
const extGroups = groups
.sort((a, b) => a.title.localeCompare(b.title))
.map(g => settingsGroupToEntry(g));
return {
id: 'extensions',
label: localize('extensions', "Extensions"),
children: extGroups
};
}
function _resolveSettingsTree(tocData: ITOCEntry, allSettings: Set<ISetting>): ITOCEntry {
let children: ITOCEntry[];
if (tocData.children) {
children = tocData.children
.map(child => _resolveSettingsTree(child, allSettings))
.filter(child => (child.children && child.children.length) || (child.settings && child.settings.length));
}
let settings: ISetting[];
if (tocData.settings) {
settings = arrays.flatten(tocData.settings.map(pattern => getMatchingSettings(allSettings, <string>pattern)));
}
if (!children && !settings) {
return null;
}
return {
id: tocData.id,
label: tocData.label,
children,
settings
};
}
function getMatchingSettings(allSettings: Set<ISetting>, pattern: string): ISetting[] {
const result: ISetting[] = [];
allSettings.forEach(s => {
if (settingMatches(s, pattern)) {
result.push(s);
allSettings.delete(s);
}
});
return result.sort((a, b) => a.key.localeCompare(b.key));
}
const settingPatternCache = new Map<string, RegExp>();
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 (let group of settingsGroups) {
for (let section of group.sections) {
for (let s of section.settings) {
if (!s.overrides || !s.overrides.length) {
result.add(s);
}
}
}
}
return result;
}
export class SettingsDataSource implements IDataSource {
getId(tree: ITree, element: SettingsTreeElement): string {
return element.id;
}
hasChildren(tree: ITree, element: SettingsTreeElement): boolean {
if (element instanceof SettingsTreeGroupElement) {
return true;
}
return false;
}
getChildren(tree: ITree, element: SettingsTreeElement): TPromise<any> {
return TPromise.as(this._getChildren(element));
}
private _getChildren(element: SettingsTreeElement): SettingsTreeElement[] {
if (element instanceof SettingsTreeGroupElement) {
return element.children;
} else {
// No children...
return null;
}
}
getParent(tree: ITree, element: SettingsTreeElement): TPromise<any> {
return TPromise.wrap(element && element.parent);
}
shouldAutoexpand(): boolean {
return true;
}
}
export class SimplePagedDataSource implements IDataSource {
private static readonly SETTINGS_PER_PAGE = 30;
private static readonly BUFFER = 5;
private loadedToIndex: number;
constructor(private realDataSource: IDataSource) {
this.reset();
}
reset(): void {
this.loadedToIndex = SimplePagedDataSource.SETTINGS_PER_PAGE * 2;
}
pageTo(index: number, top = false): boolean {
const buffer = top ? SimplePagedDataSource.SETTINGS_PER_PAGE : SimplePagedDataSource.BUFFER;
if (index > this.loadedToIndex - buffer) {
this.loadedToIndex = (Math.ceil(index / SimplePagedDataSource.SETTINGS_PER_PAGE) + 1) * SimplePagedDataSource.SETTINGS_PER_PAGE;
return true;
} else {
return false;
}
}
getId(tree: ITree, element: any): string {
return this.realDataSource.getId(tree, element);
}
hasChildren(tree: ITree, element: any): boolean {
return this.realDataSource.hasChildren(tree, element);
}
getChildren(tree: ITree, element: SettingsTreeGroupElement): TPromise<any> {
return this.realDataSource.getChildren(tree, element).then(realChildren => {
return this._getChildren(realChildren);
});
}
_getChildren(realChildren: SettingsTreeElement[]): any[] {
const lastChild = realChildren[realChildren.length - 1];
if (lastChild && lastChild.index > this.loadedToIndex) {
return realChildren.filter(child => {
return child.index < this.loadedToIndex;
});
} else {
return realChildren;
}
}
getParent(tree: ITree, element: any): TPromise<any> {
return this.realDataSource.getParent(tree, element);
}
shouldAutoexpand(tree: ITree, element: any): boolean {
return this.realDataSource.shouldAutoexpand(tree, element);
}
}
interface IDisposableTemplate {
toDispose: IDisposable[];
}
interface ISettingItemTemplate<T = any> extends IDisposableTemplate {
onChange?: (value: T) => void;
context?: SettingsTreeSettingElement;
containerElement: HTMLElement;
categoryElement: HTMLElement;
labelElement: HTMLElement;
descriptionElement: HTMLElement;
controlElement: HTMLElement;
deprecationWarningElement: HTMLElement;
otherOverridesElement: HTMLElement;
toolbar: ToolBar;
}
interface ISettingBoolItemTemplate extends ISettingItemTemplate<boolean> {
checkbox: Checkbox;
}
interface ISettingTextItemTemplate extends ISettingItemTemplate<string> {
inputBox: InputBox;
validationErrorMessageElement: HTMLElement;
}
type ISettingNumberItemTemplate = ISettingTextItemTemplate;
interface ISettingEnumItemTemplate extends ISettingItemTemplate<number> {
selectBox: SelectBox;
enumDescriptionElement: HTMLElement;
}
interface ISettingComplexItemTemplate extends ISettingItemTemplate<void> {
button: Button;
}
interface ISettingExcludeItemTemplate extends ISettingItemTemplate<void> {
excludeWidget: ExcludeSettingWidget;
}
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_NUMBER_TEMPLATE_ID = 'settings.number.template';
const SETTINGS_ENUM_TEMPLATE_ID = 'settings.enum.template';
const SETTINGS_BOOL_TEMPLATE_ID = 'settings.bool.template';
const SETTINGS_EXCLUDE_TEMPLATE_ID = 'settings.exclude.template';
const SETTINGS_COMPLEX_TEMPLATE_ID = 'settings.complex.template';
const SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID = 'settings.newExtensions.template';
const SETTINGS_GROUP_ELEMENT_TEMPLATE_ID = 'settings.group.template';
export interface ISettingChangeEvent {
key: string;
value: any; // undefined => reset/unconfigure
}
export interface ISettingLinkClickEvent {
source: SettingsTreeSettingElement;
targetKey: string;
}
export class SettingsRenderer implements ITreeRenderer {
public static readonly CONTROL_CLASS = 'setting-control-focus-target';
public static readonly CONTROL_SELECTOR = '.' + SettingsRenderer.CONTROL_CLASS;
public static readonly SETTING_KEY_ATTR = 'data-key';
private readonly _onDidChangeSetting: Emitter<ISettingChangeEvent> = new Emitter<ISettingChangeEvent>();
public readonly onDidChangeSetting: Event<ISettingChangeEvent> = this._onDidChangeSetting.event;
private readonly _onDidOpenSettings: Emitter<string> = new Emitter<string>();
public readonly onDidOpenSettings: Event<string> = this._onDidOpenSettings.event;
private readonly _onDidClickSettingLink: Emitter<ISettingLinkClickEvent> = new Emitter<ISettingLinkClickEvent>();
public readonly onDidClickSettingLink: Event<ISettingLinkClickEvent> = this._onDidClickSettingLink.event;
private readonly _onDidFocusSetting: Emitter<SettingsTreeSettingElement> = new Emitter<SettingsTreeSettingElement>();
public readonly onDidFocusSetting: Event<SettingsTreeSettingElement> = this._onDidFocusSetting.event;
private descriptionMeasureContainer: HTMLElement;
private longestSingleLineDescription = 0;
private rowHeightCache = new Map<string, number>();
private lastRenderedWidth: number;
private settingActions: IAction[];
constructor(
_measureContainer: HTMLElement,
@IThemeService private themeService: IThemeService,
@IContextViewService private contextViewService: IContextViewService,
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@ICommandService private readonly commandService: ICommandService,
@IContextMenuService private contextMenuService: IContextMenuService
) {
this.descriptionMeasureContainer = $('.setting-item-description');
DOM.append(_measureContainer,
$('.setting-measure-container.monaco-tree-row', undefined,
$('.setting-item', undefined,
this.descriptionMeasureContainer)));
this.settingActions = [
new Action('settings.resetSetting', localize('resetSettingLabel', "Reset Setting"), undefined, undefined, (context: SettingsTreeSettingElement) => {
if (context) {
this._onDidChangeSetting.fire({ key: context.setting.key, value: undefined });
}
return TPromise.wrap(null);
}),
new Separator(),
this.instantiationService.createInstance(CopySettingIdAction),
this.instantiationService.createInstance(CopySettingAsJSONAction),
];
}
showContextMenu(element: SettingsTreeSettingElement, settingDOMElement: HTMLElement): void {
const toolbarElement: HTMLElement = settingDOMElement.querySelector('.toolbar-toggle-more');
if (toolbarElement) {
this.contextMenuService.showContextMenu({
getActions: () => TPromise.wrap(this.settingActions),
getAnchor: () => toolbarElement,
getActionsContext: () => element
});
}
}
updateWidth(width: number): void {
if (this.lastRenderedWidth !== width) {
this.rowHeightCache = new Map<string, number>();
}
this.longestSingleLineDescription = 0;
this.lastRenderedWidth = width;
}
getHeight(tree: ITree, element: SettingsTreeElement): number {
if (this.rowHeightCache.has(element.id) && !(element instanceof SettingsTreeSettingElement && isExcludeSetting(element.setting))) {
return this.rowHeightCache.get(element.id);
}
const h = this._getHeight(tree, element);
this.rowHeightCache.set(element.id, h);
return h;
}
_getHeight(tree: ITree, element: SettingsTreeElement): number {
if (element instanceof SettingsTreeGroupElement) {
if (element.isFirstGroup) {
return 31;
}
return 40 + (7 * element.level);
}
if (element instanceof SettingsTreeSettingElement) {
if (isExcludeSetting(element.setting)) {
return this._getExcludeSettingHeight(element);
} else {
return this.measureSettingElementHeight(tree, element);
}
}
if (element instanceof SettingsTreeNewExtensionsElement) {
return 40;
}
return 0;
}
_getExcludeSettingHeight(element: SettingsTreeSettingElement): number {
const displayValue = getExcludeDisplayValue(element);
return (displayValue.length + 1) * 22 + 66 + this.measureSettingDescription(element);
}
private measureSettingElementHeight(tree: ITree, element: SettingsTreeSettingElement): number {
let heightExcludingDescription = 86;
if (element.valueType === 'boolean') {
heightExcludingDescription = 60;
}
return heightExcludingDescription + this.measureSettingDescription(element);
}
private measureSettingDescription(element: SettingsTreeSettingElement): number {
if (element.description.length < this.longestSingleLineDescription * .8) {
// Most setting descriptions are one short line, so try to avoid measuring them.
// If the description is less than 80% of the longest single line description, assume this will also render to be one line.
return 18;
}
const boolMeasureClass = 'measure-bool-description';
if (element.valueType === 'boolean') {
this.descriptionMeasureContainer.classList.add(boolMeasureClass);
} else if (this.descriptionMeasureContainer.classList.contains(boolMeasureClass)) {
this.descriptionMeasureContainer.classList.remove(boolMeasureClass);
}
const shouldRenderMarkdown = element.setting.descriptionIsMarkdown && element.description.indexOf('\n- ') >= 0;
while (this.descriptionMeasureContainer.firstChild) {
this.descriptionMeasureContainer.removeChild(this.descriptionMeasureContainer.firstChild);
}
if (shouldRenderMarkdown) {
const text = fixSettingLinks(element.description);
const rendered = renderMarkdown({ value: text });
rendered.classList.add('setting-item-description-markdown');
this.descriptionMeasureContainer.appendChild(rendered);
return this.descriptionMeasureContainer.offsetHeight;
} else {
// Remove markdown links, setting links, backticks
const measureText = element.setting.descriptionIsMarkdown ?
fixSettingLinks(element.description)
.replace(/\[(.*)\]\(.*\)/g, '$1')
.replace(/`([^`]*)`/g, '$1') :
element.description;
this.descriptionMeasureContainer.innerText = measureText;
const h = this.descriptionMeasureContainer.offsetHeight;
if (h < 20 && measureText.length > this.longestSingleLineDescription) {
this.longestSingleLineDescription = measureText.length;
}
return h;
}
}
getTemplateId(tree: ITree, element: SettingsTreeElement): string {
if (element instanceof SettingsTreeGroupElement) {
return SETTINGS_GROUP_ELEMENT_TEMPLATE_ID;
}
if (element instanceof SettingsTreeSettingElement) {
if (element.valueType === 'boolean') {
return SETTINGS_BOOL_TEMPLATE_ID;
}
if (element.valueType === 'integer' || element.valueType === 'number' || element.valueType === 'nullable-integer' || element.valueType === 'nullable-number') {
return SETTINGS_NUMBER_TEMPLATE_ID;
}
if (element.valueType === 'string') {
return SETTINGS_TEXT_TEMPLATE_ID;
}
if (element.valueType === 'enum') {
return SETTINGS_ENUM_TEMPLATE_ID;
}
if (element.valueType === 'exclude') {
return SETTINGS_EXCLUDE_TEMPLATE_ID;
}
return SETTINGS_COMPLEX_TEMPLATE_ID;
}
if (element instanceof SettingsTreeNewExtensionsElement) {
return SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID;
}
return '';
}
renderTemplate(tree: ITree, templateId: string, container: HTMLElement) {
if (templateId === SETTINGS_GROUP_ELEMENT_TEMPLATE_ID) {
return this.renderGroupTitleTemplate(container);
}
if (templateId === SETTINGS_TEXT_TEMPLATE_ID) {
return this.renderSettingTextTemplate(tree, container);
}
if (templateId === SETTINGS_NUMBER_TEMPLATE_ID) {
return this.renderSettingNumberTemplate(tree, container);
}
if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
return this.renderSettingBoolTemplate(tree, container);
}
if (templateId === SETTINGS_ENUM_TEMPLATE_ID) {
return this.renderSettingEnumTemplate(tree, container);
}
if (templateId === SETTINGS_EXCLUDE_TEMPLATE_ID) {
return this.renderSettingExcludeTemplate(tree, container);
}
if (templateId === SETTINGS_COMPLEX_TEMPLATE_ID) {
return this.renderSettingComplexTemplate(tree, container);
}
if (templateId === SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID) {
return this.renderNewExtensionsTemplate(container);
}
return null;
}
private renderGroupTitleTemplate(container: HTMLElement): IGroupTitleTemplate {
DOM.addClass(container, 'group-title');
const toDispose = [];
const template: IGroupTitleTemplate = {
parent: container,
toDispose
};
return template;
}
private renderCommonTemplate(tree: ITree, container: HTMLElement, typeClass: string): ISettingItemTemplate {
DOM.addClass(container, 'setting-item');
DOM.addClass(container, 'setting-item-' + typeClass);
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 labelElement = DOM.append(labelCategoryContainer, $('span.setting-item-label'));
const otherOverridesElement = DOM.append(titleElement, $('span.setting-item-overrides'));
const descriptionElement = DOM.append(container, $('.setting-item-description'));
const modifiedIndicatorElement = DOM.append(container, $('.setting-item-modified-indicator'));
modifiedIndicatorElement.title = localize('modified', "Modified");
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 toDispose = [];
const toolbar = this.renderSettingToolbar(container);
const template: ISettingItemTemplate = {
toDispose,
containerElement: container,
categoryElement,
labelElement,
descriptionElement,
controlElement,
deprecationWarningElement,
otherOverridesElement,
toolbar
};
// Prevent clicks from being handled by list
toDispose.push(DOM.addDisposableListener(controlElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addStandardDisposableListener(valueElement, 'keydown', (e: StandardKeyboardEvent) => {
if (e.keyCode === KeyCode.Escape) {
tree.domFocus();
e.browserEvent.stopPropagation();
}
}));
return template;
}
private addSettingElementFocusHandler(template: ISettingItemTemplate): void {
const focusTracker = DOM.trackFocus(template.containerElement);
template.toDispose.push(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);
}
});
}
private renderSettingTextTemplate(tree: ITree, container: HTMLElement, type = 'text'): ISettingTextItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'text');
const validationErrorMessageElement = DOM.append(container, $('.setting-item-validation-message'));
const inputBox = new InputBox(common.controlElement, this.contextViewService);
common.toDispose.push(inputBox);
common.toDispose.push(attachInputBoxStyler(inputBox, this.themeService, {
inputBackground: settingsTextInputBackground,
inputForeground: settingsTextInputForeground,
inputBorder: settingsTextInputBorder
}));
common.toDispose.push(
inputBox.onDidChange(e => {
if (template.onChange) {
template.onChange(e);
}
}));
common.toDispose.push(inputBox);
inputBox.inputElement.classList.add(SettingsRenderer.CONTROL_CLASS);
const template: ISettingTextItemTemplate = {
...common,
inputBox,
validationErrorMessageElement
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderSettingNumberTemplate(tree: ITree, container: HTMLElement): ISettingNumberItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'number');
const validationErrorMessageElement = DOM.append(container, $('.setting-item-validation-message'));
const inputBox = new InputBox(common.controlElement, this.contextViewService, { type: 'number' });
common.toDispose.push(inputBox);
common.toDispose.push(attachInputBoxStyler(inputBox, this.themeService, {
inputBackground: settingsNumberInputBackground,
inputForeground: settingsNumberInputForeground,
inputBorder: settingsNumberInputBorder
}));
common.toDispose.push(
inputBox.onDidChange(e => {
if (template.onChange) {
template.onChange(e);
}
}));
common.toDispose.push(inputBox);
inputBox.inputElement.classList.add(SettingsRenderer.CONTROL_CLASS);
const template: ISettingNumberItemTemplate = {
...common,
inputBox,
validationErrorMessageElement
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderSettingToolbar(container: HTMLElement): ToolBar {
const toolbar = new ToolBar(container, this.contextMenuService, {});
toolbar.setActions([], this.settingActions)();
const button = container.querySelector('.toolbar-toggle-more');
if (button) {
(<HTMLElement>button).tabIndex = -1;
}
return toolbar;
}
private renderSettingBoolTemplate(tree: ITree, container: HTMLElement): ISettingBoolItemTemplate {
DOM.addClass(container, 'setting-item');
DOM.addClass(container, 'setting-item-bool');
const titleElement = DOM.append(container, $('.setting-item-title'));
const categoryElement = DOM.append(titleElement, $('span.setting-item-category'));
const labelElement = DOM.append(titleElement, $('span.setting-item-label'));
const otherOverridesElement = DOM.append(titleElement, $('span.setting-item-overrides'));
const descriptionAndValueElement = DOM.append(container, $('.setting-item-value-description'));
const controlElement = DOM.append(descriptionAndValueElement, $('.setting-item-bool-control'));
const descriptionElement = DOM.append(descriptionAndValueElement, $('.setting-item-description'));
const modifiedIndicatorElement = DOM.append(container, $('.setting-item-modified-indicator'));
modifiedIndicatorElement.title = localize('modified', "Modified");
const deprecationWarningElement = DOM.append(container, $('.setting-item-deprecation-message'));
const toDispose = [];
const checkbox = new Checkbox({ actionClassName: 'setting-value-checkbox', isChecked: true, title: '', inputActiveOptionBorder: null });
controlElement.appendChild(checkbox.domNode);
toDispose.push(checkbox);
toDispose.push(checkbox.onChange(() => {
if (template.onChange) {
template.onChange(checkbox.checked);
}
}));
// Need to listen for mouse clicks on description and toggle checkbox - use target ID for safety
// Also have to ignore embedded links - too buried to stop propagation
toDispose.push(DOM.addDisposableListener(descriptionElement, DOM.EventType.MOUSE_DOWN, (e) => {
const targetElement = <HTMLElement>e.toElement;
const targetId = descriptionElement.getAttribute('checkbox_label_target_id');
// Make sure we are not a link and the target ID matches
// Toggle target checkbox
if (targetElement.tagName.toLowerCase() !== 'a' && targetId === template.checkbox.domNode.id) {
template.checkbox.checked = template.checkbox.checked ? false : true;
template.onChange(checkbox.checked);
}
DOM.EventHelper.stop(e);
}));
checkbox.domNode.classList.add(SettingsRenderer.CONTROL_CLASS);
const toolbar = this.renderSettingToolbar(container);
toDispose.push(toolbar);
const template: ISettingBoolItemTemplate = {
toDispose,
containerElement: container,
categoryElement,
labelElement,
controlElement,
checkbox,
descriptionElement,
deprecationWarningElement,
otherOverridesElement,
toolbar
};
this.addSettingElementFocusHandler(template);
// Prevent clicks from being handled by list
toDispose.push(DOM.addDisposableListener(controlElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addStandardDisposableListener(controlElement, 'keydown', (e: StandardKeyboardEvent) => {
if (e.keyCode === KeyCode.Escape) {
tree.domFocus();
e.browserEvent.stopPropagation();
}
}));
return template;
}
public cancelSuggesters() {
this.contextViewService.hideContextView();
}
private renderSettingEnumTemplate(tree: ITree, container: HTMLElement): ISettingEnumItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'enum');
const selectBox = new SelectBox([], undefined, this.contextViewService, undefined, {
hasDetails: true
});
common.toDispose.push(selectBox);
common.toDispose.push(attachSelectBoxStyler(selectBox, this.themeService, {
selectBackground: settingsSelectBackground,
selectForeground: settingsSelectForeground,
selectBorder: settingsSelectBorder,
selectListBorder: settingsSelectListBorder
}));
selectBox.render(common.controlElement);
const selectElement = common.controlElement.querySelector('select');
if (selectElement) {
selectElement.classList.add(SettingsRenderer.CONTROL_CLASS);
}
common.toDispose.push(
selectBox.onDidSelect(e => {
if (template.onChange) {
template.onChange(e.index);
}
}));
const enumDescriptionElement = common.containerElement.insertBefore($('.setting-item-enumDescription'), common.descriptionElement.nextSibling);
const template: ISettingEnumItemTemplate = {
...common,
selectBox,
enumDescriptionElement
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderSettingExcludeTemplate(tree: ITree, container: HTMLElement): ISettingExcludeItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'exclude');
const excludeWidget = this.instantiationService.createInstance(ExcludeSettingWidget, common.controlElement);
excludeWidget.domNode.classList.add(SettingsRenderer.CONTROL_CLASS);
common.toDispose.push(excludeWidget);
const template: ISettingExcludeItemTemplate = {
...common,
excludeWidget
};
this.addSettingElementFocusHandler(template);
common.toDispose.push(excludeWidget.onDidChangeExclude(e => {
if (template.context) {
let newValue = { ...template.context.scopeValue };
// first delete the existing entry, if present
if (e.originalPattern) {
if (e.originalPattern in template.context.defaultValue) {
// delete a default by overriding it
newValue[e.originalPattern] = false;
} else {
delete newValue[e.originalPattern];
}
}
// then add the new or updated entry, if present
if (e.pattern) {
if (e.pattern in template.context.defaultValue && !e.sibling) {
// add a default by deleting its override
delete newValue[e.pattern];
} else {
newValue[e.pattern] = e.sibling ? { when: e.sibling } : true;
}
}
const sortKeys = (obj) => {
const keyArray = Object.keys(obj)
.map(key => ({ key, val: obj[key] }))
.sort((a, b) => a.key.localeCompare(b.key));
const retVal = {};
keyArray.forEach(pair => {
retVal[pair.key] = pair.val;
});
return retVal;
};
this._onDidChangeSetting.fire({
key: template.context.setting.key,
value: Object.keys(newValue).length === 0 ? undefined : sortKeys(newValue)
});
}
}));
return template;
}
private renderSettingComplexTemplate(tree: ITree, container: HTMLElement): ISettingComplexItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'complex');
const openSettingsButton = new Button(common.controlElement, { title: true, buttonBackground: null, buttonHoverBackground: null });
common.toDispose.push(openSettingsButton);
common.toDispose.push(openSettingsButton.onDidClick(() => template.onChange(null)));
openSettingsButton.label = localize('editInSettingsJson', "Edit in settings.json");
openSettingsButton.element.classList.add('edit-in-settings-button');
common.toDispose.push(attachButtonStyler(openSettingsButton, this.themeService, {
buttonBackground: Color.transparent.toString(),
buttonHoverBackground: Color.transparent.toString(),
buttonForeground: 'foreground'
}));
const template: ISettingComplexItemTemplate = {
...common,
button: openSettingsButton
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderNewExtensionsTemplate(container: HTMLElement): ISettingNewExtensionsTemplate {
const toDispose = [];
container.classList.add('setting-item-new-extensions');
const button = new Button(container, { title: true, buttonBackground: null, buttonHoverBackground: null });
toDispose.push(button);
toDispose.push(button.onDidClick(() => {
if (template.context) {
this.commandService.executeCommand('workbench.extensions.action.showExtensionsWithIds', template.context.extensionIds);
}
}));
button.label = localize('newExtensionsButtonLabel', "Show matching extensions");
button.element.classList.add('settings-new-extensions-button');
toDispose.push(attachButtonStyler(button, this.themeService));
const template: ISettingNewExtensionsTemplate = {
button,
toDispose
};
// this.addSettingElementFocusHandler(template);
return template;
}
renderElement(tree: ITree, element: SettingsTreeElement, templateId: string, template: any): void {
if (templateId === SETTINGS_GROUP_ELEMENT_TEMPLATE_ID) {
return this.renderGroupElement(<SettingsTreeGroupElement>element, template);
}
if (templateId === SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID) {
return this.renderNewExtensionsElement(<SettingsTreeNewExtensionsElement>element, template);
}
return this.renderSettingElement(tree, <SettingsTreeSettingElement>element, templateId, template);
}
private renderGroupElement(element: SettingsTreeGroupElement, template: IGroupTitleTemplate): void {
template.parent.innerHTML = '';
const labelElement = DOM.append(template.parent, $('div.settings-group-title-label'));
labelElement.classList.add(`settings-group-level-${element.level}`);
labelElement.textContent = (<SettingsTreeGroupElement>element).label;
if (element.isFirstGroup) {
labelElement.classList.add('settings-group-first');
}
}
private renderNewExtensionsElement(element: SettingsTreeNewExtensionsElement, template: ISettingNewExtensionsTemplate): void {
template.context = element;
}
public getSettingDOMElementForDOMElement(domElement: HTMLElement): HTMLElement {
const parent = DOM.findParentWithClass(domElement, 'setting-item');
if (parent) {
return parent;
}
return null;
}
public getDOMElementsForSettingKey(treeContainer: HTMLElement, key: string): NodeListOf<HTMLElement> {
return treeContainer.querySelectorAll(`[${SettingsRenderer.SETTING_KEY_ATTR}="${key}"]`);
}
public getKeyForDOMElementInSetting(element: HTMLElement): string {
const settingElement = this.getSettingDOMElementForDOMElement(element);
return settingElement && settingElement.getAttribute(SettingsRenderer.SETTING_KEY_ATTR);
}
private renderSettingElement(tree: ITree, element: SettingsTreeSettingElement, templateId: string, template: ISettingItemTemplate | ISettingBoolItemTemplate): void {
template.context = element;
template.toolbar.context = element;
const setting = element.setting;
DOM.toggleClass(template.containerElement, 'is-configured', element.isConfigured);
DOM.toggleClass(template.containerElement, 'is-expanded', true);
template.containerElement.setAttribute(SettingsRenderer.SETTING_KEY_ATTR, element.setting.key);
const titleTooltip = setting.key + (element.isConfigured ? ' - Modified' : '');
template.categoryElement.textContent = element.displayCategory && (element.displayCategory + ': ');
template.categoryElement.title = titleTooltip;
template.labelElement.textContent = element.displayLabel;
template.labelElement.title = titleTooltip;
this.renderValue(element, templateId, <ISettingItemTemplate>template);
template.descriptionElement.innerHTML = '';
if (element.setting.descriptionIsMarkdown) {
const renderedDescription = this.renderDescriptionMarkdown(element, element.description, template.toDispose);
template.descriptionElement.appendChild(renderedDescription);
} else {
template.descriptionElement.innerText = element.description;
}
const baseId = (element.displayCategory + '_' + element.displayLabel).replace(/ /g, '_').toLowerCase();
template.descriptionElement.id = baseId + '_setting_description';
if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
// Add checkbox target to description clickable and able to toggle checkbox
template.descriptionElement.setAttribute('checkbox_label_target_id', baseId + '_setting_item');
}
if (element.overriddenScopeList.length) {
let otherOverridesLabel = element.isConfigured ?
localize('alsoConfiguredIn', "Also modified in") :
localize('configuredIn', "Modified in");
template.otherOverridesElement.textContent = `(${otherOverridesLabel}: ${element.overriddenScopeList.join(', ')})`;
} else {
template.otherOverridesElement.textContent = '';
}
// Remove tree attributes - sometimes overridden by tree - should be managed there
template.containerElement.parentElement.removeAttribute('role');
template.containerElement.parentElement.removeAttribute('aria-level');
template.containerElement.parentElement.removeAttribute('aria-posinset');
template.containerElement.parentElement.removeAttribute('aria-setsize');
}
private renderDescriptionMarkdown(element: SettingsTreeSettingElement, text: string, disposeables: IDisposable[]): HTMLElement {
// Rewrite `#editor.fontSize#` to link format
text = fixSettingLinks(text);
const renderedMarkdown = renderMarkdown({ value: text }, {
actionHandler: {
callback: (content: string) => {
if (startsWith(content, '#')) {
const e: ISettingLinkClickEvent = {
source: element,
targetKey: content.substr(1)
};
this._onDidClickSettingLink.fire(e);
} else {
this.openerService.open(URI.parse(content)).then(void 0, onUnexpectedError);
}
},
disposeables
}
});
renderedMarkdown.classList.add('setting-item-description-markdown');
cleanRenderedMarkdown(renderedMarkdown);
return renderedMarkdown;
}
private renderValue(element: SettingsTreeSettingElement, templateId: string, template: ISettingItemTemplate | ISettingBoolItemTemplate): void {
const onChange = value => this._onDidChangeSetting.fire({ key: element.setting.key, value });
template.deprecationWarningElement.innerText = element.setting.deprecationMessage || '';
if (templateId === SETTINGS_ENUM_TEMPLATE_ID) {
this.renderEnum(element, <ISettingEnumItemTemplate>template, onChange);
} else if (templateId === SETTINGS_TEXT_TEMPLATE_ID) {
this.renderText(element, <ISettingTextItemTemplate>template, onChange);
} else if (templateId === SETTINGS_NUMBER_TEMPLATE_ID) {
this.renderNumber(element, <ISettingTextItemTemplate>template, onChange);
} else if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
this.renderBool(element, <ISettingBoolItemTemplate>template, onChange);
} else if (templateId === SETTINGS_EXCLUDE_TEMPLATE_ID) {
this.renderExcludeSetting(element, <ISettingExcludeItemTemplate>template);
} else if (templateId === SETTINGS_COMPLEX_TEMPLATE_ID) {
this.renderComplexSetting(element, <ISettingComplexItemTemplate>template);
}
}
private renderBool(dataElement: SettingsTreeSettingElement, template: ISettingBoolItemTemplate, onChange: (value: boolean) => void): void {
template.onChange = null;
template.checkbox.checked = dataElement.value;
template.onChange = onChange;
// Setup and add ARIA attributes
// Create id and label for control/input element - parent is wrapper div
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' ' + modifiedText;
// We use the parent control div for the aria-labelledby target
// Does not appear you can use the direct label on the element itself within a tree
template.checkbox.domNode.parentElement.id = baseId + '_setting_label';
template.checkbox.domNode.parentElement.setAttribute('aria-label', label);
// Labels will not be read on descendent input elements of the parent treeitem
// unless defined as role=treeitem and indirect aria-labelledby approach
template.checkbox.domNode.id = baseId + '_setting_item';
template.checkbox.domNode.setAttribute('role', 'checkbox');
template.checkbox.domNode.setAttribute('aria-labelledby', baseId + '_setting_label');
template.checkbox.domNode.setAttribute('aria-describedby', baseId + '_setting_description');
}
private renderEnum(dataElement: SettingsTreeSettingElement, template: ISettingEnumItemTemplate, onChange: (value: string) => void): void {
const displayOptions = dataElement.setting.enum
.map(String)
.map(escapeInvisibleChars);
template.selectBox.setOptions(displayOptions);
const enumDescriptions = dataElement.setting.enumDescriptions;
const enumDescriptionsAreMarkdown = dataElement.setting.enumDescriptionsAreMarkdown;
template.selectBox.setDetailsProvider(index =>
({
details: enumDescriptions && enumDescriptions[index] && (enumDescriptionsAreMarkdown ? fixSettingLinks(enumDescriptions[index], false) : enumDescriptions[index]),
isMarkdown: enumDescriptionsAreMarkdown
}));
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' ' + modifiedText;
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
template.selectBox.setAriaLabel(label);
const idx = dataElement.setting.enum.indexOf(dataElement.value);
template.onChange = null;
template.selectBox.select(idx);
template.onChange = idx => onChange(dataElement.setting.enum[idx]);
if (template.controlElement.firstElementChild) {
// SelectBox needs to have treeitem changed to combobox to read correctly within tree
template.controlElement.firstElementChild.setAttribute('role', 'combobox');
template.controlElement.firstElementChild.setAttribute('aria-describedby', baseId + '_setting_description');
}
template.enumDescriptionElement.innerHTML = '';
}
private renderText(dataElement: SettingsTreeSettingElement, template: ISettingTextItemTemplate, onChange: (value: string) => void): void {
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' ' + modifiedText; template.onChange = null;
template.inputBox.value = dataElement.value;
template.onChange = value => { renderValidations(dataElement, template, false, label); onChange(value); };
// Setup and add ARIA attributes
// Create id and label for control/input element - parent is wrapper div
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
// We use the parent control div for the aria-labelledby target
// Does not appear you can use the direct label on the element itself within a tree
template.inputBox.inputElement.parentElement.id = baseId + '_setting_label';
template.inputBox.inputElement.parentElement.setAttribute('aria-label', label);
// Labels will not be read on descendent input elements of the parent treeitem
// unless defined as role=treeitem and indirect aria-labelledby approach
template.inputBox.inputElement.id = baseId + '_setting_item';
template.inputBox.inputElement.setAttribute('role', 'textbox');
template.inputBox.inputElement.setAttribute('aria-labelledby', baseId + '_setting_label');
template.inputBox.inputElement.setAttribute('aria-describedby', baseId + '_setting_description');
renderValidations(dataElement, template, true, label);
}
private renderNumber(dataElement: SettingsTreeSettingElement, template: ISettingTextItemTemplate, onChange: (value: number) => void): void {
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' number ' + modifiedText; const numParseFn = (dataElement.valueType === 'integer' || dataElement.valueType === 'nullable-integer')
? parseInt : parseFloat;
const nullNumParseFn = (dataElement.valueType === 'nullable-integer' || dataElement.valueType === 'nullable-number')
? (v => v === '' ? null : numParseFn(v)) : numParseFn;
template.onChange = null;
template.inputBox.value = dataElement.value;
template.onChange = value => { renderValidations(dataElement, template, false, label); onChange(nullNumParseFn(value)); };
// Setup and add ARIA attributes
// Create id and label for control/input element - parent is wrapper div
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
// We use the parent control div for the aria-labelledby target
// Does not appear you can use the direct label on the element itself within a tree
template.inputBox.inputElement.parentElement.id = baseId + '_setting_label';
template.inputBox.inputElement.parentElement.setAttribute('aria-label', label);
// Labels will not be read on descendent input elements of the parent treeitem
// unless defined as role=treeitem and indirect aria-labelledby approach
template.inputBox.inputElement.id = baseId + '_setting_item';
template.inputBox.inputElement.setAttribute('role', 'textbox');
template.inputBox.inputElement.setAttribute('aria-labelledby', baseId + '_setting_label');
template.inputBox.inputElement.setAttribute('aria-describedby', baseId + '_setting_description');
renderValidations(dataElement, template, true, label);
}
private renderExcludeSetting(dataElement: SettingsTreeSettingElement, template: ISettingExcludeItemTemplate): void {
const value = getExcludeDisplayValue(dataElement);
template.excludeWidget.setValue(value);
template.context = dataElement;
}
private renderComplexSetting(dataElement: SettingsTreeSettingElement, template: ISettingComplexItemTemplate): void {
template.onChange = () => this._onDidOpenSettings.fire(dataElement.setting.key);
}
disposeTemplate(tree: ITree, templateId: string, template: IDisposableTemplate): void {
dispose(template.toDispose);
}
}
function renderValidations(dataElement: SettingsTreeSettingElement, template: ISettingTextItemTemplate, calledOnStartup: boolean, originalAriaLabel: string) {
if (dataElement.setting.validator) {
let errMsg = dataElement.setting.validator(template.inputBox.value);
if (errMsg) {
DOM.addClass(template.containerElement, 'invalid-input');
template.validationErrorMessageElement.innerText = errMsg;
let validationError = localize('validationError', "Validation Error.");
template.inputBox.inputElement.parentElement.setAttribute('aria-label', [originalAriaLabel, validationError, errMsg].join(' '));
if (!calledOnStartup) { ariaAlert(validationError + ' ' + errMsg); }
return;
} else {
template.inputBox.inputElement.parentElement.setAttribute('aria-label', originalAriaLabel);
}
}
DOM.removeClass(template.containerElement, 'invalid-input');
}
function cleanRenderedMarkdown(element: Node): void {
for (let i = 0; i < element.childNodes.length; i++) {
const child = element.childNodes.item(i);
const tagName = (<Element>child).tagName && (<Element>child).tagName.toLowerCase();
if (tagName === 'img') {
element.removeChild(child);
} else {
cleanRenderedMarkdown(child);
}
}
}
function fixSettingLinks(text: string, linkify = true): string {
return text.replace(/`#([^#]*)#`/g, (match, settingKey) => {
const targetDisplayFormat = settingKeyToDisplayFormat(settingKey);
const targetName = `${targetDisplayFormat.category}: ${targetDisplayFormat.label}`;
return linkify ?
`[${targetName}](#${settingKey})` :
`"${targetName}"`;
});
}
function escapeInvisibleChars(enumValue: string): string {
return enumValue && enumValue
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r');
}
export class SettingsTreeFilter implements IFilter {
constructor(
private viewState: ISettingsEditorViewState,
) { }
isVisible(tree: ITree, element: SettingsTreeElement): boolean {
// Filter during search
if (this.viewState.filterToCategory && element instanceof SettingsTreeSettingElement) {
if (!this.settingContainedInGroup(element.setting, this.viewState.filterToCategory)) {
return false;
}
}
if (element instanceof SettingsTreeSettingElement && this.viewState.tagFilters) {
return element.matchesAllTags(this.viewState.tagFilters);
}
if (element instanceof SettingsTreeGroupElement) {
if (typeof element.count === 'number') {
return element.count > 0;
}
return element.children.some(child => this.isVisible(tree, child));
}
if (element instanceof SettingsTreeNewExtensionsElement) {
if ((this.viewState.tagFilters && this.viewState.tagFilters.size) || this.viewState.filterToCategory) {
return false;
}
}
return true;
}
private settingContainedInGroup(setting: ISetting, group: SettingsTreeGroupElement): boolean {
return group.children.some(child => {
if (child instanceof SettingsTreeGroupElement) {
return this.settingContainedInGroup(setting, child);
} else if (child instanceof SettingsTreeSettingElement) {
return child.setting.key === setting.key;
} else {
return false;
}
});
}
}
export class SettingsTreeController extends WorkbenchTreeController {
constructor(
@IConfigurationService configurationService: IConfigurationService
) {
super({}, configurationService);
}
protected onLeftClick(tree: ITree, element: any, eventish: IMouseEvent, origin?: string): boolean {
const isLink = eventish.target.tagName.toLowerCase() === 'a' ||
eventish.target.parentElement.tagName.toLowerCase() === 'a'; // <code> inside <a>
if (isLink && (DOM.findParentWithClass(eventish.target, 'setting-item-description-markdown', tree.getHTMLElement()) || DOM.findParentWithClass(eventish.target, 'select-box-description-markdown'))) {
return true;
}
return false;
}
}
export class SettingsAccessibilityProvider implements IAccessibilityProvider {
getAriaLabel(tree: ITree, element: SettingsTreeElement): string {
if (!element) {
return '';
}
if (element instanceof SettingsTreeSettingElement) {
return localize('settingRowAriaLabel', "{0} {1}, Setting", element.displayCategory, element.displayLabel);
}
if (element instanceof SettingsTreeGroupElement) {
return localize('groupRowAriaLabel', "{0}, group", element.label);
}
return '';
}
}
class NonExpandableOrSelectableTree extends Tree {
expand(): TPromise<any> {
return TPromise.wrap(null);
}
collapse(): TPromise<any> {
return TPromise.wrap(null);
}
public setFocus(element?: any, eventPayload?: any): void {
return;
}
public focusNext(count?: number, eventPayload?: any): void {
return;
}
public focusPrevious(count?: number, eventPayload?: any): void {
return;
}
public focusParent(eventPayload?: any): void {
return;
}
public focusFirstChild(eventPayload?: any): void {
return;
}
public focusFirst(eventPayload?: any, from?: any): void {
return;
}
public focusNth(index: number, eventPayload?: any): void {
return;
}
public focusLast(eventPayload?: any, from?: any): void {
return;
}
public focusNextPage(eventPayload?: any): void {
return;
}
public focusPreviousPage(eventPayload?: any): void {
return;
}
public select(element: any, eventPayload?: any): void {
return;
}
public selectRange(fromElement: any, toElement: any, eventPayload?: any): void {
return;
}
public selectAll(elements: any[], eventPayload?: any): void {
return;
}
public setSelection(elements: any[], eventPayload?: any): void {
return;
}
public toggleSelection(element: any, eventPayload?: any): void {
return;
}
}
export class SettingsTree extends NonExpandableOrSelectableTree {
protected disposables: IDisposable[];
constructor(
container: HTMLElement,
viewState: ISettingsEditorViewState,
configuration: Partial<ITreeConfiguration>,
@IThemeService themeService: IThemeService,
@IInstantiationService instantiationService: IInstantiationService
) {
const treeClass = 'settings-editor-tree';
const controller = instantiationService.createInstance(SettingsTreeController);
const fullConfiguration = <ITreeConfiguration>{
controller,
accessibilityProvider: instantiationService.createInstance(SettingsAccessibilityProvider),
filter: instantiationService.createInstance(SettingsTreeFilter, viewState),
styler: new DefaultTreestyler(DOM.createStyleSheet(container), treeClass),
...configuration
};
const options = {
ariaLabel: localize('treeAriaLabel', "Settings"),
showLoading: false,
indentPixels: 0,
twistiePixels: 20, // Actually for gear button
};
super(container,
fullConfiguration,
options);
this.disposables = [];
this.disposables.push(controller);
this.disposables.push(registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
const activeBorderColor = theme.getColor(focusBorder);
if (activeBorderColor) {
// TODO@rob - why isn't this applied when added to the stylesheet from tocTree.ts? Seems like a chromium glitch.
collector.addRule(`.settings-editor > .settings-body > .settings-toc-container .monaco-tree:focus .monaco-tree-row.focused {outline: solid 1px ${activeBorderColor}; outline-offset: -1px; }`);
}
const foregroundColor = theme.getColor(foreground);
if (foregroundColor) {
// Links appear inside other elements in markdown. CSS opacity acts like a mask. So we have to dynamically compute the description color to avoid
// applying an opacity to the link color.
const fgWithOpacity = new Color(new RGBA(foregroundColor.rgba.r, foregroundColor.rgba.g, foregroundColor.rgba.b, .9));
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-description { color: ${fgWithOpacity}; }`);
}
const errorColor = theme.getColor(errorForeground);
if (errorColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-deprecation-message { color: ${errorColor}; }`);
}
const invalidInputBackground = theme.getColor(inputValidationErrorBackground);
if (invalidInputBackground) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-validation-message { background-color: ${invalidInputBackground}; }`);
}
const invalidInputForeground = theme.getColor(inputValidationErrorForeground);
if (invalidInputForeground) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-validation-message { color: ${invalidInputForeground}; }`);
}
const invalidInputBorder = theme.getColor(inputValidationErrorBorder);
if (invalidInputBorder) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-validation-message { border-style:solid; border-width: 1px; border-color: ${invalidInputBorder}; }`);
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item.invalid-input .setting-item-control .monaco-inputbox.idle { outline-width: 0; border-style:solid; border-width: 1px; border-color: ${invalidInputBorder}; }`);
}
const headerForegroundColor = theme.getColor(settingsHeaderForeground);
if (headerForegroundColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .settings-group-title-label { color: ${headerForegroundColor}; }`);
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item-label { color: ${headerForegroundColor}; }`);
}
const focusBorderColor = theme.getColor(focusBorder);
if (focusBorderColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-description-markdown a:focus { outline-color: ${focusBorderColor} }`);
}
}));
this.getHTMLElement().classList.add(treeClass);
this.disposables.push(attachStyler(themeService, {
listActiveSelectionBackground: editorBackground,
listActiveSelectionForeground: foreground,
listFocusAndSelectionBackground: editorBackground,
listFocusAndSelectionForeground: foreground,
listFocusBackground: editorBackground,
listFocusForeground: foreground,
listHoverForeground: foreground,
listHoverBackground: editorBackground,
listHoverOutline: editorBackground,
listFocusOutline: editorBackground,
listInactiveSelectionBackground: editorBackground,
listInactiveSelectionForeground: foreground
}, colors => {
this.style(colors);
}));
}
}
class CopySettingIdAction extends Action {
static readonly ID = 'settings.copySettingId';
static readonly LABEL = localize('copySettingIdLabel', "Copy Setting ID");
constructor(
@IClipboardService private clipboardService: IClipboardService
) {
super(CopySettingIdAction.ID, CopySettingIdAction.LABEL);
}
run(context: SettingsTreeSettingElement): TPromise<void> {
if (context) {
this.clipboardService.writeText(context.setting.key);
}
return TPromise.as(null);
}
}
class CopySettingAsJSONAction extends Action {
static readonly ID = 'settings.copySettingAsJSON';
static readonly LABEL = localize('copySettingAsJSONLabel', "Copy Setting as JSON");
constructor(
@IClipboardService private clipboardService: IClipboardService
) {
super(CopySettingAsJSONAction.ID, CopySettingAsJSONAction.LABEL);
}
run(context: SettingsTreeSettingElement): TPromise<void> {
if (context) {
const jsonResult = `"${context.setting.key}": ${JSON.stringify(context.value, undefined, ' ')}`;
this.clipboardService.writeText(jsonResult);
}
return TPromise.as(null);
}
} | src/vs/workbench/parts/preferences/browser/settingsTree.ts | 1 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.9949920773506165,
0.006541775539517403,
0.00016227633750531822,
0.0001709245116217062,
0.07888796925544739
]
|
{
"id": 3,
"code_window": [
"import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';\n",
"import { ICommandService } from 'vs/platform/commands/common/commands';\n",
"import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n",
"import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';\n",
"import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';\n",
"import { WorkbenchTreeController } from 'vs/platform/list/browser/listService';\n",
"import { IOpenerService } from 'vs/platform/opener/common/opener';\n",
"import { editorBackground, errorForeground, focusBorder, foreground, inputValidationErrorBackground, inputValidationErrorForeground, inputValidationErrorBorder } from 'vs/platform/theme/common/colorRegistry';\n",
"import { attachButtonStyler, attachInputBoxStyler, attachSelectBoxStyler, attachStyler } from 'vs/platform/theme/common/styler';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "add",
"edit_start_line_idx": 35
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as sinon from 'sinon';
import * as assert from 'assert';
import * as path from 'path';
import * as fs from 'fs';
import * as os from 'os';
import { TPromise } from 'vs/base/common/winjs.base';
import * as uuid from 'vs/base/common/uuid';
import { mkdirp } from 'vs/base/node/pfs';
import {
IExtensionGalleryService, IGalleryExtensionAssets, IGalleryExtension, IExtensionManagementService, LocalExtensionType,
IExtensionEnablementService, DidInstallExtensionEvent, DidUninstallExtensionEvent, InstallExtensionEvent, IExtensionIdentifier
} from 'vs/platform/extensionManagement/common/extensionManagement';
import { ExtensionTipsService } from 'vs/workbench/parts/extensions/electron-browser/extensionTipsService';
import { ExtensionGalleryService } from 'vs/platform/extensionManagement/node/extensionGalleryService';
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import { Emitter } from 'vs/base/common/event';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { TestTextResourceConfigurationService, TestContextService, TestLifecycleService, TestEnvironmentService, TestStorageService } from 'vs/workbench/test/workbenchTestServices';
import { TestNotificationService } from 'vs/platform/notification/test/common/testNotificationService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { URI } from 'vs/base/common/uri';
import { testWorkspace } from 'vs/platform/workspace/test/common/testWorkspace';
import { IFileService } from 'vs/platform/files/common/files';
import { FileService } from 'vs/workbench/services/files/electron-browser/fileService';
import * as extfs from 'vs/base/node/extfs';
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
import { IPager } from 'vs/base/common/paging';
import { assign } from 'vs/base/common/objects';
import { getGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { ConfigurationKey } from 'vs/workbench/parts/extensions/common/extensions';
import { ExtensionManagementService } from 'vs/platform/extensionManagement/node/extensionManagementService';
import { TestExtensionEnablementService } from 'vs/platform/extensionManagement/test/common/extensionEnablementService.test';
import { IURLService } from 'vs/platform/url/common/url';
import product from 'vs/platform/node/product';
import { ITextModel } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/modelService';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
import { INotificationService, Severity, IPromptChoice } from 'vs/platform/notification/common/notification';
import { URLService } from 'vs/platform/url/common/urlService';
import { IExperimentService } from 'vs/workbench/parts/experiments/node/experimentService';
import { TestExperimentService } from 'vs/workbench/parts/experiments/test/node/experimentService.test';
const mockExtensionGallery: IGalleryExtension[] = [
aGalleryExtension('MockExtension1', {
displayName: 'Mock Extension 1',
version: '1.5',
publisherId: 'mockPublisher1Id',
publisher: 'mockPublisher1',
publisherDisplayName: 'Mock Publisher 1',
description: 'Mock Description',
installCount: 1000,
rating: 4,
ratingCount: 100
}, {
dependencies: ['pub.1'],
}, {
manifest: { uri: 'uri:manifest', fallbackUri: 'fallback:manifest' },
readme: { uri: 'uri:readme', fallbackUri: 'fallback:readme' },
changelog: { uri: 'uri:changelog', fallbackUri: 'fallback:changlog' },
download: { uri: 'uri:download', fallbackUri: 'fallback:download' },
icon: { uri: 'uri:icon', fallbackUri: 'fallback:icon' },
license: { uri: 'uri:license', fallbackUri: 'fallback:license' },
repository: { uri: 'uri:repository', fallbackUri: 'fallback:repository' },
coreTranslations: {}
}),
aGalleryExtension('MockExtension2', {
displayName: 'Mock Extension 2',
version: '1.5',
publisherId: 'mockPublisher2Id',
publisher: 'mockPublisher2',
publisherDisplayName: 'Mock Publisher 2',
description: 'Mock Description',
installCount: 1000,
rating: 4,
ratingCount: 100
}, {
dependencies: ['pub.1', 'pub.2'],
}, {
manifest: { uri: 'uri:manifest', fallbackUri: 'fallback:manifest' },
readme: { uri: 'uri:readme', fallbackUri: 'fallback:readme' },
changelog: { uri: 'uri:changelog', fallbackUri: 'fallback:changlog' },
download: { uri: 'uri:download', fallbackUri: 'fallback:download' },
icon: { uri: 'uri:icon', fallbackUri: 'fallback:icon' },
license: { uri: 'uri:license', fallbackUri: 'fallback:license' },
repository: { uri: 'uri:repository', fallbackUri: 'fallback:repository' },
coreTranslations: {}
})
];
const mockExtensionLocal = [
{
type: LocalExtensionType.User,
identifier: mockExtensionGallery[0].identifier,
manifest: {
name: mockExtensionGallery[0].name,
publisher: mockExtensionGallery[0].publisher,
version: mockExtensionGallery[0].version
},
metadata: null,
path: 'somepath',
readmeUrl: 'some readmeUrl',
changelogUrl: 'some changelogUrl'
},
{
type: LocalExtensionType.User,
identifier: mockExtensionGallery[1].identifier,
manifest: {
name: mockExtensionGallery[1].name,
publisher: mockExtensionGallery[1].publisher,
version: mockExtensionGallery[1].version
},
metadata: null,
path: 'somepath',
readmeUrl: 'some readmeUrl',
changelogUrl: 'some changelogUrl'
}
];
const mockTestData = {
recommendedExtensions: [
'mockPublisher1.mockExtension1',
'MOCKPUBLISHER2.mockextension2',
'badlyformattedextension',
'MOCKPUBLISHER2.mockextension2',
'unknown.extension'
],
validRecommendedExtensions: [
'mockPublisher1.mockExtension1',
'MOCKPUBLISHER2.mockextension2'
]
};
function aPage<T>(...objects: T[]): IPager<T> {
return { firstPage: objects, total: objects.length, pageSize: objects.length, getPage: () => null };
}
const noAssets: IGalleryExtensionAssets = {
changelog: null,
download: null,
icon: null,
license: null,
manifest: null,
readme: null,
repository: null,
coreTranslations: null
};
function aGalleryExtension(name: string, properties: any = {}, galleryExtensionProperties: any = {}, assets: IGalleryExtensionAssets = noAssets): IGalleryExtension {
const galleryExtension = <IGalleryExtension>Object.create({});
assign(galleryExtension, { name, publisher: 'pub', version: '1.0.0', properties: {}, assets: {} }, properties);
assign(galleryExtension.properties, { dependencies: [] }, galleryExtensionProperties);
assign(galleryExtension.assets, assets);
galleryExtension.identifier = { id: getGalleryExtensionId(galleryExtension.publisher, galleryExtension.name), uuid: uuid.generateUuid() };
return <IGalleryExtension>galleryExtension;
}
suite('ExtensionsTipsService Test', () => {
let workspaceService: IWorkspaceContextService;
let instantiationService: TestInstantiationService;
let testConfigurationService: TestConfigurationService;
let testObject: ExtensionTipsService;
let parentResource: string;
let installEvent: Emitter<InstallExtensionEvent>,
didInstallEvent: Emitter<DidInstallExtensionEvent>,
uninstallEvent: Emitter<IExtensionIdentifier>,
didUninstallEvent: Emitter<DidUninstallExtensionEvent>;
let prompted: boolean;
let onModelAddedEvent: Emitter<ITextModel>;
let experimentService: TestExperimentService;
suiteSetup(() => {
instantiationService = new TestInstantiationService();
installEvent = new Emitter<InstallExtensionEvent>();
didInstallEvent = new Emitter<DidInstallExtensionEvent>();
uninstallEvent = new Emitter<IExtensionIdentifier>();
didUninstallEvent = new Emitter<DidUninstallExtensionEvent>();
instantiationService.stub(IExtensionGalleryService, ExtensionGalleryService);
instantiationService.stub(ILifecycleService, new TestLifecycleService());
testConfigurationService = new TestConfigurationService();
instantiationService.stub(IConfigurationService, testConfigurationService);
instantiationService.stub(INotificationService, new TestNotificationService());
instantiationService.stub(IExtensionManagementService, ExtensionManagementService);
instantiationService.stub(IExtensionManagementService, 'onInstallExtension', installEvent.event);
instantiationService.stub(IExtensionManagementService, 'onDidInstallExtension', didInstallEvent.event);
instantiationService.stub(IExtensionManagementService, 'onUninstallExtension', uninstallEvent.event);
instantiationService.stub(IExtensionManagementService, 'onDidUninstallExtension', didUninstallEvent.event);
instantiationService.stub(IExtensionEnablementService, new TestExtensionEnablementService(instantiationService));
instantiationService.stub(ITelemetryService, NullTelemetryService);
instantiationService.stub(IURLService, URLService);
experimentService = instantiationService.createInstance(TestExperimentService);
instantiationService.stub(IExperimentService, experimentService);
onModelAddedEvent = new Emitter<ITextModel>();
product.extensionTips = {
'ms-vscode.csharp': '{**/*.cs,**/project.json,**/global.json,**/*.csproj,**/*.sln,**/appsettings.json}',
'msjsdiag.debugger-for-chrome': '{**/*.ts,**/*.tsx**/*.js,**/*.jsx,**/*.es6,**/.babelrc}',
'lukehoban.Go': '**/*.go'
};
product.extensionImportantTips = {
'ms-python.python': {
'name': 'Python',
'pattern': '{**/*.py}'
},
'ms-vscode.PowerShell': {
'name': 'PowerShell',
'pattern': '{**/*.ps,**/*.ps1}'
}
};
});
suiteTeardown(() => {
if (experimentService) {
experimentService.dispose();
}
});
setup(() => {
instantiationService.stub(IEnvironmentService, { extensionDevelopmentPath: false });
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', []);
instantiationService.stub(IExtensionGalleryService, 'isEnabled', true);
instantiationService.stubPromise(IExtensionGalleryService, 'query', aPage<IGalleryExtension>(...mockExtensionGallery));
prompted = false;
class TestNotificationService2 extends TestNotificationService {
public prompt(severity: Severity, message: string, choices: IPromptChoice[], onCancel?: () => void) {
prompted = true;
return null;
}
}
instantiationService.stub(INotificationService, new TestNotificationService2());
testConfigurationService.setUserConfiguration(ConfigurationKey, { ignoreRecommendations: false, showRecommendationsOnlyOnDemand: false });
instantiationService.stub(IStorageService, { get: (a, b, c) => c, getBoolean: (a, b, c) => c, store: () => { } });
instantiationService.stub(IModelService, <IModelService>{
getModels(): any { return []; },
onModelAdded: onModelAddedEvent.event
});
});
teardown(done => {
(<ExtensionTipsService>testObject).dispose();
if (parentResource) {
extfs.del(parentResource, os.tmpdir(), () => { }, done);
} else {
done();
}
});
function setUpFolderWorkspace(folderName: string, recommendedExtensions: string[], ignoredRecommendations: string[] = []): TPromise<void> {
const id = uuid.generateUuid();
parentResource = path.join(os.tmpdir(), 'vsctests', id);
return setUpFolder(folderName, parentResource, recommendedExtensions, ignoredRecommendations);
}
function setUpFolder(folderName: string, parentDir: string, recommendedExtensions: string[], ignoredRecommendations: string[] = []): TPromise<void> {
const folderDir = path.join(parentDir, folderName);
const workspaceSettingsDir = path.join(folderDir, '.vscode');
return mkdirp(workspaceSettingsDir, 493).then(() => {
const configPath = path.join(workspaceSettingsDir, 'extensions.json');
fs.writeFileSync(configPath, JSON.stringify({
'recommendations': recommendedExtensions,
'unwantedRecommendations': ignoredRecommendations,
}, null, '\t'));
const myWorkspace = testWorkspace(URI.from({ scheme: 'file', path: folderDir }));
workspaceService = new TestContextService(myWorkspace);
instantiationService.stub(IWorkspaceContextService, workspaceService);
instantiationService.stub(IFileService, new FileService(workspaceService, TestEnvironmentService, new TestTextResourceConfigurationService(), new TestConfigurationService(), new TestLifecycleService(), new TestStorageService(), new TestNotificationService(), { disableWatcher: true }));
});
}
function testNoPromptForValidRecommendations(recommendations: string[]) {
return setUpFolderWorkspace('myFolder', recommendations).then(() => {
testObject = instantiationService.createInstance(ExtensionTipsService);
return testObject.loadWorkspaceConfigPromise.then(() => {
assert.equal(Object.keys(testObject.getAllRecommendationsWithReason()).length, recommendations.length);
assert.ok(!prompted);
});
});
}
function testNoPromptOrRecommendationsForValidRecommendations(recommendations: string[]) {
return setUpFolderWorkspace('myFolder', mockTestData.validRecommendedExtensions).then(() => {
testObject = instantiationService.createInstance(ExtensionTipsService);
assert.equal(!testObject.loadWorkspaceConfigPromise, true);
assert.ok(!prompted);
return testObject.getWorkspaceRecommendations().then(() => {
assert.equal(Object.keys(testObject.getAllRecommendationsWithReason()).length, 0);
assert.ok(!prompted);
});
});
}
test('ExtensionTipsService: No Prompt for valid workspace recommendations when galleryService is absent', () => {
const galleryQuerySpy = sinon.spy();
instantiationService.stub(IExtensionGalleryService, { query: galleryQuerySpy, isEnabled: () => false });
return testNoPromptOrRecommendationsForValidRecommendations(mockTestData.validRecommendedExtensions)
.then(() => assert.ok(galleryQuerySpy.notCalled));
});
test('ExtensionTipsService: No Prompt for valid workspace recommendations during extension development', () => {
instantiationService.stub(IEnvironmentService, { extensionDevelopmentLocationURI: true });
return testNoPromptOrRecommendationsForValidRecommendations(mockTestData.validRecommendedExtensions);
});
test('ExtensionTipsService: No workspace recommendations or prompts when extensions.json has empty array', () => {
return testNoPromptForValidRecommendations([]);
});
test('ExtensionTipsService: Prompt for valid workspace recommendations', () => {
return setUpFolderWorkspace('myFolder', mockTestData.recommendedExtensions).then(() => {
testObject = instantiationService.createInstance(ExtensionTipsService);
return testObject.loadWorkspaceConfigPromise.then(() => {
const recommendations = Object.keys(testObject.getAllRecommendationsWithReason());
assert.equal(recommendations.length, mockTestData.validRecommendedExtensions.length);
mockTestData.validRecommendedExtensions.forEach(x => {
assert.equal(recommendations.indexOf(x.toLowerCase()) > -1, true);
});
assert.ok(prompted);
});
});
});
test('ExtensionTipsService: No Prompt for valid workspace recommendations if they are already installed', () => {
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', mockExtensionLocal);
return testNoPromptForValidRecommendations(mockTestData.validRecommendedExtensions);
});
test('ExtensionTipsService: No Prompt for valid workspace recommendations with casing mismatch if they are already installed', () => {
instantiationService.stubPromise(IExtensionManagementService, 'getInstalled', mockExtensionLocal);
return testNoPromptForValidRecommendations(mockTestData.validRecommendedExtensions.map(x => x.toUpperCase()));
});
test('ExtensionTipsService: No Prompt for valid workspace recommendations if ignoreRecommendations is set', () => {
testConfigurationService.setUserConfiguration(ConfigurationKey, { ignoreRecommendations: true });
return testNoPromptForValidRecommendations(mockTestData.validRecommendedExtensions);
});
test('ExtensionTipsService: No Prompt for valid workspace recommendations if showRecommendationsOnlyOnDemand is set', () => {
testConfigurationService.setUserConfiguration(ConfigurationKey, { showRecommendationsOnlyOnDemand: true });
return setUpFolderWorkspace('myFolder', mockTestData.validRecommendedExtensions).then(() => {
testObject = instantiationService.createInstance(ExtensionTipsService);
return testObject.loadWorkspaceConfigPromise.then(() => {
assert.equal(Object.keys(testObject.getAllRecommendationsWithReason()).length, 0);
assert.ok(!prompted);
});
});
});
test('ExtensionTipsService: No Prompt for valid workspace recommendations if ignoreRecommendations is set for current workspace', () => {
instantiationService.stub(IStorageService, { get: (a, b, c) => c, getBoolean: (a, b, c) => a === 'extensionsAssistant/workspaceRecommendationsIgnore' || c });
return testNoPromptForValidRecommendations(mockTestData.validRecommendedExtensions);
});
test('ExtensionTipsService: No Recommendations of globally ignored recommendations', () => {
const storageGetterStub = (a, _, c) => {
const storedRecommendations = '["ms-vscode.csharp", "ms-python.python", "eg2.tslint"]';
const ignoredRecommendations = '["ms-vscode.csharp", "mockpublisher2.mockextension2"]'; // ignore a stored recommendation and a workspace recommendation.
if (a === 'extensionsAssistant/recommendations') { return storedRecommendations; }
if (a === 'extensionsAssistant/ignored_recommendations') { return ignoredRecommendations; }
return c;
};
instantiationService.stub(IStorageService, {
get: storageGetterStub,
getBoolean: (a, _, c) => a === 'extensionsAssistant/workspaceRecommendationsIgnore' || c
});
return setUpFolderWorkspace('myFolder', mockTestData.validRecommendedExtensions).then(() => {
testObject = instantiationService.createInstance(ExtensionTipsService);
return testObject.loadWorkspaceConfigPromise.then(() => {
const recommendations = testObject.getAllRecommendationsWithReason();
assert.ok(!recommendations['ms-vscode.csharp']); // stored recommendation that has been globally ignored
assert.ok(recommendations['ms-python.python']); // stored recommendation
assert.ok(recommendations['mockpublisher1.mockextension1']); // workspace recommendation
assert.ok(!recommendations['mockpublisher2.mockextension2']); // workspace recommendation that has been globally ignored
});
});
});
test('ExtensionTipsService: No Recommendations of workspace ignored recommendations', () => {
const ignoredRecommendations = ['ms-vscode.csharp', 'mockpublisher2.mockextension2']; // ignore a stored recommendation and a workspace recommendation.
const storedRecommendations = '["ms-vscode.csharp", "ms-python.python"]';
instantiationService.stub(IStorageService, {
get: (a, b, c) => a === 'extensionsAssistant/recommendations' ? storedRecommendations : c,
getBoolean: (a, _, c) => a === 'extensionsAssistant/workspaceRecommendationsIgnore' || c
});
return setUpFolderWorkspace('myFolder', mockTestData.validRecommendedExtensions, ignoredRecommendations).then(() => {
testObject = instantiationService.createInstance(ExtensionTipsService);
return testObject.loadWorkspaceConfigPromise.then(() => {
const recommendations = testObject.getAllRecommendationsWithReason();
assert.ok(!recommendations['ms-vscode.csharp']); // stored recommendation that has been workspace ignored
assert.ok(recommendations['ms-python.python']); // stored recommendation
assert.ok(recommendations['mockpublisher1.mockextension1']); // workspace recommendation
assert.ok(!recommendations['mockpublisher2.mockextension2']); // workspace recommendation that has been workspace ignored
});
});
});
test('ExtensionTipsService: Able to retrieve collection of all ignored recommendations', () => {
const storageGetterStub = (a, _, c) => {
const storedRecommendations = '["ms-vscode.csharp", "ms-python.python"]';
const globallyIgnoredRecommendations = '["mockpublisher2.mockextension2"]'; // ignore a workspace recommendation.
if (a === 'extensionsAssistant/recommendations') { return storedRecommendations; }
if (a === 'extensionsAssistant/ignored_recommendations') { return globallyIgnoredRecommendations; }
return c;
};
const workspaceIgnoredRecommendations = ['ms-vscode.csharp']; // ignore a stored recommendation and a workspace recommendation.
instantiationService.stub(IStorageService, {
get: storageGetterStub,
getBoolean: (a, _, c) => a === 'extensionsAssistant/workspaceRecommendationsIgnore' || c
});
return setUpFolderWorkspace('myFolder', mockTestData.validRecommendedExtensions, workspaceIgnoredRecommendations).then(() => {
testObject = instantiationService.createInstance(ExtensionTipsService);
return testObject.loadWorkspaceConfigPromise.then(() => {
const recommendations = testObject.getAllRecommendationsWithReason();
assert.ok(recommendations['ms-python.python']);
assert.ok(!recommendations['mockpublisher2.mockextension2']);
assert.ok(!recommendations['ms-vscode.csharp']);
});
});
});
test('ExtensionTipsService: Able to dynamically ignore/unignore global recommendations', () => {
const storageGetterStub = (a, _, c) => {
const storedRecommendations = '["ms-vscode.csharp", "ms-python.python"]';
const globallyIgnoredRecommendations = '["mockpublisher2.mockextension2"]'; // ignore a workspace recommendation.
if (a === 'extensionsAssistant/recommendations') { return storedRecommendations; }
if (a === 'extensionsAssistant/ignored_recommendations') { return globallyIgnoredRecommendations; }
return c;
};
instantiationService.stub(IStorageService, {
get: storageGetterStub,
store: () => { },
getBoolean: (a, _, c) => a === 'extensionsAssistant/workspaceRecommendationsIgnore' || c
});
return setUpFolderWorkspace('myFolder', mockTestData.validRecommendedExtensions).then(() => {
testObject = instantiationService.createInstance(ExtensionTipsService);
return testObject.loadWorkspaceConfigPromise.then(() => {
const recommendations = testObject.getAllRecommendationsWithReason();
assert.ok(recommendations['ms-python.python']);
assert.ok(recommendations['mockpublisher1.mockextension1']);
assert.ok(!recommendations['mockpublisher2.mockextension2']);
return testObject.toggleIgnoredRecommendation('mockpublisher1.mockextension1', true);
}).then(() => {
const recommendations = testObject.getAllRecommendationsWithReason();
assert.ok(recommendations['ms-python.python']);
assert.ok(!recommendations['mockpublisher1.mockextension1']);
assert.ok(!recommendations['mockpublisher2.mockextension2']);
return testObject.toggleIgnoredRecommendation('mockpublisher1.mockextension1', false);
}).then(() => {
const recommendations = testObject.getAllRecommendationsWithReason();
assert.ok(recommendations['ms-python.python']);
assert.ok(recommendations['mockpublisher1.mockextension1']);
assert.ok(!recommendations['mockpublisher2.mockextension2']);
});
});
});
test('test global extensions are modified and recommendation change event is fired when an extension is ignored', () => {
const storageSetterTarget = sinon.spy();
const changeHandlerTarget = sinon.spy();
const ignoredExtensionId = 'Some.Extension';
instantiationService.stub(IStorageService, {
get: (a, b, c) => a === 'extensionsAssistant/ignored_recommendations' ? '["ms-vscode.vscode"]' : c,
store: (...args) => {
storageSetterTarget(...args);
}
});
return setUpFolderWorkspace('myFolder', []).then(() => {
testObject = instantiationService.createInstance(ExtensionTipsService);
testObject.onRecommendationChange(changeHandlerTarget);
testObject.toggleIgnoredRecommendation(ignoredExtensionId, true);
assert.ok(changeHandlerTarget.calledOnce);
assert.ok(changeHandlerTarget.getCall(0).calledWithMatch({ extensionId: 'Some.Extension', isRecommended: false }));
assert.ok(storageSetterTarget.calledWithExactly('extensionsAssistant/ignored_recommendations', `["ms-vscode.vscode","${ignoredExtensionId.toLowerCase()}"]`, StorageScope.GLOBAL));
});
});
test('ExtensionTipsService: Get file based recommendations from storage (old format)', () => {
const storedRecommendations = '["ms-vscode.csharp", "ms-python.python", "eg2.tslint"]';
instantiationService.stub(IStorageService, { get: (a, b, c) => a === 'extensionsAssistant/recommendations' ? storedRecommendations : c });
return setUpFolderWorkspace('myFolder', []).then(() => {
testObject = instantiationService.createInstance(ExtensionTipsService);
return testObject.loadWorkspaceConfigPromise.then(() => {
const recommendations = testObject.getFileBasedRecommendations();
assert.equal(recommendations.length, 2);
assert.ok(recommendations.some(({ extensionId }) => extensionId === 'ms-vscode.csharp')); // stored recommendation that exists in product.extensionTips
assert.ok(recommendations.some(({ extensionId }) => extensionId === 'ms-python.python')); // stored recommendation that exists in product.extensionImportantTips
assert.ok(recommendations.every(({ extensionId }) => extensionId !== 'eg2.tslint')); // stored recommendation that is no longer in neither product.extensionTips nor product.extensionImportantTips
});
});
});
test('ExtensionTipsService: Get file based recommendations from storage (new format)', () => {
const milliSecondsInADay = 1000 * 60 * 60 * 24;
const now = Date.now();
const tenDaysOld = 10 * milliSecondsInADay;
const storedRecommendations = `{"ms-vscode.csharp": ${now}, "ms-python.python": ${now}, "eg2.tslint": ${now}, "lukehoban.Go": ${tenDaysOld}}`;
instantiationService.stub(IStorageService, { get: (a, b, c) => a === 'extensionsAssistant/recommendations' ? storedRecommendations : c });
return setUpFolderWorkspace('myFolder', []).then(() => {
testObject = instantiationService.createInstance(ExtensionTipsService);
return testObject.loadWorkspaceConfigPromise.then(() => {
const recommendations = testObject.getFileBasedRecommendations();
assert.equal(recommendations.length, 2);
assert.ok(recommendations.some(({ extensionId }) => extensionId === 'ms-vscode.csharp')); // stored recommendation that exists in product.extensionTips
assert.ok(recommendations.some(({ extensionId }) => extensionId === 'ms-python.python')); // stored recommendation that exists in product.extensionImportantTips
assert.ok(recommendations.every(({ extensionId }) => extensionId !== 'eg2.tslint')); // stored recommendation that is no longer in neither product.extensionTips nor product.extensionImportantTips
assert.ok(recommendations.every(({ extensionId }) => extensionId !== 'lukehoban.Go')); //stored recommendation that is older than a week
});
});
});
});
| src/vs/workbench/parts/extensions/test/electron-browser/extensionsTipsService.test.ts | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.00040078547317534685,
0.00018664757953956723,
0.0001647622702876106,
0.00017481783288531005,
0.000043500422179931775
]
|
{
"id": 3,
"code_window": [
"import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';\n",
"import { ICommandService } from 'vs/platform/commands/common/commands';\n",
"import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n",
"import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';\n",
"import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';\n",
"import { WorkbenchTreeController } from 'vs/platform/list/browser/listService';\n",
"import { IOpenerService } from 'vs/platform/opener/common/opener';\n",
"import { editorBackground, errorForeground, focusBorder, foreground, inputValidationErrorBackground, inputValidationErrorForeground, inputValidationErrorBorder } from 'vs/platform/theme/common/colorRegistry';\n",
"import { attachButtonStyler, attachInputBoxStyler, attachSelectBoxStyler, attachStyler } from 'vs/platform/theme/common/styler';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "add",
"edit_start_line_idx": 35
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Code } from '../../vscode/code';
export enum StatusBarElement {
BRANCH_STATUS = 0,
SYNC_STATUS = 1,
PROBLEMS_STATUS = 2,
SELECTION_STATUS = 3,
INDENTATION_STATUS = 4,
ENCODING_STATUS = 5,
EOL_STATUS = 6,
LANGUAGE_STATUS = 7,
FEEDBACK_ICON = 8
}
export class StatusBar {
private readonly mainSelector = 'div[id="workbench.parts.statusbar"]';
private readonly leftSelector = '.statusbar-item.left';
private readonly rightSelector = '.statusbar-item.right';
constructor(private code: Code) { }
async waitForStatusbarElement(element: StatusBarElement): Promise<void> {
await this.code.waitForElement(this.getSelector(element));
}
async clickOn(element: StatusBarElement): Promise<void> {
await this.code.waitAndClick(this.getSelector(element));
}
async waitForEOL(eol: string): Promise<string> {
return this.code.waitForTextContent(this.getSelector(StatusBarElement.EOL_STATUS), eol);
}
async waitForStatusbarText(title: string, text: string): Promise<void> {
await this.code.waitForTextContent(`${this.mainSelector} span[title="${title}"]`, text);
}
private getSelector(element: StatusBarElement): string {
switch (element) {
case StatusBarElement.BRANCH_STATUS:
return `${this.mainSelector} ${this.leftSelector} .octicon.octicon-git-branch`;
case StatusBarElement.SYNC_STATUS:
return `${this.mainSelector} ${this.leftSelector} .octicon.octicon-sync`;
case StatusBarElement.PROBLEMS_STATUS:
return `${this.mainSelector} ${this.leftSelector} .task-statusbar-item[title="Problems"]`;
case StatusBarElement.SELECTION_STATUS:
return `${this.mainSelector} ${this.rightSelector} .editor-status-selection`;
case StatusBarElement.INDENTATION_STATUS:
return `${this.mainSelector} ${this.rightSelector} .editor-status-indentation`;
case StatusBarElement.ENCODING_STATUS:
return `${this.mainSelector} ${this.rightSelector} .editor-status-encoding`;
case StatusBarElement.EOL_STATUS:
return `${this.mainSelector} ${this.rightSelector} .editor-status-eol`;
case StatusBarElement.LANGUAGE_STATUS:
return `${this.mainSelector} ${this.rightSelector} .editor-status-mode`;
case StatusBarElement.FEEDBACK_ICON:
return `${this.mainSelector} ${this.rightSelector} .monaco-dropdown.send-feedback`;
default:
throw new Error(element);
}
}
} | test/smoke/src/areas/statusbar/statusbar.ts | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.0001743756583891809,
0.00017176511755678803,
0.000168249272974208,
0.00017133611254394054,
0.0000023522688934463076
]
|
{
"id": 3,
"code_window": [
"import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';\n",
"import { ICommandService } from 'vs/platform/commands/common/commands';\n",
"import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n",
"import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';\n",
"import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';\n",
"import { WorkbenchTreeController } from 'vs/platform/list/browser/listService';\n",
"import { IOpenerService } from 'vs/platform/opener/common/opener';\n",
"import { editorBackground, errorForeground, focusBorder, foreground, inputValidationErrorBackground, inputValidationErrorForeground, inputValidationErrorBorder } from 'vs/platform/theme/common/colorRegistry';\n",
"import { attachButtonStyler, attachInputBoxStyler, attachSelectBoxStyler, attachStyler } from 'vs/platform/theme/common/styler';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "add",
"edit_start_line_idx": 35
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
var updateGrammar = require('../../../build/npm/update-grammar');
function adaptToJavaScript(grammar, replacementScope) {
grammar.name = 'JavaScript (with React support)';
grammar.fileTypes = ['.js', '.jsx', '.es6', '.mjs' ];
grammar.scopeName = `source${replacementScope}`;
var fixScopeNames = function(rule) {
if (typeof rule.name === 'string') {
rule.name = rule.name.replace(/\.tsx/g, replacementScope);
}
if (typeof rule.contentName === 'string') {
rule.contentName = rule.contentName.replace(/\.tsx/g, replacementScope);
}
for (var property in rule) {
var value = rule[property];
if (typeof value === 'object') {
fixScopeNames(value);
}
}
};
var repository = grammar.repository;
for (var key in repository) {
fixScopeNames(repository[key]);
}
}
var tsGrammarRepo = 'Microsoft/TypeScript-TmLanguage';
updateGrammar.update(tsGrammarRepo, 'TypeScript.tmLanguage', './syntaxes/TypeScript.tmLanguage.json');
updateGrammar.update(tsGrammarRepo, 'TypeScriptReact.tmLanguage', './syntaxes/TypeScriptReact.tmLanguage.json');
updateGrammar.update(tsGrammarRepo, 'TypeScriptReact.tmLanguage', '../javascript/syntaxes/JavaScript.tmLanguage.json', grammar => adaptToJavaScript(grammar, '.js'));
updateGrammar.update(tsGrammarRepo, 'TypeScriptReact.tmLanguage', '../javascript/syntaxes/JavaScriptReact.tmLanguage.json', grammar => adaptToJavaScript(grammar, '.js.jsx'));
| extensions/typescript-basics/build/update-grammars.js | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.00017621928418520838,
0.00017237721476703882,
0.00016505001985933632,
0.00017404044046998024,
0.000003872568868246162
]
|
{
"id": 4,
"code_window": [
"import { editorBackground, errorForeground, focusBorder, foreground, inputValidationErrorBackground, inputValidationErrorForeground, inputValidationErrorBorder } from 'vs/platform/theme/common/colorRegistry';\n",
"import { attachButtonStyler, attachInputBoxStyler, attachSelectBoxStyler, attachStyler } from 'vs/platform/theme/common/styler';\n",
"import { ICssStyleCollector, ITheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';\n",
"import { ITOCEntry } from 'vs/workbench/parts/preferences/browser/settingsLayout';\n",
"import { ISettingsEditorViewState, isExcludeSetting, SettingsTreeElement, SettingsTreeGroupElement, SettingsTreeNewExtensionsElement, settingKeyToDisplayFormat, SettingsTreeSettingElement } from 'vs/workbench/parts/preferences/browser/settingsTreeModels';\n",
"import { ExcludeSettingWidget, IExcludeDataItem, settingsHeaderForeground, settingsNumberInputBackground, settingsNumberInputBorder, settingsNumberInputForeground, settingsSelectBackground, settingsSelectBorder, settingsSelectListBorder, settingsSelectForeground, settingsTextInputBackground, settingsTextInputBorder, settingsTextInputForeground } from 'vs/workbench/parts/preferences/browser/settingsWidgets';\n",
"import { ISetting, ISettingsGroup } from 'vs/workbench/services/preferences/common/preferences';\n",
"\n",
"const $ = DOM.$;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { ISettingsEditorViewState, isExcludeSetting, settingKeyToDisplayFormat, SettingsTreeElement, SettingsTreeGroupElement, SettingsTreeNewExtensionsElement, SettingsTreeSettingElement } from 'vs/workbench/parts/preferences/browser/settingsTreeModels';\n",
"import { ExcludeSettingWidget, IExcludeDataItem, settingsHeaderForeground, settingsNumberInputBackground, settingsNumberInputBorder, settingsNumberInputForeground, settingsSelectBackground, settingsSelectBorder, settingsSelectForeground, settingsSelectListBorder, settingsTextInputBackground, settingsTextInputBorder, settingsTextInputForeground } from 'vs/workbench/parts/preferences/browser/settingsWidgets';\n",
"import { SETTINGS_EDITOR_COMMAND_SHOW_CONTEXT_MENU } from 'vs/workbench/parts/preferences/common/preferences';\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "replace",
"edit_start_line_idx": 41
} | /*---------------------------------------------------------------------------------------------
* 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 { renderMarkdown } from 'vs/base/browser/htmlContentRenderer';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { alert as ariaAlert } from 'vs/base/browser/ui/aria/aria';
import { Button } from 'vs/base/browser/ui/button/button';
import { Checkbox } from 'vs/base/browser/ui/checkbox/checkbox';
import { InputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { SelectBox } from 'vs/base/browser/ui/selectBox/selectBox';
import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar';
import { Action, IAction } from 'vs/base/common/actions';
import * as arrays from 'vs/base/common/arrays';
import { Color, RGBA } from 'vs/base/common/color';
import { onUnexpectedError } from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
import { KeyCode } from 'vs/base/common/keyCodes';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { escapeRegExpCharacters, startsWith } from 'vs/base/common/strings';
import { URI } from 'vs/base/common/uri';
import { TPromise } from 'vs/base/common/winjs.base';
import { IAccessibilityProvider, IDataSource, IFilter, IRenderer as ITreeRenderer, ITree, ITreeConfiguration } from 'vs/base/parts/tree/browser/tree';
import { DefaultTreestyler } from 'vs/base/parts/tree/browser/treeDefaults';
import { Tree } from 'vs/base/parts/tree/browser/treeImpl';
import { localize } from 'vs/nls';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { WorkbenchTreeController } from 'vs/platform/list/browser/listService';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { editorBackground, errorForeground, focusBorder, foreground, inputValidationErrorBackground, inputValidationErrorForeground, inputValidationErrorBorder } from 'vs/platform/theme/common/colorRegistry';
import { attachButtonStyler, attachInputBoxStyler, attachSelectBoxStyler, attachStyler } from 'vs/platform/theme/common/styler';
import { ICssStyleCollector, ITheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { ITOCEntry } from 'vs/workbench/parts/preferences/browser/settingsLayout';
import { ISettingsEditorViewState, isExcludeSetting, SettingsTreeElement, SettingsTreeGroupElement, SettingsTreeNewExtensionsElement, settingKeyToDisplayFormat, SettingsTreeSettingElement } from 'vs/workbench/parts/preferences/browser/settingsTreeModels';
import { ExcludeSettingWidget, IExcludeDataItem, settingsHeaderForeground, settingsNumberInputBackground, settingsNumberInputBorder, settingsNumberInputForeground, settingsSelectBackground, settingsSelectBorder, settingsSelectListBorder, settingsSelectForeground, settingsTextInputBackground, settingsTextInputBorder, settingsTextInputForeground } from 'vs/workbench/parts/preferences/browser/settingsWidgets';
import { ISetting, ISettingsGroup } from 'vs/workbench/services/preferences/common/preferences';
const $ = DOM.$;
function getExcludeDisplayValue(element: SettingsTreeSettingElement): IExcludeDataItem[] {
const data = element.isConfigured ?
{ ...element.defaultValue, ...element.scopeValue } :
element.defaultValue;
return Object.keys(data)
.filter(key => !!data[key])
.map(key => {
const value = data[key];
const sibling = typeof value === 'boolean' ? undefined : value.when;
return {
id: key,
pattern: key,
sibling
};
});
}
export function resolveSettingsTree(tocData: ITOCEntry, coreSettingsGroups: ISettingsGroup[]): { tree: ITOCEntry, leftoverSettings: Set<ISetting> } {
const allSettings = getFlatSettings(coreSettingsGroups);
return {
tree: _resolveSettingsTree(tocData, allSettings),
leftoverSettings: allSettings
};
}
export function resolveExtensionsSettings(groups: ISettingsGroup[]): ITOCEntry {
const settingsGroupToEntry = (group: ISettingsGroup) => {
const flatSettings = arrays.flatten(
group.sections.map(section => section.settings));
return {
id: group.id,
label: group.title,
settings: flatSettings
};
};
const extGroups = groups
.sort((a, b) => a.title.localeCompare(b.title))
.map(g => settingsGroupToEntry(g));
return {
id: 'extensions',
label: localize('extensions', "Extensions"),
children: extGroups
};
}
function _resolveSettingsTree(tocData: ITOCEntry, allSettings: Set<ISetting>): ITOCEntry {
let children: ITOCEntry[];
if (tocData.children) {
children = tocData.children
.map(child => _resolveSettingsTree(child, allSettings))
.filter(child => (child.children && child.children.length) || (child.settings && child.settings.length));
}
let settings: ISetting[];
if (tocData.settings) {
settings = arrays.flatten(tocData.settings.map(pattern => getMatchingSettings(allSettings, <string>pattern)));
}
if (!children && !settings) {
return null;
}
return {
id: tocData.id,
label: tocData.label,
children,
settings
};
}
function getMatchingSettings(allSettings: Set<ISetting>, pattern: string): ISetting[] {
const result: ISetting[] = [];
allSettings.forEach(s => {
if (settingMatches(s, pattern)) {
result.push(s);
allSettings.delete(s);
}
});
return result.sort((a, b) => a.key.localeCompare(b.key));
}
const settingPatternCache = new Map<string, RegExp>();
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 (let group of settingsGroups) {
for (let section of group.sections) {
for (let s of section.settings) {
if (!s.overrides || !s.overrides.length) {
result.add(s);
}
}
}
}
return result;
}
export class SettingsDataSource implements IDataSource {
getId(tree: ITree, element: SettingsTreeElement): string {
return element.id;
}
hasChildren(tree: ITree, element: SettingsTreeElement): boolean {
if (element instanceof SettingsTreeGroupElement) {
return true;
}
return false;
}
getChildren(tree: ITree, element: SettingsTreeElement): TPromise<any> {
return TPromise.as(this._getChildren(element));
}
private _getChildren(element: SettingsTreeElement): SettingsTreeElement[] {
if (element instanceof SettingsTreeGroupElement) {
return element.children;
} else {
// No children...
return null;
}
}
getParent(tree: ITree, element: SettingsTreeElement): TPromise<any> {
return TPromise.wrap(element && element.parent);
}
shouldAutoexpand(): boolean {
return true;
}
}
export class SimplePagedDataSource implements IDataSource {
private static readonly SETTINGS_PER_PAGE = 30;
private static readonly BUFFER = 5;
private loadedToIndex: number;
constructor(private realDataSource: IDataSource) {
this.reset();
}
reset(): void {
this.loadedToIndex = SimplePagedDataSource.SETTINGS_PER_PAGE * 2;
}
pageTo(index: number, top = false): boolean {
const buffer = top ? SimplePagedDataSource.SETTINGS_PER_PAGE : SimplePagedDataSource.BUFFER;
if (index > this.loadedToIndex - buffer) {
this.loadedToIndex = (Math.ceil(index / SimplePagedDataSource.SETTINGS_PER_PAGE) + 1) * SimplePagedDataSource.SETTINGS_PER_PAGE;
return true;
} else {
return false;
}
}
getId(tree: ITree, element: any): string {
return this.realDataSource.getId(tree, element);
}
hasChildren(tree: ITree, element: any): boolean {
return this.realDataSource.hasChildren(tree, element);
}
getChildren(tree: ITree, element: SettingsTreeGroupElement): TPromise<any> {
return this.realDataSource.getChildren(tree, element).then(realChildren => {
return this._getChildren(realChildren);
});
}
_getChildren(realChildren: SettingsTreeElement[]): any[] {
const lastChild = realChildren[realChildren.length - 1];
if (lastChild && lastChild.index > this.loadedToIndex) {
return realChildren.filter(child => {
return child.index < this.loadedToIndex;
});
} else {
return realChildren;
}
}
getParent(tree: ITree, element: any): TPromise<any> {
return this.realDataSource.getParent(tree, element);
}
shouldAutoexpand(tree: ITree, element: any): boolean {
return this.realDataSource.shouldAutoexpand(tree, element);
}
}
interface IDisposableTemplate {
toDispose: IDisposable[];
}
interface ISettingItemTemplate<T = any> extends IDisposableTemplate {
onChange?: (value: T) => void;
context?: SettingsTreeSettingElement;
containerElement: HTMLElement;
categoryElement: HTMLElement;
labelElement: HTMLElement;
descriptionElement: HTMLElement;
controlElement: HTMLElement;
deprecationWarningElement: HTMLElement;
otherOverridesElement: HTMLElement;
toolbar: ToolBar;
}
interface ISettingBoolItemTemplate extends ISettingItemTemplate<boolean> {
checkbox: Checkbox;
}
interface ISettingTextItemTemplate extends ISettingItemTemplate<string> {
inputBox: InputBox;
validationErrorMessageElement: HTMLElement;
}
type ISettingNumberItemTemplate = ISettingTextItemTemplate;
interface ISettingEnumItemTemplate extends ISettingItemTemplate<number> {
selectBox: SelectBox;
enumDescriptionElement: HTMLElement;
}
interface ISettingComplexItemTemplate extends ISettingItemTemplate<void> {
button: Button;
}
interface ISettingExcludeItemTemplate extends ISettingItemTemplate<void> {
excludeWidget: ExcludeSettingWidget;
}
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_NUMBER_TEMPLATE_ID = 'settings.number.template';
const SETTINGS_ENUM_TEMPLATE_ID = 'settings.enum.template';
const SETTINGS_BOOL_TEMPLATE_ID = 'settings.bool.template';
const SETTINGS_EXCLUDE_TEMPLATE_ID = 'settings.exclude.template';
const SETTINGS_COMPLEX_TEMPLATE_ID = 'settings.complex.template';
const SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID = 'settings.newExtensions.template';
const SETTINGS_GROUP_ELEMENT_TEMPLATE_ID = 'settings.group.template';
export interface ISettingChangeEvent {
key: string;
value: any; // undefined => reset/unconfigure
}
export interface ISettingLinkClickEvent {
source: SettingsTreeSettingElement;
targetKey: string;
}
export class SettingsRenderer implements ITreeRenderer {
public static readonly CONTROL_CLASS = 'setting-control-focus-target';
public static readonly CONTROL_SELECTOR = '.' + SettingsRenderer.CONTROL_CLASS;
public static readonly SETTING_KEY_ATTR = 'data-key';
private readonly _onDidChangeSetting: Emitter<ISettingChangeEvent> = new Emitter<ISettingChangeEvent>();
public readonly onDidChangeSetting: Event<ISettingChangeEvent> = this._onDidChangeSetting.event;
private readonly _onDidOpenSettings: Emitter<string> = new Emitter<string>();
public readonly onDidOpenSettings: Event<string> = this._onDidOpenSettings.event;
private readonly _onDidClickSettingLink: Emitter<ISettingLinkClickEvent> = new Emitter<ISettingLinkClickEvent>();
public readonly onDidClickSettingLink: Event<ISettingLinkClickEvent> = this._onDidClickSettingLink.event;
private readonly _onDidFocusSetting: Emitter<SettingsTreeSettingElement> = new Emitter<SettingsTreeSettingElement>();
public readonly onDidFocusSetting: Event<SettingsTreeSettingElement> = this._onDidFocusSetting.event;
private descriptionMeasureContainer: HTMLElement;
private longestSingleLineDescription = 0;
private rowHeightCache = new Map<string, number>();
private lastRenderedWidth: number;
private settingActions: IAction[];
constructor(
_measureContainer: HTMLElement,
@IThemeService private themeService: IThemeService,
@IContextViewService private contextViewService: IContextViewService,
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@ICommandService private readonly commandService: ICommandService,
@IContextMenuService private contextMenuService: IContextMenuService
) {
this.descriptionMeasureContainer = $('.setting-item-description');
DOM.append(_measureContainer,
$('.setting-measure-container.monaco-tree-row', undefined,
$('.setting-item', undefined,
this.descriptionMeasureContainer)));
this.settingActions = [
new Action('settings.resetSetting', localize('resetSettingLabel', "Reset Setting"), undefined, undefined, (context: SettingsTreeSettingElement) => {
if (context) {
this._onDidChangeSetting.fire({ key: context.setting.key, value: undefined });
}
return TPromise.wrap(null);
}),
new Separator(),
this.instantiationService.createInstance(CopySettingIdAction),
this.instantiationService.createInstance(CopySettingAsJSONAction),
];
}
showContextMenu(element: SettingsTreeSettingElement, settingDOMElement: HTMLElement): void {
const toolbarElement: HTMLElement = settingDOMElement.querySelector('.toolbar-toggle-more');
if (toolbarElement) {
this.contextMenuService.showContextMenu({
getActions: () => TPromise.wrap(this.settingActions),
getAnchor: () => toolbarElement,
getActionsContext: () => element
});
}
}
updateWidth(width: number): void {
if (this.lastRenderedWidth !== width) {
this.rowHeightCache = new Map<string, number>();
}
this.longestSingleLineDescription = 0;
this.lastRenderedWidth = width;
}
getHeight(tree: ITree, element: SettingsTreeElement): number {
if (this.rowHeightCache.has(element.id) && !(element instanceof SettingsTreeSettingElement && isExcludeSetting(element.setting))) {
return this.rowHeightCache.get(element.id);
}
const h = this._getHeight(tree, element);
this.rowHeightCache.set(element.id, h);
return h;
}
_getHeight(tree: ITree, element: SettingsTreeElement): number {
if (element instanceof SettingsTreeGroupElement) {
if (element.isFirstGroup) {
return 31;
}
return 40 + (7 * element.level);
}
if (element instanceof SettingsTreeSettingElement) {
if (isExcludeSetting(element.setting)) {
return this._getExcludeSettingHeight(element);
} else {
return this.measureSettingElementHeight(tree, element);
}
}
if (element instanceof SettingsTreeNewExtensionsElement) {
return 40;
}
return 0;
}
_getExcludeSettingHeight(element: SettingsTreeSettingElement): number {
const displayValue = getExcludeDisplayValue(element);
return (displayValue.length + 1) * 22 + 66 + this.measureSettingDescription(element);
}
private measureSettingElementHeight(tree: ITree, element: SettingsTreeSettingElement): number {
let heightExcludingDescription = 86;
if (element.valueType === 'boolean') {
heightExcludingDescription = 60;
}
return heightExcludingDescription + this.measureSettingDescription(element);
}
private measureSettingDescription(element: SettingsTreeSettingElement): number {
if (element.description.length < this.longestSingleLineDescription * .8) {
// Most setting descriptions are one short line, so try to avoid measuring them.
// If the description is less than 80% of the longest single line description, assume this will also render to be one line.
return 18;
}
const boolMeasureClass = 'measure-bool-description';
if (element.valueType === 'boolean') {
this.descriptionMeasureContainer.classList.add(boolMeasureClass);
} else if (this.descriptionMeasureContainer.classList.contains(boolMeasureClass)) {
this.descriptionMeasureContainer.classList.remove(boolMeasureClass);
}
const shouldRenderMarkdown = element.setting.descriptionIsMarkdown && element.description.indexOf('\n- ') >= 0;
while (this.descriptionMeasureContainer.firstChild) {
this.descriptionMeasureContainer.removeChild(this.descriptionMeasureContainer.firstChild);
}
if (shouldRenderMarkdown) {
const text = fixSettingLinks(element.description);
const rendered = renderMarkdown({ value: text });
rendered.classList.add('setting-item-description-markdown');
this.descriptionMeasureContainer.appendChild(rendered);
return this.descriptionMeasureContainer.offsetHeight;
} else {
// Remove markdown links, setting links, backticks
const measureText = element.setting.descriptionIsMarkdown ?
fixSettingLinks(element.description)
.replace(/\[(.*)\]\(.*\)/g, '$1')
.replace(/`([^`]*)`/g, '$1') :
element.description;
this.descriptionMeasureContainer.innerText = measureText;
const h = this.descriptionMeasureContainer.offsetHeight;
if (h < 20 && measureText.length > this.longestSingleLineDescription) {
this.longestSingleLineDescription = measureText.length;
}
return h;
}
}
getTemplateId(tree: ITree, element: SettingsTreeElement): string {
if (element instanceof SettingsTreeGroupElement) {
return SETTINGS_GROUP_ELEMENT_TEMPLATE_ID;
}
if (element instanceof SettingsTreeSettingElement) {
if (element.valueType === 'boolean') {
return SETTINGS_BOOL_TEMPLATE_ID;
}
if (element.valueType === 'integer' || element.valueType === 'number' || element.valueType === 'nullable-integer' || element.valueType === 'nullable-number') {
return SETTINGS_NUMBER_TEMPLATE_ID;
}
if (element.valueType === 'string') {
return SETTINGS_TEXT_TEMPLATE_ID;
}
if (element.valueType === 'enum') {
return SETTINGS_ENUM_TEMPLATE_ID;
}
if (element.valueType === 'exclude') {
return SETTINGS_EXCLUDE_TEMPLATE_ID;
}
return SETTINGS_COMPLEX_TEMPLATE_ID;
}
if (element instanceof SettingsTreeNewExtensionsElement) {
return SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID;
}
return '';
}
renderTemplate(tree: ITree, templateId: string, container: HTMLElement) {
if (templateId === SETTINGS_GROUP_ELEMENT_TEMPLATE_ID) {
return this.renderGroupTitleTemplate(container);
}
if (templateId === SETTINGS_TEXT_TEMPLATE_ID) {
return this.renderSettingTextTemplate(tree, container);
}
if (templateId === SETTINGS_NUMBER_TEMPLATE_ID) {
return this.renderSettingNumberTemplate(tree, container);
}
if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
return this.renderSettingBoolTemplate(tree, container);
}
if (templateId === SETTINGS_ENUM_TEMPLATE_ID) {
return this.renderSettingEnumTemplate(tree, container);
}
if (templateId === SETTINGS_EXCLUDE_TEMPLATE_ID) {
return this.renderSettingExcludeTemplate(tree, container);
}
if (templateId === SETTINGS_COMPLEX_TEMPLATE_ID) {
return this.renderSettingComplexTemplate(tree, container);
}
if (templateId === SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID) {
return this.renderNewExtensionsTemplate(container);
}
return null;
}
private renderGroupTitleTemplate(container: HTMLElement): IGroupTitleTemplate {
DOM.addClass(container, 'group-title');
const toDispose = [];
const template: IGroupTitleTemplate = {
parent: container,
toDispose
};
return template;
}
private renderCommonTemplate(tree: ITree, container: HTMLElement, typeClass: string): ISettingItemTemplate {
DOM.addClass(container, 'setting-item');
DOM.addClass(container, 'setting-item-' + typeClass);
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 labelElement = DOM.append(labelCategoryContainer, $('span.setting-item-label'));
const otherOverridesElement = DOM.append(titleElement, $('span.setting-item-overrides'));
const descriptionElement = DOM.append(container, $('.setting-item-description'));
const modifiedIndicatorElement = DOM.append(container, $('.setting-item-modified-indicator'));
modifiedIndicatorElement.title = localize('modified', "Modified");
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 toDispose = [];
const toolbar = this.renderSettingToolbar(container);
const template: ISettingItemTemplate = {
toDispose,
containerElement: container,
categoryElement,
labelElement,
descriptionElement,
controlElement,
deprecationWarningElement,
otherOverridesElement,
toolbar
};
// Prevent clicks from being handled by list
toDispose.push(DOM.addDisposableListener(controlElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addStandardDisposableListener(valueElement, 'keydown', (e: StandardKeyboardEvent) => {
if (e.keyCode === KeyCode.Escape) {
tree.domFocus();
e.browserEvent.stopPropagation();
}
}));
return template;
}
private addSettingElementFocusHandler(template: ISettingItemTemplate): void {
const focusTracker = DOM.trackFocus(template.containerElement);
template.toDispose.push(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);
}
});
}
private renderSettingTextTemplate(tree: ITree, container: HTMLElement, type = 'text'): ISettingTextItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'text');
const validationErrorMessageElement = DOM.append(container, $('.setting-item-validation-message'));
const inputBox = new InputBox(common.controlElement, this.contextViewService);
common.toDispose.push(inputBox);
common.toDispose.push(attachInputBoxStyler(inputBox, this.themeService, {
inputBackground: settingsTextInputBackground,
inputForeground: settingsTextInputForeground,
inputBorder: settingsTextInputBorder
}));
common.toDispose.push(
inputBox.onDidChange(e => {
if (template.onChange) {
template.onChange(e);
}
}));
common.toDispose.push(inputBox);
inputBox.inputElement.classList.add(SettingsRenderer.CONTROL_CLASS);
const template: ISettingTextItemTemplate = {
...common,
inputBox,
validationErrorMessageElement
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderSettingNumberTemplate(tree: ITree, container: HTMLElement): ISettingNumberItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'number');
const validationErrorMessageElement = DOM.append(container, $('.setting-item-validation-message'));
const inputBox = new InputBox(common.controlElement, this.contextViewService, { type: 'number' });
common.toDispose.push(inputBox);
common.toDispose.push(attachInputBoxStyler(inputBox, this.themeService, {
inputBackground: settingsNumberInputBackground,
inputForeground: settingsNumberInputForeground,
inputBorder: settingsNumberInputBorder
}));
common.toDispose.push(
inputBox.onDidChange(e => {
if (template.onChange) {
template.onChange(e);
}
}));
common.toDispose.push(inputBox);
inputBox.inputElement.classList.add(SettingsRenderer.CONTROL_CLASS);
const template: ISettingNumberItemTemplate = {
...common,
inputBox,
validationErrorMessageElement
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderSettingToolbar(container: HTMLElement): ToolBar {
const toolbar = new ToolBar(container, this.contextMenuService, {});
toolbar.setActions([], this.settingActions)();
const button = container.querySelector('.toolbar-toggle-more');
if (button) {
(<HTMLElement>button).tabIndex = -1;
}
return toolbar;
}
private renderSettingBoolTemplate(tree: ITree, container: HTMLElement): ISettingBoolItemTemplate {
DOM.addClass(container, 'setting-item');
DOM.addClass(container, 'setting-item-bool');
const titleElement = DOM.append(container, $('.setting-item-title'));
const categoryElement = DOM.append(titleElement, $('span.setting-item-category'));
const labelElement = DOM.append(titleElement, $('span.setting-item-label'));
const otherOverridesElement = DOM.append(titleElement, $('span.setting-item-overrides'));
const descriptionAndValueElement = DOM.append(container, $('.setting-item-value-description'));
const controlElement = DOM.append(descriptionAndValueElement, $('.setting-item-bool-control'));
const descriptionElement = DOM.append(descriptionAndValueElement, $('.setting-item-description'));
const modifiedIndicatorElement = DOM.append(container, $('.setting-item-modified-indicator'));
modifiedIndicatorElement.title = localize('modified', "Modified");
const deprecationWarningElement = DOM.append(container, $('.setting-item-deprecation-message'));
const toDispose = [];
const checkbox = new Checkbox({ actionClassName: 'setting-value-checkbox', isChecked: true, title: '', inputActiveOptionBorder: null });
controlElement.appendChild(checkbox.domNode);
toDispose.push(checkbox);
toDispose.push(checkbox.onChange(() => {
if (template.onChange) {
template.onChange(checkbox.checked);
}
}));
// Need to listen for mouse clicks on description and toggle checkbox - use target ID for safety
// Also have to ignore embedded links - too buried to stop propagation
toDispose.push(DOM.addDisposableListener(descriptionElement, DOM.EventType.MOUSE_DOWN, (e) => {
const targetElement = <HTMLElement>e.toElement;
const targetId = descriptionElement.getAttribute('checkbox_label_target_id');
// Make sure we are not a link and the target ID matches
// Toggle target checkbox
if (targetElement.tagName.toLowerCase() !== 'a' && targetId === template.checkbox.domNode.id) {
template.checkbox.checked = template.checkbox.checked ? false : true;
template.onChange(checkbox.checked);
}
DOM.EventHelper.stop(e);
}));
checkbox.domNode.classList.add(SettingsRenderer.CONTROL_CLASS);
const toolbar = this.renderSettingToolbar(container);
toDispose.push(toolbar);
const template: ISettingBoolItemTemplate = {
toDispose,
containerElement: container,
categoryElement,
labelElement,
controlElement,
checkbox,
descriptionElement,
deprecationWarningElement,
otherOverridesElement,
toolbar
};
this.addSettingElementFocusHandler(template);
// Prevent clicks from being handled by list
toDispose.push(DOM.addDisposableListener(controlElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addStandardDisposableListener(controlElement, 'keydown', (e: StandardKeyboardEvent) => {
if (e.keyCode === KeyCode.Escape) {
tree.domFocus();
e.browserEvent.stopPropagation();
}
}));
return template;
}
public cancelSuggesters() {
this.contextViewService.hideContextView();
}
private renderSettingEnumTemplate(tree: ITree, container: HTMLElement): ISettingEnumItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'enum');
const selectBox = new SelectBox([], undefined, this.contextViewService, undefined, {
hasDetails: true
});
common.toDispose.push(selectBox);
common.toDispose.push(attachSelectBoxStyler(selectBox, this.themeService, {
selectBackground: settingsSelectBackground,
selectForeground: settingsSelectForeground,
selectBorder: settingsSelectBorder,
selectListBorder: settingsSelectListBorder
}));
selectBox.render(common.controlElement);
const selectElement = common.controlElement.querySelector('select');
if (selectElement) {
selectElement.classList.add(SettingsRenderer.CONTROL_CLASS);
}
common.toDispose.push(
selectBox.onDidSelect(e => {
if (template.onChange) {
template.onChange(e.index);
}
}));
const enumDescriptionElement = common.containerElement.insertBefore($('.setting-item-enumDescription'), common.descriptionElement.nextSibling);
const template: ISettingEnumItemTemplate = {
...common,
selectBox,
enumDescriptionElement
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderSettingExcludeTemplate(tree: ITree, container: HTMLElement): ISettingExcludeItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'exclude');
const excludeWidget = this.instantiationService.createInstance(ExcludeSettingWidget, common.controlElement);
excludeWidget.domNode.classList.add(SettingsRenderer.CONTROL_CLASS);
common.toDispose.push(excludeWidget);
const template: ISettingExcludeItemTemplate = {
...common,
excludeWidget
};
this.addSettingElementFocusHandler(template);
common.toDispose.push(excludeWidget.onDidChangeExclude(e => {
if (template.context) {
let newValue = { ...template.context.scopeValue };
// first delete the existing entry, if present
if (e.originalPattern) {
if (e.originalPattern in template.context.defaultValue) {
// delete a default by overriding it
newValue[e.originalPattern] = false;
} else {
delete newValue[e.originalPattern];
}
}
// then add the new or updated entry, if present
if (e.pattern) {
if (e.pattern in template.context.defaultValue && !e.sibling) {
// add a default by deleting its override
delete newValue[e.pattern];
} else {
newValue[e.pattern] = e.sibling ? { when: e.sibling } : true;
}
}
const sortKeys = (obj) => {
const keyArray = Object.keys(obj)
.map(key => ({ key, val: obj[key] }))
.sort((a, b) => a.key.localeCompare(b.key));
const retVal = {};
keyArray.forEach(pair => {
retVal[pair.key] = pair.val;
});
return retVal;
};
this._onDidChangeSetting.fire({
key: template.context.setting.key,
value: Object.keys(newValue).length === 0 ? undefined : sortKeys(newValue)
});
}
}));
return template;
}
private renderSettingComplexTemplate(tree: ITree, container: HTMLElement): ISettingComplexItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'complex');
const openSettingsButton = new Button(common.controlElement, { title: true, buttonBackground: null, buttonHoverBackground: null });
common.toDispose.push(openSettingsButton);
common.toDispose.push(openSettingsButton.onDidClick(() => template.onChange(null)));
openSettingsButton.label = localize('editInSettingsJson', "Edit in settings.json");
openSettingsButton.element.classList.add('edit-in-settings-button');
common.toDispose.push(attachButtonStyler(openSettingsButton, this.themeService, {
buttonBackground: Color.transparent.toString(),
buttonHoverBackground: Color.transparent.toString(),
buttonForeground: 'foreground'
}));
const template: ISettingComplexItemTemplate = {
...common,
button: openSettingsButton
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderNewExtensionsTemplate(container: HTMLElement): ISettingNewExtensionsTemplate {
const toDispose = [];
container.classList.add('setting-item-new-extensions');
const button = new Button(container, { title: true, buttonBackground: null, buttonHoverBackground: null });
toDispose.push(button);
toDispose.push(button.onDidClick(() => {
if (template.context) {
this.commandService.executeCommand('workbench.extensions.action.showExtensionsWithIds', template.context.extensionIds);
}
}));
button.label = localize('newExtensionsButtonLabel', "Show matching extensions");
button.element.classList.add('settings-new-extensions-button');
toDispose.push(attachButtonStyler(button, this.themeService));
const template: ISettingNewExtensionsTemplate = {
button,
toDispose
};
// this.addSettingElementFocusHandler(template);
return template;
}
renderElement(tree: ITree, element: SettingsTreeElement, templateId: string, template: any): void {
if (templateId === SETTINGS_GROUP_ELEMENT_TEMPLATE_ID) {
return this.renderGroupElement(<SettingsTreeGroupElement>element, template);
}
if (templateId === SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID) {
return this.renderNewExtensionsElement(<SettingsTreeNewExtensionsElement>element, template);
}
return this.renderSettingElement(tree, <SettingsTreeSettingElement>element, templateId, template);
}
private renderGroupElement(element: SettingsTreeGroupElement, template: IGroupTitleTemplate): void {
template.parent.innerHTML = '';
const labelElement = DOM.append(template.parent, $('div.settings-group-title-label'));
labelElement.classList.add(`settings-group-level-${element.level}`);
labelElement.textContent = (<SettingsTreeGroupElement>element).label;
if (element.isFirstGroup) {
labelElement.classList.add('settings-group-first');
}
}
private renderNewExtensionsElement(element: SettingsTreeNewExtensionsElement, template: ISettingNewExtensionsTemplate): void {
template.context = element;
}
public getSettingDOMElementForDOMElement(domElement: HTMLElement): HTMLElement {
const parent = DOM.findParentWithClass(domElement, 'setting-item');
if (parent) {
return parent;
}
return null;
}
public getDOMElementsForSettingKey(treeContainer: HTMLElement, key: string): NodeListOf<HTMLElement> {
return treeContainer.querySelectorAll(`[${SettingsRenderer.SETTING_KEY_ATTR}="${key}"]`);
}
public getKeyForDOMElementInSetting(element: HTMLElement): string {
const settingElement = this.getSettingDOMElementForDOMElement(element);
return settingElement && settingElement.getAttribute(SettingsRenderer.SETTING_KEY_ATTR);
}
private renderSettingElement(tree: ITree, element: SettingsTreeSettingElement, templateId: string, template: ISettingItemTemplate | ISettingBoolItemTemplate): void {
template.context = element;
template.toolbar.context = element;
const setting = element.setting;
DOM.toggleClass(template.containerElement, 'is-configured', element.isConfigured);
DOM.toggleClass(template.containerElement, 'is-expanded', true);
template.containerElement.setAttribute(SettingsRenderer.SETTING_KEY_ATTR, element.setting.key);
const titleTooltip = setting.key + (element.isConfigured ? ' - Modified' : '');
template.categoryElement.textContent = element.displayCategory && (element.displayCategory + ': ');
template.categoryElement.title = titleTooltip;
template.labelElement.textContent = element.displayLabel;
template.labelElement.title = titleTooltip;
this.renderValue(element, templateId, <ISettingItemTemplate>template);
template.descriptionElement.innerHTML = '';
if (element.setting.descriptionIsMarkdown) {
const renderedDescription = this.renderDescriptionMarkdown(element, element.description, template.toDispose);
template.descriptionElement.appendChild(renderedDescription);
} else {
template.descriptionElement.innerText = element.description;
}
const baseId = (element.displayCategory + '_' + element.displayLabel).replace(/ /g, '_').toLowerCase();
template.descriptionElement.id = baseId + '_setting_description';
if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
// Add checkbox target to description clickable and able to toggle checkbox
template.descriptionElement.setAttribute('checkbox_label_target_id', baseId + '_setting_item');
}
if (element.overriddenScopeList.length) {
let otherOverridesLabel = element.isConfigured ?
localize('alsoConfiguredIn', "Also modified in") :
localize('configuredIn', "Modified in");
template.otherOverridesElement.textContent = `(${otherOverridesLabel}: ${element.overriddenScopeList.join(', ')})`;
} else {
template.otherOverridesElement.textContent = '';
}
// Remove tree attributes - sometimes overridden by tree - should be managed there
template.containerElement.parentElement.removeAttribute('role');
template.containerElement.parentElement.removeAttribute('aria-level');
template.containerElement.parentElement.removeAttribute('aria-posinset');
template.containerElement.parentElement.removeAttribute('aria-setsize');
}
private renderDescriptionMarkdown(element: SettingsTreeSettingElement, text: string, disposeables: IDisposable[]): HTMLElement {
// Rewrite `#editor.fontSize#` to link format
text = fixSettingLinks(text);
const renderedMarkdown = renderMarkdown({ value: text }, {
actionHandler: {
callback: (content: string) => {
if (startsWith(content, '#')) {
const e: ISettingLinkClickEvent = {
source: element,
targetKey: content.substr(1)
};
this._onDidClickSettingLink.fire(e);
} else {
this.openerService.open(URI.parse(content)).then(void 0, onUnexpectedError);
}
},
disposeables
}
});
renderedMarkdown.classList.add('setting-item-description-markdown');
cleanRenderedMarkdown(renderedMarkdown);
return renderedMarkdown;
}
private renderValue(element: SettingsTreeSettingElement, templateId: string, template: ISettingItemTemplate | ISettingBoolItemTemplate): void {
const onChange = value => this._onDidChangeSetting.fire({ key: element.setting.key, value });
template.deprecationWarningElement.innerText = element.setting.deprecationMessage || '';
if (templateId === SETTINGS_ENUM_TEMPLATE_ID) {
this.renderEnum(element, <ISettingEnumItemTemplate>template, onChange);
} else if (templateId === SETTINGS_TEXT_TEMPLATE_ID) {
this.renderText(element, <ISettingTextItemTemplate>template, onChange);
} else if (templateId === SETTINGS_NUMBER_TEMPLATE_ID) {
this.renderNumber(element, <ISettingTextItemTemplate>template, onChange);
} else if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
this.renderBool(element, <ISettingBoolItemTemplate>template, onChange);
} else if (templateId === SETTINGS_EXCLUDE_TEMPLATE_ID) {
this.renderExcludeSetting(element, <ISettingExcludeItemTemplate>template);
} else if (templateId === SETTINGS_COMPLEX_TEMPLATE_ID) {
this.renderComplexSetting(element, <ISettingComplexItemTemplate>template);
}
}
private renderBool(dataElement: SettingsTreeSettingElement, template: ISettingBoolItemTemplate, onChange: (value: boolean) => void): void {
template.onChange = null;
template.checkbox.checked = dataElement.value;
template.onChange = onChange;
// Setup and add ARIA attributes
// Create id and label for control/input element - parent is wrapper div
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' ' + modifiedText;
// We use the parent control div for the aria-labelledby target
// Does not appear you can use the direct label on the element itself within a tree
template.checkbox.domNode.parentElement.id = baseId + '_setting_label';
template.checkbox.domNode.parentElement.setAttribute('aria-label', label);
// Labels will not be read on descendent input elements of the parent treeitem
// unless defined as role=treeitem and indirect aria-labelledby approach
template.checkbox.domNode.id = baseId + '_setting_item';
template.checkbox.domNode.setAttribute('role', 'checkbox');
template.checkbox.domNode.setAttribute('aria-labelledby', baseId + '_setting_label');
template.checkbox.domNode.setAttribute('aria-describedby', baseId + '_setting_description');
}
private renderEnum(dataElement: SettingsTreeSettingElement, template: ISettingEnumItemTemplate, onChange: (value: string) => void): void {
const displayOptions = dataElement.setting.enum
.map(String)
.map(escapeInvisibleChars);
template.selectBox.setOptions(displayOptions);
const enumDescriptions = dataElement.setting.enumDescriptions;
const enumDescriptionsAreMarkdown = dataElement.setting.enumDescriptionsAreMarkdown;
template.selectBox.setDetailsProvider(index =>
({
details: enumDescriptions && enumDescriptions[index] && (enumDescriptionsAreMarkdown ? fixSettingLinks(enumDescriptions[index], false) : enumDescriptions[index]),
isMarkdown: enumDescriptionsAreMarkdown
}));
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' ' + modifiedText;
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
template.selectBox.setAriaLabel(label);
const idx = dataElement.setting.enum.indexOf(dataElement.value);
template.onChange = null;
template.selectBox.select(idx);
template.onChange = idx => onChange(dataElement.setting.enum[idx]);
if (template.controlElement.firstElementChild) {
// SelectBox needs to have treeitem changed to combobox to read correctly within tree
template.controlElement.firstElementChild.setAttribute('role', 'combobox');
template.controlElement.firstElementChild.setAttribute('aria-describedby', baseId + '_setting_description');
}
template.enumDescriptionElement.innerHTML = '';
}
private renderText(dataElement: SettingsTreeSettingElement, template: ISettingTextItemTemplate, onChange: (value: string) => void): void {
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' ' + modifiedText; template.onChange = null;
template.inputBox.value = dataElement.value;
template.onChange = value => { renderValidations(dataElement, template, false, label); onChange(value); };
// Setup and add ARIA attributes
// Create id and label for control/input element - parent is wrapper div
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
// We use the parent control div for the aria-labelledby target
// Does not appear you can use the direct label on the element itself within a tree
template.inputBox.inputElement.parentElement.id = baseId + '_setting_label';
template.inputBox.inputElement.parentElement.setAttribute('aria-label', label);
// Labels will not be read on descendent input elements of the parent treeitem
// unless defined as role=treeitem and indirect aria-labelledby approach
template.inputBox.inputElement.id = baseId + '_setting_item';
template.inputBox.inputElement.setAttribute('role', 'textbox');
template.inputBox.inputElement.setAttribute('aria-labelledby', baseId + '_setting_label');
template.inputBox.inputElement.setAttribute('aria-describedby', baseId + '_setting_description');
renderValidations(dataElement, template, true, label);
}
private renderNumber(dataElement: SettingsTreeSettingElement, template: ISettingTextItemTemplate, onChange: (value: number) => void): void {
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' number ' + modifiedText; const numParseFn = (dataElement.valueType === 'integer' || dataElement.valueType === 'nullable-integer')
? parseInt : parseFloat;
const nullNumParseFn = (dataElement.valueType === 'nullable-integer' || dataElement.valueType === 'nullable-number')
? (v => v === '' ? null : numParseFn(v)) : numParseFn;
template.onChange = null;
template.inputBox.value = dataElement.value;
template.onChange = value => { renderValidations(dataElement, template, false, label); onChange(nullNumParseFn(value)); };
// Setup and add ARIA attributes
// Create id and label for control/input element - parent is wrapper div
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
// We use the parent control div for the aria-labelledby target
// Does not appear you can use the direct label on the element itself within a tree
template.inputBox.inputElement.parentElement.id = baseId + '_setting_label';
template.inputBox.inputElement.parentElement.setAttribute('aria-label', label);
// Labels will not be read on descendent input elements of the parent treeitem
// unless defined as role=treeitem and indirect aria-labelledby approach
template.inputBox.inputElement.id = baseId + '_setting_item';
template.inputBox.inputElement.setAttribute('role', 'textbox');
template.inputBox.inputElement.setAttribute('aria-labelledby', baseId + '_setting_label');
template.inputBox.inputElement.setAttribute('aria-describedby', baseId + '_setting_description');
renderValidations(dataElement, template, true, label);
}
private renderExcludeSetting(dataElement: SettingsTreeSettingElement, template: ISettingExcludeItemTemplate): void {
const value = getExcludeDisplayValue(dataElement);
template.excludeWidget.setValue(value);
template.context = dataElement;
}
private renderComplexSetting(dataElement: SettingsTreeSettingElement, template: ISettingComplexItemTemplate): void {
template.onChange = () => this._onDidOpenSettings.fire(dataElement.setting.key);
}
disposeTemplate(tree: ITree, templateId: string, template: IDisposableTemplate): void {
dispose(template.toDispose);
}
}
function renderValidations(dataElement: SettingsTreeSettingElement, template: ISettingTextItemTemplate, calledOnStartup: boolean, originalAriaLabel: string) {
if (dataElement.setting.validator) {
let errMsg = dataElement.setting.validator(template.inputBox.value);
if (errMsg) {
DOM.addClass(template.containerElement, 'invalid-input');
template.validationErrorMessageElement.innerText = errMsg;
let validationError = localize('validationError', "Validation Error.");
template.inputBox.inputElement.parentElement.setAttribute('aria-label', [originalAriaLabel, validationError, errMsg].join(' '));
if (!calledOnStartup) { ariaAlert(validationError + ' ' + errMsg); }
return;
} else {
template.inputBox.inputElement.parentElement.setAttribute('aria-label', originalAriaLabel);
}
}
DOM.removeClass(template.containerElement, 'invalid-input');
}
function cleanRenderedMarkdown(element: Node): void {
for (let i = 0; i < element.childNodes.length; i++) {
const child = element.childNodes.item(i);
const tagName = (<Element>child).tagName && (<Element>child).tagName.toLowerCase();
if (tagName === 'img') {
element.removeChild(child);
} else {
cleanRenderedMarkdown(child);
}
}
}
function fixSettingLinks(text: string, linkify = true): string {
return text.replace(/`#([^#]*)#`/g, (match, settingKey) => {
const targetDisplayFormat = settingKeyToDisplayFormat(settingKey);
const targetName = `${targetDisplayFormat.category}: ${targetDisplayFormat.label}`;
return linkify ?
`[${targetName}](#${settingKey})` :
`"${targetName}"`;
});
}
function escapeInvisibleChars(enumValue: string): string {
return enumValue && enumValue
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r');
}
export class SettingsTreeFilter implements IFilter {
constructor(
private viewState: ISettingsEditorViewState,
) { }
isVisible(tree: ITree, element: SettingsTreeElement): boolean {
// Filter during search
if (this.viewState.filterToCategory && element instanceof SettingsTreeSettingElement) {
if (!this.settingContainedInGroup(element.setting, this.viewState.filterToCategory)) {
return false;
}
}
if (element instanceof SettingsTreeSettingElement && this.viewState.tagFilters) {
return element.matchesAllTags(this.viewState.tagFilters);
}
if (element instanceof SettingsTreeGroupElement) {
if (typeof element.count === 'number') {
return element.count > 0;
}
return element.children.some(child => this.isVisible(tree, child));
}
if (element instanceof SettingsTreeNewExtensionsElement) {
if ((this.viewState.tagFilters && this.viewState.tagFilters.size) || this.viewState.filterToCategory) {
return false;
}
}
return true;
}
private settingContainedInGroup(setting: ISetting, group: SettingsTreeGroupElement): boolean {
return group.children.some(child => {
if (child instanceof SettingsTreeGroupElement) {
return this.settingContainedInGroup(setting, child);
} else if (child instanceof SettingsTreeSettingElement) {
return child.setting.key === setting.key;
} else {
return false;
}
});
}
}
export class SettingsTreeController extends WorkbenchTreeController {
constructor(
@IConfigurationService configurationService: IConfigurationService
) {
super({}, configurationService);
}
protected onLeftClick(tree: ITree, element: any, eventish: IMouseEvent, origin?: string): boolean {
const isLink = eventish.target.tagName.toLowerCase() === 'a' ||
eventish.target.parentElement.tagName.toLowerCase() === 'a'; // <code> inside <a>
if (isLink && (DOM.findParentWithClass(eventish.target, 'setting-item-description-markdown', tree.getHTMLElement()) || DOM.findParentWithClass(eventish.target, 'select-box-description-markdown'))) {
return true;
}
return false;
}
}
export class SettingsAccessibilityProvider implements IAccessibilityProvider {
getAriaLabel(tree: ITree, element: SettingsTreeElement): string {
if (!element) {
return '';
}
if (element instanceof SettingsTreeSettingElement) {
return localize('settingRowAriaLabel', "{0} {1}, Setting", element.displayCategory, element.displayLabel);
}
if (element instanceof SettingsTreeGroupElement) {
return localize('groupRowAriaLabel', "{0}, group", element.label);
}
return '';
}
}
class NonExpandableOrSelectableTree extends Tree {
expand(): TPromise<any> {
return TPromise.wrap(null);
}
collapse(): TPromise<any> {
return TPromise.wrap(null);
}
public setFocus(element?: any, eventPayload?: any): void {
return;
}
public focusNext(count?: number, eventPayload?: any): void {
return;
}
public focusPrevious(count?: number, eventPayload?: any): void {
return;
}
public focusParent(eventPayload?: any): void {
return;
}
public focusFirstChild(eventPayload?: any): void {
return;
}
public focusFirst(eventPayload?: any, from?: any): void {
return;
}
public focusNth(index: number, eventPayload?: any): void {
return;
}
public focusLast(eventPayload?: any, from?: any): void {
return;
}
public focusNextPage(eventPayload?: any): void {
return;
}
public focusPreviousPage(eventPayload?: any): void {
return;
}
public select(element: any, eventPayload?: any): void {
return;
}
public selectRange(fromElement: any, toElement: any, eventPayload?: any): void {
return;
}
public selectAll(elements: any[], eventPayload?: any): void {
return;
}
public setSelection(elements: any[], eventPayload?: any): void {
return;
}
public toggleSelection(element: any, eventPayload?: any): void {
return;
}
}
export class SettingsTree extends NonExpandableOrSelectableTree {
protected disposables: IDisposable[];
constructor(
container: HTMLElement,
viewState: ISettingsEditorViewState,
configuration: Partial<ITreeConfiguration>,
@IThemeService themeService: IThemeService,
@IInstantiationService instantiationService: IInstantiationService
) {
const treeClass = 'settings-editor-tree';
const controller = instantiationService.createInstance(SettingsTreeController);
const fullConfiguration = <ITreeConfiguration>{
controller,
accessibilityProvider: instantiationService.createInstance(SettingsAccessibilityProvider),
filter: instantiationService.createInstance(SettingsTreeFilter, viewState),
styler: new DefaultTreestyler(DOM.createStyleSheet(container), treeClass),
...configuration
};
const options = {
ariaLabel: localize('treeAriaLabel', "Settings"),
showLoading: false,
indentPixels: 0,
twistiePixels: 20, // Actually for gear button
};
super(container,
fullConfiguration,
options);
this.disposables = [];
this.disposables.push(controller);
this.disposables.push(registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
const activeBorderColor = theme.getColor(focusBorder);
if (activeBorderColor) {
// TODO@rob - why isn't this applied when added to the stylesheet from tocTree.ts? Seems like a chromium glitch.
collector.addRule(`.settings-editor > .settings-body > .settings-toc-container .monaco-tree:focus .monaco-tree-row.focused {outline: solid 1px ${activeBorderColor}; outline-offset: -1px; }`);
}
const foregroundColor = theme.getColor(foreground);
if (foregroundColor) {
// Links appear inside other elements in markdown. CSS opacity acts like a mask. So we have to dynamically compute the description color to avoid
// applying an opacity to the link color.
const fgWithOpacity = new Color(new RGBA(foregroundColor.rgba.r, foregroundColor.rgba.g, foregroundColor.rgba.b, .9));
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-description { color: ${fgWithOpacity}; }`);
}
const errorColor = theme.getColor(errorForeground);
if (errorColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-deprecation-message { color: ${errorColor}; }`);
}
const invalidInputBackground = theme.getColor(inputValidationErrorBackground);
if (invalidInputBackground) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-validation-message { background-color: ${invalidInputBackground}; }`);
}
const invalidInputForeground = theme.getColor(inputValidationErrorForeground);
if (invalidInputForeground) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-validation-message { color: ${invalidInputForeground}; }`);
}
const invalidInputBorder = theme.getColor(inputValidationErrorBorder);
if (invalidInputBorder) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-validation-message { border-style:solid; border-width: 1px; border-color: ${invalidInputBorder}; }`);
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item.invalid-input .setting-item-control .monaco-inputbox.idle { outline-width: 0; border-style:solid; border-width: 1px; border-color: ${invalidInputBorder}; }`);
}
const headerForegroundColor = theme.getColor(settingsHeaderForeground);
if (headerForegroundColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .settings-group-title-label { color: ${headerForegroundColor}; }`);
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item-label { color: ${headerForegroundColor}; }`);
}
const focusBorderColor = theme.getColor(focusBorder);
if (focusBorderColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-description-markdown a:focus { outline-color: ${focusBorderColor} }`);
}
}));
this.getHTMLElement().classList.add(treeClass);
this.disposables.push(attachStyler(themeService, {
listActiveSelectionBackground: editorBackground,
listActiveSelectionForeground: foreground,
listFocusAndSelectionBackground: editorBackground,
listFocusAndSelectionForeground: foreground,
listFocusBackground: editorBackground,
listFocusForeground: foreground,
listHoverForeground: foreground,
listHoverBackground: editorBackground,
listHoverOutline: editorBackground,
listFocusOutline: editorBackground,
listInactiveSelectionBackground: editorBackground,
listInactiveSelectionForeground: foreground
}, colors => {
this.style(colors);
}));
}
}
class CopySettingIdAction extends Action {
static readonly ID = 'settings.copySettingId';
static readonly LABEL = localize('copySettingIdLabel', "Copy Setting ID");
constructor(
@IClipboardService private clipboardService: IClipboardService
) {
super(CopySettingIdAction.ID, CopySettingIdAction.LABEL);
}
run(context: SettingsTreeSettingElement): TPromise<void> {
if (context) {
this.clipboardService.writeText(context.setting.key);
}
return TPromise.as(null);
}
}
class CopySettingAsJSONAction extends Action {
static readonly ID = 'settings.copySettingAsJSON';
static readonly LABEL = localize('copySettingAsJSONLabel', "Copy Setting as JSON");
constructor(
@IClipboardService private clipboardService: IClipboardService
) {
super(CopySettingAsJSONAction.ID, CopySettingAsJSONAction.LABEL);
}
run(context: SettingsTreeSettingElement): TPromise<void> {
if (context) {
const jsonResult = `"${context.setting.key}": ${JSON.stringify(context.value, undefined, ' ')}`;
this.clipboardService.writeText(jsonResult);
}
return TPromise.as(null);
}
} | src/vs/workbench/parts/preferences/browser/settingsTree.ts | 1 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.8698854446411133,
0.007371915969997644,
0.00016019196482375264,
0.00017866111011244357,
0.06908366829156876
]
|
{
"id": 4,
"code_window": [
"import { editorBackground, errorForeground, focusBorder, foreground, inputValidationErrorBackground, inputValidationErrorForeground, inputValidationErrorBorder } from 'vs/platform/theme/common/colorRegistry';\n",
"import { attachButtonStyler, attachInputBoxStyler, attachSelectBoxStyler, attachStyler } from 'vs/platform/theme/common/styler';\n",
"import { ICssStyleCollector, ITheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';\n",
"import { ITOCEntry } from 'vs/workbench/parts/preferences/browser/settingsLayout';\n",
"import { ISettingsEditorViewState, isExcludeSetting, SettingsTreeElement, SettingsTreeGroupElement, SettingsTreeNewExtensionsElement, settingKeyToDisplayFormat, SettingsTreeSettingElement } from 'vs/workbench/parts/preferences/browser/settingsTreeModels';\n",
"import { ExcludeSettingWidget, IExcludeDataItem, settingsHeaderForeground, settingsNumberInputBackground, settingsNumberInputBorder, settingsNumberInputForeground, settingsSelectBackground, settingsSelectBorder, settingsSelectListBorder, settingsSelectForeground, settingsTextInputBackground, settingsTextInputBorder, settingsTextInputForeground } from 'vs/workbench/parts/preferences/browser/settingsWidgets';\n",
"import { ISetting, ISettingsGroup } from 'vs/workbench/services/preferences/common/preferences';\n",
"\n",
"const $ = DOM.$;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { ISettingsEditorViewState, isExcludeSetting, settingKeyToDisplayFormat, SettingsTreeElement, SettingsTreeGroupElement, SettingsTreeNewExtensionsElement, SettingsTreeSettingElement } from 'vs/workbench/parts/preferences/browser/settingsTreeModels';\n",
"import { ExcludeSettingWidget, IExcludeDataItem, settingsHeaderForeground, settingsNumberInputBackground, settingsNumberInputBorder, settingsNumberInputForeground, settingsSelectBackground, settingsSelectBorder, settingsSelectForeground, settingsSelectListBorder, settingsTextInputBackground, settingsTextInputBorder, settingsTextInputForeground } from 'vs/workbench/parts/preferences/browser/settingsWidgets';\n",
"import { SETTINGS_EDITOR_COMMAND_SHOW_CONTEXT_MENU } from 'vs/workbench/parts/preferences/common/preferences';\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "replace",
"edit_start_line_idx": 41
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import 'vs/css!./media/editordroptarget';
import { LocalSelectionTransfer, DraggedEditorIdentifier, ResourcesDropHandler, DraggedEditorGroupIdentifier, DragAndDropObserver } from 'vs/workbench/browser/dnd';
import { addDisposableListener, EventType, EventHelper, isAncestor, toggleClass, addClass, removeClass } from 'vs/base/browser/dom';
import { IEditorGroupsAccessor, EDITOR_TITLE_HEIGHT, IEditorGroupView, getActiveTextEditorOptions } from 'vs/workbench/browser/parts/editor/editor';
import { EDITOR_DRAG_AND_DROP_BACKGROUND, Themable } from 'vs/workbench/common/theme';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { activeContrastBorder } from 'vs/platform/theme/common/colorRegistry';
import { IEditorIdentifier, EditorInput, EditorOptions } from 'vs/workbench/common/editor';
import { isMacintosh } from 'vs/base/common/platform';
import { GroupDirection, MergeGroupMode } from 'vs/workbench/services/group/common/editorGroupsService';
import { toDisposable } from 'vs/base/common/lifecycle';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { RunOnceScheduler } from 'vs/base/common/async';
interface IDropOperation {
splitDirection?: GroupDirection;
}
class DropOverlay extends Themable {
private static OVERLAY_ID = 'monaco-workbench-editor-drop-overlay';
private container: HTMLElement;
private overlay: HTMLElement;
private currentDropOperation: IDropOperation;
private _disposed: boolean;
private cleanupOverlayScheduler: RunOnceScheduler;
private readonly editorTransfer = LocalSelectionTransfer.getInstance<DraggedEditorIdentifier>();
private readonly groupTransfer = LocalSelectionTransfer.getInstance<DraggedEditorGroupIdentifier>();
constructor(
private accessor: IEditorGroupsAccessor,
private groupView: IEditorGroupView,
themeService: IThemeService,
private instantiationService: IInstantiationService
) {
super(themeService);
this.cleanupOverlayScheduler = this._register(new RunOnceScheduler(() => this.dispose(), 300));
this.create();
}
get disposed(): boolean {
return this._disposed;
}
private create(): void {
const overlayOffsetHeight = this.getOverlayOffsetHeight();
// Container
this.container = document.createElement('div');
this.container.id = DropOverlay.OVERLAY_ID;
this.container.style.top = `${overlayOffsetHeight}px`;
// Parent
this.groupView.element.appendChild(this.container);
addClass(this.groupView.element, 'dragged-over');
this._register(toDisposable(() => {
this.groupView.element.removeChild(this.container);
removeClass(this.groupView.element, 'dragged-over');
}));
// Overlay
this.overlay = document.createElement('div');
addClass(this.overlay, 'editor-group-overlay-indicator');
this.container.appendChild(this.overlay);
// Overlay Event Handling
this.registerListeners();
// Styles
this.updateStyles();
}
protected updateStyles(): void {
// Overlay drop background
this.overlay.style.backgroundColor = this.getColor(EDITOR_DRAG_AND_DROP_BACKGROUND);
// Overlay contrast border (if any)
const activeContrastBorderColor = this.getColor(activeContrastBorder);
this.overlay.style.outlineColor = activeContrastBorderColor;
this.overlay.style.outlineOffset = activeContrastBorderColor ? '-2px' : null;
this.overlay.style.outlineStyle = activeContrastBorderColor ? 'dashed' : null;
this.overlay.style.outlineWidth = activeContrastBorderColor ? '2px' : null;
}
private registerListeners(): void {
this._register(new DragAndDropObserver(this.container, {
onDragEnter: e => void 0,
onDragOver: e => {
const isDraggingGroup = this.groupTransfer.hasData(DraggedEditorGroupIdentifier.prototype);
const isDraggingEditor = this.editorTransfer.hasData(DraggedEditorIdentifier.prototype);
// Update the dropEffect to "copy" if there is no local data to be dragged because
// in that case we can only copy the data into and not move it from its source
if (!isDraggingEditor && !isDraggingGroup) {
e.dataTransfer.dropEffect = 'copy';
}
// Find out if operation is valid
const isCopy = isDraggingGroup ? this.isCopyOperation(e) : isDraggingEditor ? this.isCopyOperation(e, this.editorTransfer.getData(DraggedEditorIdentifier.prototype)[0].identifier) : true;
if (!isCopy) {
const sourceGroupView = this.findSourceGroupView();
if (sourceGroupView === this.groupView) {
if (isDraggingGroup || (isDraggingEditor && sourceGroupView.count < 2)) {
this.hideOverlay();
return; // do not allow to drop group/editor on itself if this results in an empty group
}
}
}
// Position overlay
this.positionOverlay(e.offsetX, e.offsetY, isDraggingGroup);
// Make sure to stop any running cleanup scheduler to remove the overlay
if (this.cleanupOverlayScheduler.isScheduled()) {
this.cleanupOverlayScheduler.cancel();
}
},
onDragLeave: e => this.dispose(),
onDragEnd: e => this.dispose(),
onDrop: e => {
EventHelper.stop(e, true);
// Dispose overlay
this.dispose();
// Handle drop if we have a valid operation
if (this.currentDropOperation) {
this.handleDrop(e, this.currentDropOperation.splitDirection);
}
}
}));
this._register(addDisposableListener(this.container, EventType.MOUSE_OVER, () => {
// Under some circumstances we have seen reports where the drop overlay is not being
// cleaned up and as such the editor area remains under the overlay so that you cannot
// type into the editor anymore. This seems related to using VMs and DND via host and
// guest OS, though some users also saw it without VMs.
// To protect against this issue we always destroy the overlay as soon as we detect a
// mouse event over it. The delay is used to guarantee we are not interfering with the
// actual DROP event that can also trigger a mouse over event.
if (!this.cleanupOverlayScheduler.isScheduled()) {
this.cleanupOverlayScheduler.schedule();
}
}));
}
private findSourceGroupView(): IEditorGroupView {
// Check for group transfer
if (this.groupTransfer.hasData(DraggedEditorGroupIdentifier.prototype)) {
return this.accessor.getGroup(this.groupTransfer.getData(DraggedEditorGroupIdentifier.prototype)[0].identifier);
}
// Check for editor transfer
else if (this.editorTransfer.hasData(DraggedEditorIdentifier.prototype)) {
return this.accessor.getGroup(this.editorTransfer.getData(DraggedEditorIdentifier.prototype)[0].identifier.groupId);
}
return void 0;
}
private handleDrop(event: DragEvent, splitDirection?: GroupDirection): void {
// Determine target group
const ensureTargetGroup = () => {
let targetGroup: IEditorGroupView;
if (typeof splitDirection === 'number') {
targetGroup = this.accessor.addGroup(this.groupView, splitDirection);
} else {
targetGroup = this.groupView;
}
return targetGroup;
};
// Check for group transfer
if (this.groupTransfer.hasData(DraggedEditorGroupIdentifier.prototype)) {
const draggedEditorGroup = this.groupTransfer.getData(DraggedEditorGroupIdentifier.prototype)[0].identifier;
// Return if the drop is a no-op
const sourceGroup = this.accessor.getGroup(draggedEditorGroup);
if (typeof splitDirection !== 'number' && sourceGroup === this.groupView) {
return;
}
// Split to new group
let targetGroup: IEditorGroupView;
if (typeof splitDirection === 'number') {
if (this.isCopyOperation(event)) {
targetGroup = this.accessor.copyGroup(sourceGroup, this.groupView, splitDirection);
} else {
targetGroup = this.accessor.moveGroup(sourceGroup, this.groupView, splitDirection);
}
}
// Merge into existing group
else {
if (this.isCopyOperation(event)) {
targetGroup = this.accessor.mergeGroup(sourceGroup, this.groupView, { mode: MergeGroupMode.COPY_EDITORS });
} else {
targetGroup = this.accessor.mergeGroup(sourceGroup, this.groupView);
}
}
this.accessor.activateGroup(targetGroup);
this.groupTransfer.clearData(DraggedEditorGroupIdentifier.prototype);
}
// Check for editor transfer
else if (this.editorTransfer.hasData(DraggedEditorIdentifier.prototype)) {
const draggedEditor = this.editorTransfer.getData(DraggedEditorIdentifier.prototype)[0].identifier;
const targetGroup = ensureTargetGroup();
// Return if the drop is a no-op
const sourceGroup = this.accessor.getGroup(draggedEditor.groupId);
if (sourceGroup === targetGroup) {
return;
}
// Open in target group
const options = getActiveTextEditorOptions(sourceGroup, draggedEditor.editor, EditorOptions.create({ pinned: true }));
targetGroup.openEditor(draggedEditor.editor, options);
// Ensure target has focus
targetGroup.focus();
// Close in source group unless we copy
const copyEditor = this.isCopyOperation(event, draggedEditor);
if (!copyEditor) {
sourceGroup.closeEditor(draggedEditor.editor);
}
this.editorTransfer.clearData(DraggedEditorIdentifier.prototype);
}
// Check for URI transfer
else {
const dropHandler = this.instantiationService.createInstance(ResourcesDropHandler, { allowWorkspaceOpen: true /* open workspace instead of file if dropped */ });
dropHandler.handleDrop(event, () => ensureTargetGroup(), targetGroup => targetGroup.focus());
}
}
private isCopyOperation(e: DragEvent, draggedEditor?: IEditorIdentifier): boolean {
if (draggedEditor && !(draggedEditor.editor as EditorInput).supportsSplitEditor()) {
return false;
}
return (e.ctrlKey && !isMacintosh) || (e.altKey && isMacintosh);
}
private positionOverlay(mousePosX: number, mousePosY: number, isDraggingGroup: boolean): void {
const preferSplitVertically = this.accessor.partOptions.openSideBySideDirection === 'right';
const editorControlWidth = this.groupView.element.clientWidth;
const editorControlHeight = this.groupView.element.clientHeight - this.getOverlayOffsetHeight();
let edgeWidthThresholdFactor: number;
if (isDraggingGroup) {
edgeWidthThresholdFactor = preferSplitVertically ? 0.3 : 0.1; // give larger threshold when dragging group depending on preferred split direction
} else {
edgeWidthThresholdFactor = 0.1; // 10% threshold to split if dragging editors
}
let edgeHeightThresholdFactor: number;
if (isDraggingGroup) {
edgeHeightThresholdFactor = preferSplitVertically ? 0.1 : 0.3; // give larger threshold when dragging group depending on preferred split direction
} else {
edgeHeightThresholdFactor = 0.1; // 10% threshold to split if dragging editors
}
const edgeWidthThreshold = editorControlWidth * edgeWidthThresholdFactor;
const edgeHeightThreshold = editorControlHeight * edgeHeightThresholdFactor;
const splitWidthThreshold = editorControlWidth / 3; // offer to split left/right at 33%
const splitHeightThreshold = editorControlHeight / 3; // offer to split up/down at 33%
// Enable to debug the drop threshold square
// let child = this.overlay.children.item(0) as HTMLElement || this.overlay.appendChild(document.createElement('div'));
// child.style.backgroundColor = 'red';
// child.style.position = 'absolute';
// child.style.width = (groupViewWidth - (2 * edgeWidthThreshold)) + 'px';
// child.style.height = (groupViewHeight - (2 * edgeHeightThreshold)) + 'px';
// child.style.left = edgeWidthThreshold + 'px';
// child.style.top = edgeHeightThreshold + 'px';
// No split if mouse is above certain threshold in the center of the view
let splitDirection: GroupDirection;
if (
mousePosX > edgeWidthThreshold && mousePosX < editorControlWidth - edgeWidthThreshold &&
mousePosY > edgeHeightThreshold && mousePosY < editorControlHeight - edgeHeightThreshold
) {
splitDirection = void 0;
}
// Offer to split otherwise
else {
// User prefers to split vertically: offer a larger hitzone
// for this direction like so:
// ----------------------------------------------
// | | SPLIT UP | |
// | SPLIT |-----------------------| SPLIT |
// | | MERGE | |
// | LEFT |-----------------------| RIGHT |
// | | SPLIT DOWN | |
// ----------------------------------------------
if (preferSplitVertically) {
if (mousePosX < splitWidthThreshold) {
splitDirection = GroupDirection.LEFT;
} else if (mousePosX > splitWidthThreshold * 2) {
splitDirection = GroupDirection.RIGHT;
} else if (mousePosY < editorControlHeight / 2) {
splitDirection = GroupDirection.UP;
} else {
splitDirection = GroupDirection.DOWN;
}
}
// User prefers to split horizontally: offer a larger hitzone
// for this direction like so:
// ----------------------------------------------
// | SPLIT UP |
// |--------------------------------------------|
// | SPLIT LEFT | MERGE | SPLIT RIGHT |
// |--------------------------------------------|
// | SPLIT DOWN |
// ----------------------------------------------
else {
if (mousePosY < splitHeightThreshold) {
splitDirection = GroupDirection.UP;
} else if (mousePosY > splitHeightThreshold * 2) {
splitDirection = GroupDirection.DOWN;
} else if (mousePosX < editorControlWidth / 2) {
splitDirection = GroupDirection.LEFT;
} else {
splitDirection = GroupDirection.RIGHT;
}
}
}
// Draw overlay based on split direction
switch (splitDirection) {
case GroupDirection.UP:
this.doPositionOverlay({ top: '0', left: '0', width: '100%', height: '50%' });
break;
case GroupDirection.DOWN:
this.doPositionOverlay({ top: '50%', left: '0', width: '100%', height: '50%' });
break;
case GroupDirection.LEFT:
this.doPositionOverlay({ top: '0', left: '0', width: '50%', height: '100%' });
break;
case GroupDirection.RIGHT:
this.doPositionOverlay({ top: '0', left: '50%', width: '50%', height: '100%' });
break;
default:
this.doPositionOverlay({ top: '0', left: '0', width: '100%', height: '100%' });
}
// Make sure the overlay is visible now
this.overlay.style.opacity = '1';
// Enable transition after a timeout to prevent initial animation
setTimeout(() => addClass(this.overlay, 'overlay-move-transition'), 0);
// Remember as current split direction
this.currentDropOperation = { splitDirection };
}
private doPositionOverlay(options: { top: string, left: string, width: string, height: string }): void {
// Container
const offsetHeight = this.getOverlayOffsetHeight();
if (offsetHeight) {
this.container.style.height = `calc(100% - ${offsetHeight}px)`;
} else {
this.container.style.height = '100%';
}
// Overlay
this.overlay.style.top = options.top;
this.overlay.style.left = options.left;
this.overlay.style.width = options.width;
this.overlay.style.height = options.height;
}
private getOverlayOffsetHeight(): number {
if (!this.groupView.isEmpty() && this.accessor.partOptions.showTabs) {
return EDITOR_TITLE_HEIGHT; // show overlay below title if group shows tabs
}
return 0;
}
private hideOverlay(): void {
// Reset overlay
this.doPositionOverlay({ top: '0', left: '0', width: '100%', height: '100%' });
this.overlay.style.opacity = '0';
removeClass(this.overlay, 'overlay-move-transition');
// Reset current operation
this.currentDropOperation = void 0;
}
contains(element: HTMLElement): boolean {
return element === this.container || element === this.overlay;
}
dispose(): void {
super.dispose();
this._disposed = true;
}
}
export class EditorDropTarget extends Themable {
private _overlay: DropOverlay;
private counter = 0;
private readonly editorTransfer = LocalSelectionTransfer.getInstance<DraggedEditorIdentifier>();
private readonly groupTransfer = LocalSelectionTransfer.getInstance<DraggedEditorGroupIdentifier>();
constructor(
private accessor: IEditorGroupsAccessor,
private container: HTMLElement,
@IThemeService themeService: IThemeService,
@IInstantiationService private instantiationService: IInstantiationService
) {
super(themeService);
this.registerListeners();
}
private get overlay(): DropOverlay {
if (this._overlay && !this._overlay.disposed) {
return this._overlay;
}
return void 0;
}
private registerListeners(): void {
this._register(addDisposableListener(this.container, EventType.DRAG_ENTER, e => this.onDragEnter(e)));
this._register(addDisposableListener(this.container, EventType.DRAG_LEAVE, () => this.onDragLeave()));
[this.container, window].forEach(node => this._register(addDisposableListener(node as HTMLElement, EventType.DRAG_END, () => this.onDragEnd())));
}
private onDragEnter(event: DragEvent): void {
this.counter++;
// Validate transfer
if (
!this.editorTransfer.hasData(DraggedEditorIdentifier.prototype) &&
!this.groupTransfer.hasData(DraggedEditorGroupIdentifier.prototype) &&
!event.dataTransfer.types.length // see https://github.com/Microsoft/vscode/issues/25789
) {
event.dataTransfer.dropEffect = 'none';
return; // unsupported transfer
}
// Signal DND start
this.updateContainer(true);
const target = event.target as HTMLElement;
if (target) {
// Somehow we managed to move the mouse quickly out of the current overlay, so destroy it
if (this.overlay && !this.overlay.contains(target)) {
this.disposeOverlay();
}
// Create overlay over target
if (!this.overlay) {
const targetGroupView = this.findTargetGroupView(target);
if (targetGroupView) {
this._overlay = new DropOverlay(this.accessor, targetGroupView, this.themeService, this.instantiationService);
}
}
}
}
private onDragLeave(): void {
this.counter--;
if (this.counter === 0) {
this.updateContainer(false);
}
}
private onDragEnd(): void {
this.counter = 0;
this.updateContainer(false);
this.disposeOverlay();
}
private findTargetGroupView(child: HTMLElement): IEditorGroupView {
const groups = this.accessor.groups;
for (let i = 0; i < groups.length; i++) {
const groupView = groups[i];
if (isAncestor(child, groupView.element)) {
return groupView;
}
}
return void 0;
}
private updateContainer(isDraggedOver: boolean): void {
toggleClass(this.container, 'dragged-over', isDraggedOver);
}
dispose(): void {
super.dispose();
this.disposeOverlay();
}
private disposeOverlay(): void {
if (this.overlay) {
this.overlay.dispose();
this._overlay = void 0;
}
}
}
| src/vs/workbench/browser/parts/editor/editorDropTarget.ts | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.0008202540338970721,
0.00018488946079742163,
0.00016308047634083778,
0.000170371204148978,
0.00008712606359040365
]
|
{
"id": 4,
"code_window": [
"import { editorBackground, errorForeground, focusBorder, foreground, inputValidationErrorBackground, inputValidationErrorForeground, inputValidationErrorBorder } from 'vs/platform/theme/common/colorRegistry';\n",
"import { attachButtonStyler, attachInputBoxStyler, attachSelectBoxStyler, attachStyler } from 'vs/platform/theme/common/styler';\n",
"import { ICssStyleCollector, ITheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';\n",
"import { ITOCEntry } from 'vs/workbench/parts/preferences/browser/settingsLayout';\n",
"import { ISettingsEditorViewState, isExcludeSetting, SettingsTreeElement, SettingsTreeGroupElement, SettingsTreeNewExtensionsElement, settingKeyToDisplayFormat, SettingsTreeSettingElement } from 'vs/workbench/parts/preferences/browser/settingsTreeModels';\n",
"import { ExcludeSettingWidget, IExcludeDataItem, settingsHeaderForeground, settingsNumberInputBackground, settingsNumberInputBorder, settingsNumberInputForeground, settingsSelectBackground, settingsSelectBorder, settingsSelectListBorder, settingsSelectForeground, settingsTextInputBackground, settingsTextInputBorder, settingsTextInputForeground } from 'vs/workbench/parts/preferences/browser/settingsWidgets';\n",
"import { ISetting, ISettingsGroup } from 'vs/workbench/services/preferences/common/preferences';\n",
"\n",
"const $ = DOM.$;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { ISettingsEditorViewState, isExcludeSetting, settingKeyToDisplayFormat, SettingsTreeElement, SettingsTreeGroupElement, SettingsTreeNewExtensionsElement, SettingsTreeSettingElement } from 'vs/workbench/parts/preferences/browser/settingsTreeModels';\n",
"import { ExcludeSettingWidget, IExcludeDataItem, settingsHeaderForeground, settingsNumberInputBackground, settingsNumberInputBorder, settingsNumberInputForeground, settingsSelectBackground, settingsSelectBorder, settingsSelectForeground, settingsSelectListBorder, settingsTextInputBackground, settingsTextInputBorder, settingsTextInputForeground } from 'vs/workbench/parts/preferences/browser/settingsWidgets';\n",
"import { SETTINGS_EDITOR_COMMAND_SHOW_CONTEXT_MENU } from 'vs/workbench/parts/preferences/common/preferences';\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "replace",
"edit_start_line_idx": 41
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { URI } from 'vs/base/common/uri';
import { isFalsyOrEmpty } from 'vs/base/common/arrays';
import { MainThreadDiaglogsShape, MainContext, IExtHostContext, MainThreadDialogOpenOptions, MainThreadDialogSaveOptions } from '../node/extHost.protocol';
import { extHostNamedCustomer } from 'vs/workbench/api/electron-browser/extHostCustomers';
import { IWindowService } from 'vs/platform/windows/common/windows';
import { forEach } from 'vs/base/common/collections';
@extHostNamedCustomer(MainContext.MainThreadDialogs)
export class MainThreadDialogs implements MainThreadDiaglogsShape {
constructor(
context: IExtHostContext,
@IWindowService private readonly _windowService: IWindowService
) {
//
}
dispose(): void {
//
}
$showOpenDialog(options: MainThreadDialogOpenOptions): Promise<string[]> {
// TODO@joh what about remote dev setup?
if (options.defaultUri && options.defaultUri.scheme !== 'file') {
return Promise.reject(new Error('Not supported - Open-dialogs can only be opened on `file`-uris.'));
}
return new Promise<string[]>(resolve => {
this._windowService.showOpenDialog(
MainThreadDialogs._convertOpenOptions(options)
).then(filenames => resolve(isFalsyOrEmpty(filenames) ? undefined : filenames));
});
}
$showSaveDialog(options: MainThreadDialogSaveOptions): Promise<string> {
// TODO@joh what about remote dev setup?
if (options.defaultUri && options.defaultUri.scheme !== 'file') {
return Promise.reject(new Error('Not supported - Save-dialogs can only be opened on `file`-uris.'));
}
return new Promise<string>(resolve => {
this._windowService.showSaveDialog(
MainThreadDialogs._convertSaveOptions(options)
).then(filename => resolve(!filename ? undefined : filename));
});
}
private static _convertOpenOptions(options: MainThreadDialogOpenOptions): Electron.OpenDialogOptions {
const result: Electron.OpenDialogOptions = {
properties: ['createDirectory']
};
if (options.openLabel) {
result.buttonLabel = options.openLabel;
}
if (options.defaultUri) {
result.defaultPath = URI.revive(options.defaultUri).fsPath;
}
if (!options.canSelectFiles && !options.canSelectFolders) {
options.canSelectFiles = true;
}
if (options.canSelectFiles) {
result.properties.push('openFile');
}
if (options.canSelectFolders) {
result.properties.push('openDirectory');
}
if (options.canSelectMany) {
result.properties.push('multiSelections');
}
if (options.filters) {
result.filters = [];
forEach(options.filters, entry => result.filters.push({ name: entry.key, extensions: entry.value }));
}
return result;
}
private static _convertSaveOptions(options: MainThreadDialogSaveOptions): Electron.SaveDialogOptions {
const result: Electron.SaveDialogOptions = {
};
if (options.defaultUri) {
result.defaultPath = URI.revive(options.defaultUri).fsPath;
}
if (options.saveLabel) {
result.buttonLabel = options.saveLabel;
}
if (options.filters) {
result.filters = [];
forEach(options.filters, entry => result.filters.push({ name: entry.key, extensions: entry.value }));
}
return result;
}
}
| src/vs/workbench/api/electron-browser/mainThreadDialogs.ts | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.00017240380111616105,
0.00016895198496058583,
0.00016341467562597245,
0.0001694832171779126,
0.000002520594534871634
]
|
{
"id": 4,
"code_window": [
"import { editorBackground, errorForeground, focusBorder, foreground, inputValidationErrorBackground, inputValidationErrorForeground, inputValidationErrorBorder } from 'vs/platform/theme/common/colorRegistry';\n",
"import { attachButtonStyler, attachInputBoxStyler, attachSelectBoxStyler, attachStyler } from 'vs/platform/theme/common/styler';\n",
"import { ICssStyleCollector, ITheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';\n",
"import { ITOCEntry } from 'vs/workbench/parts/preferences/browser/settingsLayout';\n",
"import { ISettingsEditorViewState, isExcludeSetting, SettingsTreeElement, SettingsTreeGroupElement, SettingsTreeNewExtensionsElement, settingKeyToDisplayFormat, SettingsTreeSettingElement } from 'vs/workbench/parts/preferences/browser/settingsTreeModels';\n",
"import { ExcludeSettingWidget, IExcludeDataItem, settingsHeaderForeground, settingsNumberInputBackground, settingsNumberInputBorder, settingsNumberInputForeground, settingsSelectBackground, settingsSelectBorder, settingsSelectListBorder, settingsSelectForeground, settingsTextInputBackground, settingsTextInputBorder, settingsTextInputForeground } from 'vs/workbench/parts/preferences/browser/settingsWidgets';\n",
"import { ISetting, ISettingsGroup } from 'vs/workbench/services/preferences/common/preferences';\n",
"\n",
"const $ = DOM.$;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { ISettingsEditorViewState, isExcludeSetting, settingKeyToDisplayFormat, SettingsTreeElement, SettingsTreeGroupElement, SettingsTreeNewExtensionsElement, SettingsTreeSettingElement } from 'vs/workbench/parts/preferences/browser/settingsTreeModels';\n",
"import { ExcludeSettingWidget, IExcludeDataItem, settingsHeaderForeground, settingsNumberInputBackground, settingsNumberInputBorder, settingsNumberInputForeground, settingsSelectBackground, settingsSelectBorder, settingsSelectForeground, settingsSelectListBorder, settingsTextInputBackground, settingsTextInputBorder, settingsTextInputForeground } from 'vs/workbench/parts/preferences/browser/settingsWidgets';\n",
"import { SETTINGS_EDITOR_COMMAND_SHOW_CONTEXT_MENU } from 'vs/workbench/parts/preferences/common/preferences';\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "replace",
"edit_start_line_idx": 41
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.update-activity {
-webkit-mask: url('update.svg') no-repeat 50% 50%;
-webkit-mask-size: 22px;
}
| src/vs/workbench/parts/update/electron-browser/media/update.contribution.css | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.00017387623665854335,
0.00017387623665854335,
0.00017387623665854335,
0.00017387623665854335,
0
]
|
{
"id": 5,
"code_window": [
"\t\t@IOpenerService private readonly openerService: IOpenerService,\n",
"\t\t@IInstantiationService private readonly instantiationService: IInstantiationService,\n",
"\t\t@ICommandService private readonly commandService: ICommandService,\n",
"\t\t@IContextMenuService private contextMenuService: IContextMenuService\n",
"\t) {\n",
"\t\tthis.descriptionMeasureContainer = $('.setting-item-description');\n",
"\t\tDOM.append(_measureContainer,\n",
"\t\t\t$('.setting-measure-container.monaco-tree-row', undefined,\n",
"\t\t\t\t$('.setting-item', undefined,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t@IContextMenuService private contextMenuService: IContextMenuService,\n",
"\t\t@IKeybindingService private keybindingService: IKeybindingService,\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "replace",
"edit_start_line_idx": 372
} | /*---------------------------------------------------------------------------------------------
* 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 { renderMarkdown } from 'vs/base/browser/htmlContentRenderer';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { alert as ariaAlert } from 'vs/base/browser/ui/aria/aria';
import { Button } from 'vs/base/browser/ui/button/button';
import { Checkbox } from 'vs/base/browser/ui/checkbox/checkbox';
import { InputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { SelectBox } from 'vs/base/browser/ui/selectBox/selectBox';
import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar';
import { Action, IAction } from 'vs/base/common/actions';
import * as arrays from 'vs/base/common/arrays';
import { Color, RGBA } from 'vs/base/common/color';
import { onUnexpectedError } from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
import { KeyCode } from 'vs/base/common/keyCodes';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { escapeRegExpCharacters, startsWith } from 'vs/base/common/strings';
import { URI } from 'vs/base/common/uri';
import { TPromise } from 'vs/base/common/winjs.base';
import { IAccessibilityProvider, IDataSource, IFilter, IRenderer as ITreeRenderer, ITree, ITreeConfiguration } from 'vs/base/parts/tree/browser/tree';
import { DefaultTreestyler } from 'vs/base/parts/tree/browser/treeDefaults';
import { Tree } from 'vs/base/parts/tree/browser/treeImpl';
import { localize } from 'vs/nls';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { WorkbenchTreeController } from 'vs/platform/list/browser/listService';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { editorBackground, errorForeground, focusBorder, foreground, inputValidationErrorBackground, inputValidationErrorForeground, inputValidationErrorBorder } from 'vs/platform/theme/common/colorRegistry';
import { attachButtonStyler, attachInputBoxStyler, attachSelectBoxStyler, attachStyler } from 'vs/platform/theme/common/styler';
import { ICssStyleCollector, ITheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { ITOCEntry } from 'vs/workbench/parts/preferences/browser/settingsLayout';
import { ISettingsEditorViewState, isExcludeSetting, SettingsTreeElement, SettingsTreeGroupElement, SettingsTreeNewExtensionsElement, settingKeyToDisplayFormat, SettingsTreeSettingElement } from 'vs/workbench/parts/preferences/browser/settingsTreeModels';
import { ExcludeSettingWidget, IExcludeDataItem, settingsHeaderForeground, settingsNumberInputBackground, settingsNumberInputBorder, settingsNumberInputForeground, settingsSelectBackground, settingsSelectBorder, settingsSelectListBorder, settingsSelectForeground, settingsTextInputBackground, settingsTextInputBorder, settingsTextInputForeground } from 'vs/workbench/parts/preferences/browser/settingsWidgets';
import { ISetting, ISettingsGroup } from 'vs/workbench/services/preferences/common/preferences';
const $ = DOM.$;
function getExcludeDisplayValue(element: SettingsTreeSettingElement): IExcludeDataItem[] {
const data = element.isConfigured ?
{ ...element.defaultValue, ...element.scopeValue } :
element.defaultValue;
return Object.keys(data)
.filter(key => !!data[key])
.map(key => {
const value = data[key];
const sibling = typeof value === 'boolean' ? undefined : value.when;
return {
id: key,
pattern: key,
sibling
};
});
}
export function resolveSettingsTree(tocData: ITOCEntry, coreSettingsGroups: ISettingsGroup[]): { tree: ITOCEntry, leftoverSettings: Set<ISetting> } {
const allSettings = getFlatSettings(coreSettingsGroups);
return {
tree: _resolveSettingsTree(tocData, allSettings),
leftoverSettings: allSettings
};
}
export function resolveExtensionsSettings(groups: ISettingsGroup[]): ITOCEntry {
const settingsGroupToEntry = (group: ISettingsGroup) => {
const flatSettings = arrays.flatten(
group.sections.map(section => section.settings));
return {
id: group.id,
label: group.title,
settings: flatSettings
};
};
const extGroups = groups
.sort((a, b) => a.title.localeCompare(b.title))
.map(g => settingsGroupToEntry(g));
return {
id: 'extensions',
label: localize('extensions', "Extensions"),
children: extGroups
};
}
function _resolveSettingsTree(tocData: ITOCEntry, allSettings: Set<ISetting>): ITOCEntry {
let children: ITOCEntry[];
if (tocData.children) {
children = tocData.children
.map(child => _resolveSettingsTree(child, allSettings))
.filter(child => (child.children && child.children.length) || (child.settings && child.settings.length));
}
let settings: ISetting[];
if (tocData.settings) {
settings = arrays.flatten(tocData.settings.map(pattern => getMatchingSettings(allSettings, <string>pattern)));
}
if (!children && !settings) {
return null;
}
return {
id: tocData.id,
label: tocData.label,
children,
settings
};
}
function getMatchingSettings(allSettings: Set<ISetting>, pattern: string): ISetting[] {
const result: ISetting[] = [];
allSettings.forEach(s => {
if (settingMatches(s, pattern)) {
result.push(s);
allSettings.delete(s);
}
});
return result.sort((a, b) => a.key.localeCompare(b.key));
}
const settingPatternCache = new Map<string, RegExp>();
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 (let group of settingsGroups) {
for (let section of group.sections) {
for (let s of section.settings) {
if (!s.overrides || !s.overrides.length) {
result.add(s);
}
}
}
}
return result;
}
export class SettingsDataSource implements IDataSource {
getId(tree: ITree, element: SettingsTreeElement): string {
return element.id;
}
hasChildren(tree: ITree, element: SettingsTreeElement): boolean {
if (element instanceof SettingsTreeGroupElement) {
return true;
}
return false;
}
getChildren(tree: ITree, element: SettingsTreeElement): TPromise<any> {
return TPromise.as(this._getChildren(element));
}
private _getChildren(element: SettingsTreeElement): SettingsTreeElement[] {
if (element instanceof SettingsTreeGroupElement) {
return element.children;
} else {
// No children...
return null;
}
}
getParent(tree: ITree, element: SettingsTreeElement): TPromise<any> {
return TPromise.wrap(element && element.parent);
}
shouldAutoexpand(): boolean {
return true;
}
}
export class SimplePagedDataSource implements IDataSource {
private static readonly SETTINGS_PER_PAGE = 30;
private static readonly BUFFER = 5;
private loadedToIndex: number;
constructor(private realDataSource: IDataSource) {
this.reset();
}
reset(): void {
this.loadedToIndex = SimplePagedDataSource.SETTINGS_PER_PAGE * 2;
}
pageTo(index: number, top = false): boolean {
const buffer = top ? SimplePagedDataSource.SETTINGS_PER_PAGE : SimplePagedDataSource.BUFFER;
if (index > this.loadedToIndex - buffer) {
this.loadedToIndex = (Math.ceil(index / SimplePagedDataSource.SETTINGS_PER_PAGE) + 1) * SimplePagedDataSource.SETTINGS_PER_PAGE;
return true;
} else {
return false;
}
}
getId(tree: ITree, element: any): string {
return this.realDataSource.getId(tree, element);
}
hasChildren(tree: ITree, element: any): boolean {
return this.realDataSource.hasChildren(tree, element);
}
getChildren(tree: ITree, element: SettingsTreeGroupElement): TPromise<any> {
return this.realDataSource.getChildren(tree, element).then(realChildren => {
return this._getChildren(realChildren);
});
}
_getChildren(realChildren: SettingsTreeElement[]): any[] {
const lastChild = realChildren[realChildren.length - 1];
if (lastChild && lastChild.index > this.loadedToIndex) {
return realChildren.filter(child => {
return child.index < this.loadedToIndex;
});
} else {
return realChildren;
}
}
getParent(tree: ITree, element: any): TPromise<any> {
return this.realDataSource.getParent(tree, element);
}
shouldAutoexpand(tree: ITree, element: any): boolean {
return this.realDataSource.shouldAutoexpand(tree, element);
}
}
interface IDisposableTemplate {
toDispose: IDisposable[];
}
interface ISettingItemTemplate<T = any> extends IDisposableTemplate {
onChange?: (value: T) => void;
context?: SettingsTreeSettingElement;
containerElement: HTMLElement;
categoryElement: HTMLElement;
labelElement: HTMLElement;
descriptionElement: HTMLElement;
controlElement: HTMLElement;
deprecationWarningElement: HTMLElement;
otherOverridesElement: HTMLElement;
toolbar: ToolBar;
}
interface ISettingBoolItemTemplate extends ISettingItemTemplate<boolean> {
checkbox: Checkbox;
}
interface ISettingTextItemTemplate extends ISettingItemTemplate<string> {
inputBox: InputBox;
validationErrorMessageElement: HTMLElement;
}
type ISettingNumberItemTemplate = ISettingTextItemTemplate;
interface ISettingEnumItemTemplate extends ISettingItemTemplate<number> {
selectBox: SelectBox;
enumDescriptionElement: HTMLElement;
}
interface ISettingComplexItemTemplate extends ISettingItemTemplate<void> {
button: Button;
}
interface ISettingExcludeItemTemplate extends ISettingItemTemplate<void> {
excludeWidget: ExcludeSettingWidget;
}
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_NUMBER_TEMPLATE_ID = 'settings.number.template';
const SETTINGS_ENUM_TEMPLATE_ID = 'settings.enum.template';
const SETTINGS_BOOL_TEMPLATE_ID = 'settings.bool.template';
const SETTINGS_EXCLUDE_TEMPLATE_ID = 'settings.exclude.template';
const SETTINGS_COMPLEX_TEMPLATE_ID = 'settings.complex.template';
const SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID = 'settings.newExtensions.template';
const SETTINGS_GROUP_ELEMENT_TEMPLATE_ID = 'settings.group.template';
export interface ISettingChangeEvent {
key: string;
value: any; // undefined => reset/unconfigure
}
export interface ISettingLinkClickEvent {
source: SettingsTreeSettingElement;
targetKey: string;
}
export class SettingsRenderer implements ITreeRenderer {
public static readonly CONTROL_CLASS = 'setting-control-focus-target';
public static readonly CONTROL_SELECTOR = '.' + SettingsRenderer.CONTROL_CLASS;
public static readonly SETTING_KEY_ATTR = 'data-key';
private readonly _onDidChangeSetting: Emitter<ISettingChangeEvent> = new Emitter<ISettingChangeEvent>();
public readonly onDidChangeSetting: Event<ISettingChangeEvent> = this._onDidChangeSetting.event;
private readonly _onDidOpenSettings: Emitter<string> = new Emitter<string>();
public readonly onDidOpenSettings: Event<string> = this._onDidOpenSettings.event;
private readonly _onDidClickSettingLink: Emitter<ISettingLinkClickEvent> = new Emitter<ISettingLinkClickEvent>();
public readonly onDidClickSettingLink: Event<ISettingLinkClickEvent> = this._onDidClickSettingLink.event;
private readonly _onDidFocusSetting: Emitter<SettingsTreeSettingElement> = new Emitter<SettingsTreeSettingElement>();
public readonly onDidFocusSetting: Event<SettingsTreeSettingElement> = this._onDidFocusSetting.event;
private descriptionMeasureContainer: HTMLElement;
private longestSingleLineDescription = 0;
private rowHeightCache = new Map<string, number>();
private lastRenderedWidth: number;
private settingActions: IAction[];
constructor(
_measureContainer: HTMLElement,
@IThemeService private themeService: IThemeService,
@IContextViewService private contextViewService: IContextViewService,
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@ICommandService private readonly commandService: ICommandService,
@IContextMenuService private contextMenuService: IContextMenuService
) {
this.descriptionMeasureContainer = $('.setting-item-description');
DOM.append(_measureContainer,
$('.setting-measure-container.monaco-tree-row', undefined,
$('.setting-item', undefined,
this.descriptionMeasureContainer)));
this.settingActions = [
new Action('settings.resetSetting', localize('resetSettingLabel', "Reset Setting"), undefined, undefined, (context: SettingsTreeSettingElement) => {
if (context) {
this._onDidChangeSetting.fire({ key: context.setting.key, value: undefined });
}
return TPromise.wrap(null);
}),
new Separator(),
this.instantiationService.createInstance(CopySettingIdAction),
this.instantiationService.createInstance(CopySettingAsJSONAction),
];
}
showContextMenu(element: SettingsTreeSettingElement, settingDOMElement: HTMLElement): void {
const toolbarElement: HTMLElement = settingDOMElement.querySelector('.toolbar-toggle-more');
if (toolbarElement) {
this.contextMenuService.showContextMenu({
getActions: () => TPromise.wrap(this.settingActions),
getAnchor: () => toolbarElement,
getActionsContext: () => element
});
}
}
updateWidth(width: number): void {
if (this.lastRenderedWidth !== width) {
this.rowHeightCache = new Map<string, number>();
}
this.longestSingleLineDescription = 0;
this.lastRenderedWidth = width;
}
getHeight(tree: ITree, element: SettingsTreeElement): number {
if (this.rowHeightCache.has(element.id) && !(element instanceof SettingsTreeSettingElement && isExcludeSetting(element.setting))) {
return this.rowHeightCache.get(element.id);
}
const h = this._getHeight(tree, element);
this.rowHeightCache.set(element.id, h);
return h;
}
_getHeight(tree: ITree, element: SettingsTreeElement): number {
if (element instanceof SettingsTreeGroupElement) {
if (element.isFirstGroup) {
return 31;
}
return 40 + (7 * element.level);
}
if (element instanceof SettingsTreeSettingElement) {
if (isExcludeSetting(element.setting)) {
return this._getExcludeSettingHeight(element);
} else {
return this.measureSettingElementHeight(tree, element);
}
}
if (element instanceof SettingsTreeNewExtensionsElement) {
return 40;
}
return 0;
}
_getExcludeSettingHeight(element: SettingsTreeSettingElement): number {
const displayValue = getExcludeDisplayValue(element);
return (displayValue.length + 1) * 22 + 66 + this.measureSettingDescription(element);
}
private measureSettingElementHeight(tree: ITree, element: SettingsTreeSettingElement): number {
let heightExcludingDescription = 86;
if (element.valueType === 'boolean') {
heightExcludingDescription = 60;
}
return heightExcludingDescription + this.measureSettingDescription(element);
}
private measureSettingDescription(element: SettingsTreeSettingElement): number {
if (element.description.length < this.longestSingleLineDescription * .8) {
// Most setting descriptions are one short line, so try to avoid measuring them.
// If the description is less than 80% of the longest single line description, assume this will also render to be one line.
return 18;
}
const boolMeasureClass = 'measure-bool-description';
if (element.valueType === 'boolean') {
this.descriptionMeasureContainer.classList.add(boolMeasureClass);
} else if (this.descriptionMeasureContainer.classList.contains(boolMeasureClass)) {
this.descriptionMeasureContainer.classList.remove(boolMeasureClass);
}
const shouldRenderMarkdown = element.setting.descriptionIsMarkdown && element.description.indexOf('\n- ') >= 0;
while (this.descriptionMeasureContainer.firstChild) {
this.descriptionMeasureContainer.removeChild(this.descriptionMeasureContainer.firstChild);
}
if (shouldRenderMarkdown) {
const text = fixSettingLinks(element.description);
const rendered = renderMarkdown({ value: text });
rendered.classList.add('setting-item-description-markdown');
this.descriptionMeasureContainer.appendChild(rendered);
return this.descriptionMeasureContainer.offsetHeight;
} else {
// Remove markdown links, setting links, backticks
const measureText = element.setting.descriptionIsMarkdown ?
fixSettingLinks(element.description)
.replace(/\[(.*)\]\(.*\)/g, '$1')
.replace(/`([^`]*)`/g, '$1') :
element.description;
this.descriptionMeasureContainer.innerText = measureText;
const h = this.descriptionMeasureContainer.offsetHeight;
if (h < 20 && measureText.length > this.longestSingleLineDescription) {
this.longestSingleLineDescription = measureText.length;
}
return h;
}
}
getTemplateId(tree: ITree, element: SettingsTreeElement): string {
if (element instanceof SettingsTreeGroupElement) {
return SETTINGS_GROUP_ELEMENT_TEMPLATE_ID;
}
if (element instanceof SettingsTreeSettingElement) {
if (element.valueType === 'boolean') {
return SETTINGS_BOOL_TEMPLATE_ID;
}
if (element.valueType === 'integer' || element.valueType === 'number' || element.valueType === 'nullable-integer' || element.valueType === 'nullable-number') {
return SETTINGS_NUMBER_TEMPLATE_ID;
}
if (element.valueType === 'string') {
return SETTINGS_TEXT_TEMPLATE_ID;
}
if (element.valueType === 'enum') {
return SETTINGS_ENUM_TEMPLATE_ID;
}
if (element.valueType === 'exclude') {
return SETTINGS_EXCLUDE_TEMPLATE_ID;
}
return SETTINGS_COMPLEX_TEMPLATE_ID;
}
if (element instanceof SettingsTreeNewExtensionsElement) {
return SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID;
}
return '';
}
renderTemplate(tree: ITree, templateId: string, container: HTMLElement) {
if (templateId === SETTINGS_GROUP_ELEMENT_TEMPLATE_ID) {
return this.renderGroupTitleTemplate(container);
}
if (templateId === SETTINGS_TEXT_TEMPLATE_ID) {
return this.renderSettingTextTemplate(tree, container);
}
if (templateId === SETTINGS_NUMBER_TEMPLATE_ID) {
return this.renderSettingNumberTemplate(tree, container);
}
if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
return this.renderSettingBoolTemplate(tree, container);
}
if (templateId === SETTINGS_ENUM_TEMPLATE_ID) {
return this.renderSettingEnumTemplate(tree, container);
}
if (templateId === SETTINGS_EXCLUDE_TEMPLATE_ID) {
return this.renderSettingExcludeTemplate(tree, container);
}
if (templateId === SETTINGS_COMPLEX_TEMPLATE_ID) {
return this.renderSettingComplexTemplate(tree, container);
}
if (templateId === SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID) {
return this.renderNewExtensionsTemplate(container);
}
return null;
}
private renderGroupTitleTemplate(container: HTMLElement): IGroupTitleTemplate {
DOM.addClass(container, 'group-title');
const toDispose = [];
const template: IGroupTitleTemplate = {
parent: container,
toDispose
};
return template;
}
private renderCommonTemplate(tree: ITree, container: HTMLElement, typeClass: string): ISettingItemTemplate {
DOM.addClass(container, 'setting-item');
DOM.addClass(container, 'setting-item-' + typeClass);
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 labelElement = DOM.append(labelCategoryContainer, $('span.setting-item-label'));
const otherOverridesElement = DOM.append(titleElement, $('span.setting-item-overrides'));
const descriptionElement = DOM.append(container, $('.setting-item-description'));
const modifiedIndicatorElement = DOM.append(container, $('.setting-item-modified-indicator'));
modifiedIndicatorElement.title = localize('modified', "Modified");
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 toDispose = [];
const toolbar = this.renderSettingToolbar(container);
const template: ISettingItemTemplate = {
toDispose,
containerElement: container,
categoryElement,
labelElement,
descriptionElement,
controlElement,
deprecationWarningElement,
otherOverridesElement,
toolbar
};
// Prevent clicks from being handled by list
toDispose.push(DOM.addDisposableListener(controlElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addStandardDisposableListener(valueElement, 'keydown', (e: StandardKeyboardEvent) => {
if (e.keyCode === KeyCode.Escape) {
tree.domFocus();
e.browserEvent.stopPropagation();
}
}));
return template;
}
private addSettingElementFocusHandler(template: ISettingItemTemplate): void {
const focusTracker = DOM.trackFocus(template.containerElement);
template.toDispose.push(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);
}
});
}
private renderSettingTextTemplate(tree: ITree, container: HTMLElement, type = 'text'): ISettingTextItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'text');
const validationErrorMessageElement = DOM.append(container, $('.setting-item-validation-message'));
const inputBox = new InputBox(common.controlElement, this.contextViewService);
common.toDispose.push(inputBox);
common.toDispose.push(attachInputBoxStyler(inputBox, this.themeService, {
inputBackground: settingsTextInputBackground,
inputForeground: settingsTextInputForeground,
inputBorder: settingsTextInputBorder
}));
common.toDispose.push(
inputBox.onDidChange(e => {
if (template.onChange) {
template.onChange(e);
}
}));
common.toDispose.push(inputBox);
inputBox.inputElement.classList.add(SettingsRenderer.CONTROL_CLASS);
const template: ISettingTextItemTemplate = {
...common,
inputBox,
validationErrorMessageElement
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderSettingNumberTemplate(tree: ITree, container: HTMLElement): ISettingNumberItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'number');
const validationErrorMessageElement = DOM.append(container, $('.setting-item-validation-message'));
const inputBox = new InputBox(common.controlElement, this.contextViewService, { type: 'number' });
common.toDispose.push(inputBox);
common.toDispose.push(attachInputBoxStyler(inputBox, this.themeService, {
inputBackground: settingsNumberInputBackground,
inputForeground: settingsNumberInputForeground,
inputBorder: settingsNumberInputBorder
}));
common.toDispose.push(
inputBox.onDidChange(e => {
if (template.onChange) {
template.onChange(e);
}
}));
common.toDispose.push(inputBox);
inputBox.inputElement.classList.add(SettingsRenderer.CONTROL_CLASS);
const template: ISettingNumberItemTemplate = {
...common,
inputBox,
validationErrorMessageElement
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderSettingToolbar(container: HTMLElement): ToolBar {
const toolbar = new ToolBar(container, this.contextMenuService, {});
toolbar.setActions([], this.settingActions)();
const button = container.querySelector('.toolbar-toggle-more');
if (button) {
(<HTMLElement>button).tabIndex = -1;
}
return toolbar;
}
private renderSettingBoolTemplate(tree: ITree, container: HTMLElement): ISettingBoolItemTemplate {
DOM.addClass(container, 'setting-item');
DOM.addClass(container, 'setting-item-bool');
const titleElement = DOM.append(container, $('.setting-item-title'));
const categoryElement = DOM.append(titleElement, $('span.setting-item-category'));
const labelElement = DOM.append(titleElement, $('span.setting-item-label'));
const otherOverridesElement = DOM.append(titleElement, $('span.setting-item-overrides'));
const descriptionAndValueElement = DOM.append(container, $('.setting-item-value-description'));
const controlElement = DOM.append(descriptionAndValueElement, $('.setting-item-bool-control'));
const descriptionElement = DOM.append(descriptionAndValueElement, $('.setting-item-description'));
const modifiedIndicatorElement = DOM.append(container, $('.setting-item-modified-indicator'));
modifiedIndicatorElement.title = localize('modified', "Modified");
const deprecationWarningElement = DOM.append(container, $('.setting-item-deprecation-message'));
const toDispose = [];
const checkbox = new Checkbox({ actionClassName: 'setting-value-checkbox', isChecked: true, title: '', inputActiveOptionBorder: null });
controlElement.appendChild(checkbox.domNode);
toDispose.push(checkbox);
toDispose.push(checkbox.onChange(() => {
if (template.onChange) {
template.onChange(checkbox.checked);
}
}));
// Need to listen for mouse clicks on description and toggle checkbox - use target ID for safety
// Also have to ignore embedded links - too buried to stop propagation
toDispose.push(DOM.addDisposableListener(descriptionElement, DOM.EventType.MOUSE_DOWN, (e) => {
const targetElement = <HTMLElement>e.toElement;
const targetId = descriptionElement.getAttribute('checkbox_label_target_id');
// Make sure we are not a link and the target ID matches
// Toggle target checkbox
if (targetElement.tagName.toLowerCase() !== 'a' && targetId === template.checkbox.domNode.id) {
template.checkbox.checked = template.checkbox.checked ? false : true;
template.onChange(checkbox.checked);
}
DOM.EventHelper.stop(e);
}));
checkbox.domNode.classList.add(SettingsRenderer.CONTROL_CLASS);
const toolbar = this.renderSettingToolbar(container);
toDispose.push(toolbar);
const template: ISettingBoolItemTemplate = {
toDispose,
containerElement: container,
categoryElement,
labelElement,
controlElement,
checkbox,
descriptionElement,
deprecationWarningElement,
otherOverridesElement,
toolbar
};
this.addSettingElementFocusHandler(template);
// Prevent clicks from being handled by list
toDispose.push(DOM.addDisposableListener(controlElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addStandardDisposableListener(controlElement, 'keydown', (e: StandardKeyboardEvent) => {
if (e.keyCode === KeyCode.Escape) {
tree.domFocus();
e.browserEvent.stopPropagation();
}
}));
return template;
}
public cancelSuggesters() {
this.contextViewService.hideContextView();
}
private renderSettingEnumTemplate(tree: ITree, container: HTMLElement): ISettingEnumItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'enum');
const selectBox = new SelectBox([], undefined, this.contextViewService, undefined, {
hasDetails: true
});
common.toDispose.push(selectBox);
common.toDispose.push(attachSelectBoxStyler(selectBox, this.themeService, {
selectBackground: settingsSelectBackground,
selectForeground: settingsSelectForeground,
selectBorder: settingsSelectBorder,
selectListBorder: settingsSelectListBorder
}));
selectBox.render(common.controlElement);
const selectElement = common.controlElement.querySelector('select');
if (selectElement) {
selectElement.classList.add(SettingsRenderer.CONTROL_CLASS);
}
common.toDispose.push(
selectBox.onDidSelect(e => {
if (template.onChange) {
template.onChange(e.index);
}
}));
const enumDescriptionElement = common.containerElement.insertBefore($('.setting-item-enumDescription'), common.descriptionElement.nextSibling);
const template: ISettingEnumItemTemplate = {
...common,
selectBox,
enumDescriptionElement
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderSettingExcludeTemplate(tree: ITree, container: HTMLElement): ISettingExcludeItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'exclude');
const excludeWidget = this.instantiationService.createInstance(ExcludeSettingWidget, common.controlElement);
excludeWidget.domNode.classList.add(SettingsRenderer.CONTROL_CLASS);
common.toDispose.push(excludeWidget);
const template: ISettingExcludeItemTemplate = {
...common,
excludeWidget
};
this.addSettingElementFocusHandler(template);
common.toDispose.push(excludeWidget.onDidChangeExclude(e => {
if (template.context) {
let newValue = { ...template.context.scopeValue };
// first delete the existing entry, if present
if (e.originalPattern) {
if (e.originalPattern in template.context.defaultValue) {
// delete a default by overriding it
newValue[e.originalPattern] = false;
} else {
delete newValue[e.originalPattern];
}
}
// then add the new or updated entry, if present
if (e.pattern) {
if (e.pattern in template.context.defaultValue && !e.sibling) {
// add a default by deleting its override
delete newValue[e.pattern];
} else {
newValue[e.pattern] = e.sibling ? { when: e.sibling } : true;
}
}
const sortKeys = (obj) => {
const keyArray = Object.keys(obj)
.map(key => ({ key, val: obj[key] }))
.sort((a, b) => a.key.localeCompare(b.key));
const retVal = {};
keyArray.forEach(pair => {
retVal[pair.key] = pair.val;
});
return retVal;
};
this._onDidChangeSetting.fire({
key: template.context.setting.key,
value: Object.keys(newValue).length === 0 ? undefined : sortKeys(newValue)
});
}
}));
return template;
}
private renderSettingComplexTemplate(tree: ITree, container: HTMLElement): ISettingComplexItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'complex');
const openSettingsButton = new Button(common.controlElement, { title: true, buttonBackground: null, buttonHoverBackground: null });
common.toDispose.push(openSettingsButton);
common.toDispose.push(openSettingsButton.onDidClick(() => template.onChange(null)));
openSettingsButton.label = localize('editInSettingsJson', "Edit in settings.json");
openSettingsButton.element.classList.add('edit-in-settings-button');
common.toDispose.push(attachButtonStyler(openSettingsButton, this.themeService, {
buttonBackground: Color.transparent.toString(),
buttonHoverBackground: Color.transparent.toString(),
buttonForeground: 'foreground'
}));
const template: ISettingComplexItemTemplate = {
...common,
button: openSettingsButton
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderNewExtensionsTemplate(container: HTMLElement): ISettingNewExtensionsTemplate {
const toDispose = [];
container.classList.add('setting-item-new-extensions');
const button = new Button(container, { title: true, buttonBackground: null, buttonHoverBackground: null });
toDispose.push(button);
toDispose.push(button.onDidClick(() => {
if (template.context) {
this.commandService.executeCommand('workbench.extensions.action.showExtensionsWithIds', template.context.extensionIds);
}
}));
button.label = localize('newExtensionsButtonLabel', "Show matching extensions");
button.element.classList.add('settings-new-extensions-button');
toDispose.push(attachButtonStyler(button, this.themeService));
const template: ISettingNewExtensionsTemplate = {
button,
toDispose
};
// this.addSettingElementFocusHandler(template);
return template;
}
renderElement(tree: ITree, element: SettingsTreeElement, templateId: string, template: any): void {
if (templateId === SETTINGS_GROUP_ELEMENT_TEMPLATE_ID) {
return this.renderGroupElement(<SettingsTreeGroupElement>element, template);
}
if (templateId === SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID) {
return this.renderNewExtensionsElement(<SettingsTreeNewExtensionsElement>element, template);
}
return this.renderSettingElement(tree, <SettingsTreeSettingElement>element, templateId, template);
}
private renderGroupElement(element: SettingsTreeGroupElement, template: IGroupTitleTemplate): void {
template.parent.innerHTML = '';
const labelElement = DOM.append(template.parent, $('div.settings-group-title-label'));
labelElement.classList.add(`settings-group-level-${element.level}`);
labelElement.textContent = (<SettingsTreeGroupElement>element).label;
if (element.isFirstGroup) {
labelElement.classList.add('settings-group-first');
}
}
private renderNewExtensionsElement(element: SettingsTreeNewExtensionsElement, template: ISettingNewExtensionsTemplate): void {
template.context = element;
}
public getSettingDOMElementForDOMElement(domElement: HTMLElement): HTMLElement {
const parent = DOM.findParentWithClass(domElement, 'setting-item');
if (parent) {
return parent;
}
return null;
}
public getDOMElementsForSettingKey(treeContainer: HTMLElement, key: string): NodeListOf<HTMLElement> {
return treeContainer.querySelectorAll(`[${SettingsRenderer.SETTING_KEY_ATTR}="${key}"]`);
}
public getKeyForDOMElementInSetting(element: HTMLElement): string {
const settingElement = this.getSettingDOMElementForDOMElement(element);
return settingElement && settingElement.getAttribute(SettingsRenderer.SETTING_KEY_ATTR);
}
private renderSettingElement(tree: ITree, element: SettingsTreeSettingElement, templateId: string, template: ISettingItemTemplate | ISettingBoolItemTemplate): void {
template.context = element;
template.toolbar.context = element;
const setting = element.setting;
DOM.toggleClass(template.containerElement, 'is-configured', element.isConfigured);
DOM.toggleClass(template.containerElement, 'is-expanded', true);
template.containerElement.setAttribute(SettingsRenderer.SETTING_KEY_ATTR, element.setting.key);
const titleTooltip = setting.key + (element.isConfigured ? ' - Modified' : '');
template.categoryElement.textContent = element.displayCategory && (element.displayCategory + ': ');
template.categoryElement.title = titleTooltip;
template.labelElement.textContent = element.displayLabel;
template.labelElement.title = titleTooltip;
this.renderValue(element, templateId, <ISettingItemTemplate>template);
template.descriptionElement.innerHTML = '';
if (element.setting.descriptionIsMarkdown) {
const renderedDescription = this.renderDescriptionMarkdown(element, element.description, template.toDispose);
template.descriptionElement.appendChild(renderedDescription);
} else {
template.descriptionElement.innerText = element.description;
}
const baseId = (element.displayCategory + '_' + element.displayLabel).replace(/ /g, '_').toLowerCase();
template.descriptionElement.id = baseId + '_setting_description';
if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
// Add checkbox target to description clickable and able to toggle checkbox
template.descriptionElement.setAttribute('checkbox_label_target_id', baseId + '_setting_item');
}
if (element.overriddenScopeList.length) {
let otherOverridesLabel = element.isConfigured ?
localize('alsoConfiguredIn', "Also modified in") :
localize('configuredIn', "Modified in");
template.otherOverridesElement.textContent = `(${otherOverridesLabel}: ${element.overriddenScopeList.join(', ')})`;
} else {
template.otherOverridesElement.textContent = '';
}
// Remove tree attributes - sometimes overridden by tree - should be managed there
template.containerElement.parentElement.removeAttribute('role');
template.containerElement.parentElement.removeAttribute('aria-level');
template.containerElement.parentElement.removeAttribute('aria-posinset');
template.containerElement.parentElement.removeAttribute('aria-setsize');
}
private renderDescriptionMarkdown(element: SettingsTreeSettingElement, text: string, disposeables: IDisposable[]): HTMLElement {
// Rewrite `#editor.fontSize#` to link format
text = fixSettingLinks(text);
const renderedMarkdown = renderMarkdown({ value: text }, {
actionHandler: {
callback: (content: string) => {
if (startsWith(content, '#')) {
const e: ISettingLinkClickEvent = {
source: element,
targetKey: content.substr(1)
};
this._onDidClickSettingLink.fire(e);
} else {
this.openerService.open(URI.parse(content)).then(void 0, onUnexpectedError);
}
},
disposeables
}
});
renderedMarkdown.classList.add('setting-item-description-markdown');
cleanRenderedMarkdown(renderedMarkdown);
return renderedMarkdown;
}
private renderValue(element: SettingsTreeSettingElement, templateId: string, template: ISettingItemTemplate | ISettingBoolItemTemplate): void {
const onChange = value => this._onDidChangeSetting.fire({ key: element.setting.key, value });
template.deprecationWarningElement.innerText = element.setting.deprecationMessage || '';
if (templateId === SETTINGS_ENUM_TEMPLATE_ID) {
this.renderEnum(element, <ISettingEnumItemTemplate>template, onChange);
} else if (templateId === SETTINGS_TEXT_TEMPLATE_ID) {
this.renderText(element, <ISettingTextItemTemplate>template, onChange);
} else if (templateId === SETTINGS_NUMBER_TEMPLATE_ID) {
this.renderNumber(element, <ISettingTextItemTemplate>template, onChange);
} else if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
this.renderBool(element, <ISettingBoolItemTemplate>template, onChange);
} else if (templateId === SETTINGS_EXCLUDE_TEMPLATE_ID) {
this.renderExcludeSetting(element, <ISettingExcludeItemTemplate>template);
} else if (templateId === SETTINGS_COMPLEX_TEMPLATE_ID) {
this.renderComplexSetting(element, <ISettingComplexItemTemplate>template);
}
}
private renderBool(dataElement: SettingsTreeSettingElement, template: ISettingBoolItemTemplate, onChange: (value: boolean) => void): void {
template.onChange = null;
template.checkbox.checked = dataElement.value;
template.onChange = onChange;
// Setup and add ARIA attributes
// Create id and label for control/input element - parent is wrapper div
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' ' + modifiedText;
// We use the parent control div for the aria-labelledby target
// Does not appear you can use the direct label on the element itself within a tree
template.checkbox.domNode.parentElement.id = baseId + '_setting_label';
template.checkbox.domNode.parentElement.setAttribute('aria-label', label);
// Labels will not be read on descendent input elements of the parent treeitem
// unless defined as role=treeitem and indirect aria-labelledby approach
template.checkbox.domNode.id = baseId + '_setting_item';
template.checkbox.domNode.setAttribute('role', 'checkbox');
template.checkbox.domNode.setAttribute('aria-labelledby', baseId + '_setting_label');
template.checkbox.domNode.setAttribute('aria-describedby', baseId + '_setting_description');
}
private renderEnum(dataElement: SettingsTreeSettingElement, template: ISettingEnumItemTemplate, onChange: (value: string) => void): void {
const displayOptions = dataElement.setting.enum
.map(String)
.map(escapeInvisibleChars);
template.selectBox.setOptions(displayOptions);
const enumDescriptions = dataElement.setting.enumDescriptions;
const enumDescriptionsAreMarkdown = dataElement.setting.enumDescriptionsAreMarkdown;
template.selectBox.setDetailsProvider(index =>
({
details: enumDescriptions && enumDescriptions[index] && (enumDescriptionsAreMarkdown ? fixSettingLinks(enumDescriptions[index], false) : enumDescriptions[index]),
isMarkdown: enumDescriptionsAreMarkdown
}));
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' ' + modifiedText;
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
template.selectBox.setAriaLabel(label);
const idx = dataElement.setting.enum.indexOf(dataElement.value);
template.onChange = null;
template.selectBox.select(idx);
template.onChange = idx => onChange(dataElement.setting.enum[idx]);
if (template.controlElement.firstElementChild) {
// SelectBox needs to have treeitem changed to combobox to read correctly within tree
template.controlElement.firstElementChild.setAttribute('role', 'combobox');
template.controlElement.firstElementChild.setAttribute('aria-describedby', baseId + '_setting_description');
}
template.enumDescriptionElement.innerHTML = '';
}
private renderText(dataElement: SettingsTreeSettingElement, template: ISettingTextItemTemplate, onChange: (value: string) => void): void {
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' ' + modifiedText; template.onChange = null;
template.inputBox.value = dataElement.value;
template.onChange = value => { renderValidations(dataElement, template, false, label); onChange(value); };
// Setup and add ARIA attributes
// Create id and label for control/input element - parent is wrapper div
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
// We use the parent control div for the aria-labelledby target
// Does not appear you can use the direct label on the element itself within a tree
template.inputBox.inputElement.parentElement.id = baseId + '_setting_label';
template.inputBox.inputElement.parentElement.setAttribute('aria-label', label);
// Labels will not be read on descendent input elements of the parent treeitem
// unless defined as role=treeitem and indirect aria-labelledby approach
template.inputBox.inputElement.id = baseId + '_setting_item';
template.inputBox.inputElement.setAttribute('role', 'textbox');
template.inputBox.inputElement.setAttribute('aria-labelledby', baseId + '_setting_label');
template.inputBox.inputElement.setAttribute('aria-describedby', baseId + '_setting_description');
renderValidations(dataElement, template, true, label);
}
private renderNumber(dataElement: SettingsTreeSettingElement, template: ISettingTextItemTemplate, onChange: (value: number) => void): void {
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' number ' + modifiedText; const numParseFn = (dataElement.valueType === 'integer' || dataElement.valueType === 'nullable-integer')
? parseInt : parseFloat;
const nullNumParseFn = (dataElement.valueType === 'nullable-integer' || dataElement.valueType === 'nullable-number')
? (v => v === '' ? null : numParseFn(v)) : numParseFn;
template.onChange = null;
template.inputBox.value = dataElement.value;
template.onChange = value => { renderValidations(dataElement, template, false, label); onChange(nullNumParseFn(value)); };
// Setup and add ARIA attributes
// Create id and label for control/input element - parent is wrapper div
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
// We use the parent control div for the aria-labelledby target
// Does not appear you can use the direct label on the element itself within a tree
template.inputBox.inputElement.parentElement.id = baseId + '_setting_label';
template.inputBox.inputElement.parentElement.setAttribute('aria-label', label);
// Labels will not be read on descendent input elements of the parent treeitem
// unless defined as role=treeitem and indirect aria-labelledby approach
template.inputBox.inputElement.id = baseId + '_setting_item';
template.inputBox.inputElement.setAttribute('role', 'textbox');
template.inputBox.inputElement.setAttribute('aria-labelledby', baseId + '_setting_label');
template.inputBox.inputElement.setAttribute('aria-describedby', baseId + '_setting_description');
renderValidations(dataElement, template, true, label);
}
private renderExcludeSetting(dataElement: SettingsTreeSettingElement, template: ISettingExcludeItemTemplate): void {
const value = getExcludeDisplayValue(dataElement);
template.excludeWidget.setValue(value);
template.context = dataElement;
}
private renderComplexSetting(dataElement: SettingsTreeSettingElement, template: ISettingComplexItemTemplate): void {
template.onChange = () => this._onDidOpenSettings.fire(dataElement.setting.key);
}
disposeTemplate(tree: ITree, templateId: string, template: IDisposableTemplate): void {
dispose(template.toDispose);
}
}
function renderValidations(dataElement: SettingsTreeSettingElement, template: ISettingTextItemTemplate, calledOnStartup: boolean, originalAriaLabel: string) {
if (dataElement.setting.validator) {
let errMsg = dataElement.setting.validator(template.inputBox.value);
if (errMsg) {
DOM.addClass(template.containerElement, 'invalid-input');
template.validationErrorMessageElement.innerText = errMsg;
let validationError = localize('validationError', "Validation Error.");
template.inputBox.inputElement.parentElement.setAttribute('aria-label', [originalAriaLabel, validationError, errMsg].join(' '));
if (!calledOnStartup) { ariaAlert(validationError + ' ' + errMsg); }
return;
} else {
template.inputBox.inputElement.parentElement.setAttribute('aria-label', originalAriaLabel);
}
}
DOM.removeClass(template.containerElement, 'invalid-input');
}
function cleanRenderedMarkdown(element: Node): void {
for (let i = 0; i < element.childNodes.length; i++) {
const child = element.childNodes.item(i);
const tagName = (<Element>child).tagName && (<Element>child).tagName.toLowerCase();
if (tagName === 'img') {
element.removeChild(child);
} else {
cleanRenderedMarkdown(child);
}
}
}
function fixSettingLinks(text: string, linkify = true): string {
return text.replace(/`#([^#]*)#`/g, (match, settingKey) => {
const targetDisplayFormat = settingKeyToDisplayFormat(settingKey);
const targetName = `${targetDisplayFormat.category}: ${targetDisplayFormat.label}`;
return linkify ?
`[${targetName}](#${settingKey})` :
`"${targetName}"`;
});
}
function escapeInvisibleChars(enumValue: string): string {
return enumValue && enumValue
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r');
}
export class SettingsTreeFilter implements IFilter {
constructor(
private viewState: ISettingsEditorViewState,
) { }
isVisible(tree: ITree, element: SettingsTreeElement): boolean {
// Filter during search
if (this.viewState.filterToCategory && element instanceof SettingsTreeSettingElement) {
if (!this.settingContainedInGroup(element.setting, this.viewState.filterToCategory)) {
return false;
}
}
if (element instanceof SettingsTreeSettingElement && this.viewState.tagFilters) {
return element.matchesAllTags(this.viewState.tagFilters);
}
if (element instanceof SettingsTreeGroupElement) {
if (typeof element.count === 'number') {
return element.count > 0;
}
return element.children.some(child => this.isVisible(tree, child));
}
if (element instanceof SettingsTreeNewExtensionsElement) {
if ((this.viewState.tagFilters && this.viewState.tagFilters.size) || this.viewState.filterToCategory) {
return false;
}
}
return true;
}
private settingContainedInGroup(setting: ISetting, group: SettingsTreeGroupElement): boolean {
return group.children.some(child => {
if (child instanceof SettingsTreeGroupElement) {
return this.settingContainedInGroup(setting, child);
} else if (child instanceof SettingsTreeSettingElement) {
return child.setting.key === setting.key;
} else {
return false;
}
});
}
}
export class SettingsTreeController extends WorkbenchTreeController {
constructor(
@IConfigurationService configurationService: IConfigurationService
) {
super({}, configurationService);
}
protected onLeftClick(tree: ITree, element: any, eventish: IMouseEvent, origin?: string): boolean {
const isLink = eventish.target.tagName.toLowerCase() === 'a' ||
eventish.target.parentElement.tagName.toLowerCase() === 'a'; // <code> inside <a>
if (isLink && (DOM.findParentWithClass(eventish.target, 'setting-item-description-markdown', tree.getHTMLElement()) || DOM.findParentWithClass(eventish.target, 'select-box-description-markdown'))) {
return true;
}
return false;
}
}
export class SettingsAccessibilityProvider implements IAccessibilityProvider {
getAriaLabel(tree: ITree, element: SettingsTreeElement): string {
if (!element) {
return '';
}
if (element instanceof SettingsTreeSettingElement) {
return localize('settingRowAriaLabel', "{0} {1}, Setting", element.displayCategory, element.displayLabel);
}
if (element instanceof SettingsTreeGroupElement) {
return localize('groupRowAriaLabel', "{0}, group", element.label);
}
return '';
}
}
class NonExpandableOrSelectableTree extends Tree {
expand(): TPromise<any> {
return TPromise.wrap(null);
}
collapse(): TPromise<any> {
return TPromise.wrap(null);
}
public setFocus(element?: any, eventPayload?: any): void {
return;
}
public focusNext(count?: number, eventPayload?: any): void {
return;
}
public focusPrevious(count?: number, eventPayload?: any): void {
return;
}
public focusParent(eventPayload?: any): void {
return;
}
public focusFirstChild(eventPayload?: any): void {
return;
}
public focusFirst(eventPayload?: any, from?: any): void {
return;
}
public focusNth(index: number, eventPayload?: any): void {
return;
}
public focusLast(eventPayload?: any, from?: any): void {
return;
}
public focusNextPage(eventPayload?: any): void {
return;
}
public focusPreviousPage(eventPayload?: any): void {
return;
}
public select(element: any, eventPayload?: any): void {
return;
}
public selectRange(fromElement: any, toElement: any, eventPayload?: any): void {
return;
}
public selectAll(elements: any[], eventPayload?: any): void {
return;
}
public setSelection(elements: any[], eventPayload?: any): void {
return;
}
public toggleSelection(element: any, eventPayload?: any): void {
return;
}
}
export class SettingsTree extends NonExpandableOrSelectableTree {
protected disposables: IDisposable[];
constructor(
container: HTMLElement,
viewState: ISettingsEditorViewState,
configuration: Partial<ITreeConfiguration>,
@IThemeService themeService: IThemeService,
@IInstantiationService instantiationService: IInstantiationService
) {
const treeClass = 'settings-editor-tree';
const controller = instantiationService.createInstance(SettingsTreeController);
const fullConfiguration = <ITreeConfiguration>{
controller,
accessibilityProvider: instantiationService.createInstance(SettingsAccessibilityProvider),
filter: instantiationService.createInstance(SettingsTreeFilter, viewState),
styler: new DefaultTreestyler(DOM.createStyleSheet(container), treeClass),
...configuration
};
const options = {
ariaLabel: localize('treeAriaLabel', "Settings"),
showLoading: false,
indentPixels: 0,
twistiePixels: 20, // Actually for gear button
};
super(container,
fullConfiguration,
options);
this.disposables = [];
this.disposables.push(controller);
this.disposables.push(registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
const activeBorderColor = theme.getColor(focusBorder);
if (activeBorderColor) {
// TODO@rob - why isn't this applied when added to the stylesheet from tocTree.ts? Seems like a chromium glitch.
collector.addRule(`.settings-editor > .settings-body > .settings-toc-container .monaco-tree:focus .monaco-tree-row.focused {outline: solid 1px ${activeBorderColor}; outline-offset: -1px; }`);
}
const foregroundColor = theme.getColor(foreground);
if (foregroundColor) {
// Links appear inside other elements in markdown. CSS opacity acts like a mask. So we have to dynamically compute the description color to avoid
// applying an opacity to the link color.
const fgWithOpacity = new Color(new RGBA(foregroundColor.rgba.r, foregroundColor.rgba.g, foregroundColor.rgba.b, .9));
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-description { color: ${fgWithOpacity}; }`);
}
const errorColor = theme.getColor(errorForeground);
if (errorColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-deprecation-message { color: ${errorColor}; }`);
}
const invalidInputBackground = theme.getColor(inputValidationErrorBackground);
if (invalidInputBackground) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-validation-message { background-color: ${invalidInputBackground}; }`);
}
const invalidInputForeground = theme.getColor(inputValidationErrorForeground);
if (invalidInputForeground) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-validation-message { color: ${invalidInputForeground}; }`);
}
const invalidInputBorder = theme.getColor(inputValidationErrorBorder);
if (invalidInputBorder) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-validation-message { border-style:solid; border-width: 1px; border-color: ${invalidInputBorder}; }`);
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item.invalid-input .setting-item-control .monaco-inputbox.idle { outline-width: 0; border-style:solid; border-width: 1px; border-color: ${invalidInputBorder}; }`);
}
const headerForegroundColor = theme.getColor(settingsHeaderForeground);
if (headerForegroundColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .settings-group-title-label { color: ${headerForegroundColor}; }`);
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item-label { color: ${headerForegroundColor}; }`);
}
const focusBorderColor = theme.getColor(focusBorder);
if (focusBorderColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-description-markdown a:focus { outline-color: ${focusBorderColor} }`);
}
}));
this.getHTMLElement().classList.add(treeClass);
this.disposables.push(attachStyler(themeService, {
listActiveSelectionBackground: editorBackground,
listActiveSelectionForeground: foreground,
listFocusAndSelectionBackground: editorBackground,
listFocusAndSelectionForeground: foreground,
listFocusBackground: editorBackground,
listFocusForeground: foreground,
listHoverForeground: foreground,
listHoverBackground: editorBackground,
listHoverOutline: editorBackground,
listFocusOutline: editorBackground,
listInactiveSelectionBackground: editorBackground,
listInactiveSelectionForeground: foreground
}, colors => {
this.style(colors);
}));
}
}
class CopySettingIdAction extends Action {
static readonly ID = 'settings.copySettingId';
static readonly LABEL = localize('copySettingIdLabel', "Copy Setting ID");
constructor(
@IClipboardService private clipboardService: IClipboardService
) {
super(CopySettingIdAction.ID, CopySettingIdAction.LABEL);
}
run(context: SettingsTreeSettingElement): TPromise<void> {
if (context) {
this.clipboardService.writeText(context.setting.key);
}
return TPromise.as(null);
}
}
class CopySettingAsJSONAction extends Action {
static readonly ID = 'settings.copySettingAsJSON';
static readonly LABEL = localize('copySettingAsJSONLabel', "Copy Setting as JSON");
constructor(
@IClipboardService private clipboardService: IClipboardService
) {
super(CopySettingAsJSONAction.ID, CopySettingAsJSONAction.LABEL);
}
run(context: SettingsTreeSettingElement): TPromise<void> {
if (context) {
const jsonResult = `"${context.setting.key}": ${JSON.stringify(context.value, undefined, ' ')}`;
this.clipboardService.writeText(jsonResult);
}
return TPromise.as(null);
}
} | src/vs/workbench/parts/preferences/browser/settingsTree.ts | 1 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.9981415271759033,
0.0066795931197702885,
0.00015990750398486853,
0.0001701153814792633,
0.07913479954004288
]
|
{
"id": 5,
"code_window": [
"\t\t@IOpenerService private readonly openerService: IOpenerService,\n",
"\t\t@IInstantiationService private readonly instantiationService: IInstantiationService,\n",
"\t\t@ICommandService private readonly commandService: ICommandService,\n",
"\t\t@IContextMenuService private contextMenuService: IContextMenuService\n",
"\t) {\n",
"\t\tthis.descriptionMeasureContainer = $('.setting-item-description');\n",
"\t\tDOM.append(_measureContainer,\n",
"\t\t\t$('.setting-measure-container.monaco-tree-row', undefined,\n",
"\t\t\t\t$('.setting-item', undefined,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t@IContextMenuService private contextMenuService: IContextMenuService,\n",
"\t\t@IKeybindingService private keybindingService: IKeybindingService,\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "replace",
"edit_start_line_idx": 372
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { KeyMod, KeyChord, KeyCode } from 'vs/base/common/keyCodes';
import { ModesRegistry } from 'vs/editor/common/modes/modesRegistry';
import { Registry } from 'vs/platform/registry/common/platform';
import { MenuId, MenuRegistry, SyncActionDescriptor } from 'vs/platform/actions/common/actions';
import { KeybindingsRegistry, IKeybindings } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IWorkbenchActionRegistry, Extensions as ActionExtensions } from 'vs/workbench/common/actions';
import { OutputService, LogContentProvider } from 'vs/workbench/parts/output/electron-browser/outputServices';
import { ToggleOutputAction, ClearOutputAction, OpenLogOutputFile } from 'vs/workbench/parts/output/browser/outputActions';
import { OUTPUT_MODE_ID, OUTPUT_MIME, OUTPUT_PANEL_ID, IOutputService, CONTEXT_IN_OUTPUT, LOG_SCHEME, COMMAND_OPEN_LOG_VIEWER, LOG_MODE_ID, LOG_MIME, CONTEXT_ACTIVE_LOG_OUTPUT } from 'vs/workbench/parts/output/common/output';
import { PanelRegistry, Extensions, PanelDescriptor } from 'vs/workbench/browser/panel';
import { CommandsRegistry, ICommandHandler } from 'vs/platform/commands/common/commands';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { OutputPanel } from 'vs/workbench/parts/output/browser/outputPanel';
import { IEditorRegistry, Extensions as EditorExtensions, EditorDescriptor } from 'vs/workbench/browser/editor';
import { LogViewer, LogViewerInput } from 'vs/workbench/parts/output/browser/logViewer';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions, IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { URI } from 'vs/base/common/uri';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
// Register Service
registerSingleton(IOutputService, OutputService);
// Register Output Mode
ModesRegistry.registerLanguage({
id: OUTPUT_MODE_ID,
extensions: [],
aliases: [null],
mimetypes: [OUTPUT_MIME]
});
// Register Log Output Mode
ModesRegistry.registerLanguage({
id: LOG_MODE_ID,
extensions: [],
aliases: [null],
mimetypes: [LOG_MIME]
});
// Register Output Panel
Registry.as<PanelRegistry>(Extensions.Panels).registerPanel(new PanelDescriptor(
OutputPanel,
OUTPUT_PANEL_ID,
nls.localize('output', "Output"),
'output',
20,
ToggleOutputAction.ID
));
Registry.as<IEditorRegistry>(EditorExtensions.Editors).registerEditor(
new EditorDescriptor(
LogViewer,
LogViewer.LOG_VIEWER_EDITOR_ID,
nls.localize('logViewer', "Log Viewer")
),
[
new SyncDescriptor(LogViewerInput)
]
);
class OutputContribution implements IWorkbenchContribution {
constructor(
@IInstantiationService instantiationService: IInstantiationService,
@ITextModelService textModelService: ITextModelService
) {
textModelService.registerTextModelContentProvider(LOG_SCHEME, instantiationService.createInstance(LogContentProvider));
}
}
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(OutputContribution, LifecyclePhase.Running);
// register toggle output action globally
const actionRegistry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions);
actionRegistry.registerWorkbenchAction(new SyncActionDescriptor(ToggleOutputAction, ToggleOutputAction.ID, ToggleOutputAction.LABEL, {
primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_U,
linux: {
primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_H) // On Ubuntu Ctrl+Shift+U is taken by some global OS command
}
}), 'View: Toggle Output', nls.localize('viewCategory', "View"));
actionRegistry.registerWorkbenchAction(new SyncActionDescriptor(ClearOutputAction, ClearOutputAction.ID, ClearOutputAction.LABEL),
'View: Clear Output', nls.localize('viewCategory', "View"));
interface IActionDescriptor {
id: string;
handler: ICommandHandler;
// ICommandUI
title: string;
category?: string;
f1?: boolean;
// menus
menu?: {
menuId: MenuId,
when?: ContextKeyExpr;
group?: string;
};
// keybindings
keybinding?: {
when?: ContextKeyExpr;
weight: number;
keys: IKeybindings;
};
}
function registerAction(desc: IActionDescriptor) {
const { id, handler, title, category, f1, menu, keybinding } = desc;
// 1) register as command
CommandsRegistry.registerCommand(id, handler);
// 2) command palette
let command = { id, title, category };
if (f1) {
MenuRegistry.addCommand(command);
}
// 3) menus
if (menu) {
let { menuId, when, group } = menu;
MenuRegistry.appendMenuItem(menuId, {
command,
when,
group
});
}
// 4) keybindings
if (keybinding) {
let { when, weight, keys } = keybinding;
KeybindingsRegistry.registerKeybindingRule({
id,
when,
weight,
primary: keys.primary,
secondary: keys.secondary,
linux: keys.linux,
mac: keys.mac,
win: keys.win
});
}
}
// Define clear command, contribute to editor context menu
registerAction({
id: 'editor.action.clearoutput',
title: nls.localize('clearOutput.label', "Clear Output"),
menu: {
menuId: MenuId.EditorContext,
when: CONTEXT_IN_OUTPUT
},
handler(accessor) {
accessor.get(IOutputService).getActiveChannel().clear();
}
});
registerAction({
id: 'workbench.action.openActiveLogOutputFile',
title: nls.localize('openActiveLogOutputFile', "View: Open Active Log Output File"),
menu: {
menuId: MenuId.CommandPalette,
when: CONTEXT_ACTIVE_LOG_OUTPUT
},
handler(accessor) {
accessor.get(IInstantiationService).createInstance(OpenLogOutputFile).run();
}
});
CommandsRegistry.registerCommand(COMMAND_OPEN_LOG_VIEWER, function (accessor: ServicesAccessor, file: URI) {
if (file) {
const editorService = accessor.get(IEditorService);
return editorService.openEditor(accessor.get(IInstantiationService).createInstance(LogViewerInput, file));
}
return null;
});
MenuRegistry.appendMenuItem(MenuId.MenubarViewMenu, {
group: '4_panels',
command: {
id: ToggleOutputAction.ID,
title: nls.localize({ key: 'miToggleOutput', comment: ['&& denotes a mnemonic'] }, "&&Output")
},
order: 1
});
| src/vs/workbench/parts/output/electron-browser/output.contribution.ts | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.00032845709938555956,
0.00018282292876392603,
0.00016437859449069947,
0.0001725153997540474,
0.00003649356949608773
]
|
{
"id": 5,
"code_window": [
"\t\t@IOpenerService private readonly openerService: IOpenerService,\n",
"\t\t@IInstantiationService private readonly instantiationService: IInstantiationService,\n",
"\t\t@ICommandService private readonly commandService: ICommandService,\n",
"\t\t@IContextMenuService private contextMenuService: IContextMenuService\n",
"\t) {\n",
"\t\tthis.descriptionMeasureContainer = $('.setting-item-description');\n",
"\t\tDOM.append(_measureContainer,\n",
"\t\t\t$('.setting-measure-container.monaco-tree-row', undefined,\n",
"\t\t\t\t$('.setting-item', undefined,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t@IContextMenuService private contextMenuService: IContextMenuService,\n",
"\t\t@IKeybindingService private keybindingService: IKeybindingService,\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "replace",
"edit_start_line_idx": 372
} | # Language Features for Markdown files
**Notice:** This extension is bundled with Visual Studio Code. It can be disabled but not uninstalled.
## Features
See [Markdown in Visual Studio Code](https://code.visualstudio.com/docs/languages/markdown) to learn about the features of this extension. | extensions/markdown-language-features/README.md | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.0001702229492366314,
0.0001702229492366314,
0.0001702229492366314,
0.0001702229492366314,
0
]
|
{
"id": 5,
"code_window": [
"\t\t@IOpenerService private readonly openerService: IOpenerService,\n",
"\t\t@IInstantiationService private readonly instantiationService: IInstantiationService,\n",
"\t\t@ICommandService private readonly commandService: ICommandService,\n",
"\t\t@IContextMenuService private contextMenuService: IContextMenuService\n",
"\t) {\n",
"\t\tthis.descriptionMeasureContainer = $('.setting-item-description');\n",
"\t\tDOM.append(_measureContainer,\n",
"\t\t\t$('.setting-measure-container.monaco-tree-row', undefined,\n",
"\t\t\t\t$('.setting-item', undefined,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t@IContextMenuService private contextMenuService: IContextMenuService,\n",
"\t\t@IKeybindingService private keybindingService: IKeybindingService,\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "replace",
"edit_start_line_idx": 372
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-shell {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
overflow: hidden;
font-size: 11px;
user-select: none;
}
/* Font Families (with CJK support) */
.monaco-shell,
.monaco-shell .monaco-menu-container .monaco-menu { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Ubuntu", "Droid Sans", sans-serif; }
.monaco-shell:lang(zh-Hans),
.monaco-shell:lang(zh-Hans) .monaco-menu-container .monaco-menu { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Microsoft YaHei", "PingFang SC", "Hiragino Sans GB", "Source Han Sans SC", "Source Han Sans CN", "Source Han Sans", sans-serif; }
.monaco-shell:lang(zh-Hant),
.monaco-shell:lang(zh-Hant) .monaco-menu-container .monaco-menu { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Microsoft Jhenghei", "PingFang TC", "Source Han Sans TC", "Source Han Sans", "Source Han Sans TW", sans-serif; }
.monaco-shell:lang(ja),
.monaco-shell:lang(ja) .monaco-menu-container .monaco-menu { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Meiryo", "Hiragino Kaku Gothic Pro", "Source Han Sans J", "Source Han Sans JP", "Source Han Sans", "Sazanami Gothic", "IPA Gothic", sans-serif; }
.monaco-shell:lang(ko),
.monaco-shell:lang(ko) .monaco-menu-container .monaco-menu { font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", "Noto Sans", "Malgun Gothic", "Nanum Gothic", "Dotom", "Apple SD Gothic Neo", "AppleGothic", "Source Han Sans K", "Source Han Sans JR", "Source Han Sans", "UnDotum", "FBaekmuk Gulim", sans-serif; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
.monaco-shell img {
border: 0;
}
.monaco-shell label {
cursor: pointer;
}
.monaco-shell a {
text-decoration: none;
}
.monaco-shell a:active {
color: inherit;
background-color: inherit;
}
.monaco-shell a.plain {
color: inherit;
text-decoration: none;
}
.monaco-shell a.plain:hover,
.monaco-shell a.plain.hover {
color: inherit;
text-decoration: none;
}
.monaco-shell input {
color: inherit;
font-family: inherit;
font-size: 100%;
}
.monaco-shell select {
font-family: inherit;
}
.monaco-shell .pointer {
cursor: pointer;
}
.monaco-shell .monaco-menu .monaco-action-bar.vertical {
padding: .5em 0;
}
.monaco-shell .monaco-menu .monaco-action-bar.vertical .action-menu-item {
height: 1.8em;
}
.monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label:not(.separator),
.monaco-shell .monaco-menu .monaco-action-bar.vertical .keybinding {
font-size: inherit;
padding: 0 2em;
}
.monaco-shell .monaco-menu .monaco-action-bar.vertical .menu-item-check {
font-size: inherit;
width: 2em;
}
.monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label.separator {
font-size: inherit;
padding: 0.2em 0 0 0;
margin-bottom: 0.2em;
}
.monaco-shell .monaco-menu .monaco-action-bar.vertical .submenu-indicator {
font-size: 60%;
padding: 0 1.8em;
}
.monaco-shell .monaco-menu .action-item {
cursor: default;
}
/* START Keyboard Focus Indication Styles */
.monaco-shell [tabindex="0"]:focus,
.monaco-shell .synthetic-focus,
.monaco-shell select:focus,
.monaco-shell input[type="button"]:focus,
.monaco-shell input[type="text"]:focus,
.monaco-shell textarea:focus,
.monaco-shell input[type="checkbox"]:focus {
outline-width: 1px;
outline-style: solid;
outline-offset: -1px;
opacity: 1 !important;
}
.monaco-shell [tabindex="0"]:active,
.monaco-shell select:active,
.monaco-shell input[type="button"]:active,
.monaco-shell input[type="checkbox"]:active,
.monaco-shell .monaco-tree .monaco-tree-row
.monaco-shell .monaco-tree.focused.no-focused-item:active:before {
outline: 0 !important; /* fixes some flashing outlines from showing up when clicking */
}
.monaco-shell .mac select:focus {
border: none; /* outline is a square, but border has a radius, so we avoid this glitch when focused (https://github.com/Microsoft/vscode/issues/26045) */
}
.monaco-shell .monaco-tree.focused .monaco-tree-row.focused [tabindex="0"]:focus {
outline-width: 1px; /* higher contrast color for focusable elements in a row that shows focus feedback */
outline-style: solid;
}
.monaco-shell .monaco-tree.focused.no-focused-item:focus:before,
.monaco-shell .monaco-list:not(.element-focused):focus:before {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 5; /* make sure we are on top of the tree items */
content: "";
pointer-events: none; /* enable click through */
outline: 1px solid; /* we still need to handle the empty tree or no focus item case */
outline-width: 1px;
outline-style: solid;
outline-offset: -1px;
}
.monaco-shell .synthetic-focus :focus {
outline: 0 !important; /* elements within widgets that draw synthetic-focus should never show focus */
}
.monaco-shell .monaco-inputbox.info.synthetic-focus,
.monaco-shell .monaco-inputbox.warning.synthetic-focus,
.monaco-shell .monaco-inputbox.error.synthetic-focus,
.monaco-shell .monaco-inputbox.info input[type="text"]:focus,
.monaco-shell .monaco-inputbox.warning input[type="text"]:focus,
.monaco-shell .monaco-inputbox.error input[type="text"]:focus {
outline: 0 !important; /* outline is not going well with decoration */
}
.monaco-shell .monaco-tree.focused:focus,
.monaco-shell .monaco-list:focus {
outline: 0 !important; /* tree indicates focus not via outline but through the focused item */
} | src/vs/workbench/electron-browser/media/shell.css | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.00019163494289387017,
0.00016922742361202836,
0.0001643568102736026,
0.00016741937724873424,
0.000006261739599722205
]
|
{
"id": 6,
"code_window": [
"\t}\n",
"\n",
"\tprivate renderSettingToolbar(container: HTMLElement): ToolBar {\n",
"\t\tconst toolbar = new ToolBar(container, this.contextMenuService, {});\n",
"\t\ttoolbar.setActions([], this.settingActions)();\n",
"\t\tconst button = container.querySelector('.toolbar-toggle-more');\n",
"\t\tif (button) {\n",
"\t\t\t(<HTMLElement>button).tabIndex = -1;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst toggleMenuKeybinding = this.keybindingService.lookupKeybinding(SETTINGS_EDITOR_COMMAND_SHOW_CONTEXT_MENU);\n",
"\t\tlet toggleMenuTitle = localize('settingsContextMenuTitle', \"More Actions... \");\n",
"\t\tif (toggleMenuKeybinding) {\n",
"\t\t\ttoggleMenuTitle += ` (${toggleMenuKeybinding && toggleMenuKeybinding.getLabel()})`;\n",
"\t\t}\n",
"\n",
"\t\tconst toolbar = new ToolBar(container, this.contextMenuService, {\n",
"\t\t\ttoggleMenuTitle\n",
"\t\t});\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "replace",
"edit_start_line_idx": 720
} | /*---------------------------------------------------------------------------------------------
* 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 { renderMarkdown } from 'vs/base/browser/htmlContentRenderer';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { alert as ariaAlert } from 'vs/base/browser/ui/aria/aria';
import { Button } from 'vs/base/browser/ui/button/button';
import { Checkbox } from 'vs/base/browser/ui/checkbox/checkbox';
import { InputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { SelectBox } from 'vs/base/browser/ui/selectBox/selectBox';
import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar';
import { Action, IAction } from 'vs/base/common/actions';
import * as arrays from 'vs/base/common/arrays';
import { Color, RGBA } from 'vs/base/common/color';
import { onUnexpectedError } from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
import { KeyCode } from 'vs/base/common/keyCodes';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { escapeRegExpCharacters, startsWith } from 'vs/base/common/strings';
import { URI } from 'vs/base/common/uri';
import { TPromise } from 'vs/base/common/winjs.base';
import { IAccessibilityProvider, IDataSource, IFilter, IRenderer as ITreeRenderer, ITree, ITreeConfiguration } from 'vs/base/parts/tree/browser/tree';
import { DefaultTreestyler } from 'vs/base/parts/tree/browser/treeDefaults';
import { Tree } from 'vs/base/parts/tree/browser/treeImpl';
import { localize } from 'vs/nls';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { WorkbenchTreeController } from 'vs/platform/list/browser/listService';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { editorBackground, errorForeground, focusBorder, foreground, inputValidationErrorBackground, inputValidationErrorForeground, inputValidationErrorBorder } from 'vs/platform/theme/common/colorRegistry';
import { attachButtonStyler, attachInputBoxStyler, attachSelectBoxStyler, attachStyler } from 'vs/platform/theme/common/styler';
import { ICssStyleCollector, ITheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { ITOCEntry } from 'vs/workbench/parts/preferences/browser/settingsLayout';
import { ISettingsEditorViewState, isExcludeSetting, SettingsTreeElement, SettingsTreeGroupElement, SettingsTreeNewExtensionsElement, settingKeyToDisplayFormat, SettingsTreeSettingElement } from 'vs/workbench/parts/preferences/browser/settingsTreeModels';
import { ExcludeSettingWidget, IExcludeDataItem, settingsHeaderForeground, settingsNumberInputBackground, settingsNumberInputBorder, settingsNumberInputForeground, settingsSelectBackground, settingsSelectBorder, settingsSelectListBorder, settingsSelectForeground, settingsTextInputBackground, settingsTextInputBorder, settingsTextInputForeground } from 'vs/workbench/parts/preferences/browser/settingsWidgets';
import { ISetting, ISettingsGroup } from 'vs/workbench/services/preferences/common/preferences';
const $ = DOM.$;
function getExcludeDisplayValue(element: SettingsTreeSettingElement): IExcludeDataItem[] {
const data = element.isConfigured ?
{ ...element.defaultValue, ...element.scopeValue } :
element.defaultValue;
return Object.keys(data)
.filter(key => !!data[key])
.map(key => {
const value = data[key];
const sibling = typeof value === 'boolean' ? undefined : value.when;
return {
id: key,
pattern: key,
sibling
};
});
}
export function resolveSettingsTree(tocData: ITOCEntry, coreSettingsGroups: ISettingsGroup[]): { tree: ITOCEntry, leftoverSettings: Set<ISetting> } {
const allSettings = getFlatSettings(coreSettingsGroups);
return {
tree: _resolveSettingsTree(tocData, allSettings),
leftoverSettings: allSettings
};
}
export function resolveExtensionsSettings(groups: ISettingsGroup[]): ITOCEntry {
const settingsGroupToEntry = (group: ISettingsGroup) => {
const flatSettings = arrays.flatten(
group.sections.map(section => section.settings));
return {
id: group.id,
label: group.title,
settings: flatSettings
};
};
const extGroups = groups
.sort((a, b) => a.title.localeCompare(b.title))
.map(g => settingsGroupToEntry(g));
return {
id: 'extensions',
label: localize('extensions', "Extensions"),
children: extGroups
};
}
function _resolveSettingsTree(tocData: ITOCEntry, allSettings: Set<ISetting>): ITOCEntry {
let children: ITOCEntry[];
if (tocData.children) {
children = tocData.children
.map(child => _resolveSettingsTree(child, allSettings))
.filter(child => (child.children && child.children.length) || (child.settings && child.settings.length));
}
let settings: ISetting[];
if (tocData.settings) {
settings = arrays.flatten(tocData.settings.map(pattern => getMatchingSettings(allSettings, <string>pattern)));
}
if (!children && !settings) {
return null;
}
return {
id: tocData.id,
label: tocData.label,
children,
settings
};
}
function getMatchingSettings(allSettings: Set<ISetting>, pattern: string): ISetting[] {
const result: ISetting[] = [];
allSettings.forEach(s => {
if (settingMatches(s, pattern)) {
result.push(s);
allSettings.delete(s);
}
});
return result.sort((a, b) => a.key.localeCompare(b.key));
}
const settingPatternCache = new Map<string, RegExp>();
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 (let group of settingsGroups) {
for (let section of group.sections) {
for (let s of section.settings) {
if (!s.overrides || !s.overrides.length) {
result.add(s);
}
}
}
}
return result;
}
export class SettingsDataSource implements IDataSource {
getId(tree: ITree, element: SettingsTreeElement): string {
return element.id;
}
hasChildren(tree: ITree, element: SettingsTreeElement): boolean {
if (element instanceof SettingsTreeGroupElement) {
return true;
}
return false;
}
getChildren(tree: ITree, element: SettingsTreeElement): TPromise<any> {
return TPromise.as(this._getChildren(element));
}
private _getChildren(element: SettingsTreeElement): SettingsTreeElement[] {
if (element instanceof SettingsTreeGroupElement) {
return element.children;
} else {
// No children...
return null;
}
}
getParent(tree: ITree, element: SettingsTreeElement): TPromise<any> {
return TPromise.wrap(element && element.parent);
}
shouldAutoexpand(): boolean {
return true;
}
}
export class SimplePagedDataSource implements IDataSource {
private static readonly SETTINGS_PER_PAGE = 30;
private static readonly BUFFER = 5;
private loadedToIndex: number;
constructor(private realDataSource: IDataSource) {
this.reset();
}
reset(): void {
this.loadedToIndex = SimplePagedDataSource.SETTINGS_PER_PAGE * 2;
}
pageTo(index: number, top = false): boolean {
const buffer = top ? SimplePagedDataSource.SETTINGS_PER_PAGE : SimplePagedDataSource.BUFFER;
if (index > this.loadedToIndex - buffer) {
this.loadedToIndex = (Math.ceil(index / SimplePagedDataSource.SETTINGS_PER_PAGE) + 1) * SimplePagedDataSource.SETTINGS_PER_PAGE;
return true;
} else {
return false;
}
}
getId(tree: ITree, element: any): string {
return this.realDataSource.getId(tree, element);
}
hasChildren(tree: ITree, element: any): boolean {
return this.realDataSource.hasChildren(tree, element);
}
getChildren(tree: ITree, element: SettingsTreeGroupElement): TPromise<any> {
return this.realDataSource.getChildren(tree, element).then(realChildren => {
return this._getChildren(realChildren);
});
}
_getChildren(realChildren: SettingsTreeElement[]): any[] {
const lastChild = realChildren[realChildren.length - 1];
if (lastChild && lastChild.index > this.loadedToIndex) {
return realChildren.filter(child => {
return child.index < this.loadedToIndex;
});
} else {
return realChildren;
}
}
getParent(tree: ITree, element: any): TPromise<any> {
return this.realDataSource.getParent(tree, element);
}
shouldAutoexpand(tree: ITree, element: any): boolean {
return this.realDataSource.shouldAutoexpand(tree, element);
}
}
interface IDisposableTemplate {
toDispose: IDisposable[];
}
interface ISettingItemTemplate<T = any> extends IDisposableTemplate {
onChange?: (value: T) => void;
context?: SettingsTreeSettingElement;
containerElement: HTMLElement;
categoryElement: HTMLElement;
labelElement: HTMLElement;
descriptionElement: HTMLElement;
controlElement: HTMLElement;
deprecationWarningElement: HTMLElement;
otherOverridesElement: HTMLElement;
toolbar: ToolBar;
}
interface ISettingBoolItemTemplate extends ISettingItemTemplate<boolean> {
checkbox: Checkbox;
}
interface ISettingTextItemTemplate extends ISettingItemTemplate<string> {
inputBox: InputBox;
validationErrorMessageElement: HTMLElement;
}
type ISettingNumberItemTemplate = ISettingTextItemTemplate;
interface ISettingEnumItemTemplate extends ISettingItemTemplate<number> {
selectBox: SelectBox;
enumDescriptionElement: HTMLElement;
}
interface ISettingComplexItemTemplate extends ISettingItemTemplate<void> {
button: Button;
}
interface ISettingExcludeItemTemplate extends ISettingItemTemplate<void> {
excludeWidget: ExcludeSettingWidget;
}
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_NUMBER_TEMPLATE_ID = 'settings.number.template';
const SETTINGS_ENUM_TEMPLATE_ID = 'settings.enum.template';
const SETTINGS_BOOL_TEMPLATE_ID = 'settings.bool.template';
const SETTINGS_EXCLUDE_TEMPLATE_ID = 'settings.exclude.template';
const SETTINGS_COMPLEX_TEMPLATE_ID = 'settings.complex.template';
const SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID = 'settings.newExtensions.template';
const SETTINGS_GROUP_ELEMENT_TEMPLATE_ID = 'settings.group.template';
export interface ISettingChangeEvent {
key: string;
value: any; // undefined => reset/unconfigure
}
export interface ISettingLinkClickEvent {
source: SettingsTreeSettingElement;
targetKey: string;
}
export class SettingsRenderer implements ITreeRenderer {
public static readonly CONTROL_CLASS = 'setting-control-focus-target';
public static readonly CONTROL_SELECTOR = '.' + SettingsRenderer.CONTROL_CLASS;
public static readonly SETTING_KEY_ATTR = 'data-key';
private readonly _onDidChangeSetting: Emitter<ISettingChangeEvent> = new Emitter<ISettingChangeEvent>();
public readonly onDidChangeSetting: Event<ISettingChangeEvent> = this._onDidChangeSetting.event;
private readonly _onDidOpenSettings: Emitter<string> = new Emitter<string>();
public readonly onDidOpenSettings: Event<string> = this._onDidOpenSettings.event;
private readonly _onDidClickSettingLink: Emitter<ISettingLinkClickEvent> = new Emitter<ISettingLinkClickEvent>();
public readonly onDidClickSettingLink: Event<ISettingLinkClickEvent> = this._onDidClickSettingLink.event;
private readonly _onDidFocusSetting: Emitter<SettingsTreeSettingElement> = new Emitter<SettingsTreeSettingElement>();
public readonly onDidFocusSetting: Event<SettingsTreeSettingElement> = this._onDidFocusSetting.event;
private descriptionMeasureContainer: HTMLElement;
private longestSingleLineDescription = 0;
private rowHeightCache = new Map<string, number>();
private lastRenderedWidth: number;
private settingActions: IAction[];
constructor(
_measureContainer: HTMLElement,
@IThemeService private themeService: IThemeService,
@IContextViewService private contextViewService: IContextViewService,
@IOpenerService private readonly openerService: IOpenerService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@ICommandService private readonly commandService: ICommandService,
@IContextMenuService private contextMenuService: IContextMenuService
) {
this.descriptionMeasureContainer = $('.setting-item-description');
DOM.append(_measureContainer,
$('.setting-measure-container.monaco-tree-row', undefined,
$('.setting-item', undefined,
this.descriptionMeasureContainer)));
this.settingActions = [
new Action('settings.resetSetting', localize('resetSettingLabel', "Reset Setting"), undefined, undefined, (context: SettingsTreeSettingElement) => {
if (context) {
this._onDidChangeSetting.fire({ key: context.setting.key, value: undefined });
}
return TPromise.wrap(null);
}),
new Separator(),
this.instantiationService.createInstance(CopySettingIdAction),
this.instantiationService.createInstance(CopySettingAsJSONAction),
];
}
showContextMenu(element: SettingsTreeSettingElement, settingDOMElement: HTMLElement): void {
const toolbarElement: HTMLElement = settingDOMElement.querySelector('.toolbar-toggle-more');
if (toolbarElement) {
this.contextMenuService.showContextMenu({
getActions: () => TPromise.wrap(this.settingActions),
getAnchor: () => toolbarElement,
getActionsContext: () => element
});
}
}
updateWidth(width: number): void {
if (this.lastRenderedWidth !== width) {
this.rowHeightCache = new Map<string, number>();
}
this.longestSingleLineDescription = 0;
this.lastRenderedWidth = width;
}
getHeight(tree: ITree, element: SettingsTreeElement): number {
if (this.rowHeightCache.has(element.id) && !(element instanceof SettingsTreeSettingElement && isExcludeSetting(element.setting))) {
return this.rowHeightCache.get(element.id);
}
const h = this._getHeight(tree, element);
this.rowHeightCache.set(element.id, h);
return h;
}
_getHeight(tree: ITree, element: SettingsTreeElement): number {
if (element instanceof SettingsTreeGroupElement) {
if (element.isFirstGroup) {
return 31;
}
return 40 + (7 * element.level);
}
if (element instanceof SettingsTreeSettingElement) {
if (isExcludeSetting(element.setting)) {
return this._getExcludeSettingHeight(element);
} else {
return this.measureSettingElementHeight(tree, element);
}
}
if (element instanceof SettingsTreeNewExtensionsElement) {
return 40;
}
return 0;
}
_getExcludeSettingHeight(element: SettingsTreeSettingElement): number {
const displayValue = getExcludeDisplayValue(element);
return (displayValue.length + 1) * 22 + 66 + this.measureSettingDescription(element);
}
private measureSettingElementHeight(tree: ITree, element: SettingsTreeSettingElement): number {
let heightExcludingDescription = 86;
if (element.valueType === 'boolean') {
heightExcludingDescription = 60;
}
return heightExcludingDescription + this.measureSettingDescription(element);
}
private measureSettingDescription(element: SettingsTreeSettingElement): number {
if (element.description.length < this.longestSingleLineDescription * .8) {
// Most setting descriptions are one short line, so try to avoid measuring them.
// If the description is less than 80% of the longest single line description, assume this will also render to be one line.
return 18;
}
const boolMeasureClass = 'measure-bool-description';
if (element.valueType === 'boolean') {
this.descriptionMeasureContainer.classList.add(boolMeasureClass);
} else if (this.descriptionMeasureContainer.classList.contains(boolMeasureClass)) {
this.descriptionMeasureContainer.classList.remove(boolMeasureClass);
}
const shouldRenderMarkdown = element.setting.descriptionIsMarkdown && element.description.indexOf('\n- ') >= 0;
while (this.descriptionMeasureContainer.firstChild) {
this.descriptionMeasureContainer.removeChild(this.descriptionMeasureContainer.firstChild);
}
if (shouldRenderMarkdown) {
const text = fixSettingLinks(element.description);
const rendered = renderMarkdown({ value: text });
rendered.classList.add('setting-item-description-markdown');
this.descriptionMeasureContainer.appendChild(rendered);
return this.descriptionMeasureContainer.offsetHeight;
} else {
// Remove markdown links, setting links, backticks
const measureText = element.setting.descriptionIsMarkdown ?
fixSettingLinks(element.description)
.replace(/\[(.*)\]\(.*\)/g, '$1')
.replace(/`([^`]*)`/g, '$1') :
element.description;
this.descriptionMeasureContainer.innerText = measureText;
const h = this.descriptionMeasureContainer.offsetHeight;
if (h < 20 && measureText.length > this.longestSingleLineDescription) {
this.longestSingleLineDescription = measureText.length;
}
return h;
}
}
getTemplateId(tree: ITree, element: SettingsTreeElement): string {
if (element instanceof SettingsTreeGroupElement) {
return SETTINGS_GROUP_ELEMENT_TEMPLATE_ID;
}
if (element instanceof SettingsTreeSettingElement) {
if (element.valueType === 'boolean') {
return SETTINGS_BOOL_TEMPLATE_ID;
}
if (element.valueType === 'integer' || element.valueType === 'number' || element.valueType === 'nullable-integer' || element.valueType === 'nullable-number') {
return SETTINGS_NUMBER_TEMPLATE_ID;
}
if (element.valueType === 'string') {
return SETTINGS_TEXT_TEMPLATE_ID;
}
if (element.valueType === 'enum') {
return SETTINGS_ENUM_TEMPLATE_ID;
}
if (element.valueType === 'exclude') {
return SETTINGS_EXCLUDE_TEMPLATE_ID;
}
return SETTINGS_COMPLEX_TEMPLATE_ID;
}
if (element instanceof SettingsTreeNewExtensionsElement) {
return SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID;
}
return '';
}
renderTemplate(tree: ITree, templateId: string, container: HTMLElement) {
if (templateId === SETTINGS_GROUP_ELEMENT_TEMPLATE_ID) {
return this.renderGroupTitleTemplate(container);
}
if (templateId === SETTINGS_TEXT_TEMPLATE_ID) {
return this.renderSettingTextTemplate(tree, container);
}
if (templateId === SETTINGS_NUMBER_TEMPLATE_ID) {
return this.renderSettingNumberTemplate(tree, container);
}
if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
return this.renderSettingBoolTemplate(tree, container);
}
if (templateId === SETTINGS_ENUM_TEMPLATE_ID) {
return this.renderSettingEnumTemplate(tree, container);
}
if (templateId === SETTINGS_EXCLUDE_TEMPLATE_ID) {
return this.renderSettingExcludeTemplate(tree, container);
}
if (templateId === SETTINGS_COMPLEX_TEMPLATE_ID) {
return this.renderSettingComplexTemplate(tree, container);
}
if (templateId === SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID) {
return this.renderNewExtensionsTemplate(container);
}
return null;
}
private renderGroupTitleTemplate(container: HTMLElement): IGroupTitleTemplate {
DOM.addClass(container, 'group-title');
const toDispose = [];
const template: IGroupTitleTemplate = {
parent: container,
toDispose
};
return template;
}
private renderCommonTemplate(tree: ITree, container: HTMLElement, typeClass: string): ISettingItemTemplate {
DOM.addClass(container, 'setting-item');
DOM.addClass(container, 'setting-item-' + typeClass);
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 labelElement = DOM.append(labelCategoryContainer, $('span.setting-item-label'));
const otherOverridesElement = DOM.append(titleElement, $('span.setting-item-overrides'));
const descriptionElement = DOM.append(container, $('.setting-item-description'));
const modifiedIndicatorElement = DOM.append(container, $('.setting-item-modified-indicator'));
modifiedIndicatorElement.title = localize('modified', "Modified");
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 toDispose = [];
const toolbar = this.renderSettingToolbar(container);
const template: ISettingItemTemplate = {
toDispose,
containerElement: container,
categoryElement,
labelElement,
descriptionElement,
controlElement,
deprecationWarningElement,
otherOverridesElement,
toolbar
};
// Prevent clicks from being handled by list
toDispose.push(DOM.addDisposableListener(controlElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addStandardDisposableListener(valueElement, 'keydown', (e: StandardKeyboardEvent) => {
if (e.keyCode === KeyCode.Escape) {
tree.domFocus();
e.browserEvent.stopPropagation();
}
}));
return template;
}
private addSettingElementFocusHandler(template: ISettingItemTemplate): void {
const focusTracker = DOM.trackFocus(template.containerElement);
template.toDispose.push(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);
}
});
}
private renderSettingTextTemplate(tree: ITree, container: HTMLElement, type = 'text'): ISettingTextItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'text');
const validationErrorMessageElement = DOM.append(container, $('.setting-item-validation-message'));
const inputBox = new InputBox(common.controlElement, this.contextViewService);
common.toDispose.push(inputBox);
common.toDispose.push(attachInputBoxStyler(inputBox, this.themeService, {
inputBackground: settingsTextInputBackground,
inputForeground: settingsTextInputForeground,
inputBorder: settingsTextInputBorder
}));
common.toDispose.push(
inputBox.onDidChange(e => {
if (template.onChange) {
template.onChange(e);
}
}));
common.toDispose.push(inputBox);
inputBox.inputElement.classList.add(SettingsRenderer.CONTROL_CLASS);
const template: ISettingTextItemTemplate = {
...common,
inputBox,
validationErrorMessageElement
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderSettingNumberTemplate(tree: ITree, container: HTMLElement): ISettingNumberItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'number');
const validationErrorMessageElement = DOM.append(container, $('.setting-item-validation-message'));
const inputBox = new InputBox(common.controlElement, this.contextViewService, { type: 'number' });
common.toDispose.push(inputBox);
common.toDispose.push(attachInputBoxStyler(inputBox, this.themeService, {
inputBackground: settingsNumberInputBackground,
inputForeground: settingsNumberInputForeground,
inputBorder: settingsNumberInputBorder
}));
common.toDispose.push(
inputBox.onDidChange(e => {
if (template.onChange) {
template.onChange(e);
}
}));
common.toDispose.push(inputBox);
inputBox.inputElement.classList.add(SettingsRenderer.CONTROL_CLASS);
const template: ISettingNumberItemTemplate = {
...common,
inputBox,
validationErrorMessageElement
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderSettingToolbar(container: HTMLElement): ToolBar {
const toolbar = new ToolBar(container, this.contextMenuService, {});
toolbar.setActions([], this.settingActions)();
const button = container.querySelector('.toolbar-toggle-more');
if (button) {
(<HTMLElement>button).tabIndex = -1;
}
return toolbar;
}
private renderSettingBoolTemplate(tree: ITree, container: HTMLElement): ISettingBoolItemTemplate {
DOM.addClass(container, 'setting-item');
DOM.addClass(container, 'setting-item-bool');
const titleElement = DOM.append(container, $('.setting-item-title'));
const categoryElement = DOM.append(titleElement, $('span.setting-item-category'));
const labelElement = DOM.append(titleElement, $('span.setting-item-label'));
const otherOverridesElement = DOM.append(titleElement, $('span.setting-item-overrides'));
const descriptionAndValueElement = DOM.append(container, $('.setting-item-value-description'));
const controlElement = DOM.append(descriptionAndValueElement, $('.setting-item-bool-control'));
const descriptionElement = DOM.append(descriptionAndValueElement, $('.setting-item-description'));
const modifiedIndicatorElement = DOM.append(container, $('.setting-item-modified-indicator'));
modifiedIndicatorElement.title = localize('modified', "Modified");
const deprecationWarningElement = DOM.append(container, $('.setting-item-deprecation-message'));
const toDispose = [];
const checkbox = new Checkbox({ actionClassName: 'setting-value-checkbox', isChecked: true, title: '', inputActiveOptionBorder: null });
controlElement.appendChild(checkbox.domNode);
toDispose.push(checkbox);
toDispose.push(checkbox.onChange(() => {
if (template.onChange) {
template.onChange(checkbox.checked);
}
}));
// Need to listen for mouse clicks on description and toggle checkbox - use target ID for safety
// Also have to ignore embedded links - too buried to stop propagation
toDispose.push(DOM.addDisposableListener(descriptionElement, DOM.EventType.MOUSE_DOWN, (e) => {
const targetElement = <HTMLElement>e.toElement;
const targetId = descriptionElement.getAttribute('checkbox_label_target_id');
// Make sure we are not a link and the target ID matches
// Toggle target checkbox
if (targetElement.tagName.toLowerCase() !== 'a' && targetId === template.checkbox.domNode.id) {
template.checkbox.checked = template.checkbox.checked ? false : true;
template.onChange(checkbox.checked);
}
DOM.EventHelper.stop(e);
}));
checkbox.domNode.classList.add(SettingsRenderer.CONTROL_CLASS);
const toolbar = this.renderSettingToolbar(container);
toDispose.push(toolbar);
const template: ISettingBoolItemTemplate = {
toDispose,
containerElement: container,
categoryElement,
labelElement,
controlElement,
checkbox,
descriptionElement,
deprecationWarningElement,
otherOverridesElement,
toolbar
};
this.addSettingElementFocusHandler(template);
// Prevent clicks from being handled by list
toDispose.push(DOM.addDisposableListener(controlElement, 'mousedown', (e: IMouseEvent) => e.stopPropagation()));
toDispose.push(DOM.addStandardDisposableListener(controlElement, 'keydown', (e: StandardKeyboardEvent) => {
if (e.keyCode === KeyCode.Escape) {
tree.domFocus();
e.browserEvent.stopPropagation();
}
}));
return template;
}
public cancelSuggesters() {
this.contextViewService.hideContextView();
}
private renderSettingEnumTemplate(tree: ITree, container: HTMLElement): ISettingEnumItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'enum');
const selectBox = new SelectBox([], undefined, this.contextViewService, undefined, {
hasDetails: true
});
common.toDispose.push(selectBox);
common.toDispose.push(attachSelectBoxStyler(selectBox, this.themeService, {
selectBackground: settingsSelectBackground,
selectForeground: settingsSelectForeground,
selectBorder: settingsSelectBorder,
selectListBorder: settingsSelectListBorder
}));
selectBox.render(common.controlElement);
const selectElement = common.controlElement.querySelector('select');
if (selectElement) {
selectElement.classList.add(SettingsRenderer.CONTROL_CLASS);
}
common.toDispose.push(
selectBox.onDidSelect(e => {
if (template.onChange) {
template.onChange(e.index);
}
}));
const enumDescriptionElement = common.containerElement.insertBefore($('.setting-item-enumDescription'), common.descriptionElement.nextSibling);
const template: ISettingEnumItemTemplate = {
...common,
selectBox,
enumDescriptionElement
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderSettingExcludeTemplate(tree: ITree, container: HTMLElement): ISettingExcludeItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'exclude');
const excludeWidget = this.instantiationService.createInstance(ExcludeSettingWidget, common.controlElement);
excludeWidget.domNode.classList.add(SettingsRenderer.CONTROL_CLASS);
common.toDispose.push(excludeWidget);
const template: ISettingExcludeItemTemplate = {
...common,
excludeWidget
};
this.addSettingElementFocusHandler(template);
common.toDispose.push(excludeWidget.onDidChangeExclude(e => {
if (template.context) {
let newValue = { ...template.context.scopeValue };
// first delete the existing entry, if present
if (e.originalPattern) {
if (e.originalPattern in template.context.defaultValue) {
// delete a default by overriding it
newValue[e.originalPattern] = false;
} else {
delete newValue[e.originalPattern];
}
}
// then add the new or updated entry, if present
if (e.pattern) {
if (e.pattern in template.context.defaultValue && !e.sibling) {
// add a default by deleting its override
delete newValue[e.pattern];
} else {
newValue[e.pattern] = e.sibling ? { when: e.sibling } : true;
}
}
const sortKeys = (obj) => {
const keyArray = Object.keys(obj)
.map(key => ({ key, val: obj[key] }))
.sort((a, b) => a.key.localeCompare(b.key));
const retVal = {};
keyArray.forEach(pair => {
retVal[pair.key] = pair.val;
});
return retVal;
};
this._onDidChangeSetting.fire({
key: template.context.setting.key,
value: Object.keys(newValue).length === 0 ? undefined : sortKeys(newValue)
});
}
}));
return template;
}
private renderSettingComplexTemplate(tree: ITree, container: HTMLElement): ISettingComplexItemTemplate {
const common = this.renderCommonTemplate(tree, container, 'complex');
const openSettingsButton = new Button(common.controlElement, { title: true, buttonBackground: null, buttonHoverBackground: null });
common.toDispose.push(openSettingsButton);
common.toDispose.push(openSettingsButton.onDidClick(() => template.onChange(null)));
openSettingsButton.label = localize('editInSettingsJson', "Edit in settings.json");
openSettingsButton.element.classList.add('edit-in-settings-button');
common.toDispose.push(attachButtonStyler(openSettingsButton, this.themeService, {
buttonBackground: Color.transparent.toString(),
buttonHoverBackground: Color.transparent.toString(),
buttonForeground: 'foreground'
}));
const template: ISettingComplexItemTemplate = {
...common,
button: openSettingsButton
};
this.addSettingElementFocusHandler(template);
return template;
}
private renderNewExtensionsTemplate(container: HTMLElement): ISettingNewExtensionsTemplate {
const toDispose = [];
container.classList.add('setting-item-new-extensions');
const button = new Button(container, { title: true, buttonBackground: null, buttonHoverBackground: null });
toDispose.push(button);
toDispose.push(button.onDidClick(() => {
if (template.context) {
this.commandService.executeCommand('workbench.extensions.action.showExtensionsWithIds', template.context.extensionIds);
}
}));
button.label = localize('newExtensionsButtonLabel', "Show matching extensions");
button.element.classList.add('settings-new-extensions-button');
toDispose.push(attachButtonStyler(button, this.themeService));
const template: ISettingNewExtensionsTemplate = {
button,
toDispose
};
// this.addSettingElementFocusHandler(template);
return template;
}
renderElement(tree: ITree, element: SettingsTreeElement, templateId: string, template: any): void {
if (templateId === SETTINGS_GROUP_ELEMENT_TEMPLATE_ID) {
return this.renderGroupElement(<SettingsTreeGroupElement>element, template);
}
if (templateId === SETTINGS_NEW_EXTENSIONS_TEMPLATE_ID) {
return this.renderNewExtensionsElement(<SettingsTreeNewExtensionsElement>element, template);
}
return this.renderSettingElement(tree, <SettingsTreeSettingElement>element, templateId, template);
}
private renderGroupElement(element: SettingsTreeGroupElement, template: IGroupTitleTemplate): void {
template.parent.innerHTML = '';
const labelElement = DOM.append(template.parent, $('div.settings-group-title-label'));
labelElement.classList.add(`settings-group-level-${element.level}`);
labelElement.textContent = (<SettingsTreeGroupElement>element).label;
if (element.isFirstGroup) {
labelElement.classList.add('settings-group-first');
}
}
private renderNewExtensionsElement(element: SettingsTreeNewExtensionsElement, template: ISettingNewExtensionsTemplate): void {
template.context = element;
}
public getSettingDOMElementForDOMElement(domElement: HTMLElement): HTMLElement {
const parent = DOM.findParentWithClass(domElement, 'setting-item');
if (parent) {
return parent;
}
return null;
}
public getDOMElementsForSettingKey(treeContainer: HTMLElement, key: string): NodeListOf<HTMLElement> {
return treeContainer.querySelectorAll(`[${SettingsRenderer.SETTING_KEY_ATTR}="${key}"]`);
}
public getKeyForDOMElementInSetting(element: HTMLElement): string {
const settingElement = this.getSettingDOMElementForDOMElement(element);
return settingElement && settingElement.getAttribute(SettingsRenderer.SETTING_KEY_ATTR);
}
private renderSettingElement(tree: ITree, element: SettingsTreeSettingElement, templateId: string, template: ISettingItemTemplate | ISettingBoolItemTemplate): void {
template.context = element;
template.toolbar.context = element;
const setting = element.setting;
DOM.toggleClass(template.containerElement, 'is-configured', element.isConfigured);
DOM.toggleClass(template.containerElement, 'is-expanded', true);
template.containerElement.setAttribute(SettingsRenderer.SETTING_KEY_ATTR, element.setting.key);
const titleTooltip = setting.key + (element.isConfigured ? ' - Modified' : '');
template.categoryElement.textContent = element.displayCategory && (element.displayCategory + ': ');
template.categoryElement.title = titleTooltip;
template.labelElement.textContent = element.displayLabel;
template.labelElement.title = titleTooltip;
this.renderValue(element, templateId, <ISettingItemTemplate>template);
template.descriptionElement.innerHTML = '';
if (element.setting.descriptionIsMarkdown) {
const renderedDescription = this.renderDescriptionMarkdown(element, element.description, template.toDispose);
template.descriptionElement.appendChild(renderedDescription);
} else {
template.descriptionElement.innerText = element.description;
}
const baseId = (element.displayCategory + '_' + element.displayLabel).replace(/ /g, '_').toLowerCase();
template.descriptionElement.id = baseId + '_setting_description';
if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
// Add checkbox target to description clickable and able to toggle checkbox
template.descriptionElement.setAttribute('checkbox_label_target_id', baseId + '_setting_item');
}
if (element.overriddenScopeList.length) {
let otherOverridesLabel = element.isConfigured ?
localize('alsoConfiguredIn', "Also modified in") :
localize('configuredIn', "Modified in");
template.otherOverridesElement.textContent = `(${otherOverridesLabel}: ${element.overriddenScopeList.join(', ')})`;
} else {
template.otherOverridesElement.textContent = '';
}
// Remove tree attributes - sometimes overridden by tree - should be managed there
template.containerElement.parentElement.removeAttribute('role');
template.containerElement.parentElement.removeAttribute('aria-level');
template.containerElement.parentElement.removeAttribute('aria-posinset');
template.containerElement.parentElement.removeAttribute('aria-setsize');
}
private renderDescriptionMarkdown(element: SettingsTreeSettingElement, text: string, disposeables: IDisposable[]): HTMLElement {
// Rewrite `#editor.fontSize#` to link format
text = fixSettingLinks(text);
const renderedMarkdown = renderMarkdown({ value: text }, {
actionHandler: {
callback: (content: string) => {
if (startsWith(content, '#')) {
const e: ISettingLinkClickEvent = {
source: element,
targetKey: content.substr(1)
};
this._onDidClickSettingLink.fire(e);
} else {
this.openerService.open(URI.parse(content)).then(void 0, onUnexpectedError);
}
},
disposeables
}
});
renderedMarkdown.classList.add('setting-item-description-markdown');
cleanRenderedMarkdown(renderedMarkdown);
return renderedMarkdown;
}
private renderValue(element: SettingsTreeSettingElement, templateId: string, template: ISettingItemTemplate | ISettingBoolItemTemplate): void {
const onChange = value => this._onDidChangeSetting.fire({ key: element.setting.key, value });
template.deprecationWarningElement.innerText = element.setting.deprecationMessage || '';
if (templateId === SETTINGS_ENUM_TEMPLATE_ID) {
this.renderEnum(element, <ISettingEnumItemTemplate>template, onChange);
} else if (templateId === SETTINGS_TEXT_TEMPLATE_ID) {
this.renderText(element, <ISettingTextItemTemplate>template, onChange);
} else if (templateId === SETTINGS_NUMBER_TEMPLATE_ID) {
this.renderNumber(element, <ISettingTextItemTemplate>template, onChange);
} else if (templateId === SETTINGS_BOOL_TEMPLATE_ID) {
this.renderBool(element, <ISettingBoolItemTemplate>template, onChange);
} else if (templateId === SETTINGS_EXCLUDE_TEMPLATE_ID) {
this.renderExcludeSetting(element, <ISettingExcludeItemTemplate>template);
} else if (templateId === SETTINGS_COMPLEX_TEMPLATE_ID) {
this.renderComplexSetting(element, <ISettingComplexItemTemplate>template);
}
}
private renderBool(dataElement: SettingsTreeSettingElement, template: ISettingBoolItemTemplate, onChange: (value: boolean) => void): void {
template.onChange = null;
template.checkbox.checked = dataElement.value;
template.onChange = onChange;
// Setup and add ARIA attributes
// Create id and label for control/input element - parent is wrapper div
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' ' + modifiedText;
// We use the parent control div for the aria-labelledby target
// Does not appear you can use the direct label on the element itself within a tree
template.checkbox.domNode.parentElement.id = baseId + '_setting_label';
template.checkbox.domNode.parentElement.setAttribute('aria-label', label);
// Labels will not be read on descendent input elements of the parent treeitem
// unless defined as role=treeitem and indirect aria-labelledby approach
template.checkbox.domNode.id = baseId + '_setting_item';
template.checkbox.domNode.setAttribute('role', 'checkbox');
template.checkbox.domNode.setAttribute('aria-labelledby', baseId + '_setting_label');
template.checkbox.domNode.setAttribute('aria-describedby', baseId + '_setting_description');
}
private renderEnum(dataElement: SettingsTreeSettingElement, template: ISettingEnumItemTemplate, onChange: (value: string) => void): void {
const displayOptions = dataElement.setting.enum
.map(String)
.map(escapeInvisibleChars);
template.selectBox.setOptions(displayOptions);
const enumDescriptions = dataElement.setting.enumDescriptions;
const enumDescriptionsAreMarkdown = dataElement.setting.enumDescriptionsAreMarkdown;
template.selectBox.setDetailsProvider(index =>
({
details: enumDescriptions && enumDescriptions[index] && (enumDescriptionsAreMarkdown ? fixSettingLinks(enumDescriptions[index], false) : enumDescriptions[index]),
isMarkdown: enumDescriptionsAreMarkdown
}));
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' ' + modifiedText;
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
template.selectBox.setAriaLabel(label);
const idx = dataElement.setting.enum.indexOf(dataElement.value);
template.onChange = null;
template.selectBox.select(idx);
template.onChange = idx => onChange(dataElement.setting.enum[idx]);
if (template.controlElement.firstElementChild) {
// SelectBox needs to have treeitem changed to combobox to read correctly within tree
template.controlElement.firstElementChild.setAttribute('role', 'combobox');
template.controlElement.firstElementChild.setAttribute('aria-describedby', baseId + '_setting_description');
}
template.enumDescriptionElement.innerHTML = '';
}
private renderText(dataElement: SettingsTreeSettingElement, template: ISettingTextItemTemplate, onChange: (value: string) => void): void {
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' ' + modifiedText; template.onChange = null;
template.inputBox.value = dataElement.value;
template.onChange = value => { renderValidations(dataElement, template, false, label); onChange(value); };
// Setup and add ARIA attributes
// Create id and label for control/input element - parent is wrapper div
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
// We use the parent control div for the aria-labelledby target
// Does not appear you can use the direct label on the element itself within a tree
template.inputBox.inputElement.parentElement.id = baseId + '_setting_label';
template.inputBox.inputElement.parentElement.setAttribute('aria-label', label);
// Labels will not be read on descendent input elements of the parent treeitem
// unless defined as role=treeitem and indirect aria-labelledby approach
template.inputBox.inputElement.id = baseId + '_setting_item';
template.inputBox.inputElement.setAttribute('role', 'textbox');
template.inputBox.inputElement.setAttribute('aria-labelledby', baseId + '_setting_label');
template.inputBox.inputElement.setAttribute('aria-describedby', baseId + '_setting_description');
renderValidations(dataElement, template, true, label);
}
private renderNumber(dataElement: SettingsTreeSettingElement, template: ISettingTextItemTemplate, onChange: (value: number) => void): void {
const modifiedText = dataElement.isConfigured ? 'Modified' : '';
const label = dataElement.displayCategory + ' ' + dataElement.displayLabel + ' number ' + modifiedText; const numParseFn = (dataElement.valueType === 'integer' || dataElement.valueType === 'nullable-integer')
? parseInt : parseFloat;
const nullNumParseFn = (dataElement.valueType === 'nullable-integer' || dataElement.valueType === 'nullable-number')
? (v => v === '' ? null : numParseFn(v)) : numParseFn;
template.onChange = null;
template.inputBox.value = dataElement.value;
template.onChange = value => { renderValidations(dataElement, template, false, label); onChange(nullNumParseFn(value)); };
// Setup and add ARIA attributes
// Create id and label for control/input element - parent is wrapper div
const baseId = (dataElement.displayCategory + '_' + dataElement.displayLabel).replace(/ /g, '_').toLowerCase();
// We use the parent control div for the aria-labelledby target
// Does not appear you can use the direct label on the element itself within a tree
template.inputBox.inputElement.parentElement.id = baseId + '_setting_label';
template.inputBox.inputElement.parentElement.setAttribute('aria-label', label);
// Labels will not be read on descendent input elements of the parent treeitem
// unless defined as role=treeitem and indirect aria-labelledby approach
template.inputBox.inputElement.id = baseId + '_setting_item';
template.inputBox.inputElement.setAttribute('role', 'textbox');
template.inputBox.inputElement.setAttribute('aria-labelledby', baseId + '_setting_label');
template.inputBox.inputElement.setAttribute('aria-describedby', baseId + '_setting_description');
renderValidations(dataElement, template, true, label);
}
private renderExcludeSetting(dataElement: SettingsTreeSettingElement, template: ISettingExcludeItemTemplate): void {
const value = getExcludeDisplayValue(dataElement);
template.excludeWidget.setValue(value);
template.context = dataElement;
}
private renderComplexSetting(dataElement: SettingsTreeSettingElement, template: ISettingComplexItemTemplate): void {
template.onChange = () => this._onDidOpenSettings.fire(dataElement.setting.key);
}
disposeTemplate(tree: ITree, templateId: string, template: IDisposableTemplate): void {
dispose(template.toDispose);
}
}
function renderValidations(dataElement: SettingsTreeSettingElement, template: ISettingTextItemTemplate, calledOnStartup: boolean, originalAriaLabel: string) {
if (dataElement.setting.validator) {
let errMsg = dataElement.setting.validator(template.inputBox.value);
if (errMsg) {
DOM.addClass(template.containerElement, 'invalid-input');
template.validationErrorMessageElement.innerText = errMsg;
let validationError = localize('validationError', "Validation Error.");
template.inputBox.inputElement.parentElement.setAttribute('aria-label', [originalAriaLabel, validationError, errMsg].join(' '));
if (!calledOnStartup) { ariaAlert(validationError + ' ' + errMsg); }
return;
} else {
template.inputBox.inputElement.parentElement.setAttribute('aria-label', originalAriaLabel);
}
}
DOM.removeClass(template.containerElement, 'invalid-input');
}
function cleanRenderedMarkdown(element: Node): void {
for (let i = 0; i < element.childNodes.length; i++) {
const child = element.childNodes.item(i);
const tagName = (<Element>child).tagName && (<Element>child).tagName.toLowerCase();
if (tagName === 'img') {
element.removeChild(child);
} else {
cleanRenderedMarkdown(child);
}
}
}
function fixSettingLinks(text: string, linkify = true): string {
return text.replace(/`#([^#]*)#`/g, (match, settingKey) => {
const targetDisplayFormat = settingKeyToDisplayFormat(settingKey);
const targetName = `${targetDisplayFormat.category}: ${targetDisplayFormat.label}`;
return linkify ?
`[${targetName}](#${settingKey})` :
`"${targetName}"`;
});
}
function escapeInvisibleChars(enumValue: string): string {
return enumValue && enumValue
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r');
}
export class SettingsTreeFilter implements IFilter {
constructor(
private viewState: ISettingsEditorViewState,
) { }
isVisible(tree: ITree, element: SettingsTreeElement): boolean {
// Filter during search
if (this.viewState.filterToCategory && element instanceof SettingsTreeSettingElement) {
if (!this.settingContainedInGroup(element.setting, this.viewState.filterToCategory)) {
return false;
}
}
if (element instanceof SettingsTreeSettingElement && this.viewState.tagFilters) {
return element.matchesAllTags(this.viewState.tagFilters);
}
if (element instanceof SettingsTreeGroupElement) {
if (typeof element.count === 'number') {
return element.count > 0;
}
return element.children.some(child => this.isVisible(tree, child));
}
if (element instanceof SettingsTreeNewExtensionsElement) {
if ((this.viewState.tagFilters && this.viewState.tagFilters.size) || this.viewState.filterToCategory) {
return false;
}
}
return true;
}
private settingContainedInGroup(setting: ISetting, group: SettingsTreeGroupElement): boolean {
return group.children.some(child => {
if (child instanceof SettingsTreeGroupElement) {
return this.settingContainedInGroup(setting, child);
} else if (child instanceof SettingsTreeSettingElement) {
return child.setting.key === setting.key;
} else {
return false;
}
});
}
}
export class SettingsTreeController extends WorkbenchTreeController {
constructor(
@IConfigurationService configurationService: IConfigurationService
) {
super({}, configurationService);
}
protected onLeftClick(tree: ITree, element: any, eventish: IMouseEvent, origin?: string): boolean {
const isLink = eventish.target.tagName.toLowerCase() === 'a' ||
eventish.target.parentElement.tagName.toLowerCase() === 'a'; // <code> inside <a>
if (isLink && (DOM.findParentWithClass(eventish.target, 'setting-item-description-markdown', tree.getHTMLElement()) || DOM.findParentWithClass(eventish.target, 'select-box-description-markdown'))) {
return true;
}
return false;
}
}
export class SettingsAccessibilityProvider implements IAccessibilityProvider {
getAriaLabel(tree: ITree, element: SettingsTreeElement): string {
if (!element) {
return '';
}
if (element instanceof SettingsTreeSettingElement) {
return localize('settingRowAriaLabel', "{0} {1}, Setting", element.displayCategory, element.displayLabel);
}
if (element instanceof SettingsTreeGroupElement) {
return localize('groupRowAriaLabel', "{0}, group", element.label);
}
return '';
}
}
class NonExpandableOrSelectableTree extends Tree {
expand(): TPromise<any> {
return TPromise.wrap(null);
}
collapse(): TPromise<any> {
return TPromise.wrap(null);
}
public setFocus(element?: any, eventPayload?: any): void {
return;
}
public focusNext(count?: number, eventPayload?: any): void {
return;
}
public focusPrevious(count?: number, eventPayload?: any): void {
return;
}
public focusParent(eventPayload?: any): void {
return;
}
public focusFirstChild(eventPayload?: any): void {
return;
}
public focusFirst(eventPayload?: any, from?: any): void {
return;
}
public focusNth(index: number, eventPayload?: any): void {
return;
}
public focusLast(eventPayload?: any, from?: any): void {
return;
}
public focusNextPage(eventPayload?: any): void {
return;
}
public focusPreviousPage(eventPayload?: any): void {
return;
}
public select(element: any, eventPayload?: any): void {
return;
}
public selectRange(fromElement: any, toElement: any, eventPayload?: any): void {
return;
}
public selectAll(elements: any[], eventPayload?: any): void {
return;
}
public setSelection(elements: any[], eventPayload?: any): void {
return;
}
public toggleSelection(element: any, eventPayload?: any): void {
return;
}
}
export class SettingsTree extends NonExpandableOrSelectableTree {
protected disposables: IDisposable[];
constructor(
container: HTMLElement,
viewState: ISettingsEditorViewState,
configuration: Partial<ITreeConfiguration>,
@IThemeService themeService: IThemeService,
@IInstantiationService instantiationService: IInstantiationService
) {
const treeClass = 'settings-editor-tree';
const controller = instantiationService.createInstance(SettingsTreeController);
const fullConfiguration = <ITreeConfiguration>{
controller,
accessibilityProvider: instantiationService.createInstance(SettingsAccessibilityProvider),
filter: instantiationService.createInstance(SettingsTreeFilter, viewState),
styler: new DefaultTreestyler(DOM.createStyleSheet(container), treeClass),
...configuration
};
const options = {
ariaLabel: localize('treeAriaLabel', "Settings"),
showLoading: false,
indentPixels: 0,
twistiePixels: 20, // Actually for gear button
};
super(container,
fullConfiguration,
options);
this.disposables = [];
this.disposables.push(controller);
this.disposables.push(registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
const activeBorderColor = theme.getColor(focusBorder);
if (activeBorderColor) {
// TODO@rob - why isn't this applied when added to the stylesheet from tocTree.ts? Seems like a chromium glitch.
collector.addRule(`.settings-editor > .settings-body > .settings-toc-container .monaco-tree:focus .monaco-tree-row.focused {outline: solid 1px ${activeBorderColor}; outline-offset: -1px; }`);
}
const foregroundColor = theme.getColor(foreground);
if (foregroundColor) {
// Links appear inside other elements in markdown. CSS opacity acts like a mask. So we have to dynamically compute the description color to avoid
// applying an opacity to the link color.
const fgWithOpacity = new Color(new RGBA(foregroundColor.rgba.r, foregroundColor.rgba.g, foregroundColor.rgba.b, .9));
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-description { color: ${fgWithOpacity}; }`);
}
const errorColor = theme.getColor(errorForeground);
if (errorColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-deprecation-message { color: ${errorColor}; }`);
}
const invalidInputBackground = theme.getColor(inputValidationErrorBackground);
if (invalidInputBackground) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-validation-message { background-color: ${invalidInputBackground}; }`);
}
const invalidInputForeground = theme.getColor(inputValidationErrorForeground);
if (invalidInputForeground) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-validation-message { color: ${invalidInputForeground}; }`);
}
const invalidInputBorder = theme.getColor(inputValidationErrorBorder);
if (invalidInputBorder) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-validation-message { border-style:solid; border-width: 1px; border-color: ${invalidInputBorder}; }`);
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item.invalid-input .setting-item-control .monaco-inputbox.idle { outline-width: 0; border-style:solid; border-width: 1px; border-color: ${invalidInputBorder}; }`);
}
const headerForegroundColor = theme.getColor(settingsHeaderForeground);
if (headerForegroundColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .settings-group-title-label { color: ${headerForegroundColor}; }`);
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item-label { color: ${headerForegroundColor}; }`);
}
const focusBorderColor = theme.getColor(focusBorder);
if (focusBorderColor) {
collector.addRule(`.settings-editor > .settings-body > .settings-tree-container .setting-item .setting-item-description-markdown a:focus { outline-color: ${focusBorderColor} }`);
}
}));
this.getHTMLElement().classList.add(treeClass);
this.disposables.push(attachStyler(themeService, {
listActiveSelectionBackground: editorBackground,
listActiveSelectionForeground: foreground,
listFocusAndSelectionBackground: editorBackground,
listFocusAndSelectionForeground: foreground,
listFocusBackground: editorBackground,
listFocusForeground: foreground,
listHoverForeground: foreground,
listHoverBackground: editorBackground,
listHoverOutline: editorBackground,
listFocusOutline: editorBackground,
listInactiveSelectionBackground: editorBackground,
listInactiveSelectionForeground: foreground
}, colors => {
this.style(colors);
}));
}
}
class CopySettingIdAction extends Action {
static readonly ID = 'settings.copySettingId';
static readonly LABEL = localize('copySettingIdLabel', "Copy Setting ID");
constructor(
@IClipboardService private clipboardService: IClipboardService
) {
super(CopySettingIdAction.ID, CopySettingIdAction.LABEL);
}
run(context: SettingsTreeSettingElement): TPromise<void> {
if (context) {
this.clipboardService.writeText(context.setting.key);
}
return TPromise.as(null);
}
}
class CopySettingAsJSONAction extends Action {
static readonly ID = 'settings.copySettingAsJSON';
static readonly LABEL = localize('copySettingAsJSONLabel', "Copy Setting as JSON");
constructor(
@IClipboardService private clipboardService: IClipboardService
) {
super(CopySettingAsJSONAction.ID, CopySettingAsJSONAction.LABEL);
}
run(context: SettingsTreeSettingElement): TPromise<void> {
if (context) {
const jsonResult = `"${context.setting.key}": ${JSON.stringify(context.value, undefined, ' ')}`;
this.clipboardService.writeText(jsonResult);
}
return TPromise.as(null);
}
} | src/vs/workbench/parts/preferences/browser/settingsTree.ts | 1 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.9984493255615234,
0.0430155023932457,
0.00016373192192986608,
0.00017502714763395488,
0.1932973563671112
]
|
{
"id": 6,
"code_window": [
"\t}\n",
"\n",
"\tprivate renderSettingToolbar(container: HTMLElement): ToolBar {\n",
"\t\tconst toolbar = new ToolBar(container, this.contextMenuService, {});\n",
"\t\ttoolbar.setActions([], this.settingActions)();\n",
"\t\tconst button = container.querySelector('.toolbar-toggle-more');\n",
"\t\tif (button) {\n",
"\t\t\t(<HTMLElement>button).tabIndex = -1;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst toggleMenuKeybinding = this.keybindingService.lookupKeybinding(SETTINGS_EDITOR_COMMAND_SHOW_CONTEXT_MENU);\n",
"\t\tlet toggleMenuTitle = localize('settingsContextMenuTitle', \"More Actions... \");\n",
"\t\tif (toggleMenuKeybinding) {\n",
"\t\t\ttoggleMenuTitle += ` (${toggleMenuKeybinding && toggleMenuKeybinding.getLabel()})`;\n",
"\t\t}\n",
"\n",
"\t\tconst toolbar = new ToolBar(container, this.contextMenuService, {\n",
"\t\t\ttoggleMenuTitle\n",
"\t\t});\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "replace",
"edit_start_line_idx": 720
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { ServiceCollection } from './serviceCollection';
import * as descriptors from './descriptors';
// ------ internal util
export namespace _util {
export const serviceIds = new Map<string, ServiceIdentifier<any>>();
export const DI_TARGET = '$di$target';
export const DI_DEPENDENCIES = '$di$dependencies';
export function getServiceDependencies(ctor: any): { id: ServiceIdentifier<any>, index: number, optional: boolean }[] {
return ctor[DI_DEPENDENCIES] || [];
}
}
// --- interfaces ------
export interface IConstructorSignature0<T> {
new(...services: { _serviceBrand: any; }[]): T;
}
export interface IConstructorSignature1<A1, T> {
new(first: A1, ...services: { _serviceBrand: any; }[]): T;
}
export interface IConstructorSignature2<A1, A2, T> {
new(first: A1, second: A2, ...services: { _serviceBrand: any; }[]): T;
}
export interface IConstructorSignature3<A1, A2, A3, T> {
new(first: A1, second: A2, third: A3, ...services: { _serviceBrand: any; }[]): T;
}
export interface IConstructorSignature4<A1, A2, A3, A4, T> {
new(first: A1, second: A2, third: A3, fourth: A4, ...services: { _serviceBrand: any; }[]): T;
}
export interface IConstructorSignature5<A1, A2, A3, A4, A5, T> {
new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, ...services: { _serviceBrand: any; }[]): T;
}
export interface IConstructorSignature6<A1, A2, A3, A4, A5, A6, T> {
new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, ...services: { _serviceBrand: any; }[]): T;
}
export interface IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T> {
new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, ...services: { _serviceBrand: any; }[]): T;
}
export interface IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T> {
new(first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8, ...services: { _serviceBrand: any; }[]): T;
}
export interface ServicesAccessor {
get<T>(id: ServiceIdentifier<T>, isOptional?: typeof optional): T;
}
export interface IFunctionSignature0<R> {
(accessor: ServicesAccessor): R;
}
export interface IFunctionSignature1<A1, R> {
(accessor: ServicesAccessor, first: A1): R;
}
export interface IFunctionSignature2<A1, A2, R> {
(accessor: ServicesAccessor, first: A1, second: A2): R;
}
export interface IFunctionSignature3<A1, A2, A3, R> {
(accessor: ServicesAccessor, first: A1, second: A2, third: A3): R;
}
export interface IFunctionSignature4<A1, A2, A3, A4, R> {
(accessor: ServicesAccessor, first: A1, second: A2, third: A3, fourth: A4): R;
}
export interface IFunctionSignature5<A1, A2, A3, A4, A5, R> {
(accessor: ServicesAccessor, first: A1, second: A2, third: A3, fourth: A4, fifth: A5): R;
}
export interface IFunctionSignature6<A1, A2, A3, A4, A5, A6, R> {
(accessor: ServicesAccessor, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6): R;
}
export interface IFunctionSignature7<A1, A2, A3, A4, A5, A6, A7, R> {
(accessor: ServicesAccessor, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7): R;
}
export interface IFunctionSignature8<A1, A2, A3, A4, A5, A6, A7, A8, R> {
(accessor: ServicesAccessor, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8): R;
}
export const IInstantiationService = createDecorator<IInstantiationService>('instantiationService');
export interface IInstantiationService {
_serviceBrand: any;
/**
* Synchronously creates an instance that is denoted by
* the descriptor
*/
createInstance<T>(descriptor: descriptors.SyncDescriptor0<T>): T;
createInstance<A1, T>(descriptor: descriptors.SyncDescriptor1<A1, T>, a1: A1): T;
createInstance<A1, A2, T>(descriptor: descriptors.SyncDescriptor2<A1, A2, T>, a1: A1, a2: A2): T;
createInstance<A1, A2, A3, T>(descriptor: descriptors.SyncDescriptor3<A1, A2, A3, T>, a1: A1, a2: A2, a3: A3): T;
createInstance<A1, A2, A3, A4, T>(descriptor: descriptors.SyncDescriptor4<A1, A2, A3, A4, T>, a1: A1, a2: A2, a3: A3, a4: A4): T;
createInstance<A1, A2, A3, A4, A5, T>(descriptor: descriptors.SyncDescriptor5<A1, A2, A3, A4, A5, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): T;
createInstance<A1, A2, A3, A4, A5, A6, T>(descriptor: descriptors.SyncDescriptor6<A1, A2, A3, A4, A5, A6, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6): T;
createInstance<A1, A2, A3, A4, A5, A6, A7, T>(descriptor: descriptors.SyncDescriptor7<A1, A2, A3, A4, A5, A6, A7, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7): T;
createInstance<A1, A2, A3, A4, A5, A6, A7, A8, T>(descriptor: descriptors.SyncDescriptor8<A1, A2, A3, A4, A5, A6, A7, A8, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8): T;
createInstance<T>(ctor: IConstructorSignature0<T>): T;
createInstance<A1, T>(ctor: IConstructorSignature1<A1, T>, first: A1): T;
createInstance<A1, A2, T>(ctor: IConstructorSignature2<A1, A2, T>, first: A1, second: A2): T;
createInstance<A1, A2, A3, T>(ctor: IConstructorSignature3<A1, A2, A3, T>, first: A1, second: A2, third: A3): T;
createInstance<A1, A2, A3, A4, T>(ctor: IConstructorSignature4<A1, A2, A3, A4, T>, first: A1, second: A2, third: A3, fourth: A4): T;
createInstance<A1, A2, A3, A4, A5, T>(ctor: IConstructorSignature5<A1, A2, A3, A4, A5, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5): T;
createInstance<A1, A2, A3, A4, A5, A6, T>(ctor: IConstructorSignature6<A1, A2, A3, A4, A5, A6, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6): T;
createInstance<A1, A2, A3, A4, A5, A6, A7, T>(ctor: IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7): T;
createInstance<A1, A2, A3, A4, A5, A6, A7, A8, T>(ctor: IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8): T;
/**
*
*/
invokeFunction<R>(ctor: IFunctionSignature0<R>): R;
invokeFunction<A1, R>(ctor: IFunctionSignature1<A1, R>, first: A1): R;
invokeFunction<A1, A2, R>(ctor: IFunctionSignature2<A1, A2, R>, first: A1, second: A2): R;
invokeFunction<A1, A2, A3, R>(ctor: IFunctionSignature3<A1, A2, A3, R>, first: A1, second: A2, third: A3): R;
invokeFunction<A1, A2, A3, A4, R>(ctor: IFunctionSignature4<A1, A2, A3, A4, R>, first: A1, second: A2, third: A3, fourth: A4): R;
invokeFunction<A1, A2, A3, A4, A5, R>(ctor: IFunctionSignature5<A1, A2, A3, A4, A5, R>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5): R;
invokeFunction<A1, A2, A3, A4, A5, A6, R>(ctor: IFunctionSignature6<A1, A2, A3, A4, A5, A6, R>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6): R;
invokeFunction<A1, A2, A3, A4, A5, A6, A7, R>(ctor: IFunctionSignature7<A1, A2, A3, A4, A5, A6, A7, R>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7): R;
invokeFunction<A1, A2, A3, A4, A5, A6, A7, A8, R>(ctor: IFunctionSignature8<A1, A2, A3, A4, A5, A6, A7, A8, R>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8): R;
/**
* Creates a child of this service which inherts all current services
* and adds/overwrites the given services
*/
createChild(services: ServiceCollection): IInstantiationService;
}
/**
* Identifies a service of type T
*/
export interface ServiceIdentifier<T> {
(...args: any[]): void;
type: T;
}
function storeServiceDependency(id: Function, target: Function, index: number, optional: boolean): void {
if (target[_util.DI_TARGET] === target) {
target[_util.DI_DEPENDENCIES].push({ id, index, optional });
} else {
target[_util.DI_DEPENDENCIES] = [{ id, index, optional }];
target[_util.DI_TARGET] = target;
}
}
/**
* A *only* valid way to create a {{ServiceIdentifier}}.
*/
export function createDecorator<T>(serviceId: string): { (...args: any[]): void; type: T; } {
if (_util.serviceIds.has(serviceId)) {
return _util.serviceIds.get(serviceId);
}
const id = <any>function (target: Function, key: string, index: number): any {
if (arguments.length !== 3) {
throw new Error('@IServiceName-decorator can only be used to decorate a parameter');
}
storeServiceDependency(id, target, index, false);
};
id.toString = () => serviceId;
_util.serviceIds.set(serviceId, id);
return id;
}
/**
* Mark a service dependency as optional.
*/
export function optional<T>(serviceIdentifier: ServiceIdentifier<T>) {
return function (target: Function, key: string, index: number) {
if (arguments.length !== 3) {
throw new Error('@optional-decorator can only be used to decorate a parameter');
}
storeServiceDependency(serviceIdentifier, target, index, true);
};
}
| src/vs/platform/instantiation/common/instantiation.ts | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.00017935071082320064,
0.00017301749903708696,
0.00016776370466686785,
0.00017305798246525228,
0.0000027058856630901573
]
|
{
"id": 6,
"code_window": [
"\t}\n",
"\n",
"\tprivate renderSettingToolbar(container: HTMLElement): ToolBar {\n",
"\t\tconst toolbar = new ToolBar(container, this.contextMenuService, {});\n",
"\t\ttoolbar.setActions([], this.settingActions)();\n",
"\t\tconst button = container.querySelector('.toolbar-toggle-more');\n",
"\t\tif (button) {\n",
"\t\t\t(<HTMLElement>button).tabIndex = -1;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst toggleMenuKeybinding = this.keybindingService.lookupKeybinding(SETTINGS_EDITOR_COMMAND_SHOW_CONTEXT_MENU);\n",
"\t\tlet toggleMenuTitle = localize('settingsContextMenuTitle', \"More Actions... \");\n",
"\t\tif (toggleMenuKeybinding) {\n",
"\t\t\ttoggleMenuTitle += ` (${toggleMenuKeybinding && toggleMenuKeybinding.getLabel()})`;\n",
"\t\t}\n",
"\n",
"\t\tconst toolbar = new ToolBar(container, this.contextMenuService, {\n",
"\t\t\ttoggleMenuTitle\n",
"\t\t});\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "replace",
"edit_start_line_idx": 720
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
let err = false;
const major = parseInt(/^(\d+)\./.exec(process.versions.node)[1]);
if (major < 8) {
console.error('\033[1;31m*** Please use node>=8.\033[0;0m');
err = true;
}
if (!/yarn\.js$|yarnpkg$/.test(process.env['npm_execpath'])) {
console.error('\033[1;31m*** Please use yarn to install dependencies.\033[0;0m');
err = true;
}
if (err) {
console.error('');
process.exit(1);
} | build/npm/preinstall.js | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.0001783070038072765,
0.00017628430214244872,
0.00017428971477784216,
0.0001762562314979732,
0.000001640171603867202
]
|
{
"id": 6,
"code_window": [
"\t}\n",
"\n",
"\tprivate renderSettingToolbar(container: HTMLElement): ToolBar {\n",
"\t\tconst toolbar = new ToolBar(container, this.contextMenuService, {});\n",
"\t\ttoolbar.setActions([], this.settingActions)();\n",
"\t\tconst button = container.querySelector('.toolbar-toggle-more');\n",
"\t\tif (button) {\n",
"\t\t\t(<HTMLElement>button).tabIndex = -1;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst toggleMenuKeybinding = this.keybindingService.lookupKeybinding(SETTINGS_EDITOR_COMMAND_SHOW_CONTEXT_MENU);\n",
"\t\tlet toggleMenuTitle = localize('settingsContextMenuTitle', \"More Actions... \");\n",
"\t\tif (toggleMenuKeybinding) {\n",
"\t\t\ttoggleMenuTitle += ` (${toggleMenuKeybinding && toggleMenuKeybinding.getLabel()})`;\n",
"\t\t}\n",
"\n",
"\t\tconst toolbar = new ToolBar(container, this.contextMenuService, {\n",
"\t\t\ttoggleMenuTitle\n",
"\t\t});\n"
],
"file_path": "src/vs/workbench/parts/preferences/browser/settingsTree.ts",
"type": "replace",
"edit_start_line_idx": 720
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as Assert from 'vs/base/common/assert';
import { onUnexpectedError } from 'vs/base/common/errors';
import { IDisposable, combinedDisposable } from 'vs/base/common/lifecycle';
import * as arrays from 'vs/base/common/arrays';
import { INavigator } from 'vs/base/common/iterator';
import * as WinJS from 'vs/base/common/winjs.base';
import * as _ from './tree';
import { Event, Emitter, once, EventMultiplexer, Relay } from 'vs/base/common/event';
interface IMap<T> { [id: string]: T; }
interface IItemMap extends IMap<Item> { }
interface ITraitMap extends IMap<IItemMap> { }
export class LockData {
private _item: Item;
private _onDispose = new Emitter<void>();
readonly onDispose: Event<void> = this._onDispose.event;
constructor(item: Item) {
this._item = item;
}
get item(): Item {
return this._item;
}
dispose(): void {
if (this._onDispose) {
this._onDispose.fire();
this._onDispose.dispose();
this._onDispose = null;
}
}
}
export class Lock {
/* When refreshing tree items, the tree's structured can be altered, by
inserting and removing sub-items. This lock helps to manage several
possibly-structure-changing calls.
API-wise, there are two possibly-structure-changing: refresh(...),
expand(...) and collapse(...). All these calls must call Lock#run(...).
Any call to Lock#run(...) needs to provide the affecting item and a
callback to execute when unlocked. It must also return a promise
which fulfills once the operation ends. Once it is called, there
are three possibilities:
- Nothing is currently running. The affecting item is remembered, and
the callback is executed.
- Or, there are on-going operations. There are two outcomes:
- The affecting item intersects with any other affecting items
of on-going run calls. In such a case, the given callback should
be executed only when the on-going one completes.
- Or, it doesn't. In such a case, both operations can be run in
parallel.
Note: two items A and B intersect if A is a descendant of B, or
vice-versa.
*/
private locks: { [id: string]: LockData; };
constructor() {
this.locks = Object.create({});
}
public isLocked(item: Item): boolean {
return !!this.locks[item.id];
}
public run(item: Item, fn: () => WinJS.Promise): WinJS.Promise {
var lock = this.getLock(item);
if (lock) {
var unbindListener: IDisposable;
return new WinJS.TPromise((c, e) => {
unbindListener = once(lock.onDispose)(() => {
return this.run(item, fn).then(c, e);
});
}, () => { unbindListener.dispose(); });
}
var result: WinJS.Promise;
return new WinJS.TPromise((c, e) => {
if (item.isDisposed()) {
return e(new Error('Item is disposed.'));
}
var lock = this.locks[item.id] = new LockData(item);
result = fn().then((r) => {
delete this.locks[item.id];
lock.dispose();
return r;
}).then(c, e);
return result;
});
}
private getLock(item: Item): LockData {
var key: string;
for (key in this.locks) {
var lock = this.locks[key];
if (item.intersects(lock.item)) {
return lock;
}
}
return null;
}
}
export class ItemRegistry {
private _isDisposed = false;
private items: IMap<{ item: Item; disposable: IDisposable; }>;
private _onDidRevealItem = new EventMultiplexer<IItemRevealEvent>();
readonly onDidRevealItem: Event<IItemRevealEvent> = this._onDidRevealItem.event;
private _onExpandItem = new EventMultiplexer<IItemExpandEvent>();
readonly onExpandItem: Event<IItemExpandEvent> = this._onExpandItem.event;
private _onDidExpandItem = new EventMultiplexer<IItemExpandEvent>();
readonly onDidExpandItem: Event<IItemExpandEvent> = this._onDidExpandItem.event;
private _onCollapseItem = new EventMultiplexer<IItemCollapseEvent>();
readonly onCollapseItem: Event<IItemCollapseEvent> = this._onCollapseItem.event;
private _onDidCollapseItem = new EventMultiplexer<IItemCollapseEvent>();
readonly onDidCollapseItem: Event<IItemCollapseEvent> = this._onDidCollapseItem.event;
private _onDidAddTraitItem = new EventMultiplexer<IItemTraitEvent>();
readonly onDidAddTraitItem: Event<IItemTraitEvent> = this._onDidAddTraitItem.event;
private _onDidRemoveTraitItem = new EventMultiplexer<IItemCollapseEvent>();
readonly onDidRemoveTraitItem: Event<IItemCollapseEvent> = this._onDidRemoveTraitItem.event;
private _onDidRefreshItem = new EventMultiplexer<Item>();
readonly onDidRefreshItem: Event<Item> = this._onDidRefreshItem.event;
private _onRefreshItemChildren = new EventMultiplexer<IItemChildrenRefreshEvent>();
readonly onRefreshItemChildren: Event<IItemChildrenRefreshEvent> = this._onRefreshItemChildren.event;
private _onDidRefreshItemChildren = new EventMultiplexer<IItemChildrenRefreshEvent>();
readonly onDidRefreshItemChildren: Event<IItemChildrenRefreshEvent> = this._onDidRefreshItemChildren.event;
private _onDidDisposeItem = new EventMultiplexer<Item>();
readonly onDidDisposeItem: Event<Item> = this._onDidDisposeItem.event;
constructor() {
this.items = {};
}
public register(item: Item): void {
Assert.ok(!this.isRegistered(item.id), 'item already registered: ' + item.id);
const disposable = combinedDisposable([
this._onDidRevealItem.add(item.onDidReveal),
this._onExpandItem.add(item.onExpand),
this._onDidExpandItem.add(item.onDidExpand),
this._onCollapseItem.add(item.onCollapse),
this._onDidCollapseItem.add(item.onDidCollapse),
this._onDidAddTraitItem.add(item.onDidAddTrait),
this._onDidRemoveTraitItem.add(item.onDidRemoveTrait),
this._onDidRefreshItem.add(item.onDidRefresh),
this._onRefreshItemChildren.add(item.onRefreshChildren),
this._onDidRefreshItemChildren.add(item.onDidRefreshChildren),
this._onDidDisposeItem.add(item.onDidDispose)
]);
this.items[item.id] = { item, disposable };
}
public deregister(item: Item): void {
Assert.ok(this.isRegistered(item.id), 'item not registered: ' + item.id);
this.items[item.id].disposable.dispose();
delete this.items[item.id];
}
public isRegistered(id: string): boolean {
return this.items.hasOwnProperty(id);
}
public getItem(id: string): Item {
const result = this.items[id];
return result ? result.item : null;
}
public dispose(): void {
this.items = null;
this._onDidRevealItem.dispose();
this._onExpandItem.dispose();
this._onDidExpandItem.dispose();
this._onCollapseItem.dispose();
this._onDidCollapseItem.dispose();
this._onDidAddTraitItem.dispose();
this._onDidRemoveTraitItem.dispose();
this._onDidRefreshItem.dispose();
this._onRefreshItemChildren.dispose();
this._onDidRefreshItemChildren.dispose();
this._isDisposed = true;
}
public isDisposed(): boolean {
return this._isDisposed;
}
}
export interface IBaseItemEvent {
item: Item;
}
export interface IItemRefreshEvent extends IBaseItemEvent { }
export interface IItemExpandEvent extends IBaseItemEvent { }
export interface IItemCollapseEvent extends IBaseItemEvent { }
export interface IItemTraitEvent extends IBaseItemEvent {
trait: string;
}
export interface IItemRevealEvent extends IBaseItemEvent {
relativeTop: number;
}
export interface IItemChildrenRefreshEvent extends IBaseItemEvent {
isNested: boolean;
}
export class Item {
private registry: ItemRegistry;
private context: _.ITreeContext;
private element: any;
private lock: Lock;
public id: string;
private needsChildrenRefresh: boolean;
private doesHaveChildren: boolean;
public parent: Item;
public previous: Item;
public next: Item;
public firstChild: Item;
public lastChild: Item;
private height: number;
private depth: number;
private visible: boolean;
private expanded: boolean;
private traits: { [trait: string]: boolean; };
private _onDidCreate = new Emitter<Item>();
readonly onDidCreate: Event<Item> = this._onDidCreate.event;
private _onDidReveal = new Emitter<IItemRevealEvent>();
readonly onDidReveal: Event<IItemRevealEvent> = this._onDidReveal.event;
private _onExpand = new Emitter<IItemExpandEvent>();
readonly onExpand: Event<IItemExpandEvent> = this._onExpand.event;
private _onDidExpand = new Emitter<IItemExpandEvent>();
readonly onDidExpand: Event<IItemExpandEvent> = this._onDidExpand.event;
private _onCollapse = new Emitter<IItemCollapseEvent>();
readonly onCollapse: Event<IItemCollapseEvent> = this._onCollapse.event;
private _onDidCollapse = new Emitter<IItemCollapseEvent>();
readonly onDidCollapse: Event<IItemCollapseEvent> = this._onDidCollapse.event;
private _onDidAddTrait = new Emitter<IItemTraitEvent>();
readonly onDidAddTrait: Event<IItemTraitEvent> = this._onDidAddTrait.event;
private _onDidRemoveTrait = new Emitter<IItemCollapseEvent>();
readonly onDidRemoveTrait: Event<IItemCollapseEvent> = this._onDidRemoveTrait.event;
private _onDidRefresh = new Emitter<Item>();
readonly onDidRefresh: Event<Item> = this._onDidRefresh.event;
private _onRefreshChildren = new Emitter<IItemChildrenRefreshEvent>();
readonly onRefreshChildren: Event<IItemChildrenRefreshEvent> = this._onRefreshChildren.event;
private _onDidRefreshChildren = new Emitter<IItemChildrenRefreshEvent>();
readonly onDidRefreshChildren: Event<IItemChildrenRefreshEvent> = this._onDidRefreshChildren.event;
private _onDidDispose = new Emitter<Item>();
readonly onDidDispose: Event<Item> = this._onDidDispose.event;
private _isDisposed: boolean;
constructor(id: string, registry: ItemRegistry, context: _.ITreeContext, lock: Lock, element: any) {
this.registry = registry;
this.context = context;
this.lock = lock;
this.element = element;
this.id = id;
this.registry.register(this);
this.doesHaveChildren = this.context.dataSource.hasChildren(this.context.tree, this.element);
this.needsChildrenRefresh = true;
this.parent = null;
this.previous = null;
this.next = null;
this.firstChild = null;
this.lastChild = null;
this.traits = {};
this.depth = 0;
this.expanded = this.context.dataSource.shouldAutoexpand && this.context.dataSource.shouldAutoexpand(this.context.tree, element);
this._onDidCreate.fire(this);
this.visible = this._isVisible();
this.height = this._getHeight();
this._isDisposed = false;
}
public getElement(): any {
return this.element;
}
public hasChildren(): boolean {
return this.doesHaveChildren;
}
public getDepth(): number {
return this.depth;
}
public isVisible(): boolean {
return this.visible;
}
public setVisible(value: boolean): void {
this.visible = value;
}
public isExpanded(): boolean {
return this.expanded;
}
/* protected */ public _setExpanded(value: boolean): void {
this.expanded = value;
}
public reveal(relativeTop: number = null): void {
var eventData: IItemRevealEvent = { item: this, relativeTop: relativeTop };
this._onDidReveal.fire(eventData);
}
public expand(): WinJS.Promise {
if (this.isExpanded() || !this.doesHaveChildren || this.lock.isLocked(this)) {
return WinJS.TPromise.as(false);
}
var result = this.lock.run(this, () => {
if (this.isExpanded() || !this.doesHaveChildren) {
return WinJS.TPromise.as(false);
}
var eventData: IItemExpandEvent = { item: this };
var result: WinJS.Promise;
this._onExpand.fire(eventData);
if (this.needsChildrenRefresh) {
result = this.refreshChildren(false, true, true);
} else {
result = WinJS.TPromise.as(null);
}
return result.then(() => {
this._setExpanded(true);
this._onDidExpand.fire(eventData);
return true;
});
});
return result.then((r) => {
if (this.isDisposed()) {
return false;
}
// Auto expand single child folders
if (this.context.options.autoExpandSingleChildren && r && this.firstChild !== null && this.firstChild === this.lastChild && this.firstChild.isVisible()) {
return this.firstChild.expand().then(() => { return true; });
}
return r;
});
}
public collapse(recursive: boolean = false): WinJS.Promise {
if (recursive) {
var collapseChildrenPromise = WinJS.TPromise.as(null);
this.forEachChild((child) => {
collapseChildrenPromise = collapseChildrenPromise.then(() => child.collapse(true));
});
return collapseChildrenPromise.then(() => {
return this.collapse(false);
});
} else {
if (!this.isExpanded() || this.lock.isLocked(this)) {
return WinJS.TPromise.as(false);
}
return this.lock.run(this, () => {
var eventData: IItemCollapseEvent = { item: this };
this._onCollapse.fire(eventData);
this._setExpanded(false);
this._onDidCollapse.fire(eventData);
return WinJS.TPromise.as(true);
});
}
}
public addTrait(trait: string): void {
var eventData: IItemTraitEvent = { item: this, trait: trait };
this.traits[trait] = true;
this._onDidAddTrait.fire(eventData);
}
public removeTrait(trait: string): void {
var eventData: IItemTraitEvent = { item: this, trait: trait };
delete this.traits[trait];
this._onDidRemoveTrait.fire(eventData);
}
public hasTrait(trait: string): boolean {
return this.traits[trait] || false;
}
public getAllTraits(): string[] {
var result: string[] = [];
var trait: string;
for (trait in this.traits) {
if (this.traits.hasOwnProperty(trait) && this.traits[trait]) {
result.push(trait);
}
}
return result;
}
public getHeight(): number {
return this.height;
}
private refreshChildren(recursive: boolean, safe: boolean = false, force: boolean = false): WinJS.Promise {
if (!force && !this.isExpanded()) {
this.needsChildrenRefresh = true;
return WinJS.TPromise.as(this);
}
this.needsChildrenRefresh = false;
var doRefresh = () => {
var eventData: IItemChildrenRefreshEvent = { item: this, isNested: safe };
this._onRefreshChildren.fire(eventData);
var childrenPromise: WinJS.Promise;
if (this.doesHaveChildren) {
childrenPromise = this.context.dataSource.getChildren(this.context.tree, this.element);
} else {
childrenPromise = WinJS.TPromise.as([]);
}
const result = childrenPromise.then((elements: any[]) => {
if (this.isDisposed() || this.registry.isDisposed()) {
return WinJS.TPromise.as(null);
}
if (!Array.isArray(elements)) {
return WinJS.TPromise.wrapError(new Error('Please return an array of children.'));
}
elements = !elements ? [] : elements.slice(0);
elements = this.sort(elements);
var staleItems: IItemMap = {};
while (this.firstChild !== null) {
staleItems[this.firstChild.id] = this.firstChild;
this.removeChild(this.firstChild);
}
for (var i = 0, len = elements.length; i < len; i++) {
var element = elements[i];
var id = this.context.dataSource.getId(this.context.tree, element);
var item = staleItems[id] || new Item(id, this.registry, this.context, this.lock, element);
item.element = element;
if (recursive) {
item.needsChildrenRefresh = recursive;
}
delete staleItems[id];
this.addChild(item);
}
for (var staleItemId in staleItems) {
if (staleItems.hasOwnProperty(staleItemId)) {
staleItems[staleItemId].dispose();
}
}
if (recursive) {
return WinJS.Promise.join(this.mapEachChild((child) => {
return child.doRefresh(recursive, true);
}));
} else {
this.mapEachChild(child => child.updateVisibility());
return WinJS.TPromise.as(null);
}
});
return result
.then(null, onUnexpectedError)
.then(() => this._onDidRefreshChildren.fire(eventData));
};
return safe ? doRefresh() : this.lock.run(this, doRefresh);
}
private doRefresh(recursive: boolean, safe: boolean = false): WinJS.Promise {
this.doesHaveChildren = this.context.dataSource.hasChildren(this.context.tree, this.element);
this.height = this._getHeight();
this.updateVisibility();
this._onDidRefresh.fire(this);
return this.refreshChildren(recursive, safe);
}
private updateVisibility(): void {
this.setVisible(this._isVisible());
}
public refresh(recursive: boolean): WinJS.Promise {
return this.doRefresh(recursive);
}
public getNavigator(): INavigator<Item> {
return new TreeNavigator(this);
}
public intersects(other: Item): boolean {
return this.isAncestorOf(other) || other.isAncestorOf(this);
}
public getHierarchy(): Item[] {
var result: Item[] = [];
var node: Item = this;
do {
result.push(node);
node = node.parent;
} while (node);
result.reverse();
return result;
}
private isAncestorOf(item: Item): boolean {
while (item) {
if (item.id === this.id) {
return true;
}
item = item.parent;
}
return false;
}
private addChild(item: Item, afterItem: Item = this.lastChild): void {
var isEmpty = this.firstChild === null;
var atHead = afterItem === null;
var atTail = afterItem === this.lastChild;
if (isEmpty) {
this.firstChild = this.lastChild = item;
item.next = item.previous = null;
} else if (atHead) {
this.firstChild.previous = item;
item.next = this.firstChild;
item.previous = null;
this.firstChild = item;
} else if (atTail) {
this.lastChild.next = item;
item.next = null;
item.previous = this.lastChild;
this.lastChild = item;
} else {
item.previous = afterItem;
item.next = afterItem.next;
afterItem.next.previous = item;
afterItem.next = item;
}
item.parent = this;
item.depth = this.depth + 1;
}
private removeChild(item: Item): void {
var isFirstChild = this.firstChild === item;
var isLastChild = this.lastChild === item;
if (isFirstChild && isLastChild) {
this.firstChild = this.lastChild = null;
} else if (isFirstChild) {
item.next.previous = null;
this.firstChild = item.next;
} else if (isLastChild) {
item.previous.next = null;
this.lastChild = item.previous;
} else {
item.next.previous = item.previous;
item.previous.next = item.next;
}
item.parent = null;
item.depth = null;
}
private forEachChild(fn: (child: Item) => void): void {
var child = this.firstChild, next: Item;
while (child) {
next = child.next;
fn(child);
child = next;
}
}
private mapEachChild<T>(fn: (child: Item) => T): T[] {
var result: T[] = [];
this.forEachChild((child) => {
result.push(fn(child));
});
return result;
}
private sort(elements: any[]): any[] {
if (this.context.sorter) {
return elements.sort((element, otherElement) => {
return this.context.sorter.compare(this.context.tree, element, otherElement);
});
}
return elements;
}
/* protected */ public _getHeight(): number {
return this.context.renderer.getHeight(this.context.tree, this.element);
}
/* protected */ public _isVisible(): boolean {
return this.context.filter.isVisible(this.context.tree, this.element);
}
public isDisposed(): boolean {
return this._isDisposed;
}
public dispose(): void {
this.forEachChild((child) => child.dispose());
this.parent = null;
this.previous = null;
this.next = null;
this.firstChild = null;
this.lastChild = null;
this._onDidDispose.fire(this);
this.registry.deregister(this);
this._onDidCreate.dispose();
this._onDidReveal.dispose();
this._onExpand.dispose();
this._onDidExpand.dispose();
this._onCollapse.dispose();
this._onDidCollapse.dispose();
this._onDidAddTrait.dispose();
this._onDidRemoveTrait.dispose();
this._onDidRefresh.dispose();
this._onRefreshChildren.dispose();
this._onDidRefreshChildren.dispose();
this._onDidDispose.dispose();
this._isDisposed = true;
}
}
class RootItem extends Item {
constructor(id: string, registry: ItemRegistry, context: _.ITreeContext, lock: Lock, element: any) {
super(id, registry, context, lock, element);
}
public isVisible(): boolean {
return false;
}
public setVisible(value: boolean): void {
// no-op
}
public isExpanded(): boolean {
return true;
}
/* protected */ public _setExpanded(value: boolean): void {
// no-op
}
public render(): void {
// no-op
}
/* protected */ public _getHeight(): number {
return 0;
}
/* protected */ public _isVisible(): boolean {
return false;
}
}
export class TreeNavigator implements INavigator<Item> {
private start: Item;
private item: Item;
static lastDescendantOf(item: Item): Item {
if (!item) {
return null;
}
if (item instanceof RootItem) {
return TreeNavigator.lastDescendantOf(item.lastChild);
}
if (!item.isVisible()) {
return TreeNavigator.lastDescendantOf(item.previous);
}
if (!item.isExpanded() || item.lastChild === null) {
return item;
}
return TreeNavigator.lastDescendantOf(item.lastChild);
}
constructor(item: Item, subTreeOnly: boolean = true) {
this.item = item;
this.start = subTreeOnly ? item : null;
}
public current(): Item {
return this.item || null;
}
public next(): Item {
if (this.item) {
do {
if ((this.item instanceof RootItem || (this.item.isVisible() && this.item.isExpanded())) && this.item.firstChild) {
this.item = this.item.firstChild;
} else if (this.item === this.start) {
this.item = null;
} else {
// select next brother, next uncle, next great-uncle, etc...
while (this.item && this.item !== this.start && !this.item.next) {
this.item = this.item.parent;
}
if (this.item === this.start) {
this.item = null;
}
this.item = !this.item ? null : this.item.next;
}
} while (this.item && !this.item.isVisible());
}
return this.item || null;
}
public previous(): Item {
if (this.item) {
do {
var previous = TreeNavigator.lastDescendantOf(this.item.previous);
if (previous) {
this.item = previous;
} else if (this.item.parent && this.item.parent !== this.start && this.item.parent.isVisible()) {
this.item = this.item.parent;
} else {
this.item = null;
}
} while (this.item && !this.item.isVisible());
}
return this.item || null;
}
public parent(): Item {
if (this.item) {
var parent = this.item.parent;
if (parent && parent !== this.start && parent.isVisible()) {
this.item = parent;
} else {
this.item = null;
}
}
return this.item || null;
}
public first(): Item {
this.item = this.start;
this.next();
return this.item || null;
}
public last(): Item {
return TreeNavigator.lastDescendantOf(this.start);
}
}
function getRange(one: Item, other: Item): Item[] {
var oneHierarchy = one.getHierarchy();
var otherHierarchy = other.getHierarchy();
var length = arrays.commonPrefixLength(oneHierarchy, otherHierarchy);
var item = oneHierarchy[length - 1];
var nav = item.getNavigator();
var oneIndex: number = null;
var otherIndex: number = null;
var index = 0;
var result: Item[] = [];
while (item && (oneIndex === null || otherIndex === null)) {
result.push(item);
if (item === one) {
oneIndex = index;
}
if (item === other) {
otherIndex = index;
}
index++;
item = nav.next();
}
if (oneIndex === null || otherIndex === null) {
return [];
}
var min = Math.min(oneIndex, otherIndex);
var max = Math.max(oneIndex, otherIndex);
return result.slice(min, max + 1);
}
export interface IBaseEvent {
item: Item;
}
export interface IInputEvent extends IBaseEvent { }
export interface IRefreshEvent extends IBaseEvent {
recursive: boolean;
}
export class TreeModel {
private context: _.ITreeContext;
private lock: Lock;
private input: Item;
private registry: ItemRegistry;
private registryDisposable: IDisposable;
private traitsToItems: ITraitMap;
private _onSetInput = new Emitter<IInputEvent>();
readonly onSetInput: Event<IInputEvent> = this._onSetInput.event;
private _onDidSetInput = new Emitter<IInputEvent>();
readonly onDidSetInput: Event<IInputEvent> = this._onDidSetInput.event;
private _onRefresh = new Emitter<IRefreshEvent>();
readonly onRefresh: Event<IRefreshEvent> = this._onRefresh.event;
private _onDidRefresh = new Emitter<IRefreshEvent>();
readonly onDidRefresh: Event<IRefreshEvent> = this._onDidRefresh.event;
private _onDidHighlight = new Emitter<_.IHighlightEvent>();
readonly onDidHighlight: Event<_.IHighlightEvent> = this._onDidHighlight.event;
private _onDidSelect = new Emitter<_.ISelectionEvent>();
readonly onDidSelect: Event<_.ISelectionEvent> = this._onDidSelect.event;
private _onDidFocus = new Emitter<_.IFocusEvent>();
readonly onDidFocus: Event<_.IFocusEvent> = this._onDidFocus.event;
private _onDidRevealItem = new Relay<IItemRevealEvent>();
readonly onDidRevealItem: Event<IItemRevealEvent> = this._onDidRevealItem.event;
private _onExpandItem = new Relay<IItemExpandEvent>();
readonly onExpandItem: Event<IItemExpandEvent> = this._onExpandItem.event;
private _onDidExpandItem = new Relay<IItemExpandEvent>();
readonly onDidExpandItem: Event<IItemExpandEvent> = this._onDidExpandItem.event;
private _onCollapseItem = new Relay<IItemCollapseEvent>();
readonly onCollapseItem: Event<IItemCollapseEvent> = this._onCollapseItem.event;
private _onDidCollapseItem = new Relay<IItemCollapseEvent>();
readonly onDidCollapseItem: Event<IItemCollapseEvent> = this._onDidCollapseItem.event;
private _onDidAddTraitItem = new Relay<IItemTraitEvent>();
readonly onDidAddTraitItem: Event<IItemTraitEvent> = this._onDidAddTraitItem.event;
private _onDidRemoveTraitItem = new Relay<IItemCollapseEvent>();
readonly onDidRemoveTraitItem: Event<IItemCollapseEvent> = this._onDidRemoveTraitItem.event;
private _onDidRefreshItem = new Relay<Item>();
readonly onDidRefreshItem: Event<Item> = this._onDidRefreshItem.event;
private _onRefreshItemChildren = new Relay<IItemChildrenRefreshEvent>();
readonly onRefreshItemChildren: Event<IItemChildrenRefreshEvent> = this._onRefreshItemChildren.event;
private _onDidRefreshItemChildren = new Relay<IItemChildrenRefreshEvent>();
readonly onDidRefreshItemChildren: Event<IItemChildrenRefreshEvent> = this._onDidRefreshItemChildren.event;
private _onDidDisposeItem = new Relay<Item>();
readonly onDidDisposeItem: Event<Item> = this._onDidDisposeItem.event;
constructor(context: _.ITreeContext) {
this.context = context;
this.input = null;
this.traitsToItems = {};
}
public setInput(element: any): WinJS.Promise {
var eventData: IInputEvent = { item: this.input };
this._onSetInput.fire(eventData);
this.setSelection([]);
this.setFocus();
this.setHighlight();
this.lock = new Lock();
if (this.input) {
this.input.dispose();
}
if (this.registry) {
this.registry.dispose();
this.registryDisposable.dispose();
}
this.registry = new ItemRegistry();
this._onDidRevealItem.input = this.registry.onDidRevealItem;
this._onExpandItem.input = this.registry.onExpandItem;
this._onDidExpandItem.input = this.registry.onDidExpandItem;
this._onCollapseItem.input = this.registry.onCollapseItem;
this._onDidCollapseItem.input = this.registry.onDidCollapseItem;
this._onDidAddTraitItem.input = this.registry.onDidAddTraitItem;
this._onDidRemoveTraitItem.input = this.registry.onDidRemoveTraitItem;
this._onDidRefreshItem.input = this.registry.onDidRefreshItem;
this._onRefreshItemChildren.input = this.registry.onRefreshItemChildren;
this._onDidRefreshItemChildren.input = this.registry.onDidRefreshItemChildren;
this._onDidDisposeItem.input = this.registry.onDidDisposeItem;
this.registryDisposable = this.registry
.onDidDisposeItem(item => item.getAllTraits().forEach(trait => delete this.traitsToItems[trait][item.id]));
var id = this.context.dataSource.getId(this.context.tree, element);
this.input = new RootItem(id, this.registry, this.context, this.lock, element);
eventData = { item: this.input };
this._onDidSetInput.fire(eventData);
return this.refresh(this.input);
}
public getInput(): any {
return this.input ? this.input.getElement() : null;
}
public refresh(element: any = null, recursive: boolean = true): WinJS.Promise {
var item = this.getItem(element);
if (!item) {
return WinJS.TPromise.as(null);
}
var eventData: IRefreshEvent = { item: item, recursive: recursive };
this._onRefresh.fire(eventData);
return item.refresh(recursive).then(() => {
this._onDidRefresh.fire(eventData);
});
}
public expand(element: any): WinJS.Promise {
var item = this.getItem(element);
if (!item) {
return WinJS.TPromise.as(false);
}
return item.expand();
}
public expandAll(elements?: any[]): WinJS.Promise {
if (!elements) {
elements = [];
var item: Item;
var nav = this.getNavigator();
while (item = nav.next()) {
elements.push(item);
}
}
var promises = [];
for (var i = 0, len = elements.length; i < len; i++) {
promises.push(this.expand(elements[i]));
}
return WinJS.Promise.join(promises);
}
public collapse(element: any, recursive: boolean = false): WinJS.Promise {
var item = this.getItem(element);
if (!item) {
return WinJS.TPromise.as(false);
}
return item.collapse(recursive);
}
public collapseAll(elements: any[] = null, recursive: boolean = false): WinJS.Promise {
if (!elements) {
elements = [this.input];
recursive = true;
}
var promises = [];
for (var i = 0, len = elements.length; i < len; i++) {
promises.push(this.collapse(elements[i], recursive));
}
return WinJS.Promise.join(promises);
}
public toggleExpansion(element: any, recursive: boolean = false): WinJS.Promise {
return this.isExpanded(element) ? this.collapse(element, recursive) : this.expand(element);
}
public toggleExpansionAll(elements: any[]): WinJS.Promise {
var promises = [];
for (var i = 0, len = elements.length; i < len; i++) {
promises.push(this.toggleExpansion(elements[i]));
}
return WinJS.Promise.join(promises);
}
public isExpanded(element: any): boolean {
var item = this.getItem(element);
if (!item) {
return false;
}
return item.isExpanded();
}
public getExpandedElements(): any[] {
var result: any[] = [];
var item: Item;
var nav = this.getNavigator();
while (item = nav.next()) {
if (item.isExpanded()) {
result.push(item.getElement());
}
}
return result;
}
public reveal(element: any, relativeTop: number = null): WinJS.Promise {
return this.resolveUnknownParentChain(element).then((chain: any[]) => {
var result = WinJS.TPromise.as(null);
chain.forEach((e) => {
result = result.then(() => this.expand(e));
});
return result;
}).then(() => {
var item = this.getItem(element);
if (item) {
return item.reveal(relativeTop);
}
});
}
private resolveUnknownParentChain(element: any): WinJS.Promise {
return this.context.dataSource.getParent(this.context.tree, element).then((parent) => {
if (!parent) {
return WinJS.TPromise.as([]);
}
return this.resolveUnknownParentChain(parent).then((result) => {
result.push(parent);
return result;
});
});
}
public setHighlight(element?: any, eventPayload?: any): void {
this.setTraits('highlighted', element ? [element] : []);
var eventData: _.IHighlightEvent = { highlight: this.getHighlight(), payload: eventPayload };
this._onDidHighlight.fire(eventData);
}
public getHighlight(includeHidden?: boolean): any {
var result = this.getElementsWithTrait('highlighted', includeHidden);
return result.length === 0 ? null : result[0];
}
public isHighlighted(element: any): boolean {
var item = this.getItem(element);
if (!item) {
return false;
}
return item.hasTrait('highlighted');
}
public select(element: any, eventPayload?: any): void {
this.selectAll([element], eventPayload);
}
public selectRange(fromElement: any, toElement: any, eventPayload?: any): void {
var fromItem = this.getItem(fromElement);
var toItem = this.getItem(toElement);
if (!fromItem || !toItem) {
return;
}
this.selectAll(getRange(fromItem, toItem), eventPayload);
}
public deselectRange(fromElement: any, toElement: any, eventPayload?: any): void {
var fromItem = this.getItem(fromElement);
var toItem = this.getItem(toElement);
if (!fromItem || !toItem) {
return;
}
this.deselectAll(getRange(fromItem, toItem), eventPayload);
}
public selectAll(elements: any[], eventPayload?: any): void {
this.addTraits('selected', elements);
var eventData: _.ISelectionEvent = { selection: this.getSelection(), payload: eventPayload };
this._onDidSelect.fire(eventData);
}
public deselect(element: any, eventPayload?: any): void {
this.deselectAll([element], eventPayload);
}
public deselectAll(elements: any[], eventPayload?: any): void {
this.removeTraits('selected', elements);
var eventData: _.ISelectionEvent = { selection: this.getSelection(), payload: eventPayload };
this._onDidSelect.fire(eventData);
}
public setSelection(elements: any[], eventPayload?: any): void {
this.setTraits('selected', elements);
var eventData: _.ISelectionEvent = { selection: this.getSelection(), payload: eventPayload };
this._onDidSelect.fire(eventData);
}
public toggleSelection(element: any, eventPayload?: any): void {
this.toggleTrait('selected', element);
var eventData: _.ISelectionEvent = { selection: this.getSelection(), payload: eventPayload };
this._onDidSelect.fire(eventData);
}
public isSelected(element: any): boolean {
var item = this.getItem(element);
if (!item) {
return false;
}
return item.hasTrait('selected');
}
public getSelection(includeHidden?: boolean): any[] {
return this.getElementsWithTrait('selected', includeHidden);
}
public selectNext(count: number = 1, clearSelection: boolean = true, eventPayload?: any): void {
var selection = this.getSelection();
var item: Item = selection.length > 0 ? selection[0] : this.input;
var nextItem: Item;
var nav = this.getNavigator(item, false);
for (var i = 0; i < count; i++) {
nextItem = nav.next();
if (!nextItem) {
break;
}
item = nextItem;
}
if (clearSelection) {
this.setSelection([item], eventPayload);
} else {
this.select(item, eventPayload);
}
}
public selectPrevious(count: number = 1, clearSelection: boolean = true, eventPayload?: any): void {
var selection = this.getSelection(),
item: Item = null,
previousItem: Item = null;
if (selection.length === 0) {
let nav = this.getNavigator(this.input);
while (item = nav.next()) {
previousItem = item;
}
item = previousItem;
} else {
item = selection[0];
let nav = this.getNavigator(item, false);
for (var i = 0; i < count; i++) {
previousItem = nav.previous();
if (!previousItem) {
break;
}
item = previousItem;
}
}
if (clearSelection) {
this.setSelection([item], eventPayload);
} else {
this.select(item, eventPayload);
}
}
public selectParent(eventPayload?: any, clearSelection: boolean = true): void {
var selection = this.getSelection();
var item: Item = selection.length > 0 ? selection[0] : this.input;
var nav = this.getNavigator(item, false);
var parent = nav.parent();
if (parent) {
if (clearSelection) {
this.setSelection([parent], eventPayload);
} else {
this.select(parent, eventPayload);
}
}
}
public setFocus(element?: any, eventPayload?: any): void {
this.setTraits('focused', element ? [element] : []);
var eventData: _.IFocusEvent = { focus: this.getFocus(), payload: eventPayload };
this._onDidFocus.fire(eventData);
}
public isFocused(element: any): boolean {
var item = this.getItem(element);
if (!item) {
return false;
}
return item.hasTrait('focused');
}
public getFocus(includeHidden?: boolean): any {
var result = this.getElementsWithTrait('focused', includeHidden);
return result.length === 0 ? null : result[0];
}
public focusNext(count: number = 1, eventPayload?: any): void {
var item: Item = this.getFocus() || this.input;
var nextItem: Item;
var nav = this.getNavigator(item, false);
for (var i = 0; i < count; i++) {
nextItem = nav.next();
if (!nextItem) {
break;
}
item = nextItem;
}
this.setFocus(item, eventPayload);
}
public focusPrevious(count: number = 1, eventPayload?: any): void {
var item: Item = this.getFocus() || this.input;
var previousItem: Item;
var nav = this.getNavigator(item, false);
for (var i = 0; i < count; i++) {
previousItem = nav.previous();
if (!previousItem) {
break;
}
item = previousItem;
}
this.setFocus(item, eventPayload);
}
public focusParent(eventPayload?: any): void {
var item: Item = this.getFocus() || this.input;
var nav = this.getNavigator(item, false);
var parent = nav.parent();
if (parent) {
this.setFocus(parent, eventPayload);
}
}
public focusFirstChild(eventPayload?: any): void {
const item = this.getItem(this.getFocus() || this.input);
const nav = this.getNavigator(item, false);
const next = nav.next();
const parent = nav.parent();
if (parent === item) {
this.setFocus(next, eventPayload);
}
}
public focusFirst(eventPayload?: any, from?: any): void {
this.focusNth(0, eventPayload, from);
}
public focusNth(index: number, eventPayload?: any, from?: any): void {
var navItem = this.getParent(from);
var nav = this.getNavigator(navItem);
var item = nav.first();
for (var i = 0; i < index; i++) {
item = nav.next();
}
if (item) {
this.setFocus(item, eventPayload);
}
}
public focusLast(eventPayload?: any, from?: any): void {
var navItem = this.getParent(from);
var item: Item;
if (from) {
item = navItem.lastChild;
} else {
var nav = this.getNavigator(navItem);
item = nav.last();
}
if (item) {
this.setFocus(item, eventPayload);
}
}
private getParent(from?: any): Item {
if (from) {
var fromItem = this.getItem(from);
if (fromItem && fromItem.parent) {
return fromItem.parent;
}
}
return this.getItem(this.input);
}
public getNavigator(element: any = null, subTreeOnly: boolean = true): INavigator<Item> {
return new TreeNavigator(this.getItem(element), subTreeOnly);
}
public getItem(element: any = null): Item {
if (element === null) {
return this.input;
} else if (element instanceof Item) {
return element;
} else if (typeof element === 'string') {
return this.registry.getItem(element);
} else {
return this.registry.getItem(this.context.dataSource.getId(this.context.tree, element));
}
}
public addTraits(trait: string, elements: any[]): void {
var items: IItemMap = this.traitsToItems[trait] || <IItemMap>{};
var item: Item;
for (var i = 0, len = elements.length; i < len; i++) {
item = this.getItem(elements[i]);
if (item) {
item.addTrait(trait);
items[item.id] = item;
}
}
this.traitsToItems[trait] = items;
}
public removeTraits(trait: string, elements: any[]): void {
var items: IItemMap = this.traitsToItems[trait] || <IItemMap>{};
var item: Item;
var id: string;
if (elements.length === 0) {
for (id in items) {
if (items.hasOwnProperty(id)) {
item = items[id];
item.removeTrait(trait);
}
}
delete this.traitsToItems[trait];
} else {
for (var i = 0, len = elements.length; i < len; i++) {
item = this.getItem(elements[i]);
if (item) {
item.removeTrait(trait);
delete items[item.id];
}
}
}
}
public hasTrait(trait: string, element: any): boolean {
var item = this.getItem(element);
return item && item.hasTrait(trait);
}
private toggleTrait(trait: string, element: any): void {
var item = this.getItem(element);
if (!item) {
return;
}
if (item.hasTrait(trait)) {
this.removeTraits(trait, [element]);
} else {
this.addTraits(trait, [element]);
}
}
private setTraits(trait: string, elements: any[]): void {
if (elements.length === 0) {
this.removeTraits(trait, elements);
} else {
var items: { [id: string]: Item; } = {};
var item: Item;
for (let i = 0, len = elements.length; i < len; i++) {
item = this.getItem(elements[i]);
if (item) {
items[item.id] = item;
}
}
var traitItems: IItemMap = this.traitsToItems[trait] || <IItemMap>{};
var itemsToRemoveTrait: Item[] = [];
var id: string;
for (id in traitItems) {
if (traitItems.hasOwnProperty(id)) {
if (items.hasOwnProperty(id)) {
delete items[id];
} else {
itemsToRemoveTrait.push(traitItems[id]);
}
}
}
for (let i = 0, len = itemsToRemoveTrait.length; i < len; i++) {
item = itemsToRemoveTrait[i];
item.removeTrait(trait);
delete traitItems[item.id];
}
for (id in items) {
if (items.hasOwnProperty(id)) {
item = items[id];
item.addTrait(trait);
traitItems[id] = item;
}
}
this.traitsToItems[trait] = traitItems;
}
}
private getElementsWithTrait(trait: string, includeHidden: boolean): any[] {
var elements = [];
var items = this.traitsToItems[trait] || {};
var id: string;
for (id in items) {
if (items.hasOwnProperty(id) && (items[id].isVisible() || includeHidden)) {
elements.push(items[id].getElement());
}
}
return elements;
}
public dispose(): void {
if (this.registry) {
this.registry.dispose();
this.registry = null;
}
this._onSetInput.dispose();
this._onDidSetInput.dispose();
this._onRefresh.dispose();
this._onDidRefresh.dispose();
this._onDidHighlight.dispose();
this._onDidSelect.dispose();
this._onDidFocus.dispose();
this._onDidRevealItem.dispose();
this._onExpandItem.dispose();
this._onDidExpandItem.dispose();
this._onCollapseItem.dispose();
this._onDidCollapseItem.dispose();
this._onDidAddTraitItem.dispose();
this._onDidRemoveTraitItem.dispose();
this._onDidRefreshItem.dispose();
this._onRefreshItemChildren.dispose();
this._onDidRefreshItemChildren.dispose();
this._onDidDisposeItem.dispose();
}
}
| src/vs/base/parts/tree/browser/treeModel.ts | 0 | https://github.com/microsoft/vscode/commit/16e2629707e79f8e705426da7e3ca7dd6fec4652 | [
0.00019703729776665568,
0.0001735598052619025,
0.00016491599672008306,
0.0001740702282404527,
0.000003768562010009191
]
|
{
"id": 0,
"code_window": [
"import {AsyncValidatorFn, ValidatorFn} from './directives/validators';\n",
"import {AbstractControl, AbstractControlOptions, FormArray, FormControl, FormGroup, FormHooks} from './model';\n",
"\n",
"/**\n",
" * @description\n",
" * Creates an `AbstractControl` from a user-specified configuration.\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"function isAbstractControlOptions(options: AbstractControlOptions | {[key: string]: any}):\n",
" options is AbstractControlOptions {\n",
" return (<AbstractControlOptions>options).asyncValidators !== undefined ||\n",
" (<AbstractControlOptions>options).validators !== undefined ||\n",
" (<AbstractControlOptions>options).updateOn !== undefined;\n",
"}\n",
"\n"
],
"file_path": "packages/forms/src/form_builder.ts",
"type": "add",
"edit_start_line_idx": 13
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injectable} from '@angular/core';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
import {AbstractControl, AbstractControlOptions, FormArray, FormControl, FormGroup, FormHooks} from './model';
/**
* @description
* Creates an `AbstractControl` from a user-specified configuration.
*
* The `FormBuilder` provides syntactic sugar that shortens creating instances of a `FormControl`,
* `FormGroup`, or `FormArray`. It reduces the amount of boilerplate needed to build complex
* forms.
*
* @see [Reactive Forms Guide](/guide/reactive-forms)
*
* @publicApi
*/
@Injectable()
export class FormBuilder {
/**
* @description
* Construct a new `FormGroup` instance.
*
* @param controlsConfig A collection of child controls. The key for each child is the name
* under which it is registered.
*
* @param legacyOrOpts Configuration options object for the `FormGroup`. The object can
* have two shapes:
*
* 1) `AbstractControlOptions` object (preferred), which consists of:
* * `validators`: A synchronous validator function, or an array of validator functions
* * `asyncValidators`: A single async validator or array of async validator functions
* * `updateOn`: The event upon which the control should be updated (options: 'change' | 'blur' |
* submit')
*
* 2) Legacy configuration object, which consists of:
* * `validator`: A synchronous validator function, or an array of validator functions
* * `asyncValidator`: A single async validator or array of async validator functions
*
*/
group(controlsConfig: {[key: string]: any}, legacyOrOpts: {[key: string]: any}|null = null):
FormGroup {
const controls = this._reduceControls(controlsConfig);
let validators: ValidatorFn|ValidatorFn[]|null = null;
let asyncValidators: AsyncValidatorFn|AsyncValidatorFn[]|null = null;
let updateOn: FormHooks|undefined = undefined;
if (legacyOrOpts != null &&
(legacyOrOpts.asyncValidator !== undefined || legacyOrOpts.validator !== undefined)) {
// `legacyOrOpts` are legacy form group options
validators = legacyOrOpts.validator != null ? legacyOrOpts.validator : null;
asyncValidators = legacyOrOpts.asyncValidator != null ? legacyOrOpts.asyncValidator : null;
} else if (legacyOrOpts != null) {
// `legacyOrOpts` are `AbstractControlOptions`
validators = legacyOrOpts.validators != null ? legacyOrOpts.validators : null;
asyncValidators = legacyOrOpts.asyncValidators != null ? legacyOrOpts.asyncValidators : null;
updateOn = legacyOrOpts.updateOn != null ? legacyOrOpts.updateOn : undefined;
}
return new FormGroup(controls, {asyncValidators, updateOn, validators});
}
/**
* @description
* Construct a new `FormControl` with the given state, validators and options.
*
* @param formState Initializes the control with an initial state value, or
* with an object that contains both a value and a disabled status.
*
* @param validatorOrOpts A synchronous validator function, or an array of
* such functions, or an `AbstractControlOptions` object that contains
* validation functions and a validation trigger.
*
* @param asyncValidator A single async validator or array of async validator
* functions.
*
* @usageNotes
*
* ### Initialize a control as disabled
*
* The following example returns a control with an initial value in a disabled state.
*
* <code-example path="forms/ts/formBuilder/form_builder_example.ts"
* linenums="false" region="disabled-control">
* </code-example>
*/
control(
formState: any, validatorOrOpts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions|null,
asyncValidator?: AsyncValidatorFn|AsyncValidatorFn[]|null): FormControl {
return new FormControl(formState, validatorOrOpts, asyncValidator);
}
/**
* Constructs a new `FormArray` from the given array of configurations,
* validators and options.
*
* @param controlsConfig An array of child controls or control configs. Each
* child control is given an index when it is registered.
*
* @param validatorOrOpts A synchronous validator function, or an array of
* such functions, or an `AbstractControlOptions` object that contains
* validation functions and a validation trigger.
*
* @param asyncValidator A single async validator or array of async validator
* functions.
*/
array(
controlsConfig: any[],
validatorOrOpts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions|null,
asyncValidator?: AsyncValidatorFn|AsyncValidatorFn[]|null): FormArray {
const controls = controlsConfig.map(c => this._createControl(c));
return new FormArray(controls, validatorOrOpts, asyncValidator);
}
/** @internal */
_reduceControls(controlsConfig: {[k: string]: any}): {[key: string]: AbstractControl} {
const controls: {[key: string]: AbstractControl} = {};
Object.keys(controlsConfig).forEach(controlName => {
controls[controlName] = this._createControl(controlsConfig[controlName]);
});
return controls;
}
/** @internal */
_createControl(controlConfig: any): AbstractControl {
if (controlConfig instanceof FormControl || controlConfig instanceof FormGroup ||
controlConfig instanceof FormArray) {
return controlConfig;
} else if (Array.isArray(controlConfig)) {
const value = controlConfig[0];
const validator: ValidatorFn = controlConfig.length > 1 ? controlConfig[1] : null;
const asyncValidator: AsyncValidatorFn = controlConfig.length > 2 ? controlConfig[2] : null;
return this.control(value, validator, asyncValidator);
} else {
return this.control(controlConfig);
}
}
}
| packages/forms/src/form_builder.ts | 1 | https://github.com/angular/angular/commit/b0c75611d6ff193afd29cd12152c1b3e3f04424a | [
0.0011925657745450735,
0.0003026239573955536,
0.00016981911903712898,
0.00019457032612990588,
0.0002563610323704779
]
|
{
"id": 0,
"code_window": [
"import {AsyncValidatorFn, ValidatorFn} from './directives/validators';\n",
"import {AbstractControl, AbstractControlOptions, FormArray, FormControl, FormGroup, FormHooks} from './model';\n",
"\n",
"/**\n",
" * @description\n",
" * Creates an `AbstractControl` from a user-specified configuration.\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"function isAbstractControlOptions(options: AbstractControlOptions | {[key: string]: any}):\n",
" options is AbstractControlOptions {\n",
" return (<AbstractControlOptions>options).asyncValidators !== undefined ||\n",
" (<AbstractControlOptions>options).validators !== undefined ||\n",
" (<AbstractControlOptions>options).updateOn !== undefined;\n",
"}\n",
"\n"
],
"file_path": "packages/forms/src/form_builder.ts",
"type": "add",
"edit_start_line_idx": 13
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
function plural(n: number): number {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0) return 1;
return 5;
}
export default [
'en-TV', [['a', 'p'], ['AM', 'PM'], u], [['AM', 'PM'], u, u],
[
['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
],
u,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
[
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December'
]
],
u, [['B', 'A'], ['BC', 'AD'], ['Before Christ', 'Anno Domini']], 1, [6, 0],
['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE, d MMMM y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1}, {0}', u, '{1} \'at\' {0}', u],
['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], '$', 'Australian Dollar',
{'AUD': ['$'], 'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']}, plural
];
| packages/common/locales/en-TV.ts | 0 | https://github.com/angular/angular/commit/b0c75611d6ff193afd29cd12152c1b3e3f04424a | [
0.00017276352446060628,
0.00017106038285419345,
0.0001695781684247777,
0.00017110933549702168,
0.0000010206024398939917
]
|
{
"id": 0,
"code_window": [
"import {AsyncValidatorFn, ValidatorFn} from './directives/validators';\n",
"import {AbstractControl, AbstractControlOptions, FormArray, FormControl, FormGroup, FormHooks} from './model';\n",
"\n",
"/**\n",
" * @description\n",
" * Creates an `AbstractControl` from a user-specified configuration.\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"function isAbstractControlOptions(options: AbstractControlOptions | {[key: string]: any}):\n",
" options is AbstractControlOptions {\n",
" return (<AbstractControlOptions>options).asyncValidators !== undefined ||\n",
" (<AbstractControlOptions>options).validators !== undefined ||\n",
" (<AbstractControlOptions>options).updateOn !== undefined;\n",
"}\n",
"\n"
],
"file_path": "packages/forms/src/form_builder.ts",
"type": "add",
"edit_start_line_idx": 13
} | // #docplaster
// #docregion
// #docregion rxjs-operator-import
import { switchMap } from 'rxjs/operators';
// #enddocregion rxjs-operator-import
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { Observable } from 'rxjs';
import { HeroService } from '../hero.service';
import { Hero } from '../hero';
@Component({
selector: 'app-hero-detail',
templateUrl: './hero-detail.component.html',
styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {
hero$: Observable<Hero>;
// #docregion ctor
constructor(
private route: ActivatedRoute,
private router: Router,
private service: HeroService
) {}
// #enddocregion ctor
// #docregion ngOnInit
ngOnInit() {
this.hero$ = this.route.paramMap.pipe(
switchMap((params: ParamMap) =>
this.service.getHero(params.get('id')))
);
}
// #enddocregion ngOnInit
// #docregion gotoHeroes
gotoHeroes(hero: Hero) {
let heroId = hero ? hero.id : null;
// Pass along the hero id if available
// so that the HeroList component can select that hero.
// Include a junk 'foo' property for fun.
this.router.navigate(['/heroes', { id: heroId, foo: 'foo' }]);
}
// #enddocregion gotoHeroes
}
/*
// #docregion redirect
this.router.navigate(['/superheroes', { id: heroId, foo: 'foo' }]);
// #enddocregion redirect
*/
| aio/content/examples/router/src/app/heroes/hero-detail/hero-detail.component.3.ts | 0 | https://github.com/angular/angular/commit/b0c75611d6ff193afd29cd12152c1b3e3f04424a | [
0.00017377629410475492,
0.00017072423361241817,
0.00016452943964395672,
0.00017118467076215893,
0.0000030348646760103293
]
|
{
"id": 0,
"code_window": [
"import {AsyncValidatorFn, ValidatorFn} from './directives/validators';\n",
"import {AbstractControl, AbstractControlOptions, FormArray, FormControl, FormGroup, FormHooks} from './model';\n",
"\n",
"/**\n",
" * @description\n",
" * Creates an `AbstractControl` from a user-specified configuration.\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"function isAbstractControlOptions(options: AbstractControlOptions | {[key: string]: any}):\n",
" options is AbstractControlOptions {\n",
" return (<AbstractControlOptions>options).asyncValidators !== undefined ||\n",
" (<AbstractControlOptions>options).validators !== undefined ||\n",
" (<AbstractControlOptions>options).updateOn !== undefined;\n",
"}\n",
"\n"
],
"file_path": "packages/forms/src/form_builder.ts",
"type": "add",
"edit_start_line_idx": 13
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export {AnimationGroupPlayer as ɵAnimationGroupPlayer} from './players/animation_group_player';
export const ɵPRE_STYLE = '!';
| packages/animations/src/private_export.ts | 0 | https://github.com/angular/angular/commit/b0c75611d6ff193afd29cd12152c1b3e3f04424a | [
0.00017104083963204175,
0.00017104083963204175,
0.00017104083963204175,
0.00017104083963204175,
0
]
|
{
"id": 1,
"code_window": [
" * @param controlsConfig A collection of child controls. The key for each child is the name\n",
" * under which it is registered.\n",
" *\n",
" * @param legacyOrOpts Configuration options object for the `FormGroup`. The object can\n",
" * have two shapes:\n",
" *\n",
" * 1) `AbstractControlOptions` object (preferred), which consists of:\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param options Configuration options object for the `FormGroup`. The object can\n"
],
"file_path": "packages/forms/src/form_builder.ts",
"type": "replace",
"edit_start_line_idx": 34
} | export declare abstract class AbstractControl {
asyncValidator: AsyncValidatorFn | null;
readonly dirty: boolean;
readonly disabled: boolean;
readonly enabled: boolean;
readonly errors: ValidationErrors | null;
readonly invalid: boolean;
readonly parent: FormGroup | FormArray;
readonly pending: boolean;
readonly pristine: boolean;
readonly root: AbstractControl;
readonly status: string;
readonly statusChanges: Observable<any>;
readonly touched: boolean;
readonly untouched: boolean;
readonly updateOn: FormHooks;
readonly valid: boolean;
validator: ValidatorFn | null;
readonly value: any;
readonly valueChanges: Observable<any>;
constructor(validator: ValidatorFn | null, asyncValidator: AsyncValidatorFn | null);
clearAsyncValidators(): void;
clearValidators(): void;
disable(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
enable(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
get(path: Array<string | number> | string): AbstractControl | null;
getError(errorCode: string, path?: string[]): any;
hasError(errorCode: string, path?: string[]): boolean;
markAsDirty(opts?: {
onlySelf?: boolean;
}): void;
markAsPending(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
markAsPristine(opts?: {
onlySelf?: boolean;
}): void;
markAsTouched(opts?: {
onlySelf?: boolean;
}): void;
markAsUntouched(opts?: {
onlySelf?: boolean;
}): void;
abstract patchValue(value: any, options?: Object): void;
abstract reset(value?: any, options?: Object): void;
setAsyncValidators(newValidator: AsyncValidatorFn | AsyncValidatorFn[] | null): void;
setErrors(errors: ValidationErrors | null, opts?: {
emitEvent?: boolean;
}): void;
setParent(parent: FormGroup | FormArray): void;
setValidators(newValidator: ValidatorFn | ValidatorFn[] | null): void;
abstract setValue(value: any, options?: Object): void;
updateValueAndValidity(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
}
export declare abstract class AbstractControlDirective {
abstract readonly control: AbstractControl | null;
readonly dirty: boolean | null;
readonly disabled: boolean | null;
readonly enabled: boolean | null;
readonly errors: ValidationErrors | null;
readonly invalid: boolean | null;
readonly path: string[] | null;
readonly pending: boolean | null;
readonly pristine: boolean | null;
readonly status: string | null;
readonly statusChanges: Observable<any> | null;
readonly touched: boolean | null;
readonly untouched: boolean | null;
readonly valid: boolean | null;
readonly value: any;
readonly valueChanges: Observable<any> | null;
getError(errorCode: string, path?: string[]): any;
hasError(errorCode: string, path?: string[]): boolean;
reset(value?: any): void;
}
export interface AbstractControlOptions {
asyncValidators?: AsyncValidatorFn | AsyncValidatorFn[] | null;
updateOn?: 'change' | 'blur' | 'submit';
validators?: ValidatorFn | ValidatorFn[] | null;
}
export declare class AbstractFormGroupDirective extends ControlContainer implements OnInit, OnDestroy {
readonly asyncValidator: AsyncValidatorFn | null;
readonly control: FormGroup;
readonly formDirective: Form | null;
readonly path: string[];
readonly validator: ValidatorFn | null;
ngOnDestroy(): void;
ngOnInit(): void;
}
export interface AsyncValidator extends Validator {
validate(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>;
}
export interface AsyncValidatorFn {
(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>;
}
export declare class CheckboxControlValueAccessor implements ControlValueAccessor {
onChange: (_: any) => void;
onTouched: () => void;
constructor(_renderer: Renderer2, _elementRef: ElementRef);
registerOnChange(fn: (_: any) => {}): void;
registerOnTouched(fn: () => {}): void;
setDisabledState(isDisabled: boolean): void;
writeValue(value: any): void;
}
export declare class CheckboxRequiredValidator extends RequiredValidator {
validate(control: AbstractControl): ValidationErrors | null;
}
export declare const COMPOSITION_BUFFER_MODE: InjectionToken<boolean>;
export declare abstract class ControlContainer extends AbstractControlDirective {
readonly formDirective: Form | null;
name: string;
readonly path: string[] | null;
}
export interface ControlValueAccessor {
registerOnChange(fn: any): void;
registerOnTouched(fn: any): void;
setDisabledState?(isDisabled: boolean): void;
writeValue(obj: any): void;
}
export declare class DefaultValueAccessor implements ControlValueAccessor {
onChange: (_: any) => void;
onTouched: () => void;
constructor(_renderer: Renderer2, _elementRef: ElementRef, _compositionMode: boolean);
registerOnChange(fn: (_: any) => void): void;
registerOnTouched(fn: () => void): void;
setDisabledState(isDisabled: boolean): void;
writeValue(value: any): void;
}
export declare class EmailValidator implements Validator {
email: boolean | string;
registerOnValidatorChange(fn: () => void): void;
validate(control: AbstractControl): ValidationErrors | null;
}
export interface Form {
addControl(dir: NgControl): void;
addFormGroup(dir: AbstractFormGroupDirective): void;
getControl(dir: NgControl): FormControl;
getFormGroup(dir: AbstractFormGroupDirective): FormGroup;
removeControl(dir: NgControl): void;
removeFormGroup(dir: AbstractFormGroupDirective): void;
updateModel(dir: NgControl, value: any): void;
}
export declare class FormArray extends AbstractControl {
controls: AbstractControl[];
readonly length: number;
constructor(controls: AbstractControl[], validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null);
at(index: number): AbstractControl;
getRawValue(): any[];
insert(index: number, control: AbstractControl): void;
patchValue(value: any[], options?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
push(control: AbstractControl): void;
removeAt(index: number): void;
reset(value?: any, options?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
setControl(index: number, control: AbstractControl): void;
setValue(value: any[], options?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
}
export declare class FormArrayName extends ControlContainer implements OnInit, OnDestroy {
readonly asyncValidator: AsyncValidatorFn | null;
readonly control: FormArray;
readonly formDirective: FormGroupDirective | null;
name: string;
readonly path: string[];
readonly validator: ValidatorFn | null;
constructor(parent: ControlContainer, validators: any[], asyncValidators: any[]);
ngOnDestroy(): void;
ngOnInit(): void;
}
export declare class FormBuilder {
array(controlsConfig: any[], validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null): FormArray;
control(formState: any, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null): FormControl;
group(controlsConfig: {
[key: string]: any;
}, legacyOrOpts?: {
[key: string]: any;
} | null): FormGroup;
}
export declare class FormControl extends AbstractControl {
constructor(formState?: any, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null);
patchValue(value: any, options?: {
onlySelf?: boolean;
emitEvent?: boolean;
emitModelToViewChange?: boolean;
emitViewToModelChange?: boolean;
}): void;
registerOnChange(fn: Function): void;
registerOnDisabledChange(fn: (isDisabled: boolean) => void): void;
reset(formState?: any, options?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
setValue(value: any, options?: {
onlySelf?: boolean;
emitEvent?: boolean;
emitModelToViewChange?: boolean;
emitViewToModelChange?: boolean;
}): void;
}
export declare class FormControlDirective extends NgControl implements OnChanges {
readonly asyncValidator: AsyncValidatorFn | null;
readonly control: FormControl;
form: FormControl;
isDisabled: boolean;
/** @deprecated */ model: any;
readonly path: string[];
/** @deprecated */ update: EventEmitter<{}>;
readonly validator: ValidatorFn | null;
viewModel: any;
constructor(validators: Array<Validator | ValidatorFn>, asyncValidators: Array<AsyncValidator | AsyncValidatorFn>, valueAccessors: ControlValueAccessor[], _ngModelWarningConfig: string | null);
ngOnChanges(changes: SimpleChanges): void;
viewToModelUpdate(newValue: any): void;
}
export declare class FormControlName extends NgControl implements OnChanges, OnDestroy {
readonly asyncValidator: AsyncValidatorFn;
readonly control: FormControl;
readonly formDirective: any;
isDisabled: boolean;
/** @deprecated */ model: any;
name: string;
readonly path: string[];
/** @deprecated */ update: EventEmitter<{}>;
readonly validator: ValidatorFn | null;
constructor(parent: ControlContainer, validators: Array<Validator | ValidatorFn>, asyncValidators: Array<AsyncValidator | AsyncValidatorFn>, valueAccessors: ControlValueAccessor[], _ngModelWarningConfig: string | null);
ngOnChanges(changes: SimpleChanges): void;
ngOnDestroy(): void;
viewToModelUpdate(newValue: any): void;
}
export declare class FormGroup extends AbstractControl {
controls: {
[key: string]: AbstractControl;
};
constructor(controls: {
[key: string]: AbstractControl;
}, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null);
addControl(name: string, control: AbstractControl): void;
contains(controlName: string): boolean;
getRawValue(): any;
patchValue(value: {
[key: string]: any;
}, options?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
registerControl(name: string, control: AbstractControl): AbstractControl;
removeControl(name: string): void;
reset(value?: any, options?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
setControl(name: string, control: AbstractControl): void;
setValue(value: {
[key: string]: any;
}, options?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
}
export declare class FormGroupDirective extends ControlContainer implements Form, OnChanges {
readonly control: FormGroup;
directives: FormControlName[];
form: FormGroup;
readonly formDirective: Form;
ngSubmit: EventEmitter<{}>;
readonly path: string[];
readonly submitted: boolean;
constructor(_validators: any[], _asyncValidators: any[]);
addControl(dir: FormControlName): FormControl;
addFormArray(dir: FormArrayName): void;
addFormGroup(dir: FormGroupName): void;
getControl(dir: FormControlName): FormControl;
getFormArray(dir: FormArrayName): FormArray;
getFormGroup(dir: FormGroupName): FormGroup;
ngOnChanges(changes: SimpleChanges): void;
onReset(): void;
onSubmit($event: Event): boolean;
removeControl(dir: FormControlName): void;
removeFormArray(dir: FormArrayName): void;
removeFormGroup(dir: FormGroupName): void;
resetForm(value?: any): void;
updateModel(dir: FormControlName, value: any): void;
}
export declare class FormGroupName extends AbstractFormGroupDirective implements OnInit, OnDestroy {
name: string;
constructor(parent: ControlContainer, validators: any[], asyncValidators: any[]);
}
export declare class FormsModule {
static withConfig(opts: { warnOnDeprecatedNgFormSelector?: 'never' | 'once' | 'always';
}): ModuleWithProviders<FormsModule>;
}
export declare class MaxLengthValidator implements Validator, OnChanges {
maxlength: string;
ngOnChanges(changes: SimpleChanges): void;
registerOnValidatorChange(fn: () => void): void;
validate(control: AbstractControl): ValidationErrors | null;
}
export declare class MinLengthValidator implements Validator, OnChanges {
minlength: string;
ngOnChanges(changes: SimpleChanges): void;
registerOnValidatorChange(fn: () => void): void;
validate(control: AbstractControl): ValidationErrors | null;
}
export declare const NG_ASYNC_VALIDATORS: InjectionToken<(Function | Validator)[]>;
export declare const NG_VALIDATORS: InjectionToken<(Function | Validator)[]>;
export declare const NG_VALUE_ACCESSOR: InjectionToken<ControlValueAccessor>;
export declare abstract class NgControl extends AbstractControlDirective {
readonly asyncValidator: AsyncValidatorFn | null;
name: string | null;
readonly validator: ValidatorFn | null;
valueAccessor: ControlValueAccessor | null;
abstract viewToModelUpdate(newValue: any): void;
}
export declare class NgControlStatus extends AbstractControlStatus {
constructor(cd: NgControl);
}
export declare class NgControlStatusGroup extends AbstractControlStatus {
constructor(cd: ControlContainer);
}
export declare class NgForm extends ControlContainer implements Form, AfterViewInit {
readonly control: FormGroup;
readonly controls: {
[key: string]: AbstractControl;
};
form: FormGroup;
readonly formDirective: Form;
ngSubmit: EventEmitter<{}>;
options: {
updateOn?: FormHooks;
};
readonly path: string[];
readonly submitted: boolean;
constructor(validators: any[], asyncValidators: any[]);
addControl(dir: NgModel): void;
addFormGroup(dir: NgModelGroup): void;
getControl(dir: NgModel): FormControl;
getFormGroup(dir: NgModelGroup): FormGroup;
ngAfterViewInit(): void;
onReset(): void;
onSubmit($event: Event): boolean;
removeControl(dir: NgModel): void;
removeFormGroup(dir: NgModelGroup): void;
resetForm(value?: any): void;
setValue(value: {
[key: string]: any;
}): void;
updateModel(dir: NgControl, value: any): void;
}
/** @deprecated */
export declare class NgFormSelectorWarning {
constructor(ngFormWarning: string | null);
}
export declare class NgModel extends NgControl implements OnChanges, OnDestroy {
readonly asyncValidator: AsyncValidatorFn | null;
readonly control: FormControl;
readonly formDirective: any;
isDisabled: boolean;
model: any;
name: string;
options: {
name?: string;
standalone?: boolean;
updateOn?: FormHooks;
};
readonly path: string[];
update: EventEmitter<{}>;
readonly validator: ValidatorFn | null;
viewModel: any;
constructor(parent: ControlContainer, validators: Array<Validator | ValidatorFn>, asyncValidators: Array<AsyncValidator | AsyncValidatorFn>, valueAccessors: ControlValueAccessor[]);
ngOnChanges(changes: SimpleChanges): void;
ngOnDestroy(): void;
viewToModelUpdate(newValue: any): void;
}
export declare class NgModelGroup extends AbstractFormGroupDirective implements OnInit, OnDestroy {
name: string;
constructor(parent: ControlContainer, validators: any[], asyncValidators: any[]);
}
export declare class NgSelectOption implements OnDestroy {
id: string;
ngValue: any;
value: any;
constructor(_element: ElementRef, _renderer: Renderer2, _select: SelectControlValueAccessor);
ngOnDestroy(): void;
}
export declare class PatternValidator implements Validator, OnChanges {
pattern: string | RegExp;
ngOnChanges(changes: SimpleChanges): void;
registerOnValidatorChange(fn: () => void): void;
validate(control: AbstractControl): ValidationErrors | null;
}
export declare class RadioControlValueAccessor implements ControlValueAccessor, OnDestroy, OnInit {
formControlName: string;
name: string;
onChange: () => void;
onTouched: () => void;
value: any;
constructor(_renderer: Renderer2, _elementRef: ElementRef, _registry: RadioControlRegistry, _injector: Injector);
fireUncheck(value: any): void;
ngOnDestroy(): void;
ngOnInit(): void;
registerOnChange(fn: (_: any) => {}): void;
registerOnTouched(fn: () => {}): void;
setDisabledState(isDisabled: boolean): void;
writeValue(value: any): void;
}
export declare class ReactiveFormsModule {
static withConfig(opts: { warnOnNgModelWithFormControl: 'never' | 'once' | 'always';
}): ModuleWithProviders<ReactiveFormsModule>;
}
export declare class RequiredValidator implements Validator {
required: boolean | string;
registerOnValidatorChange(fn: () => void): void;
validate(control: AbstractControl): ValidationErrors | null;
}
export declare class SelectControlValueAccessor implements ControlValueAccessor {
compareWith: (o1: any, o2: any) => boolean;
onChange: (_: any) => void;
onTouched: () => void;
value: any;
constructor(_renderer: Renderer2, _elementRef: ElementRef);
registerOnChange(fn: (value: any) => any): void;
registerOnTouched(fn: () => any): void;
setDisabledState(isDisabled: boolean): void;
writeValue(value: any): void;
}
export declare class SelectMultipleControlValueAccessor implements ControlValueAccessor {
compareWith: (o1: any, o2: any) => boolean;
onChange: (_: any) => void;
onTouched: () => void;
value: any;
constructor(_renderer: Renderer2, _elementRef: ElementRef);
registerOnChange(fn: (value: any) => any): void;
registerOnTouched(fn: () => any): void;
setDisabledState(isDisabled: boolean): void;
writeValue(value: any): void;
}
export declare type ValidationErrors = {
[key: string]: any;
};
export interface Validator {
registerOnValidatorChange?(fn: () => void): void;
validate(control: AbstractControl): ValidationErrors | null;
}
export interface ValidatorFn {
(control: AbstractControl): ValidationErrors | null;
}
export declare class Validators {
static compose(validators: (ValidatorFn | null | undefined)[]): ValidatorFn | null;
static compose(validators: null): null;
static composeAsync(validators: (AsyncValidatorFn | null)[]): AsyncValidatorFn | null;
static email(control: AbstractControl): ValidationErrors | null;
static max(max: number): ValidatorFn;
static maxLength(maxLength: number): ValidatorFn;
static min(min: number): ValidatorFn;
static minLength(minLength: number): ValidatorFn;
static nullValidator(control: AbstractControl): ValidationErrors | null;
static pattern(pattern: string | RegExp): ValidatorFn;
static required(control: AbstractControl): ValidationErrors | null;
static requiredTrue(control: AbstractControl): ValidationErrors | null;
}
export declare const VERSION: Version;
| tools/public_api_guard/forms/forms.d.ts | 1 | https://github.com/angular/angular/commit/b0c75611d6ff193afd29cd12152c1b3e3f04424a | [
0.004393014125525951,
0.0004382548213470727,
0.00016714850789867342,
0.0002638649893924594,
0.0006482892204076052
]
|
{
"id": 1,
"code_window": [
" * @param controlsConfig A collection of child controls. The key for each child is the name\n",
" * under which it is registered.\n",
" *\n",
" * @param legacyOrOpts Configuration options object for the `FormGroup`. The object can\n",
" * have two shapes:\n",
" *\n",
" * 1) `AbstractControlOptions` object (preferred), which consists of:\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param options Configuration options object for the `FormGroup`. The object can\n"
],
"file_path": "packages/forms/src/form_builder.ts",
"type": "replace",
"edit_start_line_idx": 34
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AotCompilerOptions} from '../aot/compiler_options';
import {StaticReflector} from '../aot/static_reflector';
import {StaticSymbol} from '../aot/static_symbol';
import {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompilePipeSummary} from '../compile_metadata';
import {BindingForm, BuiltinConverter, EventHandlerVars, LocalResolver, convertActionBinding, convertPropertyBinding, convertPropertyBindingBuiltins} from '../compiler_util/expression_converter';
import {AST, ASTWithSource, Interpolation} from '../expression_parser/ast';
import {Identifiers} from '../identifiers';
import * as o from '../output/output_ast';
import {convertValueToOutputAst} from '../output/value_util';
import {ParseSourceSpan} from '../parse_util';
import {AttrAst, BoundDirectivePropertyAst, BoundElementPropertyAst, BoundEventAst, BoundTextAst, DirectiveAst, ElementAst, EmbeddedTemplateAst, NgContentAst, PropertyBindingType, ProviderAst, ProviderAstType, QueryMatch, ReferenceAst, TemplateAst, TemplateAstVisitor, TextAst, VariableAst, templateVisitAll} from '../template_parser/template_ast';
import {OutputContext} from '../util';
/**
* Generates code that is used to type check templates.
*/
export class TypeCheckCompiler {
constructor(private options: AotCompilerOptions, private reflector: StaticReflector) {}
/**
* Important notes:
* - This must not produce new `import` statements, but only refer to types outside
* of the file via the variables provided via externalReferenceVars.
* This allows Typescript to reuse the old program's structure as no imports have changed.
* - This must not produce any exports, as this would pollute the .d.ts file
* and also violate the point above.
*/
compileComponent(
componentId: string, component: CompileDirectiveMetadata, template: TemplateAst[],
usedPipes: CompilePipeSummary[], externalReferenceVars: Map<StaticSymbol, string>,
ctx: OutputContext): o.Statement[] {
const pipes = new Map<string, StaticSymbol>();
usedPipes.forEach(p => pipes.set(p.name, p.type.reference));
let embeddedViewCount = 0;
const viewBuilderFactory =
(parent: ViewBuilder | null, guards: GuardExpression[]): ViewBuilder => {
const embeddedViewIndex = embeddedViewCount++;
return new ViewBuilder(
this.options, this.reflector, externalReferenceVars, parent, component.type.reference,
component.isHost, embeddedViewIndex, pipes, guards, ctx, viewBuilderFactory);
};
const visitor = viewBuilderFactory(null, []);
visitor.visitAll([], template);
return visitor.build(componentId);
}
}
interface GuardExpression {
guard: StaticSymbol;
useIf: boolean;
expression: Expression;
}
interface ViewBuilderFactory {
(parent: ViewBuilder, guards: GuardExpression[]): ViewBuilder;
}
// Note: This is used as key in Map and should therefore be
// unique per value.
type OutputVarType = o.BuiltinTypeName | StaticSymbol;
interface Expression {
context: OutputVarType;
sourceSpan: ParseSourceSpan;
value: AST;
}
const DYNAMIC_VAR_NAME = '_any';
class TypeCheckLocalResolver implements LocalResolver {
getLocal(name: string): o.Expression|null {
if (name === EventHandlerVars.event.name) {
// References to the event should not be type-checked.
// TODO(chuckj): determine a better type for the event.
return o.variable(DYNAMIC_VAR_NAME);
}
return null;
}
}
const defaultResolver = new TypeCheckLocalResolver();
class ViewBuilder implements TemplateAstVisitor, LocalResolver {
private refOutputVars = new Map<string, OutputVarType>();
private variables: VariableAst[] = [];
private children: ViewBuilder[] = [];
private updates: Expression[] = [];
private actions: Expression[] = [];
constructor(
private options: AotCompilerOptions, private reflector: StaticReflector,
private externalReferenceVars: Map<StaticSymbol, string>, private parent: ViewBuilder|null,
private component: StaticSymbol, private isHostComponent: boolean,
private embeddedViewIndex: number, private pipes: Map<string, StaticSymbol>,
private guards: GuardExpression[], private ctx: OutputContext,
private viewBuilderFactory: ViewBuilderFactory) {}
private getOutputVar(type: o.BuiltinTypeName|StaticSymbol): string {
let varName: string|undefined;
if (type === this.component && this.isHostComponent) {
varName = DYNAMIC_VAR_NAME;
} else if (type instanceof StaticSymbol) {
varName = this.externalReferenceVars.get(type);
} else {
varName = DYNAMIC_VAR_NAME;
}
if (!varName) {
throw new Error(
`Illegal State: referring to a type without a variable ${JSON.stringify(type)}`);
}
return varName;
}
private getTypeGuardExpressions(ast: EmbeddedTemplateAst): GuardExpression[] {
const result = [...this.guards];
for (let directive of ast.directives) {
for (let input of directive.inputs) {
const guard = directive.directive.guards[input.directiveName];
if (guard) {
const useIf = guard === 'UseIf';
result.push({
guard,
useIf,
expression: {context: this.component, value: input.value} as Expression
});
}
}
}
return result;
}
visitAll(variables: VariableAst[], astNodes: TemplateAst[]) {
this.variables = variables;
templateVisitAll(this, astNodes);
}
build(componentId: string, targetStatements: o.Statement[] = []): o.Statement[] {
this.children.forEach((child) => child.build(componentId, targetStatements));
let viewStmts: o.Statement[] =
[o.variable(DYNAMIC_VAR_NAME).set(o.NULL_EXPR).toDeclStmt(o.DYNAMIC_TYPE)];
let bindingCount = 0;
this.updates.forEach((expression) => {
const {sourceSpan, context, value} = this.preprocessUpdateExpression(expression);
const bindingId = `${bindingCount++}`;
const nameResolver = context === this.component ? this : defaultResolver;
const {stmts, currValExpr} = convertPropertyBinding(
nameResolver, o.variable(this.getOutputVar(context)), value, bindingId,
BindingForm.General);
stmts.push(new o.ExpressionStatement(currValExpr));
viewStmts.push(...stmts.map(
(stmt: o.Statement) => o.applySourceSpanToStatementIfNeeded(stmt, sourceSpan)));
});
this.actions.forEach(({sourceSpan, context, value}) => {
const bindingId = `${bindingCount++}`;
const nameResolver = context === this.component ? this : defaultResolver;
const {stmts} = convertActionBinding(
nameResolver, o.variable(this.getOutputVar(context)), value, bindingId);
viewStmts.push(...stmts.map(
(stmt: o.Statement) => o.applySourceSpanToStatementIfNeeded(stmt, sourceSpan)));
});
if (this.guards.length) {
let guardExpression: o.Expression|undefined = undefined;
for (const guard of this.guards) {
const {context, value} = this.preprocessUpdateExpression(guard.expression);
const bindingId = `${bindingCount++}`;
const nameResolver = context === this.component ? this : defaultResolver;
// We only support support simple expressions and ignore others as they
// are unlikely to affect type narrowing.
const {stmts, currValExpr} = convertPropertyBinding(
nameResolver, o.variable(this.getOutputVar(context)), value, bindingId,
BindingForm.TrySimple);
if (stmts.length == 0) {
const guardClause =
guard.useIf ? currValExpr : this.ctx.importExpr(guard.guard).callFn([currValExpr]);
guardExpression = guardExpression ? guardExpression.and(guardClause) : guardClause;
}
}
if (guardExpression) {
viewStmts = [new o.IfStmt(guardExpression, viewStmts)];
}
}
const viewName = `_View_${componentId}_${this.embeddedViewIndex}`;
const viewFactory = new o.DeclareFunctionStmt(viewName, [], viewStmts);
targetStatements.push(viewFactory);
return targetStatements;
}
visitBoundText(ast: BoundTextAst, context: any): any {
const astWithSource = <ASTWithSource>ast.value;
const inter = <Interpolation>astWithSource.ast;
inter.expressions.forEach(
(expr) =>
this.updates.push({context: this.component, value: expr, sourceSpan: ast.sourceSpan}));
}
visitEmbeddedTemplate(ast: EmbeddedTemplateAst, context: any): any {
this.visitElementOrTemplate(ast);
// Note: The old view compiler used to use an `any` type
// for the context in any embedded view.
// We keep this behaivor behind a flag for now.
if (this.options.fullTemplateTypeCheck) {
// Find any applicable type guards. For example, NgIf has a type guard on ngIf
// (see NgIf.ngIfTypeGuard) that can be used to indicate that a template is only
// stamped out if ngIf is truthy so any bindings in the template can assume that,
// if a nullable type is used for ngIf, that expression is not null or undefined.
const guards = this.getTypeGuardExpressions(ast);
const childVisitor = this.viewBuilderFactory(this, guards);
this.children.push(childVisitor);
childVisitor.visitAll(ast.variables, ast.children);
}
}
visitElement(ast: ElementAst, context: any): any {
this.visitElementOrTemplate(ast);
let inputDefs: o.Expression[] = [];
let updateRendererExpressions: Expression[] = [];
let outputDefs: o.Expression[] = [];
ast.inputs.forEach((inputAst) => {
this.updates.push(
{context: this.component, value: inputAst.value, sourceSpan: inputAst.sourceSpan});
});
templateVisitAll(this, ast.children);
}
private visitElementOrTemplate(ast: {
outputs: BoundEventAst[],
directives: DirectiveAst[],
references: ReferenceAst[],
}) {
ast.directives.forEach((dirAst) => { this.visitDirective(dirAst); });
ast.references.forEach((ref) => {
let outputVarType: OutputVarType = null !;
// Note: The old view compiler used to use an `any` type
// for directives exposed via `exportAs`.
// We keep this behaivor behind a flag for now.
if (ref.value && ref.value.identifier && this.options.fullTemplateTypeCheck) {
outputVarType = ref.value.identifier.reference;
} else {
outputVarType = o.BuiltinTypeName.Dynamic;
}
this.refOutputVars.set(ref.name, outputVarType);
});
ast.outputs.forEach((outputAst) => {
this.actions.push(
{context: this.component, value: outputAst.handler, sourceSpan: outputAst.sourceSpan});
});
}
visitDirective(dirAst: DirectiveAst) {
const dirType = dirAst.directive.type.reference;
dirAst.inputs.forEach(
(input) => this.updates.push(
{context: this.component, value: input.value, sourceSpan: input.sourceSpan}));
// Note: The old view compiler used to use an `any` type
// for expressions in host properties / events.
// We keep this behaivor behind a flag for now.
if (this.options.fullTemplateTypeCheck) {
dirAst.hostProperties.forEach(
(inputAst) => this.updates.push(
{context: dirType, value: inputAst.value, sourceSpan: inputAst.sourceSpan}));
dirAst.hostEvents.forEach((hostEventAst) => this.actions.push({
context: dirType,
value: hostEventAst.handler,
sourceSpan: hostEventAst.sourceSpan
}));
}
}
getLocal(name: string): o.Expression|null {
if (name == EventHandlerVars.event.name) {
return o.variable(this.getOutputVar(o.BuiltinTypeName.Dynamic));
}
for (let currBuilder: ViewBuilder|null = this; currBuilder; currBuilder = currBuilder.parent) {
let outputVarType: OutputVarType|undefined;
// check references
outputVarType = currBuilder.refOutputVars.get(name);
if (outputVarType == null) {
// check variables
const varAst = currBuilder.variables.find((varAst) => varAst.name === name);
if (varAst) {
outputVarType = o.BuiltinTypeName.Dynamic;
}
}
if (outputVarType != null) {
return o.variable(this.getOutputVar(outputVarType));
}
}
return null;
}
private pipeOutputVar(name: string): string {
const pipe = this.pipes.get(name);
if (!pipe) {
throw new Error(
`Illegal State: Could not find pipe ${name} in template of ${this.component}`);
}
return this.getOutputVar(pipe);
}
private preprocessUpdateExpression(expression: Expression): Expression {
return {
sourceSpan: expression.sourceSpan,
context: expression.context,
value: convertPropertyBindingBuiltins(
{
createLiteralArrayConverter: (argCount: number) => (args: o.Expression[]) => {
const arr = o.literalArr(args);
// Note: The old view compiler used to use an `any` type
// for arrays.
return this.options.fullTemplateTypeCheck ? arr : arr.cast(o.DYNAMIC_TYPE);
},
createLiteralMapConverter:
(keys: {key: string, quoted: boolean}[]) => (values: o.Expression[]) => {
const entries = keys.map((k, i) => ({
key: k.key,
value: values[i],
quoted: k.quoted,
}));
const map = o.literalMap(entries);
// Note: The old view compiler used to use an `any` type
// for maps.
return this.options.fullTemplateTypeCheck ? map : map.cast(o.DYNAMIC_TYPE);
},
createPipeConverter: (name: string, argCount: number) => (args: o.Expression[]) => {
// Note: The old view compiler used to use an `any` type
// for pipes.
const pipeExpr = this.options.fullTemplateTypeCheck ?
o.variable(this.pipeOutputVar(name)) :
o.variable(this.getOutputVar(o.BuiltinTypeName.Dynamic));
return pipeExpr.callMethod('transform', args);
},
},
expression.value)
};
}
visitNgContent(ast: NgContentAst, context: any): any {}
visitText(ast: TextAst, context: any): any {}
visitDirectiveProperty(ast: BoundDirectivePropertyAst, context: any): any {}
visitReference(ast: ReferenceAst, context: any): any {}
visitVariable(ast: VariableAst, context: any): any {}
visitEvent(ast: BoundEventAst, context: any): any {}
visitElementProperty(ast: BoundElementPropertyAst, context: any): any {}
visitAttr(ast: AttrAst, context: any): any {}
}
| packages/compiler/src/view_compiler/type_check_compiler.ts | 0 | https://github.com/angular/angular/commit/b0c75611d6ff193afd29cd12152c1b3e3f04424a | [
0.00022653609630651772,
0.00017390528228133917,
0.00016511989815626293,
0.00016954309830907732,
0.000013415517059911508
]
|
{
"id": 1,
"code_window": [
" * @param controlsConfig A collection of child controls. The key for each child is the name\n",
" * under which it is registered.\n",
" *\n",
" * @param legacyOrOpts Configuration options object for the `FormGroup`. The object can\n",
" * have two shapes:\n",
" *\n",
" * 1) `AbstractControlOptions` object (preferred), which consists of:\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param options Configuration options object for the `FormGroup`. The object can\n"
],
"file_path": "packages/forms/src/form_builder.ts",
"type": "replace",
"edit_start_line_idx": 34
} | // #docregion
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h1>Security</h1>
<app-inner-html-binding></app-inner-html-binding>
<app-bypass-security></app-bypass-security>
`
})
export class AppComponent {
}
| aio/content/examples/security/src/app/app.component.ts | 0 | https://github.com/angular/angular/commit/b0c75611d6ff193afd29cd12152c1b3e3f04424a | [
0.00019968324340879917,
0.00018442489090375602,
0.00016916652384679765,
0.00018442489090375602,
0.000015258359781000763
]
|
{
"id": 1,
"code_window": [
" * @param controlsConfig A collection of child controls. The key for each child is the name\n",
" * under which it is registered.\n",
" *\n",
" * @param legacyOrOpts Configuration options object for the `FormGroup`. The object can\n",
" * have two shapes:\n",
" *\n",
" * 1) `AbstractControlOptions` object (preferred), which consists of:\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param options Configuration options object for the `FormGroup`. The object can\n"
],
"file_path": "packages/forms/src/form_builder.ts",
"type": "replace",
"edit_start_line_idx": 34
} | // #docregion
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule);
| aio/content/examples/security/src/main.ts | 0 | https://github.com/angular/angular/commit/b0c75611d6ff193afd29cd12152c1b3e3f04424a | [
0.00016994027828332037,
0.00016849554958753288,
0.00016705083544366062,
0.00016849554958753288,
0.0000014447214198298752
]
|
{
"id": 2,
"code_window": [
" * * `asyncValidator`: A single async validator or array of async validator functions\n",
" *\n",
" */\n",
" group(controlsConfig: {[key: string]: any}, legacyOrOpts: {[key: string]: any}|null = null):\n",
" FormGroup {\n",
" const controls = this._reduceControls(controlsConfig);\n",
"\n",
" let validators: ValidatorFn|ValidatorFn[]|null = null;\n",
" let asyncValidators: AsyncValidatorFn|AsyncValidatorFn[]|null = null;\n",
" let updateOn: FormHooks|undefined = undefined;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" group(\n",
" controlsConfig: {[key: string]: any},\n",
" options: AbstractControlOptions|{[key: string]: any}|null = null): FormGroup {\n"
],
"file_path": "packages/forms/src/form_builder.ts",
"type": "replace",
"edit_start_line_idx": 48
} | export declare abstract class AbstractControl {
asyncValidator: AsyncValidatorFn | null;
readonly dirty: boolean;
readonly disabled: boolean;
readonly enabled: boolean;
readonly errors: ValidationErrors | null;
readonly invalid: boolean;
readonly parent: FormGroup | FormArray;
readonly pending: boolean;
readonly pristine: boolean;
readonly root: AbstractControl;
readonly status: string;
readonly statusChanges: Observable<any>;
readonly touched: boolean;
readonly untouched: boolean;
readonly updateOn: FormHooks;
readonly valid: boolean;
validator: ValidatorFn | null;
readonly value: any;
readonly valueChanges: Observable<any>;
constructor(validator: ValidatorFn | null, asyncValidator: AsyncValidatorFn | null);
clearAsyncValidators(): void;
clearValidators(): void;
disable(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
enable(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
get(path: Array<string | number> | string): AbstractControl | null;
getError(errorCode: string, path?: string[]): any;
hasError(errorCode: string, path?: string[]): boolean;
markAsDirty(opts?: {
onlySelf?: boolean;
}): void;
markAsPending(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
markAsPristine(opts?: {
onlySelf?: boolean;
}): void;
markAsTouched(opts?: {
onlySelf?: boolean;
}): void;
markAsUntouched(opts?: {
onlySelf?: boolean;
}): void;
abstract patchValue(value: any, options?: Object): void;
abstract reset(value?: any, options?: Object): void;
setAsyncValidators(newValidator: AsyncValidatorFn | AsyncValidatorFn[] | null): void;
setErrors(errors: ValidationErrors | null, opts?: {
emitEvent?: boolean;
}): void;
setParent(parent: FormGroup | FormArray): void;
setValidators(newValidator: ValidatorFn | ValidatorFn[] | null): void;
abstract setValue(value: any, options?: Object): void;
updateValueAndValidity(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
}
export declare abstract class AbstractControlDirective {
abstract readonly control: AbstractControl | null;
readonly dirty: boolean | null;
readonly disabled: boolean | null;
readonly enabled: boolean | null;
readonly errors: ValidationErrors | null;
readonly invalid: boolean | null;
readonly path: string[] | null;
readonly pending: boolean | null;
readonly pristine: boolean | null;
readonly status: string | null;
readonly statusChanges: Observable<any> | null;
readonly touched: boolean | null;
readonly untouched: boolean | null;
readonly valid: boolean | null;
readonly value: any;
readonly valueChanges: Observable<any> | null;
getError(errorCode: string, path?: string[]): any;
hasError(errorCode: string, path?: string[]): boolean;
reset(value?: any): void;
}
export interface AbstractControlOptions {
asyncValidators?: AsyncValidatorFn | AsyncValidatorFn[] | null;
updateOn?: 'change' | 'blur' | 'submit';
validators?: ValidatorFn | ValidatorFn[] | null;
}
export declare class AbstractFormGroupDirective extends ControlContainer implements OnInit, OnDestroy {
readonly asyncValidator: AsyncValidatorFn | null;
readonly control: FormGroup;
readonly formDirective: Form | null;
readonly path: string[];
readonly validator: ValidatorFn | null;
ngOnDestroy(): void;
ngOnInit(): void;
}
export interface AsyncValidator extends Validator {
validate(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>;
}
export interface AsyncValidatorFn {
(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>;
}
export declare class CheckboxControlValueAccessor implements ControlValueAccessor {
onChange: (_: any) => void;
onTouched: () => void;
constructor(_renderer: Renderer2, _elementRef: ElementRef);
registerOnChange(fn: (_: any) => {}): void;
registerOnTouched(fn: () => {}): void;
setDisabledState(isDisabled: boolean): void;
writeValue(value: any): void;
}
export declare class CheckboxRequiredValidator extends RequiredValidator {
validate(control: AbstractControl): ValidationErrors | null;
}
export declare const COMPOSITION_BUFFER_MODE: InjectionToken<boolean>;
export declare abstract class ControlContainer extends AbstractControlDirective {
readonly formDirective: Form | null;
name: string;
readonly path: string[] | null;
}
export interface ControlValueAccessor {
registerOnChange(fn: any): void;
registerOnTouched(fn: any): void;
setDisabledState?(isDisabled: boolean): void;
writeValue(obj: any): void;
}
export declare class DefaultValueAccessor implements ControlValueAccessor {
onChange: (_: any) => void;
onTouched: () => void;
constructor(_renderer: Renderer2, _elementRef: ElementRef, _compositionMode: boolean);
registerOnChange(fn: (_: any) => void): void;
registerOnTouched(fn: () => void): void;
setDisabledState(isDisabled: boolean): void;
writeValue(value: any): void;
}
export declare class EmailValidator implements Validator {
email: boolean | string;
registerOnValidatorChange(fn: () => void): void;
validate(control: AbstractControl): ValidationErrors | null;
}
export interface Form {
addControl(dir: NgControl): void;
addFormGroup(dir: AbstractFormGroupDirective): void;
getControl(dir: NgControl): FormControl;
getFormGroup(dir: AbstractFormGroupDirective): FormGroup;
removeControl(dir: NgControl): void;
removeFormGroup(dir: AbstractFormGroupDirective): void;
updateModel(dir: NgControl, value: any): void;
}
export declare class FormArray extends AbstractControl {
controls: AbstractControl[];
readonly length: number;
constructor(controls: AbstractControl[], validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null);
at(index: number): AbstractControl;
getRawValue(): any[];
insert(index: number, control: AbstractControl): void;
patchValue(value: any[], options?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
push(control: AbstractControl): void;
removeAt(index: number): void;
reset(value?: any, options?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
setControl(index: number, control: AbstractControl): void;
setValue(value: any[], options?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
}
export declare class FormArrayName extends ControlContainer implements OnInit, OnDestroy {
readonly asyncValidator: AsyncValidatorFn | null;
readonly control: FormArray;
readonly formDirective: FormGroupDirective | null;
name: string;
readonly path: string[];
readonly validator: ValidatorFn | null;
constructor(parent: ControlContainer, validators: any[], asyncValidators: any[]);
ngOnDestroy(): void;
ngOnInit(): void;
}
export declare class FormBuilder {
array(controlsConfig: any[], validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null): FormArray;
control(formState: any, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null): FormControl;
group(controlsConfig: {
[key: string]: any;
}, legacyOrOpts?: {
[key: string]: any;
} | null): FormGroup;
}
export declare class FormControl extends AbstractControl {
constructor(formState?: any, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null);
patchValue(value: any, options?: {
onlySelf?: boolean;
emitEvent?: boolean;
emitModelToViewChange?: boolean;
emitViewToModelChange?: boolean;
}): void;
registerOnChange(fn: Function): void;
registerOnDisabledChange(fn: (isDisabled: boolean) => void): void;
reset(formState?: any, options?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
setValue(value: any, options?: {
onlySelf?: boolean;
emitEvent?: boolean;
emitModelToViewChange?: boolean;
emitViewToModelChange?: boolean;
}): void;
}
export declare class FormControlDirective extends NgControl implements OnChanges {
readonly asyncValidator: AsyncValidatorFn | null;
readonly control: FormControl;
form: FormControl;
isDisabled: boolean;
/** @deprecated */ model: any;
readonly path: string[];
/** @deprecated */ update: EventEmitter<{}>;
readonly validator: ValidatorFn | null;
viewModel: any;
constructor(validators: Array<Validator | ValidatorFn>, asyncValidators: Array<AsyncValidator | AsyncValidatorFn>, valueAccessors: ControlValueAccessor[], _ngModelWarningConfig: string | null);
ngOnChanges(changes: SimpleChanges): void;
viewToModelUpdate(newValue: any): void;
}
export declare class FormControlName extends NgControl implements OnChanges, OnDestroy {
readonly asyncValidator: AsyncValidatorFn;
readonly control: FormControl;
readonly formDirective: any;
isDisabled: boolean;
/** @deprecated */ model: any;
name: string;
readonly path: string[];
/** @deprecated */ update: EventEmitter<{}>;
readonly validator: ValidatorFn | null;
constructor(parent: ControlContainer, validators: Array<Validator | ValidatorFn>, asyncValidators: Array<AsyncValidator | AsyncValidatorFn>, valueAccessors: ControlValueAccessor[], _ngModelWarningConfig: string | null);
ngOnChanges(changes: SimpleChanges): void;
ngOnDestroy(): void;
viewToModelUpdate(newValue: any): void;
}
export declare class FormGroup extends AbstractControl {
controls: {
[key: string]: AbstractControl;
};
constructor(controls: {
[key: string]: AbstractControl;
}, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null);
addControl(name: string, control: AbstractControl): void;
contains(controlName: string): boolean;
getRawValue(): any;
patchValue(value: {
[key: string]: any;
}, options?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
registerControl(name: string, control: AbstractControl): AbstractControl;
removeControl(name: string): void;
reset(value?: any, options?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
setControl(name: string, control: AbstractControl): void;
setValue(value: {
[key: string]: any;
}, options?: {
onlySelf?: boolean;
emitEvent?: boolean;
}): void;
}
export declare class FormGroupDirective extends ControlContainer implements Form, OnChanges {
readonly control: FormGroup;
directives: FormControlName[];
form: FormGroup;
readonly formDirective: Form;
ngSubmit: EventEmitter<{}>;
readonly path: string[];
readonly submitted: boolean;
constructor(_validators: any[], _asyncValidators: any[]);
addControl(dir: FormControlName): FormControl;
addFormArray(dir: FormArrayName): void;
addFormGroup(dir: FormGroupName): void;
getControl(dir: FormControlName): FormControl;
getFormArray(dir: FormArrayName): FormArray;
getFormGroup(dir: FormGroupName): FormGroup;
ngOnChanges(changes: SimpleChanges): void;
onReset(): void;
onSubmit($event: Event): boolean;
removeControl(dir: FormControlName): void;
removeFormArray(dir: FormArrayName): void;
removeFormGroup(dir: FormGroupName): void;
resetForm(value?: any): void;
updateModel(dir: FormControlName, value: any): void;
}
export declare class FormGroupName extends AbstractFormGroupDirective implements OnInit, OnDestroy {
name: string;
constructor(parent: ControlContainer, validators: any[], asyncValidators: any[]);
}
export declare class FormsModule {
static withConfig(opts: { warnOnDeprecatedNgFormSelector?: 'never' | 'once' | 'always';
}): ModuleWithProviders<FormsModule>;
}
export declare class MaxLengthValidator implements Validator, OnChanges {
maxlength: string;
ngOnChanges(changes: SimpleChanges): void;
registerOnValidatorChange(fn: () => void): void;
validate(control: AbstractControl): ValidationErrors | null;
}
export declare class MinLengthValidator implements Validator, OnChanges {
minlength: string;
ngOnChanges(changes: SimpleChanges): void;
registerOnValidatorChange(fn: () => void): void;
validate(control: AbstractControl): ValidationErrors | null;
}
export declare const NG_ASYNC_VALIDATORS: InjectionToken<(Function | Validator)[]>;
export declare const NG_VALIDATORS: InjectionToken<(Function | Validator)[]>;
export declare const NG_VALUE_ACCESSOR: InjectionToken<ControlValueAccessor>;
export declare abstract class NgControl extends AbstractControlDirective {
readonly asyncValidator: AsyncValidatorFn | null;
name: string | null;
readonly validator: ValidatorFn | null;
valueAccessor: ControlValueAccessor | null;
abstract viewToModelUpdate(newValue: any): void;
}
export declare class NgControlStatus extends AbstractControlStatus {
constructor(cd: NgControl);
}
export declare class NgControlStatusGroup extends AbstractControlStatus {
constructor(cd: ControlContainer);
}
export declare class NgForm extends ControlContainer implements Form, AfterViewInit {
readonly control: FormGroup;
readonly controls: {
[key: string]: AbstractControl;
};
form: FormGroup;
readonly formDirective: Form;
ngSubmit: EventEmitter<{}>;
options: {
updateOn?: FormHooks;
};
readonly path: string[];
readonly submitted: boolean;
constructor(validators: any[], asyncValidators: any[]);
addControl(dir: NgModel): void;
addFormGroup(dir: NgModelGroup): void;
getControl(dir: NgModel): FormControl;
getFormGroup(dir: NgModelGroup): FormGroup;
ngAfterViewInit(): void;
onReset(): void;
onSubmit($event: Event): boolean;
removeControl(dir: NgModel): void;
removeFormGroup(dir: NgModelGroup): void;
resetForm(value?: any): void;
setValue(value: {
[key: string]: any;
}): void;
updateModel(dir: NgControl, value: any): void;
}
/** @deprecated */
export declare class NgFormSelectorWarning {
constructor(ngFormWarning: string | null);
}
export declare class NgModel extends NgControl implements OnChanges, OnDestroy {
readonly asyncValidator: AsyncValidatorFn | null;
readonly control: FormControl;
readonly formDirective: any;
isDisabled: boolean;
model: any;
name: string;
options: {
name?: string;
standalone?: boolean;
updateOn?: FormHooks;
};
readonly path: string[];
update: EventEmitter<{}>;
readonly validator: ValidatorFn | null;
viewModel: any;
constructor(parent: ControlContainer, validators: Array<Validator | ValidatorFn>, asyncValidators: Array<AsyncValidator | AsyncValidatorFn>, valueAccessors: ControlValueAccessor[]);
ngOnChanges(changes: SimpleChanges): void;
ngOnDestroy(): void;
viewToModelUpdate(newValue: any): void;
}
export declare class NgModelGroup extends AbstractFormGroupDirective implements OnInit, OnDestroy {
name: string;
constructor(parent: ControlContainer, validators: any[], asyncValidators: any[]);
}
export declare class NgSelectOption implements OnDestroy {
id: string;
ngValue: any;
value: any;
constructor(_element: ElementRef, _renderer: Renderer2, _select: SelectControlValueAccessor);
ngOnDestroy(): void;
}
export declare class PatternValidator implements Validator, OnChanges {
pattern: string | RegExp;
ngOnChanges(changes: SimpleChanges): void;
registerOnValidatorChange(fn: () => void): void;
validate(control: AbstractControl): ValidationErrors | null;
}
export declare class RadioControlValueAccessor implements ControlValueAccessor, OnDestroy, OnInit {
formControlName: string;
name: string;
onChange: () => void;
onTouched: () => void;
value: any;
constructor(_renderer: Renderer2, _elementRef: ElementRef, _registry: RadioControlRegistry, _injector: Injector);
fireUncheck(value: any): void;
ngOnDestroy(): void;
ngOnInit(): void;
registerOnChange(fn: (_: any) => {}): void;
registerOnTouched(fn: () => {}): void;
setDisabledState(isDisabled: boolean): void;
writeValue(value: any): void;
}
export declare class ReactiveFormsModule {
static withConfig(opts: { warnOnNgModelWithFormControl: 'never' | 'once' | 'always';
}): ModuleWithProviders<ReactiveFormsModule>;
}
export declare class RequiredValidator implements Validator {
required: boolean | string;
registerOnValidatorChange(fn: () => void): void;
validate(control: AbstractControl): ValidationErrors | null;
}
export declare class SelectControlValueAccessor implements ControlValueAccessor {
compareWith: (o1: any, o2: any) => boolean;
onChange: (_: any) => void;
onTouched: () => void;
value: any;
constructor(_renderer: Renderer2, _elementRef: ElementRef);
registerOnChange(fn: (value: any) => any): void;
registerOnTouched(fn: () => any): void;
setDisabledState(isDisabled: boolean): void;
writeValue(value: any): void;
}
export declare class SelectMultipleControlValueAccessor implements ControlValueAccessor {
compareWith: (o1: any, o2: any) => boolean;
onChange: (_: any) => void;
onTouched: () => void;
value: any;
constructor(_renderer: Renderer2, _elementRef: ElementRef);
registerOnChange(fn: (value: any) => any): void;
registerOnTouched(fn: () => any): void;
setDisabledState(isDisabled: boolean): void;
writeValue(value: any): void;
}
export declare type ValidationErrors = {
[key: string]: any;
};
export interface Validator {
registerOnValidatorChange?(fn: () => void): void;
validate(control: AbstractControl): ValidationErrors | null;
}
export interface ValidatorFn {
(control: AbstractControl): ValidationErrors | null;
}
export declare class Validators {
static compose(validators: (ValidatorFn | null | undefined)[]): ValidatorFn | null;
static compose(validators: null): null;
static composeAsync(validators: (AsyncValidatorFn | null)[]): AsyncValidatorFn | null;
static email(control: AbstractControl): ValidationErrors | null;
static max(max: number): ValidatorFn;
static maxLength(maxLength: number): ValidatorFn;
static min(min: number): ValidatorFn;
static minLength(minLength: number): ValidatorFn;
static nullValidator(control: AbstractControl): ValidationErrors | null;
static pattern(pattern: string | RegExp): ValidatorFn;
static required(control: AbstractControl): ValidationErrors | null;
static requiredTrue(control: AbstractControl): ValidationErrors | null;
}
export declare const VERSION: Version;
| tools/public_api_guard/forms/forms.d.ts | 1 | https://github.com/angular/angular/commit/b0c75611d6ff193afd29cd12152c1b3e3f04424a | [
0.9972023963928223,
0.12775400280952454,
0.0001638462272239849,
0.0010059649357572198,
0.3009066581726074
]
|
{
"id": 2,
"code_window": [
" * * `asyncValidator`: A single async validator or array of async validator functions\n",
" *\n",
" */\n",
" group(controlsConfig: {[key: string]: any}, legacyOrOpts: {[key: string]: any}|null = null):\n",
" FormGroup {\n",
" const controls = this._reduceControls(controlsConfig);\n",
"\n",
" let validators: ValidatorFn|ValidatorFn[]|null = null;\n",
" let asyncValidators: AsyncValidatorFn|AsyncValidatorFn[]|null = null;\n",
" let updateOn: FormHooks|undefined = undefined;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" group(\n",
" controlsConfig: {[key: string]: any},\n",
" options: AbstractControlOptions|{[key: string]: any}|null = null): FormGroup {\n"
],
"file_path": "packages/forms/src/form_builder.ts",
"type": "replace",
"edit_start_line_idx": 48
} | import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.1.html'
})
// #docregion class
export class AppComponent {
color = 'yellow';
}
| aio/content/examples/attribute-directives/src/app/app.component.1.ts | 0 | https://github.com/angular/angular/commit/b0c75611d6ff193afd29cd12152c1b3e3f04424a | [
0.00017119519179686904,
0.00017075428331736475,
0.00017031337483786047,
0.00017075428331736475,
4.4090847950428724e-7
]
|
{
"id": 2,
"code_window": [
" * * `asyncValidator`: A single async validator or array of async validator functions\n",
" *\n",
" */\n",
" group(controlsConfig: {[key: string]: any}, legacyOrOpts: {[key: string]: any}|null = null):\n",
" FormGroup {\n",
" const controls = this._reduceControls(controlsConfig);\n",
"\n",
" let validators: ValidatorFn|ValidatorFn[]|null = null;\n",
" let asyncValidators: AsyncValidatorFn|AsyncValidatorFn[]|null = null;\n",
" let updateOn: FormHooks|undefined = undefined;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" group(\n",
" controlsConfig: {[key: string]: any},\n",
" options: AbstractControlOptions|{[key: string]: any}|null = null): FormGroup {\n"
],
"file_path": "packages/forms/src/form_builder.ts",
"type": "replace",
"edit_start_line_idx": 48
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
export default [
[
['mn.', 'mg.', 'fm.', 'em.', 'kv.', 'nt.'],
['midn.', 'morg.', 'form.', 'etterm.', 'kveld', 'natt'],
['midnatt', 'morgenen', 'formiddagen', 'ettermiddagen', 'kvelden', 'natten']
],
[
['mn.', 'mg.', 'fm.', 'em.', 'kv.', 'nt.'],
['midn.', 'morg.', 'form.', 'etterm.', 'kveld', 'natt'],
['midnatt', 'morgen', 'formiddag', 'ettermiddag', 'kveld', 'natt']
],
[
'00:00', ['06:00', '10:00'], ['10:00', '12:00'], ['12:00', '18:00'], ['18:00', '24:00'],
['00:00', '06:00']
]
];
| packages/common/locales/extra/nb-SJ.ts | 0 | https://github.com/angular/angular/commit/b0c75611d6ff193afd29cd12152c1b3e3f04424a | [
0.0001727146009216085,
0.00017214058607351035,
0.0001712939701974392,
0.00017241317254956812,
6.111614538895083e-7
]
|
{
"id": 2,
"code_window": [
" * * `asyncValidator`: A single async validator or array of async validator functions\n",
" *\n",
" */\n",
" group(controlsConfig: {[key: string]: any}, legacyOrOpts: {[key: string]: any}|null = null):\n",
" FormGroup {\n",
" const controls = this._reduceControls(controlsConfig);\n",
"\n",
" let validators: ValidatorFn|ValidatorFn[]|null = null;\n",
" let asyncValidators: AsyncValidatorFn|AsyncValidatorFn[]|null = null;\n",
" let updateOn: FormHooks|undefined = undefined;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" group(\n",
" controlsConfig: {[key: string]: any},\n",
" options: AbstractControlOptions|{[key: string]: any}|null = null): FormGroup {\n"
],
"file_path": "packages/forms/src/form_builder.ts",
"type": "replace",
"edit_start_line_idx": 48
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
module.exports = {
// Serve the built files
default: (gulp) => () => {
const connect = require('gulp-connect');
const cors = require('cors');
const path = require('path');
connect.server({
root: path.resolve(__dirname, '../../dist'),
port: 8000,
livereload: false,
open: false,
middleware: (connect, opt) => [cors()],
});
},
// Serve the examples
examples: (gulp) => () => {
const connect = require('gulp-connect');
const cors = require('cors');
const path = require('path');
connect.server({
root: path.resolve(__dirname, '../../dist/examples'),
port: 8001,
livereload: false,
open: false,
middleware: (connect, opt) => [cors()],
});
}
};
| tools/gulp-tasks/serve.js | 0 | https://github.com/angular/angular/commit/b0c75611d6ff193afd29cd12152c1b3e3f04424a | [
0.0001756594720063731,
0.00017369978013448417,
0.00017165204917546362,
0.00017389845743309706,
0.0000012919192613480845
]
|
{
"id": 3,
"code_window": [
" let validators: ValidatorFn|ValidatorFn[]|null = null;\n",
" let asyncValidators: AsyncValidatorFn|AsyncValidatorFn[]|null = null;\n",
" let updateOn: FormHooks|undefined = undefined;\n",
"\n",
" if (legacyOrOpts != null &&\n",
" (legacyOrOpts.asyncValidator !== undefined || legacyOrOpts.validator !== undefined)) {\n",
" // `legacyOrOpts` are legacy form group options\n",
" validators = legacyOrOpts.validator != null ? legacyOrOpts.validator : null;\n",
" asyncValidators = legacyOrOpts.asyncValidator != null ? legacyOrOpts.asyncValidator : null;\n",
" } else if (legacyOrOpts != null) {\n",
" // `legacyOrOpts` are `AbstractControlOptions`\n",
" validators = legacyOrOpts.validators != null ? legacyOrOpts.validators : null;\n",
" asyncValidators = legacyOrOpts.asyncValidators != null ? legacyOrOpts.asyncValidators : null;\n",
" updateOn = legacyOrOpts.updateOn != null ? legacyOrOpts.updateOn : undefined;\n",
" }\n",
"\n",
" return new FormGroup(controls, {asyncValidators, updateOn, validators});\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (options != null) {\n",
" if (isAbstractControlOptions(options)) {\n",
" // `options` are `AbstractControlOptions`\n",
" validators = options.validators != null ? options.validators : null;\n",
" asyncValidators = options.asyncValidators != null ? options.asyncValidators : null;\n",
" updateOn = options.updateOn != null ? options.updateOn : undefined;\n",
" } else {\n",
" // `options` are legacy form group options\n",
" validators = options.validator != null ? options.validator : null;\n",
" asyncValidators = options.asyncValidator != null ? options.asyncValidator : null;\n",
" }\n"
],
"file_path": "packages/forms/src/form_builder.ts",
"type": "replace",
"edit_start_line_idx": 56
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injectable} from '@angular/core';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
import {AbstractControl, AbstractControlOptions, FormArray, FormControl, FormGroup, FormHooks} from './model';
/**
* @description
* Creates an `AbstractControl` from a user-specified configuration.
*
* The `FormBuilder` provides syntactic sugar that shortens creating instances of a `FormControl`,
* `FormGroup`, or `FormArray`. It reduces the amount of boilerplate needed to build complex
* forms.
*
* @see [Reactive Forms Guide](/guide/reactive-forms)
*
* @publicApi
*/
@Injectable()
export class FormBuilder {
/**
* @description
* Construct a new `FormGroup` instance.
*
* @param controlsConfig A collection of child controls. The key for each child is the name
* under which it is registered.
*
* @param legacyOrOpts Configuration options object for the `FormGroup`. The object can
* have two shapes:
*
* 1) `AbstractControlOptions` object (preferred), which consists of:
* * `validators`: A synchronous validator function, or an array of validator functions
* * `asyncValidators`: A single async validator or array of async validator functions
* * `updateOn`: The event upon which the control should be updated (options: 'change' | 'blur' |
* submit')
*
* 2) Legacy configuration object, which consists of:
* * `validator`: A synchronous validator function, or an array of validator functions
* * `asyncValidator`: A single async validator or array of async validator functions
*
*/
group(controlsConfig: {[key: string]: any}, legacyOrOpts: {[key: string]: any}|null = null):
FormGroup {
const controls = this._reduceControls(controlsConfig);
let validators: ValidatorFn|ValidatorFn[]|null = null;
let asyncValidators: AsyncValidatorFn|AsyncValidatorFn[]|null = null;
let updateOn: FormHooks|undefined = undefined;
if (legacyOrOpts != null &&
(legacyOrOpts.asyncValidator !== undefined || legacyOrOpts.validator !== undefined)) {
// `legacyOrOpts` are legacy form group options
validators = legacyOrOpts.validator != null ? legacyOrOpts.validator : null;
asyncValidators = legacyOrOpts.asyncValidator != null ? legacyOrOpts.asyncValidator : null;
} else if (legacyOrOpts != null) {
// `legacyOrOpts` are `AbstractControlOptions`
validators = legacyOrOpts.validators != null ? legacyOrOpts.validators : null;
asyncValidators = legacyOrOpts.asyncValidators != null ? legacyOrOpts.asyncValidators : null;
updateOn = legacyOrOpts.updateOn != null ? legacyOrOpts.updateOn : undefined;
}
return new FormGroup(controls, {asyncValidators, updateOn, validators});
}
/**
* @description
* Construct a new `FormControl` with the given state, validators and options.
*
* @param formState Initializes the control with an initial state value, or
* with an object that contains both a value and a disabled status.
*
* @param validatorOrOpts A synchronous validator function, or an array of
* such functions, or an `AbstractControlOptions` object that contains
* validation functions and a validation trigger.
*
* @param asyncValidator A single async validator or array of async validator
* functions.
*
* @usageNotes
*
* ### Initialize a control as disabled
*
* The following example returns a control with an initial value in a disabled state.
*
* <code-example path="forms/ts/formBuilder/form_builder_example.ts"
* linenums="false" region="disabled-control">
* </code-example>
*/
control(
formState: any, validatorOrOpts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions|null,
asyncValidator?: AsyncValidatorFn|AsyncValidatorFn[]|null): FormControl {
return new FormControl(formState, validatorOrOpts, asyncValidator);
}
/**
* Constructs a new `FormArray` from the given array of configurations,
* validators and options.
*
* @param controlsConfig An array of child controls or control configs. Each
* child control is given an index when it is registered.
*
* @param validatorOrOpts A synchronous validator function, or an array of
* such functions, or an `AbstractControlOptions` object that contains
* validation functions and a validation trigger.
*
* @param asyncValidator A single async validator or array of async validator
* functions.
*/
array(
controlsConfig: any[],
validatorOrOpts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions|null,
asyncValidator?: AsyncValidatorFn|AsyncValidatorFn[]|null): FormArray {
const controls = controlsConfig.map(c => this._createControl(c));
return new FormArray(controls, validatorOrOpts, asyncValidator);
}
/** @internal */
_reduceControls(controlsConfig: {[k: string]: any}): {[key: string]: AbstractControl} {
const controls: {[key: string]: AbstractControl} = {};
Object.keys(controlsConfig).forEach(controlName => {
controls[controlName] = this._createControl(controlsConfig[controlName]);
});
return controls;
}
/** @internal */
_createControl(controlConfig: any): AbstractControl {
if (controlConfig instanceof FormControl || controlConfig instanceof FormGroup ||
controlConfig instanceof FormArray) {
return controlConfig;
} else if (Array.isArray(controlConfig)) {
const value = controlConfig[0];
const validator: ValidatorFn = controlConfig.length > 1 ? controlConfig[1] : null;
const asyncValidator: AsyncValidatorFn = controlConfig.length > 2 ? controlConfig[2] : null;
return this.control(value, validator, asyncValidator);
} else {
return this.control(controlConfig);
}
}
}
| packages/forms/src/form_builder.ts | 1 | https://github.com/angular/angular/commit/b0c75611d6ff193afd29cd12152c1b3e3f04424a | [
0.9977769255638123,
0.14645813405513763,
0.00017312663840129972,
0.0010147105203941464,
0.33602333068847656
]
|
{
"id": 3,
"code_window": [
" let validators: ValidatorFn|ValidatorFn[]|null = null;\n",
" let asyncValidators: AsyncValidatorFn|AsyncValidatorFn[]|null = null;\n",
" let updateOn: FormHooks|undefined = undefined;\n",
"\n",
" if (legacyOrOpts != null &&\n",
" (legacyOrOpts.asyncValidator !== undefined || legacyOrOpts.validator !== undefined)) {\n",
" // `legacyOrOpts` are legacy form group options\n",
" validators = legacyOrOpts.validator != null ? legacyOrOpts.validator : null;\n",
" asyncValidators = legacyOrOpts.asyncValidator != null ? legacyOrOpts.asyncValidator : null;\n",
" } else if (legacyOrOpts != null) {\n",
" // `legacyOrOpts` are `AbstractControlOptions`\n",
" validators = legacyOrOpts.validators != null ? legacyOrOpts.validators : null;\n",
" asyncValidators = legacyOrOpts.asyncValidators != null ? legacyOrOpts.asyncValidators : null;\n",
" updateOn = legacyOrOpts.updateOn != null ? legacyOrOpts.updateOn : undefined;\n",
" }\n",
"\n",
" return new FormGroup(controls, {asyncValidators, updateOn, validators});\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (options != null) {\n",
" if (isAbstractControlOptions(options)) {\n",
" // `options` are `AbstractControlOptions`\n",
" validators = options.validators != null ? options.validators : null;\n",
" asyncValidators = options.asyncValidators != null ? options.asyncValidators : null;\n",
" updateOn = options.updateOn != null ? options.updateOn : undefined;\n",
" } else {\n",
" // `options` are legacy form group options\n",
" validators = options.validator != null ? options.validator : null;\n",
" asyncValidators = options.asyncValidator != null ? options.asyncValidator : null;\n",
" }\n"
],
"file_path": "packages/forms/src/form_builder.ts",
"type": "replace",
"edit_start_line_idx": 56
} | // #docplaster
import {
LightswitchComponent,
MasterService,
ValueService,
ReversePipe
} from './demo';
///////// Fakes /////////
export class FakeValueService extends ValueService {
value = 'faked service value';
}
////////////////////////
describe('demo (no TestBed):', () => {
// #docregion ValueService
// Straight Jasmine testing without Angular's testing support
describe('ValueService', () => {
let service: ValueService;
beforeEach(() => { service = new ValueService(); });
it('#getValue should return real value', () => {
expect(service.getValue()).toBe('real value');
});
it('#getObservableValue should return value from observable',
(done: DoneFn) => {
service.getObservableValue().subscribe(value => {
expect(value).toBe('observable value');
done();
});
});
it('#getPromiseValue should return value from a promise',
(done: DoneFn) => {
service.getPromiseValue().then(value => {
expect(value).toBe('promise value');
done();
});
});
});
// #enddocregion ValueService
// MasterService requires injection of a ValueService
// #docregion MasterService
describe('MasterService without Angular testing support', () => {
let masterService: MasterService;
it('#getValue should return real value from the real service', () => {
masterService = new MasterService(new ValueService());
expect(masterService.getValue()).toBe('real value');
});
it('#getValue should return faked value from a fakeService', () => {
masterService = new MasterService(new FakeValueService());
expect(masterService.getValue()).toBe('faked service value');
});
it('#getValue should return faked value from a fake object', () => {
const fake = { getValue: () => 'fake value' };
masterService = new MasterService(fake as ValueService);
expect(masterService.getValue()).toBe('fake value');
});
it('#getValue should return stubbed value from a spy', () => {
// create `getValue` spy on an object representing the ValueService
const valueServiceSpy =
jasmine.createSpyObj('ValueService', ['getValue']);
// set the value to return when the `getValue` spy is called.
const stubValue = 'stub value';
valueServiceSpy.getValue.and.returnValue(stubValue);
masterService = new MasterService(valueServiceSpy);
expect(masterService.getValue())
.toBe(stubValue, 'service returned stub value');
expect(valueServiceSpy.getValue.calls.count())
.toBe(1, 'spy method was called once');
expect(valueServiceSpy.getValue.calls.mostRecent().returnValue)
.toBe(stubValue);
});
});
// #enddocregion MasterService
describe('MasterService (no beforeEach)', () => {
// #docregion no-before-each-test
it('#getValue should return stubbed value from a spy', () => {
// #docregion no-before-each-setup-call
const { masterService, stubValue, valueServiceSpy } = setup();
// #enddocregion no-before-each-setup-call
expect(masterService.getValue())
.toBe(stubValue, 'service returned stub value');
expect(valueServiceSpy.getValue.calls.count())
.toBe(1, 'spy method was called once');
expect(valueServiceSpy.getValue.calls.mostRecent().returnValue)
.toBe(stubValue);
});
// #enddocregion no-before-each-test
// #docregion no-before-each-setup
function setup() {
const valueServiceSpy =
jasmine.createSpyObj('ValueService', ['getValue']);
const stubValue = 'stub value';
const masterService = new MasterService(valueServiceSpy);
valueServiceSpy.getValue.and.returnValue(stubValue);
return { masterService, stubValue, valueServiceSpy };
}
// #enddocregion no-before-each-setup
});
// #docregion ReversePipe
describe('ReversePipe', () => {
let pipe: ReversePipe;
beforeEach(() => { pipe = new ReversePipe(); });
it('transforms "abc" to "cba"', () => {
expect(pipe.transform('abc')).toBe('cba');
});
it('no change to palindrome: "able was I ere I saw elba"', () => {
const palindrome = 'able was I ere I saw elba';
expect(pipe.transform(palindrome)).toBe(palindrome);
});
});
// #enddocregion ReversePipe
// #docregion Lightswitch
describe('LightswitchComp', () => {
it('#clicked() should toggle #isOn', () => {
const comp = new LightswitchComponent();
expect(comp.isOn).toBe(false, 'off at first');
comp.clicked();
expect(comp.isOn).toBe(true, 'on after click');
comp.clicked();
expect(comp.isOn).toBe(false, 'off after second click');
});
it('#clicked() should set #message to "is on"', () => {
const comp = new LightswitchComponent();
expect(comp.message).toMatch(/is off/i, 'off at first');
comp.clicked();
expect(comp.message).toMatch(/is on/i, 'on after clicked');
});
});
// #enddocregion Lightswitch
});
| aio/content/examples/testing/src/app/demo/demo.spec.ts | 0 | https://github.com/angular/angular/commit/b0c75611d6ff193afd29cd12152c1b3e3f04424a | [
0.00017296346777584404,
0.00017075597133953124,
0.00016750572831369936,
0.00017131565255112946,
0.000001438727281311003
]
|
{
"id": 3,
"code_window": [
" let validators: ValidatorFn|ValidatorFn[]|null = null;\n",
" let asyncValidators: AsyncValidatorFn|AsyncValidatorFn[]|null = null;\n",
" let updateOn: FormHooks|undefined = undefined;\n",
"\n",
" if (legacyOrOpts != null &&\n",
" (legacyOrOpts.asyncValidator !== undefined || legacyOrOpts.validator !== undefined)) {\n",
" // `legacyOrOpts` are legacy form group options\n",
" validators = legacyOrOpts.validator != null ? legacyOrOpts.validator : null;\n",
" asyncValidators = legacyOrOpts.asyncValidator != null ? legacyOrOpts.asyncValidator : null;\n",
" } else if (legacyOrOpts != null) {\n",
" // `legacyOrOpts` are `AbstractControlOptions`\n",
" validators = legacyOrOpts.validators != null ? legacyOrOpts.validators : null;\n",
" asyncValidators = legacyOrOpts.asyncValidators != null ? legacyOrOpts.asyncValidators : null;\n",
" updateOn = legacyOrOpts.updateOn != null ? legacyOrOpts.updateOn : undefined;\n",
" }\n",
"\n",
" return new FormGroup(controls, {asyncValidators, updateOn, validators});\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (options != null) {\n",
" if (isAbstractControlOptions(options)) {\n",
" // `options` are `AbstractControlOptions`\n",
" validators = options.validators != null ? options.validators : null;\n",
" asyncValidators = options.asyncValidators != null ? options.asyncValidators : null;\n",
" updateOn = options.updateOn != null ? options.updateOn : undefined;\n",
" } else {\n",
" // `options` are legacy form group options\n",
" validators = options.validator != null ? options.validator : null;\n",
" asyncValidators = options.asyncValidator != null ? options.asyncValidator : null;\n",
" }\n"
],
"file_path": "packages/forms/src/form_builder.ts",
"type": "replace",
"edit_start_line_idx": 56
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CompileDirectiveMetadata, CompileDirectiveSummary, CompilePipeSummary, CompileTokenMetadata, CompileTypeMetadata, identifierName} from '../compile_metadata';
import {CompileReflector} from '../compile_reflector';
import {CompilerConfig} from '../config';
import {SchemaMetadata} from '../core';
import {AST, ASTWithSource, EmptyExpr, ParsedEvent, ParsedProperty, ParsedVariable} from '../expression_parser/ast';
import {Parser} from '../expression_parser/parser';
import {Identifiers, createTokenForExternalReference, createTokenForReference} from '../identifiers';
import * as html from '../ml_parser/ast';
import {HtmlParser, ParseTreeResult} from '../ml_parser/html_parser';
import {removeWhitespaces, replaceNgsp} from '../ml_parser/html_whitespaces';
import {expandNodes} from '../ml_parser/icu_ast_expander';
import {InterpolationConfig} from '../ml_parser/interpolation_config';
import {isNgTemplate, splitNsName} from '../ml_parser/tags';
import {ParseError, ParseErrorLevel, ParseSourceSpan} from '../parse_util';
import {ProviderElementContext, ProviderViewContext} from '../provider_analyzer';
import {ElementSchemaRegistry} from '../schema/element_schema_registry';
import {CssSelector, SelectorMatcher} from '../selector';
import {isStyleUrlResolvable} from '../style_url_resolver';
import {Console, syntaxError} from '../util';
import {BindingParser} from './binding_parser';
import * as t from './template_ast';
import {PreparsedElementType, preparseElement} from './template_preparser';
const BIND_NAME_REGEXP =
/^(?:(?:(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/;
// Group 1 = "bind-"
const KW_BIND_IDX = 1;
// Group 2 = "let-"
const KW_LET_IDX = 2;
// Group 3 = "ref-/#"
const KW_REF_IDX = 3;
// Group 4 = "on-"
const KW_ON_IDX = 4;
// Group 5 = "bindon-"
const KW_BINDON_IDX = 5;
// Group 6 = "@"
const KW_AT_IDX = 6;
// Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@"
const IDENT_KW_IDX = 7;
// Group 8 = identifier inside [()]
const IDENT_BANANA_BOX_IDX = 8;
// Group 9 = identifier inside []
const IDENT_PROPERTY_IDX = 9;
// Group 10 = identifier inside ()
const IDENT_EVENT_IDX = 10;
const TEMPLATE_ATTR_PREFIX = '*';
const CLASS_ATTR = 'class';
let _TEXT_CSS_SELECTOR !: CssSelector;
function TEXT_CSS_SELECTOR(): CssSelector {
if (!_TEXT_CSS_SELECTOR) {
_TEXT_CSS_SELECTOR = CssSelector.parse('*')[0];
}
return _TEXT_CSS_SELECTOR;
}
export class TemplateParseError extends ParseError {
constructor(message: string, span: ParseSourceSpan, level: ParseErrorLevel) {
super(span, message, level);
}
}
export class TemplateParseResult {
constructor(
public templateAst?: t.TemplateAst[], public usedPipes?: CompilePipeSummary[],
public errors?: ParseError[]) {}
}
export class TemplateParser {
constructor(
private _config: CompilerConfig, private _reflector: CompileReflector,
private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry,
private _htmlParser: HtmlParser, private _console: Console,
public transforms: t.TemplateAstVisitor[]) {}
public get expressionParser() { return this._exprParser; }
parse(
component: CompileDirectiveMetadata, template: string|ParseTreeResult,
directives: CompileDirectiveSummary[], pipes: CompilePipeSummary[], schemas: SchemaMetadata[],
templateUrl: string,
preserveWhitespaces: boolean): {template: t.TemplateAst[], pipes: CompilePipeSummary[]} {
const result = this.tryParse(
component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces);
const warnings = result.errors !.filter(error => error.level === ParseErrorLevel.WARNING);
const errors = result.errors !.filter(error => error.level === ParseErrorLevel.ERROR);
if (warnings.length > 0) {
this._console.warn(`Template parse warnings:\n${warnings.join('\n')}`);
}
if (errors.length > 0) {
const errorString = errors.join('\n');
throw syntaxError(`Template parse errors:\n${errorString}`, errors);
}
return {template: result.templateAst !, pipes: result.usedPipes !};
}
tryParse(
component: CompileDirectiveMetadata, template: string|ParseTreeResult,
directives: CompileDirectiveSummary[], pipes: CompilePipeSummary[], schemas: SchemaMetadata[],
templateUrl: string, preserveWhitespaces: boolean): TemplateParseResult {
let htmlParseResult = typeof template === 'string' ?
this._htmlParser !.parse(
template, templateUrl, true, this.getInterpolationConfig(component)) :
template;
if (!preserveWhitespaces) {
htmlParseResult = removeWhitespaces(htmlParseResult);
}
return this.tryParseHtml(
this.expandHtml(htmlParseResult), component, directives, pipes, schemas);
}
tryParseHtml(
htmlAstWithErrors: ParseTreeResult, component: CompileDirectiveMetadata,
directives: CompileDirectiveSummary[], pipes: CompilePipeSummary[],
schemas: SchemaMetadata[]): TemplateParseResult {
let result: t.TemplateAst[];
const errors = htmlAstWithErrors.errors;
const usedPipes: CompilePipeSummary[] = [];
if (htmlAstWithErrors.rootNodes.length > 0) {
const uniqDirectives = removeSummaryDuplicates(directives);
const uniqPipes = removeSummaryDuplicates(pipes);
const providerViewContext = new ProviderViewContext(this._reflector, component);
let interpolationConfig: InterpolationConfig = undefined !;
if (component.template && component.template.interpolation) {
interpolationConfig = {
start: component.template.interpolation[0],
end: component.template.interpolation[1]
};
}
const bindingParser = new BindingParser(
this._exprParser, interpolationConfig !, this._schemaRegistry, uniqPipes, errors);
const parseVisitor = new TemplateParseVisitor(
this._reflector, this._config, providerViewContext, uniqDirectives, bindingParser,
this._schemaRegistry, schemas, errors);
result = html.visitAll(parseVisitor, htmlAstWithErrors.rootNodes, EMPTY_ELEMENT_CONTEXT);
errors.push(...providerViewContext.errors);
usedPipes.push(...bindingParser.getUsedPipes());
} else {
result = [];
}
this._assertNoReferenceDuplicationOnTemplate(result, errors);
if (errors.length > 0) {
return new TemplateParseResult(result, usedPipes, errors);
}
if (this.transforms) {
this.transforms.forEach(
(transform: t.TemplateAstVisitor) => { result = t.templateVisitAll(transform, result); });
}
return new TemplateParseResult(result, usedPipes, errors);
}
expandHtml(htmlAstWithErrors: ParseTreeResult, forced: boolean = false): ParseTreeResult {
const errors: ParseError[] = htmlAstWithErrors.errors;
if (errors.length == 0 || forced) {
// Transform ICU messages to angular directives
const expandedHtmlAst = expandNodes(htmlAstWithErrors.rootNodes);
errors.push(...expandedHtmlAst.errors);
htmlAstWithErrors = new ParseTreeResult(expandedHtmlAst.nodes, errors);
}
return htmlAstWithErrors;
}
getInterpolationConfig(component: CompileDirectiveMetadata): InterpolationConfig|undefined {
if (component.template) {
return InterpolationConfig.fromArray(component.template.interpolation);
}
return undefined;
}
/** @internal */
_assertNoReferenceDuplicationOnTemplate(result: t.TemplateAst[], errors: TemplateParseError[]):
void {
const existingReferences: string[] = [];
result.filter(element => !!(<any>element).references)
.forEach(element => (<any>element).references.forEach((reference: t.ReferenceAst) => {
const name = reference.name;
if (existingReferences.indexOf(name) < 0) {
existingReferences.push(name);
} else {
const error = new TemplateParseError(
`Reference "#${name}" is defined several times`, reference.sourceSpan,
ParseErrorLevel.ERROR);
errors.push(error);
}
}));
}
}
class TemplateParseVisitor implements html.Visitor {
selectorMatcher = new SelectorMatcher();
directivesIndex = new Map<CompileDirectiveSummary, number>();
ngContentCount = 0;
contentQueryStartId: number;
constructor(
private reflector: CompileReflector, private config: CompilerConfig,
public providerViewContext: ProviderViewContext, directives: CompileDirectiveSummary[],
private _bindingParser: BindingParser, private _schemaRegistry: ElementSchemaRegistry,
private _schemas: SchemaMetadata[], private _targetErrors: TemplateParseError[]) {
// Note: queries start with id 1 so we can use the number in a Bloom filter!
this.contentQueryStartId = providerViewContext.component.viewQueries.length + 1;
directives.forEach((directive, index) => {
const selector = CssSelector.parse(directive.selector !);
this.selectorMatcher.addSelectables(selector, directive);
this.directivesIndex.set(directive, index);
});
}
visitExpansion(expansion: html.Expansion, context: any): any { return null; }
visitExpansionCase(expansionCase: html.ExpansionCase, context: any): any { return null; }
visitText(text: html.Text, parent: ElementContext): any {
const ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR()) !;
const valueNoNgsp = replaceNgsp(text.value);
const expr = this._bindingParser.parseInterpolation(valueNoNgsp, text.sourceSpan !);
return expr ? new t.BoundTextAst(expr, ngContentIndex, text.sourceSpan !) :
new t.TextAst(valueNoNgsp, ngContentIndex, text.sourceSpan !);
}
visitAttribute(attribute: html.Attribute, context: any): any {
return new t.AttrAst(attribute.name, attribute.value, attribute.sourceSpan);
}
visitComment(comment: html.Comment, context: any): any { return null; }
visitElement(element: html.Element, parent: ElementContext): any {
const queryStartIndex = this.contentQueryStartId;
const elName = element.name;
const preparsedElement = preparseElement(element);
if (preparsedElement.type === PreparsedElementType.SCRIPT ||
preparsedElement.type === PreparsedElementType.STYLE) {
// Skipping <script> for security reasons
// Skipping <style> as we already processed them
// in the StyleCompiler
return null;
}
if (preparsedElement.type === PreparsedElementType.STYLESHEET &&
isStyleUrlResolvable(preparsedElement.hrefAttr)) {
// Skipping stylesheets with either relative urls or package scheme as we already processed
// them in the StyleCompiler
return null;
}
const matchableAttrs: [string, string][] = [];
const elementOrDirectiveProps: ParsedProperty[] = [];
const elementOrDirectiveRefs: ElementOrDirectiveRef[] = [];
const elementVars: t.VariableAst[] = [];
const events: t.BoundEventAst[] = [];
const templateElementOrDirectiveProps: ParsedProperty[] = [];
const templateMatchableAttrs: [string, string][] = [];
const templateElementVars: t.VariableAst[] = [];
let hasInlineTemplates = false;
const attrs: t.AttrAst[] = [];
const isTemplateElement = isNgTemplate(element.name);
element.attrs.forEach(attr => {
const parsedVariables: ParsedVariable[] = [];
const hasBinding = this._parseAttr(
isTemplateElement, attr, matchableAttrs, elementOrDirectiveProps, events,
elementOrDirectiveRefs, elementVars);
elementVars.push(...parsedVariables.map(v => t.VariableAst.fromParsedVariable(v)));
let templateValue: string|undefined;
let templateKey: string|undefined;
const normalizedName = this._normalizeAttributeName(attr.name);
if (normalizedName.startsWith(TEMPLATE_ATTR_PREFIX)) {
templateValue = attr.value;
templateKey = normalizedName.substring(TEMPLATE_ATTR_PREFIX.length);
}
const hasTemplateBinding = templateValue != null;
if (hasTemplateBinding) {
if (hasInlineTemplates) {
this._reportError(
`Can't have multiple template bindings on one element. Use only one attribute prefixed with *`,
attr.sourceSpan);
}
hasInlineTemplates = true;
const parsedVariables: ParsedVariable[] = [];
this._bindingParser.parseInlineTemplateBinding(
templateKey !, templateValue !, attr.sourceSpan, templateMatchableAttrs,
templateElementOrDirectiveProps, parsedVariables);
templateElementVars.push(...parsedVariables.map(v => t.VariableAst.fromParsedVariable(v)));
}
if (!hasBinding && !hasTemplateBinding) {
// don't include the bindings as attributes as well in the AST
attrs.push(this.visitAttribute(attr, null));
matchableAttrs.push([attr.name, attr.value]);
}
});
const elementCssSelector = createElementCssSelector(elName, matchableAttrs);
const {directives: directiveMetas, matchElement} =
this._parseDirectives(this.selectorMatcher, elementCssSelector);
const references: t.ReferenceAst[] = [];
const boundDirectivePropNames = new Set<string>();
const directiveAsts = this._createDirectiveAsts(
isTemplateElement, element.name, directiveMetas, elementOrDirectiveProps,
elementOrDirectiveRefs, element.sourceSpan !, references, boundDirectivePropNames);
const elementProps: t.BoundElementPropertyAst[] = this._createElementPropertyAsts(
element.name, elementOrDirectiveProps, boundDirectivePropNames);
const isViewRoot = parent.isTemplateElement || hasInlineTemplates;
const providerContext = new ProviderElementContext(
this.providerViewContext, parent.providerContext !, isViewRoot, directiveAsts, attrs,
references, isTemplateElement, queryStartIndex, element.sourceSpan !);
const children: t.TemplateAst[] = html.visitAll(
preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this, element.children,
ElementContext.create(
isTemplateElement, directiveAsts,
isTemplateElement ? parent.providerContext ! : providerContext));
providerContext.afterElement();
// Override the actual selector when the `ngProjectAs` attribute is provided
const projectionSelector = preparsedElement.projectAs != '' ?
CssSelector.parse(preparsedElement.projectAs)[0] :
elementCssSelector;
const ngContentIndex = parent.findNgContentIndex(projectionSelector) !;
let parsedElement: t.TemplateAst;
if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
// `<ng-content>` element
if (element.children && !element.children.every(_isEmptyTextNode)) {
this._reportError(`<ng-content> element cannot have content.`, element.sourceSpan !);
}
parsedElement = new t.NgContentAst(
this.ngContentCount++, hasInlineTemplates ? null ! : ngContentIndex,
element.sourceSpan !);
} else if (isTemplateElement) {
// `<ng-template>` element
this._assertAllEventsPublishedByDirectives(directiveAsts, events);
this._assertNoComponentsNorElementBindingsOnTemplate(
directiveAsts, elementProps, element.sourceSpan !);
parsedElement = new t.EmbeddedTemplateAst(
attrs, events, references, elementVars, providerContext.transformedDirectiveAsts,
providerContext.transformProviders, providerContext.transformedHasViewContainer,
providerContext.queryMatches, children, hasInlineTemplates ? null ! : ngContentIndex,
element.sourceSpan !);
} else {
// element other than `<ng-content>` and `<ng-template>`
this._assertElementExists(matchElement, element);
this._assertOnlyOneComponent(directiveAsts, element.sourceSpan !);
const ngContentIndex =
hasInlineTemplates ? null : parent.findNgContentIndex(projectionSelector);
parsedElement = new t.ElementAst(
elName, attrs, elementProps, events, references, providerContext.transformedDirectiveAsts,
providerContext.transformProviders, providerContext.transformedHasViewContainer,
providerContext.queryMatches, children, hasInlineTemplates ? null : ngContentIndex,
element.sourceSpan, element.endSourceSpan || null);
}
if (hasInlineTemplates) {
// The element as a *-attribute
const templateQueryStartIndex = this.contentQueryStartId;
const templateSelector = createElementCssSelector('ng-template', templateMatchableAttrs);
const {directives} = this._parseDirectives(this.selectorMatcher, templateSelector);
const templateBoundDirectivePropNames = new Set<string>();
const templateDirectiveAsts = this._createDirectiveAsts(
true, elName, directives, templateElementOrDirectiveProps, [], element.sourceSpan !, [],
templateBoundDirectivePropNames);
const templateElementProps: t.BoundElementPropertyAst[] = this._createElementPropertyAsts(
elName, templateElementOrDirectiveProps, templateBoundDirectivePropNames);
this._assertNoComponentsNorElementBindingsOnTemplate(
templateDirectiveAsts, templateElementProps, element.sourceSpan !);
const templateProviderContext = new ProviderElementContext(
this.providerViewContext, parent.providerContext !, parent.isTemplateElement,
templateDirectiveAsts, [], [], true, templateQueryStartIndex, element.sourceSpan !);
templateProviderContext.afterElement();
parsedElement = new t.EmbeddedTemplateAst(
[], [], [], templateElementVars, templateProviderContext.transformedDirectiveAsts,
templateProviderContext.transformProviders,
templateProviderContext.transformedHasViewContainer, templateProviderContext.queryMatches,
[parsedElement], ngContentIndex, element.sourceSpan !);
}
return parsedElement;
}
private _parseAttr(
isTemplateElement: boolean, attr: html.Attribute, targetMatchableAttrs: string[][],
targetProps: ParsedProperty[], targetEvents: t.BoundEventAst[],
targetRefs: ElementOrDirectiveRef[], targetVars: t.VariableAst[]): boolean {
const name = this._normalizeAttributeName(attr.name);
const value = attr.value;
const srcSpan = attr.sourceSpan;
const boundEvents: ParsedEvent[] = [];
const bindParts = name.match(BIND_NAME_REGEXP);
let hasBinding = false;
if (bindParts !== null) {
hasBinding = true;
if (bindParts[KW_BIND_IDX] != null) {
this._bindingParser.parsePropertyBinding(
bindParts[IDENT_KW_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
} else if (bindParts[KW_LET_IDX]) {
if (isTemplateElement) {
const identifier = bindParts[IDENT_KW_IDX];
this._parseVariable(identifier, value, srcSpan, targetVars);
} else {
this._reportError(`"let-" is only supported on ng-template elements.`, srcSpan);
}
} else if (bindParts[KW_REF_IDX]) {
const identifier = bindParts[IDENT_KW_IDX];
this._parseReference(identifier, value, srcSpan, targetRefs);
} else if (bindParts[KW_ON_IDX]) {
this._bindingParser.parseEvent(
bindParts[IDENT_KW_IDX], value, srcSpan, targetMatchableAttrs, boundEvents);
} else if (bindParts[KW_BINDON_IDX]) {
this._bindingParser.parsePropertyBinding(
bindParts[IDENT_KW_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
this._parseAssignmentEvent(
bindParts[IDENT_KW_IDX], value, srcSpan, targetMatchableAttrs, boundEvents);
} else if (bindParts[KW_AT_IDX]) {
this._bindingParser.parseLiteralAttr(
name, value, srcSpan, targetMatchableAttrs, targetProps);
} else if (bindParts[IDENT_BANANA_BOX_IDX]) {
this._bindingParser.parsePropertyBinding(
bindParts[IDENT_BANANA_BOX_IDX], value, false, srcSpan, targetMatchableAttrs,
targetProps);
this._parseAssignmentEvent(
bindParts[IDENT_BANANA_BOX_IDX], value, srcSpan, targetMatchableAttrs, boundEvents);
} else if (bindParts[IDENT_PROPERTY_IDX]) {
this._bindingParser.parsePropertyBinding(
bindParts[IDENT_PROPERTY_IDX], value, false, srcSpan, targetMatchableAttrs,
targetProps);
} else if (bindParts[IDENT_EVENT_IDX]) {
this._bindingParser.parseEvent(
bindParts[IDENT_EVENT_IDX], value, srcSpan, targetMatchableAttrs, boundEvents);
}
} else {
hasBinding = this._bindingParser.parsePropertyInterpolation(
name, value, srcSpan, targetMatchableAttrs, targetProps);
}
if (!hasBinding) {
this._bindingParser.parseLiteralAttr(name, value, srcSpan, targetMatchableAttrs, targetProps);
}
targetEvents.push(...boundEvents.map(e => t.BoundEventAst.fromParsedEvent(e)));
return hasBinding;
}
private _normalizeAttributeName(attrName: string): string {
return /^data-/i.test(attrName) ? attrName.substring(5) : attrName;
}
private _parseVariable(
identifier: string, value: string, sourceSpan: ParseSourceSpan, targetVars: t.VariableAst[]) {
if (identifier.indexOf('-') > -1) {
this._reportError(`"-" is not allowed in variable names`, sourceSpan);
}
targetVars.push(new t.VariableAst(identifier, value, sourceSpan));
}
private _parseReference(
identifier: string, value: string, sourceSpan: ParseSourceSpan,
targetRefs: ElementOrDirectiveRef[]) {
if (identifier.indexOf('-') > -1) {
this._reportError(`"-" is not allowed in reference names`, sourceSpan);
}
targetRefs.push(new ElementOrDirectiveRef(identifier, value, sourceSpan));
}
private _parseAssignmentEvent(
name: string, expression: string, sourceSpan: ParseSourceSpan,
targetMatchableAttrs: string[][], targetEvents: ParsedEvent[]) {
this._bindingParser.parseEvent(
`${name}Change`, `${expression}=$event`, sourceSpan, targetMatchableAttrs, targetEvents);
}
private _parseDirectives(selectorMatcher: SelectorMatcher, elementCssSelector: CssSelector):
{directives: CompileDirectiveSummary[], matchElement: boolean} {
// Need to sort the directives so that we get consistent results throughout,
// as selectorMatcher uses Maps inside.
// Also deduplicate directives as they might match more than one time!
const directives = new Array(this.directivesIndex.size);
// Whether any directive selector matches on the element name
let matchElement = false;
selectorMatcher.match(elementCssSelector, (selector, directive) => {
directives[this.directivesIndex.get(directive) !] = directive;
matchElement = matchElement || selector.hasElementSelector();
});
return {
directives: directives.filter(dir => !!dir),
matchElement,
};
}
private _createDirectiveAsts(
isTemplateElement: boolean, elementName: string, directives: CompileDirectiveSummary[],
props: ParsedProperty[], elementOrDirectiveRefs: ElementOrDirectiveRef[],
elementSourceSpan: ParseSourceSpan, targetReferences: t.ReferenceAst[],
targetBoundDirectivePropNames: Set<string>): t.DirectiveAst[] {
const matchedReferences = new Set<string>();
let component: CompileDirectiveSummary = null !;
const directiveAsts = directives.map((directive) => {
const sourceSpan = new ParseSourceSpan(
elementSourceSpan.start, elementSourceSpan.end,
`Directive ${identifierName(directive.type)}`);
if (directive.isComponent) {
component = directive;
}
const directiveProperties: t.BoundDirectivePropertyAst[] = [];
const boundProperties =
this._bindingParser.createDirectiveHostPropertyAsts(directive, elementName, sourceSpan) !;
let hostProperties =
boundProperties.map(prop => t.BoundElementPropertyAst.fromBoundProperty(prop));
// Note: We need to check the host properties here as well,
// as we don't know the element name in the DirectiveWrapperCompiler yet.
hostProperties = this._checkPropertiesInSchema(elementName, hostProperties);
const parsedEvents =
this._bindingParser.createDirectiveHostEventAsts(directive, sourceSpan) !;
this._createDirectivePropertyAsts(
directive.inputs, props, directiveProperties, targetBoundDirectivePropNames);
elementOrDirectiveRefs.forEach((elOrDirRef) => {
if ((elOrDirRef.value.length === 0 && directive.isComponent) ||
(elOrDirRef.isReferenceToDirective(directive))) {
targetReferences.push(new t.ReferenceAst(
elOrDirRef.name, createTokenForReference(directive.type.reference), elOrDirRef.value,
elOrDirRef.sourceSpan));
matchedReferences.add(elOrDirRef.name);
}
});
const hostEvents = parsedEvents.map(e => t.BoundEventAst.fromParsedEvent(e));
const contentQueryStartId = this.contentQueryStartId;
this.contentQueryStartId += directive.queries.length;
return new t.DirectiveAst(
directive, directiveProperties, hostProperties, hostEvents, contentQueryStartId,
sourceSpan);
});
elementOrDirectiveRefs.forEach((elOrDirRef) => {
if (elOrDirRef.value.length > 0) {
if (!matchedReferences.has(elOrDirRef.name)) {
this._reportError(
`There is no directive with "exportAs" set to "${elOrDirRef.value}"`,
elOrDirRef.sourceSpan);
}
} else if (!component) {
let refToken: CompileTokenMetadata = null !;
if (isTemplateElement) {
refToken = createTokenForExternalReference(this.reflector, Identifiers.TemplateRef);
}
targetReferences.push(
new t.ReferenceAst(elOrDirRef.name, refToken, elOrDirRef.value, elOrDirRef.sourceSpan));
}
});
return directiveAsts;
}
private _createDirectivePropertyAsts(
directiveProperties: {[key: string]: string}, boundProps: ParsedProperty[],
targetBoundDirectiveProps: t.BoundDirectivePropertyAst[],
targetBoundDirectivePropNames: Set<string>) {
if (directiveProperties) {
const boundPropsByName = new Map<string, ParsedProperty>();
boundProps.forEach(boundProp => {
const prevValue = boundPropsByName.get(boundProp.name);
if (!prevValue || prevValue.isLiteral) {
// give [a]="b" a higher precedence than a="b" on the same element
boundPropsByName.set(boundProp.name, boundProp);
}
});
Object.keys(directiveProperties).forEach(dirProp => {
const elProp = directiveProperties[dirProp];
const boundProp = boundPropsByName.get(elProp);
// Bindings are optional, so this binding only needs to be set up if an expression is given.
if (boundProp) {
targetBoundDirectivePropNames.add(boundProp.name);
if (!isEmptyExpression(boundProp.expression)) {
targetBoundDirectiveProps.push(new t.BoundDirectivePropertyAst(
dirProp, boundProp.name, boundProp.expression, boundProp.sourceSpan));
}
}
});
}
}
private _createElementPropertyAsts(
elementName: string, props: ParsedProperty[],
boundDirectivePropNames: Set<string>): t.BoundElementPropertyAst[] {
const boundElementProps: t.BoundElementPropertyAst[] = [];
props.forEach((prop: ParsedProperty) => {
if (!prop.isLiteral && !boundDirectivePropNames.has(prop.name)) {
const boundProp = this._bindingParser.createBoundElementProperty(elementName, prop);
boundElementProps.push(t.BoundElementPropertyAst.fromBoundProperty(boundProp));
}
});
return this._checkPropertiesInSchema(elementName, boundElementProps);
}
private _findComponentDirectives(directives: t.DirectiveAst[]): t.DirectiveAst[] {
return directives.filter(directive => directive.directive.isComponent);
}
private _findComponentDirectiveNames(directives: t.DirectiveAst[]): string[] {
return this._findComponentDirectives(directives)
.map(directive => identifierName(directive.directive.type) !);
}
private _assertOnlyOneComponent(directives: t.DirectiveAst[], sourceSpan: ParseSourceSpan) {
const componentTypeNames = this._findComponentDirectiveNames(directives);
if (componentTypeNames.length > 1) {
this._reportError(
`More than one component matched on this element.\n` +
`Make sure that only one component's selector can match a given element.\n` +
`Conflicting components: ${componentTypeNames.join(',')}`,
sourceSpan);
}
}
/**
* Make sure that non-angular tags conform to the schemas.
*
* Note: An element is considered an angular tag when at least one directive selector matches the
* tag name.
*
* @param matchElement Whether any directive has matched on the tag name
* @param element the html element
*/
private _assertElementExists(matchElement: boolean, element: html.Element) {
const elName = element.name.replace(/^:xhtml:/, '');
if (!matchElement && !this._schemaRegistry.hasElement(elName, this._schemas)) {
let errorMsg = `'${elName}' is not a known element:\n`;
errorMsg +=
`1. If '${elName}' is an Angular component, then verify that it is part of this module.\n`;
if (elName.indexOf('-') > -1) {
errorMsg +=
`2. If '${elName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.`;
} else {
errorMsg +=
`2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`;
}
this._reportError(errorMsg, element.sourceSpan !);
}
}
private _assertNoComponentsNorElementBindingsOnTemplate(
directives: t.DirectiveAst[], elementProps: t.BoundElementPropertyAst[],
sourceSpan: ParseSourceSpan) {
const componentTypeNames: string[] = this._findComponentDirectiveNames(directives);
if (componentTypeNames.length > 0) {
this._reportError(
`Components on an embedded template: ${componentTypeNames.join(',')}`, sourceSpan);
}
elementProps.forEach(prop => {
this._reportError(
`Property binding ${prop.name} not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "@NgModule.declarations".`,
sourceSpan);
});
}
private _assertAllEventsPublishedByDirectives(
directives: t.DirectiveAst[], events: t.BoundEventAst[]) {
const allDirectiveEvents = new Set<string>();
directives.forEach(directive => {
Object.keys(directive.directive.outputs).forEach(k => {
const eventName = directive.directive.outputs[k];
allDirectiveEvents.add(eventName);
});
});
events.forEach(event => {
if (event.target != null || !allDirectiveEvents.has(event.name)) {
this._reportError(
`Event binding ${event.fullName} not emitted by any directive on an embedded template. Make sure that the event name is spelled correctly and all directives are listed in the "@NgModule.declarations".`,
event.sourceSpan);
}
});
}
private _checkPropertiesInSchema(elementName: string, boundProps: t.BoundElementPropertyAst[]):
t.BoundElementPropertyAst[] {
// Note: We can't filter out empty expressions before this method,
// as we still want to validate them!
return boundProps.filter((boundProp) => {
if (boundProp.type === t.PropertyBindingType.Property &&
!this._schemaRegistry.hasProperty(elementName, boundProp.name, this._schemas)) {
let errorMsg =
`Can't bind to '${boundProp.name}' since it isn't a known property of '${elementName}'.`;
if (elementName.startsWith('ng-')) {
errorMsg +=
`\n1. If '${boundProp.name}' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.` +
`\n2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`;
} else if (elementName.indexOf('-') > -1) {
errorMsg +=
`\n1. If '${elementName}' is an Angular component and it has '${boundProp.name}' input, then verify that it is part of this module.` +
`\n2. If '${elementName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.` +
`\n3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`;
}
this._reportError(errorMsg, boundProp.sourceSpan);
}
return !isEmptyExpression(boundProp.value);
});
}
private _reportError(
message: string, sourceSpan: ParseSourceSpan,
level: ParseErrorLevel = ParseErrorLevel.ERROR) {
this._targetErrors.push(new ParseError(sourceSpan, message, level));
}
}
class NonBindableVisitor implements html.Visitor {
visitElement(ast: html.Element, parent: ElementContext): t.ElementAst|null {
const preparsedElement = preparseElement(ast);
if (preparsedElement.type === PreparsedElementType.SCRIPT ||
preparsedElement.type === PreparsedElementType.STYLE ||
preparsedElement.type === PreparsedElementType.STYLESHEET) {
// Skipping <script> for security reasons
// Skipping <style> and stylesheets as we already processed them
// in the StyleCompiler
return null;
}
const attrNameAndValues = ast.attrs.map((attr): [string, string] => [attr.name, attr.value]);
const selector = createElementCssSelector(ast.name, attrNameAndValues);
const ngContentIndex = parent.findNgContentIndex(selector);
const children: t.TemplateAst[] = html.visitAll(this, ast.children, EMPTY_ELEMENT_CONTEXT);
return new t.ElementAst(
ast.name, html.visitAll(this, ast.attrs), [], [], [], [], [], false, [], children,
ngContentIndex, ast.sourceSpan, ast.endSourceSpan);
}
visitComment(comment: html.Comment, context: any): any { return null; }
visitAttribute(attribute: html.Attribute, context: any): t.AttrAst {
return new t.AttrAst(attribute.name, attribute.value, attribute.sourceSpan);
}
visitText(text: html.Text, parent: ElementContext): t.TextAst {
const ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR()) !;
return new t.TextAst(text.value, ngContentIndex, text.sourceSpan !);
}
visitExpansion(expansion: html.Expansion, context: any): any { return expansion; }
visitExpansionCase(expansionCase: html.ExpansionCase, context: any): any { return expansionCase; }
}
/**
* A reference to an element or directive in a template. E.g., the reference in this template:
*
* <div #myMenu="coolMenu">
*
* would be {name: 'myMenu', value: 'coolMenu', sourceSpan: ...}
*/
class ElementOrDirectiveRef {
constructor(public name: string, public value: string, public sourceSpan: ParseSourceSpan) {}
/** Gets whether this is a reference to the given directive. */
isReferenceToDirective(directive: CompileDirectiveSummary) {
return splitExportAs(directive.exportAs).indexOf(this.value) !== -1;
}
}
/** Splits a raw, potentially comma-delimited `exportAs` value into an array of names. */
function splitExportAs(exportAs: string | null): string[] {
return exportAs ? exportAs.split(',').map(e => e.trim()) : [];
}
export function splitClasses(classAttrValue: string): string[] {
return classAttrValue.trim().split(/\s+/g);
}
class ElementContext {
static create(
isTemplateElement: boolean, directives: t.DirectiveAst[],
providerContext: ProviderElementContext): ElementContext {
const matcher = new SelectorMatcher();
let wildcardNgContentIndex: number = null !;
const component = directives.find(directive => directive.directive.isComponent);
if (component) {
const ngContentSelectors = component.directive.template !.ngContentSelectors;
for (let i = 0; i < ngContentSelectors.length; i++) {
const selector = ngContentSelectors[i];
if (selector === '*') {
wildcardNgContentIndex = i;
} else {
matcher.addSelectables(CssSelector.parse(ngContentSelectors[i]), i);
}
}
}
return new ElementContext(isTemplateElement, matcher, wildcardNgContentIndex, providerContext);
}
constructor(
public isTemplateElement: boolean, private _ngContentIndexMatcher: SelectorMatcher,
private _wildcardNgContentIndex: number|null,
public providerContext: ProviderElementContext|null) {}
findNgContentIndex(selector: CssSelector): number|null {
const ngContentIndices: number[] = [];
this._ngContentIndexMatcher.match(
selector, (selector, ngContentIndex) => { ngContentIndices.push(ngContentIndex); });
ngContentIndices.sort();
if (this._wildcardNgContentIndex != null) {
ngContentIndices.push(this._wildcardNgContentIndex);
}
return ngContentIndices.length > 0 ? ngContentIndices[0] : null;
}
}
export function createElementCssSelector(
elementName: string, attributes: [string, string][]): CssSelector {
const cssSelector = new CssSelector();
const elNameNoNs = splitNsName(elementName)[1];
cssSelector.setElement(elNameNoNs);
for (let i = 0; i < attributes.length; i++) {
const attrName = attributes[i][0];
const attrNameNoNs = splitNsName(attrName)[1];
const attrValue = attributes[i][1];
cssSelector.addAttribute(attrNameNoNs, attrValue);
if (attrName.toLowerCase() == CLASS_ATTR) {
const classes = splitClasses(attrValue);
classes.forEach(className => cssSelector.addClassName(className));
}
}
return cssSelector;
}
const EMPTY_ELEMENT_CONTEXT = new ElementContext(true, new SelectorMatcher(), null, null);
const NON_BINDABLE_VISITOR = new NonBindableVisitor();
function _isEmptyTextNode(node: html.Node): boolean {
return node instanceof html.Text && node.value.trim().length == 0;
}
export function removeSummaryDuplicates<T extends{type: CompileTypeMetadata}>(items: T[]): T[] {
const map = new Map<any, T>();
items.forEach((item) => {
if (!map.get(item.type.reference)) {
map.set(item.type.reference, item);
}
});
return Array.from(map.values());
}
function isEmptyExpression(ast: AST): boolean {
if (ast instanceof ASTWithSource) {
ast = ast.ast;
}
return ast instanceof EmptyExpr;
} | packages/compiler/src/template_parser/template_parser.ts | 0 | https://github.com/angular/angular/commit/b0c75611d6ff193afd29cd12152c1b3e3f04424a | [
0.000649713387247175,
0.00017688483058009297,
0.00016296048124786466,
0.00016962879453785717,
0.00005427972791949287
]
|
{
"id": 3,
"code_window": [
" let validators: ValidatorFn|ValidatorFn[]|null = null;\n",
" let asyncValidators: AsyncValidatorFn|AsyncValidatorFn[]|null = null;\n",
" let updateOn: FormHooks|undefined = undefined;\n",
"\n",
" if (legacyOrOpts != null &&\n",
" (legacyOrOpts.asyncValidator !== undefined || legacyOrOpts.validator !== undefined)) {\n",
" // `legacyOrOpts` are legacy form group options\n",
" validators = legacyOrOpts.validator != null ? legacyOrOpts.validator : null;\n",
" asyncValidators = legacyOrOpts.asyncValidator != null ? legacyOrOpts.asyncValidator : null;\n",
" } else if (legacyOrOpts != null) {\n",
" // `legacyOrOpts` are `AbstractControlOptions`\n",
" validators = legacyOrOpts.validators != null ? legacyOrOpts.validators : null;\n",
" asyncValidators = legacyOrOpts.asyncValidators != null ? legacyOrOpts.asyncValidators : null;\n",
" updateOn = legacyOrOpts.updateOn != null ? legacyOrOpts.updateOn : undefined;\n",
" }\n",
"\n",
" return new FormGroup(controls, {asyncValidators, updateOn, validators});\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (options != null) {\n",
" if (isAbstractControlOptions(options)) {\n",
" // `options` are `AbstractControlOptions`\n",
" validators = options.validators != null ? options.validators : null;\n",
" asyncValidators = options.asyncValidators != null ? options.asyncValidators : null;\n",
" updateOn = options.updateOn != null ? options.updateOn : undefined;\n",
" } else {\n",
" // `options` are legacy form group options\n",
" validators = options.validator != null ? options.validator : null;\n",
" asyncValidators = options.asyncValidator != null ? options.asyncValidator : null;\n",
" }\n"
],
"file_path": "packages/forms/src/form_builder.ts",
"type": "replace",
"edit_start_line_idx": 56
} | <!DOCTYPE HTML>
<html lang="en">
<head>
<title>Angular Upgrade</title>
<base href="/">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.js"></script>
<!-- Polyfills -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.1.js"></script>
<script>
System.import('app/downgrade-io/app.module')
.then(null, console.error.bind(console));
</script>
</head>
<body>
<hero-app>
<!-- #docregion usecomponent -->
<div ng-controller="MainController as mainCtrl">
<hero-detail [hero]="mainCtrl.hero"
(deleted)="mainCtrl.onDelete($event)">
</hero-detail>
</div>
<!-- #enddocregion usecomponent -->
<!-- #docregion userepeatedcomponent -->
<div ng-controller="MainController as mainCtrl">
<hero-detail [hero]="hero"
(deleted)="mainCtrl.onDelete($event)"
ng-repeat="hero in mainCtrl.heroes">
</hero-detail>
</div>
<!-- #enddocregion userepeatedcomponent-->
</hero-app>
</body>
</html>
| aio/content/examples/upgrade-module/src/index-downgrade-io.html | 0 | https://github.com/angular/angular/commit/b0c75611d6ff193afd29cd12152c1b3e3f04424a | [
0.0001711760851321742,
0.00017042369290720671,
0.00016921799397096038,
0.00017055406351573765,
7.463781912520062e-7
]
|
{
"id": 4,
"code_window": [
" array(controlsConfig: any[], validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null): FormArray;\n",
" control(formState: any, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null): FormControl;\n",
" group(controlsConfig: {\n",
" [key: string]: any;\n",
" }, legacyOrOpts?: {\n",
" [key: string]: any;\n",
" } | null): FormGroup;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" }, options?: AbstractControlOptions | {\n"
],
"file_path": "tools/public_api_guard/forms/forms.d.ts",
"type": "replace",
"edit_start_line_idx": 207
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injectable} from '@angular/core';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
import {AbstractControl, AbstractControlOptions, FormArray, FormControl, FormGroup, FormHooks} from './model';
/**
* @description
* Creates an `AbstractControl` from a user-specified configuration.
*
* The `FormBuilder` provides syntactic sugar that shortens creating instances of a `FormControl`,
* `FormGroup`, or `FormArray`. It reduces the amount of boilerplate needed to build complex
* forms.
*
* @see [Reactive Forms Guide](/guide/reactive-forms)
*
* @publicApi
*/
@Injectable()
export class FormBuilder {
/**
* @description
* Construct a new `FormGroup` instance.
*
* @param controlsConfig A collection of child controls. The key for each child is the name
* under which it is registered.
*
* @param legacyOrOpts Configuration options object for the `FormGroup`. The object can
* have two shapes:
*
* 1) `AbstractControlOptions` object (preferred), which consists of:
* * `validators`: A synchronous validator function, or an array of validator functions
* * `asyncValidators`: A single async validator or array of async validator functions
* * `updateOn`: The event upon which the control should be updated (options: 'change' | 'blur' |
* submit')
*
* 2) Legacy configuration object, which consists of:
* * `validator`: A synchronous validator function, or an array of validator functions
* * `asyncValidator`: A single async validator or array of async validator functions
*
*/
group(controlsConfig: {[key: string]: any}, legacyOrOpts: {[key: string]: any}|null = null):
FormGroup {
const controls = this._reduceControls(controlsConfig);
let validators: ValidatorFn|ValidatorFn[]|null = null;
let asyncValidators: AsyncValidatorFn|AsyncValidatorFn[]|null = null;
let updateOn: FormHooks|undefined = undefined;
if (legacyOrOpts != null &&
(legacyOrOpts.asyncValidator !== undefined || legacyOrOpts.validator !== undefined)) {
// `legacyOrOpts` are legacy form group options
validators = legacyOrOpts.validator != null ? legacyOrOpts.validator : null;
asyncValidators = legacyOrOpts.asyncValidator != null ? legacyOrOpts.asyncValidator : null;
} else if (legacyOrOpts != null) {
// `legacyOrOpts` are `AbstractControlOptions`
validators = legacyOrOpts.validators != null ? legacyOrOpts.validators : null;
asyncValidators = legacyOrOpts.asyncValidators != null ? legacyOrOpts.asyncValidators : null;
updateOn = legacyOrOpts.updateOn != null ? legacyOrOpts.updateOn : undefined;
}
return new FormGroup(controls, {asyncValidators, updateOn, validators});
}
/**
* @description
* Construct a new `FormControl` with the given state, validators and options.
*
* @param formState Initializes the control with an initial state value, or
* with an object that contains both a value and a disabled status.
*
* @param validatorOrOpts A synchronous validator function, or an array of
* such functions, or an `AbstractControlOptions` object that contains
* validation functions and a validation trigger.
*
* @param asyncValidator A single async validator or array of async validator
* functions.
*
* @usageNotes
*
* ### Initialize a control as disabled
*
* The following example returns a control with an initial value in a disabled state.
*
* <code-example path="forms/ts/formBuilder/form_builder_example.ts"
* linenums="false" region="disabled-control">
* </code-example>
*/
control(
formState: any, validatorOrOpts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions|null,
asyncValidator?: AsyncValidatorFn|AsyncValidatorFn[]|null): FormControl {
return new FormControl(formState, validatorOrOpts, asyncValidator);
}
/**
* Constructs a new `FormArray` from the given array of configurations,
* validators and options.
*
* @param controlsConfig An array of child controls or control configs. Each
* child control is given an index when it is registered.
*
* @param validatorOrOpts A synchronous validator function, or an array of
* such functions, or an `AbstractControlOptions` object that contains
* validation functions and a validation trigger.
*
* @param asyncValidator A single async validator or array of async validator
* functions.
*/
array(
controlsConfig: any[],
validatorOrOpts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions|null,
asyncValidator?: AsyncValidatorFn|AsyncValidatorFn[]|null): FormArray {
const controls = controlsConfig.map(c => this._createControl(c));
return new FormArray(controls, validatorOrOpts, asyncValidator);
}
/** @internal */
_reduceControls(controlsConfig: {[k: string]: any}): {[key: string]: AbstractControl} {
const controls: {[key: string]: AbstractControl} = {};
Object.keys(controlsConfig).forEach(controlName => {
controls[controlName] = this._createControl(controlsConfig[controlName]);
});
return controls;
}
/** @internal */
_createControl(controlConfig: any): AbstractControl {
if (controlConfig instanceof FormControl || controlConfig instanceof FormGroup ||
controlConfig instanceof FormArray) {
return controlConfig;
} else if (Array.isArray(controlConfig)) {
const value = controlConfig[0];
const validator: ValidatorFn = controlConfig.length > 1 ? controlConfig[1] : null;
const asyncValidator: AsyncValidatorFn = controlConfig.length > 2 ? controlConfig[2] : null;
return this.control(value, validator, asyncValidator);
} else {
return this.control(controlConfig);
}
}
}
| packages/forms/src/form_builder.ts | 1 | https://github.com/angular/angular/commit/b0c75611d6ff193afd29cd12152c1b3e3f04424a | [
0.9925398230552673,
0.07982869446277618,
0.00016882314230315387,
0.0033804350532591343,
0.24499811232089996
]
|
{
"id": 4,
"code_window": [
" array(controlsConfig: any[], validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null): FormArray;\n",
" control(formState: any, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null): FormControl;\n",
" group(controlsConfig: {\n",
" [key: string]: any;\n",
" }, legacyOrOpts?: {\n",
" [key: string]: any;\n",
" } | null): FormGroup;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" }, options?: AbstractControlOptions | {\n"
],
"file_path": "tools/public_api_guard/forms/forms.d.ts",
"type": "replace",
"edit_start_line_idx": 207
} | /* tslint:disable:no-unused-variable member-ordering */
// #docplaster
// #docregion imports,
import { Directive, ElementRef, HostListener } from '@angular/core';
// #enddocregion imports,
import { Input } from '@angular/core';
// #docregion
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
// #docregion ctor
constructor(private el: ElementRef) { }
// #enddocregion ctor
// #docregion mouse-methods, host
@HostListener('mouseenter') onMouseEnter() {
// #enddocregion host
this.highlight('yellow');
// #docregion host
}
@HostListener('mouseleave') onMouseLeave() {
// #enddocregion host
this.highlight(null);
// #docregion host
}
// #enddocregion host
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
// #enddocregion mouse-methods,
// #docregion color
@Input() highlightColor: string;
// #enddocregion color
// #docregion color-2
@Input() appHighlight: string;
// #enddocregion color-2
// #docregion
}
// #enddocregion
| aio/content/examples/attribute-directives/src/app/highlight.directive.2.ts | 0 | https://github.com/angular/angular/commit/b0c75611d6ff193afd29cd12152c1b3e3f04424a | [
0.00017708606901578605,
0.00017115091031882912,
0.00015719025395810604,
0.0001750521914800629,
0.000007347493465204025
]
|
{
"id": 4,
"code_window": [
" array(controlsConfig: any[], validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null): FormArray;\n",
" control(formState: any, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null): FormControl;\n",
" group(controlsConfig: {\n",
" [key: string]: any;\n",
" }, legacyOrOpts?: {\n",
" [key: string]: any;\n",
" } | null): FormGroup;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" }, options?: AbstractControlOptions | {\n"
],
"file_path": "tools/public_api_guard/forms/forms.d.ts",
"type": "replace",
"edit_start_line_idx": 207
} | aio/content/examples/attribute-directives/example-config.json | 0 | https://github.com/angular/angular/commit/b0c75611d6ff193afd29cd12152c1b3e3f04424a | [
0.00017241497698705643,
0.00017241497698705643,
0.00017241497698705643,
0.00017241497698705643,
0
]
|
|
{
"id": 4,
"code_window": [
" array(controlsConfig: any[], validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null): FormArray;\n",
" control(formState: any, validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null): FormControl;\n",
" group(controlsConfig: {\n",
" [key: string]: any;\n",
" }, legacyOrOpts?: {\n",
" [key: string]: any;\n",
" } | null): FormGroup;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" }, options?: AbstractControlOptions | {\n"
],
"file_path": "tools/public_api_guard/forms/forms.d.ts",
"type": "replace",
"edit_start_line_idx": 207
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {EventEmitter, Injectable, NgZone} from '@angular/core';
import {MessageBus, MessageBusSink, MessageBusSource} from './message_bus';
// TODO(jteplitz602): Replace this with the definition in lib.webworker.d.ts(#3492)
export interface PostMessageTarget {
postMessage: (message: any, transfer?: [ArrayBuffer]) => void;
}
export class PostMessageBusSink implements MessageBusSink {
// TODO(issue/24571): remove '!'.
private _zone !: NgZone;
private _channels: {[key: string]: _Channel} = {};
private _messageBuffer: Array<Object> = [];
constructor(private _postMessageTarget: PostMessageTarget) {}
attachToZone(zone: NgZone): void {
this._zone = zone;
this._zone.runOutsideAngular(
() => { this._zone.onStable.subscribe({next: () => { this._handleOnEventDone(); }}); });
}
initChannel(channel: string, runInZone: boolean = true): void {
if (this._channels.hasOwnProperty(channel)) {
throw new Error(`${channel} has already been initialized`);
}
const emitter = new EventEmitter(false);
const channelInfo = new _Channel(emitter, runInZone);
this._channels[channel] = channelInfo;
emitter.subscribe((data: Object) => {
const message = {channel: channel, message: data};
if (runInZone) {
this._messageBuffer.push(message);
} else {
this._sendMessages([message]);
}
});
}
to(channel: string): EventEmitter<any> {
if (this._channels.hasOwnProperty(channel)) {
return this._channels[channel].emitter;
} else {
throw new Error(`${channel} is not set up. Did you forget to call initChannel?`);
}
}
private _handleOnEventDone() {
if (this._messageBuffer.length > 0) {
this._sendMessages(this._messageBuffer);
this._messageBuffer = [];
}
}
private _sendMessages(messages: Array<Object>) { this._postMessageTarget.postMessage(messages); }
}
export class PostMessageBusSource implements MessageBusSource {
// TODO(issue/24571): remove '!'.
private _zone !: NgZone;
private _channels: {[key: string]: _Channel} = {};
constructor(eventTarget?: EventTarget) {
if (eventTarget) {
eventTarget.addEventListener('message', (ev: MessageEvent) => this._handleMessages(ev));
} else {
// if no eventTarget is given we assume we're in a WebWorker and listen on the global scope
const workerScope = <EventTarget>self;
workerScope.addEventListener('message', (ev: MessageEvent) => this._handleMessages(ev));
}
}
attachToZone(zone: NgZone) { this._zone = zone; }
initChannel(channel: string, runInZone: boolean = true) {
if (this._channels.hasOwnProperty(channel)) {
throw new Error(`${channel} has already been initialized`);
}
const emitter = new EventEmitter(false);
const channelInfo = new _Channel(emitter, runInZone);
this._channels[channel] = channelInfo;
}
from(channel: string): EventEmitter<any> {
if (this._channels.hasOwnProperty(channel)) {
return this._channels[channel].emitter;
} else {
throw new Error(`${channel} is not set up. Did you forget to call initChannel?`);
}
}
private _handleMessages(ev: MessageEvent): void {
const messages = ev.data;
for (let i = 0; i < messages.length; i++) {
this._handleMessage(messages[i]);
}
}
private _handleMessage(data: any): void {
const channel = data.channel;
if (this._channels.hasOwnProperty(channel)) {
const channelInfo = this._channels[channel];
if (channelInfo.runInZone) {
this._zone.run(() => { channelInfo.emitter.emit(data.message); });
} else {
channelInfo.emitter.emit(data.message);
}
}
}
}
/**
* A TypeScript implementation of {@link MessageBus} for communicating via JavaScript's
* postMessage API.
*/
@Injectable()
export class PostMessageBus implements MessageBus {
constructor(public sink: PostMessageBusSink, public source: PostMessageBusSource) {}
attachToZone(zone: NgZone): void {
this.source.attachToZone(zone);
this.sink.attachToZone(zone);
}
initChannel(channel: string, runInZone: boolean = true): void {
this.source.initChannel(channel, runInZone);
this.sink.initChannel(channel, runInZone);
}
from(channel: string): EventEmitter<any> { return this.source.from(channel); }
to(channel: string): EventEmitter<any> { return this.sink.to(channel); }
}
/**
* Helper class that wraps a channel's {@link EventEmitter} and
* keeps track of if it should run in the zone.
*/
class _Channel {
constructor(public emitter: EventEmitter<any>, public runInZone: boolean) {}
}
| packages/platform-webworker/src/web_workers/shared/post_message_bus.ts | 0 | https://github.com/angular/angular/commit/b0c75611d6ff193afd29cd12152c1b3e3f04424a | [
0.0001844675134634599,
0.00017270860553253442,
0.00016130722360685468,
0.00017276822472922504,
0.000004362411345937289
]
|
{
"id": 0,
"code_window": [
"\t\t\tprefRoute.Post(\"/set-home-dash\", bind(models.SavePreferencesCommand{}), routing.Wrap(SetHomeDashboard))\n",
"\t\t})\n",
"\n",
"\t\t// Data sources\n",
"\t\tapiRoute.Group(\"/datasources\", func(datasourceRoute routing.RouteRegister) {\n",
"\t\t\tdatasourceRoute.Get(\"/\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesRead)), routing.Wrap(hs.GetDataSources))\n",
"\t\t\tdatasourceRoute.Post(\"/\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesCreate)), quota(\"data_source\"), bind(models.AddDataSourceCommand{}), routing.Wrap(AddDataSource))\n",
"\t\t\tdatasourceRoute.Put(\"/:id\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesWrite, ScopeDatasourceID)), bind(models.UpdateDataSourceCommand{}), routing.Wrap(hs.UpdateDataSource))\n",
"\t\t\tdatasourceRoute.Delete(\"/:id\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesDelete, ScopeDatasourceID)), routing.Wrap(hs.DeleteDataSourceById))\n",
"\t\t\tdatasourceRoute.Delete(\"/uid/:uid\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesDelete, ScopeDatasourceUID)), routing.Wrap(hs.DeleteDataSourceByUID))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tdatasourceRoute.Get(\"/\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesRead, ScopeDatasourcesAll)), routing.Wrap(hs.GetDataSources))\n"
],
"file_path": "pkg/api/api.go",
"type": "replace",
"edit_start_line_idx": 268
} | package mock
import (
"context"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol"
)
type fullAccessControl interface {
accesscontrol.AccessControl
GetUserBuiltInRoles(user *models.SignedInUser) []string
RegisterFixedRoles() error
}
type Calls struct {
Evaluate []interface{}
GetUserPermissions []interface{}
IsDisabled []interface{}
DeclareFixedRoles []interface{}
GetUserBuiltInRoles []interface{}
RegisterFixedRoles []interface{}
}
type Mock struct {
// Unless an override is provided, permissions will be returned by GetUserPermissions
permissions []*accesscontrol.Permission
// Unless an override is provided, disabled will be returned by IsDisabled
disabled bool
// Unless an override is provided, builtInRoles will be returned by GetUserBuiltInRoles
builtInRoles []string
// Track the list of calls
Calls Calls
// Override functions
EvaluateFunc func(context.Context, *models.SignedInUser, accesscontrol.Evaluator) (bool, error)
GetUserPermissionsFunc func(context.Context, *models.SignedInUser) ([]*accesscontrol.Permission, error)
IsDisabledFunc func() bool
DeclareFixedRolesFunc func(...accesscontrol.RoleRegistration) error
GetUserBuiltInRolesFunc func(user *models.SignedInUser) []string
RegisterFixedRolesFunc func() error
}
type MockOptions func(*Mock)
// Ensure the mock stays in line with the interface
var _ fullAccessControl = New()
func New() *Mock {
mock := &Mock{
Calls: Calls{},
disabled: false,
permissions: []*accesscontrol.Permission{},
builtInRoles: []string{},
}
return mock
}
func (m Mock) WithPermissions(permissions []*accesscontrol.Permission) *Mock {
m.permissions = permissions
return &m
}
func (m Mock) WithDisabled() *Mock {
m.disabled = true
return &m
}
func (m Mock) WithBuiltInRoles(builtInRoles []string) *Mock {
m.builtInRoles = builtInRoles
return &m
}
// Evaluate evaluates access to the given resource.
// This mock uses GetUserPermissions to then call the evaluator Evaluate function.
func (m *Mock) Evaluate(ctx context.Context, user *models.SignedInUser, evaluator accesscontrol.Evaluator) (bool, error) {
m.Calls.Evaluate = append(m.Calls.Evaluate, []interface{}{ctx, user, evaluator})
// Use override if provided
if m.EvaluateFunc != nil {
return m.EvaluateFunc(ctx, user, evaluator)
}
// Otherwise perform an actual evaluation of the permissions
permissions, err := m.GetUserPermissions(ctx, user)
if err != nil {
return false, err
}
return evaluator.Evaluate(accesscontrol.GroupScopesByAction(permissions))
}
// GetUserPermissions returns user permissions.
// This mock return m.permissions unless an override is provided.
func (m *Mock) GetUserPermissions(ctx context.Context, user *models.SignedInUser) ([]*accesscontrol.Permission, error) {
m.Calls.GetUserPermissions = append(m.Calls.GetUserPermissions, []interface{}{ctx, user})
// Use override if provided
if m.GetUserPermissionsFunc != nil {
return m.GetUserPermissionsFunc(ctx, user)
}
// Otherwise return the Permissions list
return m.permissions, nil
}
// Middleware checks if service disabled or not to switch to fallback authorization.
// This mock return m.disabled unless an override is provided.
func (m *Mock) IsDisabled() bool {
m.Calls.IsDisabled = append(m.Calls.IsDisabled, struct{}{})
// Use override if provided
if m.IsDisabledFunc != nil {
return m.IsDisabledFunc()
}
// Otherwise return the Disabled bool
return m.disabled
}
// DeclareFixedRoles allow the caller to declare, to the service, fixed roles and their
// assignments to organization roles ("Viewer", "Editor", "Admin") or "Grafana Admin"
// This mock returns no error unless an override is provided.
func (m *Mock) DeclareFixedRoles(registrations ...accesscontrol.RoleRegistration) error {
m.Calls.DeclareFixedRoles = append(m.Calls.DeclareFixedRoles, []interface{}{registrations})
// Use override if provided
if m.DeclareFixedRolesFunc != nil {
return m.DeclareFixedRolesFunc(registrations...)
}
return nil
}
// GetUserBuiltInRoles returns the list of organizational roles ("Viewer", "Editor", "Admin")
// or "Grafana Admin" associated to a user
// This mock returns m.builtInRoles unless an override is provided.
func (m *Mock) GetUserBuiltInRoles(user *models.SignedInUser) []string {
m.Calls.GetUserBuiltInRoles = append(m.Calls.GetUserBuiltInRoles, []interface{}{user})
// Use override if provided
if m.GetUserBuiltInRolesFunc != nil {
return m.GetUserBuiltInRolesFunc(user)
}
// Otherwise return the BuiltInRoles list
return m.builtInRoles
}
// RegisterFixedRoles registers all roles declared to AccessControl
// This mock returns no error unless an override is provided.
func (m *Mock) RegisterFixedRoles() error {
m.Calls.RegisterFixedRoles = append(m.Calls.RegisterFixedRoles, []struct{}{})
// Use override if provided
if m.RegisterFixedRolesFunc != nil {
return m.RegisterFixedRolesFunc()
}
return nil
}
| pkg/services/accesscontrol/mock/mock.go | 1 | https://github.com/grafana/grafana/commit/a811d7d76fda5809d58ea43c56b7f372719acca1 | [
0.001088811201043427,
0.00026947929291054606,
0.00015881298168096691,
0.0001671532227192074,
0.00027562520699575543
]
|
{
"id": 0,
"code_window": [
"\t\t\tprefRoute.Post(\"/set-home-dash\", bind(models.SavePreferencesCommand{}), routing.Wrap(SetHomeDashboard))\n",
"\t\t})\n",
"\n",
"\t\t// Data sources\n",
"\t\tapiRoute.Group(\"/datasources\", func(datasourceRoute routing.RouteRegister) {\n",
"\t\t\tdatasourceRoute.Get(\"/\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesRead)), routing.Wrap(hs.GetDataSources))\n",
"\t\t\tdatasourceRoute.Post(\"/\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesCreate)), quota(\"data_source\"), bind(models.AddDataSourceCommand{}), routing.Wrap(AddDataSource))\n",
"\t\t\tdatasourceRoute.Put(\"/:id\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesWrite, ScopeDatasourceID)), bind(models.UpdateDataSourceCommand{}), routing.Wrap(hs.UpdateDataSource))\n",
"\t\t\tdatasourceRoute.Delete(\"/:id\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesDelete, ScopeDatasourceID)), routing.Wrap(hs.DeleteDataSourceById))\n",
"\t\t\tdatasourceRoute.Delete(\"/uid/:uid\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesDelete, ScopeDatasourceUID)), routing.Wrap(hs.DeleteDataSourceByUID))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tdatasourceRoute.Get(\"/\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesRead, ScopeDatasourcesAll)), routing.Wrap(hs.GetDataSources))\n"
],
"file_path": "pkg/api/api.go",
"type": "replace",
"edit_start_line_idx": 268
} | {
"__inputs": [],
"__requires": [
{
"type": "grafana",
"id": "grafana",
"name": "Grafana",
"version": "7.3.0-pre"
},
{
"type": "panel",
"id": "graph",
"name": "Graph",
"version": ""
},
{
"type": "datasource",
"id": "stackdriver",
"name": "Google Cloud Monitoring",
"version": "1.0.0"
}
],
"annotations": {
"list": [
{
"builtIn": 1,
"datasource": "-- Grafana --",
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations & Alerts",
"type": "dashboard"
}
]
},
"editable": true,
"gnetId": null,
"graphTooltip": 0,
"id": null,
"links": [],
"panels": [
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "$datasource",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 0
},
"hiddenSeries": false,
"id": 1,
"legend": {
"alignAsTable": false,
"avg": false,
"current": false,
"max": false,
"min": false,
"rightSide": false,
"show": true,
"sideWidth": 220,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "7.4.2",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"metricQuery": {
"aliasBy": "",
"alignmentPeriod": "$alignmentPeriod",
"crossSeriesReducer": "REDUCE_SUM",
"editorMode": "visual",
"filters": [
"resource.type",
"=",
"https_lb_rule",
"AND",
"resource.label.backend_target_name",
"=",
"$backend"
],
"groupBys": [
"resource.label.url_map_name",
"resource.label.backend_target_name",
"metric.label.response_code_class"
],
"metricKind": "DELTA",
"metricType": "loadbalancing.googleapis.com/https/backend_request_count",
"perSeriesAligner": "ALIGN_RATE",
"projectName": "$project",
"query": "",
"unit": "1",
"valueType": "INT64"
},
"queryType": "metrics",
"refId": "A"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Backend Request Count by Code Class",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "$datasource",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 0
},
"hiddenSeries": false,
"id": 2,
"legend": {
"alignAsTable": false,
"avg": false,
"current": false,
"max": false,
"min": false,
"rightSide": false,
"show": true,
"sideWidth": 220,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "7.4.2",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"metricQuery": {
"aliasBy": "",
"alignmentPeriod": "$alignmentPeriod",
"crossSeriesReducer": "REDUCE_SUM",
"filters": [
"resource.type",
"=",
"https_lb_rule",
"AND",
"resource.label.backend_target_name",
"=",
"$backend"
],
"groupBys": [
"resource.label.url_map_name",
"resource.label.backend_target_name",
"resource.label.matched_url_path_rule"
],
"metricKind": "DELTA",
"metricType": "loadbalancing.googleapis.com/https/backend_request_count",
"perSeriesAligner": "ALIGN_RATE",
"projectName": "$project",
"unit": "1",
"valueType": "INT64"
},
"queryType": "metrics",
"refId": "A"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Backend Request Count by Path",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "$datasource",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 8
},
"hiddenSeries": false,
"id": 3,
"legend": {
"alignAsTable": false,
"avg": false,
"current": false,
"max": false,
"min": false,
"rightSide": false,
"show": true,
"sideWidth": 220,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "7.4.2",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"mqlQuery": {
"aliasBy": "",
"expression": "fetch https_lb_rule::loadbalancing.googleapis.com/https/backend_request_count\n| { t_0:\n filter metric.response_code_class = 500\n | align delta()\n | group_by [resource.backend_target_name],\n [value_backend_request_count_aggregate:\n aggregate(value.backend_request_count)]\n ; t_1:\n ident\n | align delta()\n | group_by [resource.backend_target_name],\n [value_backend_request_count_aggregate:\n aggregate(value.backend_request_count)] }\n| outer_join [0]\n| value\n [t_0_value_backend_request_count_aggregate_div:\n div(t_0.value_backend_request_count_aggregate,\n t_1.value_backend_request_count_aggregate)]",
"projectName": "$project",
"query": "fetch https_lb_rule::loadbalancing.googleapis.com/https/backend_request_count\n| { t_0:\n filter metric.response_code_class = 500\n | align delta()\n | group_by [resource.backend_target_name],\n [value_backend_request_count_aggregate:\n aggregate(value.backend_request_count)]\n ; t_1:\n ident\n | align delta()\n | group_by [resource.backend_target_name],\n [value_backend_request_count_aggregate:\n aggregate(value.backend_request_count)] }\n| outer_join [0]\n| value\n [t_0_value_backend_request_count_aggregate_div:\n div(t_0.value_backend_request_count_aggregate,\n t_1.value_backend_request_count_aggregate)]"
},
"queryType": "metrics",
"refId": "A"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Error Rate",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "$datasource",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 8
},
"hiddenSeries": false,
"id": 4,
"legend": {
"alignAsTable": false,
"avg": false,
"current": false,
"max": false,
"min": false,
"rightSide": false,
"show": true,
"sideWidth": 220,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "7.4.2",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"mqlQuery": {
"aliasBy": "",
"expression": "fetch https_lb_rule::loadbalancing.googleapis.com/https/backend_request_count\n| filter metric.response_code_class = 500\n| align delta()\n| group_by\n [resource.matched_url_path_rule, resource.backend_target_name,\n metric.response_code],\n [value_backend_request_count_aggregate:\n aggregate(value.backend_request_count)]",
"projectName": "$project",
"query": "fetch https_lb_rule::loadbalancing.googleapis.com/https/backend_request_count\n| filter metric.response_code_class = 500\n| align delta()\n| group_by\n [resource.matched_url_path_rule, resource.backend_target_name,\n metric.response_code],\n [value_backend_request_count_aggregate:\n aggregate(value.backend_request_count)]"
},
"queryType": "metrics",
"refId": "A"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Error Count by Path and Code",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "$datasource",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 16
},
"hiddenSeries": false,
"id": 5,
"legend": {
"alignAsTable": false,
"avg": false,
"current": false,
"max": false,
"min": false,
"rightSide": false,
"show": true,
"sideWidth": 220,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "7.4.2",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"metricQuery": {
"aliasBy": "",
"alignmentPeriod": "$alignmentPeriod",
"crossSeriesReducer": "REDUCE_PERCENTILE_95",
"filters": [
"resource.type",
"=",
"https_lb_rule",
"AND",
"resource.label.backend_target_name",
"=",
"$backend"
],
"groupBys": ["resource.label.url_map_name", "resource.label.backend_target_name"],
"metricKind": "DELTA",
"metricType": "loadbalancing.googleapis.com/https/backend_latencies",
"perSeriesAligner": "ALIGN_DELTA",
"projectName": "$project",
"unit": "ms",
"valueType": "DISTRIBUTION"
},
"queryType": "metrics",
"refId": "A"
},
{
"metricQuery": {
"aliasBy": "",
"alignmentPeriod": "$alignmentPeriod",
"crossSeriesReducer": "REDUCE_PERCENTILE_05",
"filters": [
"resource.type",
"=",
"https_lb_rule",
"AND",
"resource.label.backend_target_name",
"=",
"$backend"
],
"groupBys": [],
"metricKind": "DELTA",
"metricType": "loadbalancing.googleapis.com/https/backend_latencies",
"perSeriesAligner": "ALIGN_DELTA",
"projectName": "$project",
"unit": "ms",
"valueType": "DISTRIBUTION"
},
"queryType": "metrics",
"refId": "B"
},
{
"metricQuery": {
"aliasBy": "",
"alignmentPeriod": "$alignmentPeriod",
"crossSeriesReducer": "REDUCE_PERCENTILE_50",
"filters": [
"resource.type",
"=",
"https_lb_rule",
"AND",
"resource.label.backend_target_name",
"=",
"$backend"
],
"groupBys": [],
"metricKind": "DELTA",
"metricType": "loadbalancing.googleapis.com/https/backend_latencies",
"perSeriesAligner": "ALIGN_DELTA",
"projectName": "$project",
"unit": "ms",
"valueType": "DISTRIBUTION"
},
"queryType": "metrics",
"refId": "C"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Backend Latency",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "ms",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "$datasource",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 16
},
"hiddenSeries": false,
"id": 6,
"legend": {
"alignAsTable": false,
"avg": false,
"current": false,
"max": false,
"min": false,
"rightSide": false,
"show": true,
"sideWidth": 220,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "7.4.2",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"metricQuery": {
"aliasBy": "",
"alignmentPeriod": "$alignmentPeriod",
"crossSeriesReducer": "REDUCE_PERCENTILE_50",
"filters": [
"resource.type",
"=",
"https_lb_rule",
"AND",
"resource.label.backend_target_name",
"=",
"$backend"
],
"groupBys": [
"resource.label.url_map_name",
"resource.label.backend_target_name",
"resource.label.matched_url_path_rule"
],
"metricKind": "DELTA",
"metricType": "loadbalancing.googleapis.com/https/backend_latencies",
"perSeriesAligner": "ALIGN_DELTA",
"projectName": "$project",
"unit": "ms",
"valueType": "DISTRIBUTION"
},
"queryType": "metrics",
"refId": "A"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Backend P50 Latency by Path",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "ms",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "$datasource",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 24
},
"hiddenSeries": false,
"id": 7,
"legend": {
"alignAsTable": false,
"avg": false,
"current": false,
"max": false,
"min": false,
"rightSide": false,
"show": true,
"sideWidth": 220,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "7.4.2",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"metricQuery": {
"aliasBy": "",
"alignmentPeriod": "$alignmentPeriod",
"crossSeriesReducer": "REDUCE_SUM",
"filters": [
"resource.type",
"=",
"https_lb_rule",
"AND",
"resource.label.backend_target_name",
"=",
"$backend"
],
"groupBys": ["resource.label.url_map_name", "resource.label.backend_target_name"],
"metricKind": "DELTA",
"metricType": "loadbalancing.googleapis.com/https/backend_request_bytes_count",
"perSeriesAligner": "ALIGN_RATE",
"projectName": "$project",
"unit": "By",
"valueType": "INT64"
},
"queryType": "metrics",
"refId": "A"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Backend Request Bytes",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "bytes",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "$datasource",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 24
},
"hiddenSeries": false,
"id": 8,
"legend": {
"alignAsTable": false,
"avg": false,
"current": false,
"max": false,
"min": false,
"rightSide": false,
"show": true,
"sideWidth": 220,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "7.4.2",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"metricQuery": {
"aliasBy": "",
"alignmentPeriod": "$alignmentPeriod",
"crossSeriesReducer": "REDUCE_SUM",
"filters": [
"resource.type",
"=",
"https_lb_rule",
"AND",
"resource.label.backend_target_name",
"=",
"$backend"
],
"groupBys": [
"resource.label.url_map_name",
"resource.label.backend_target_name",
"resource.label.matched_url_path_rule"
],
"metricKind": "DELTA",
"metricType": "loadbalancing.googleapis.com/https/backend_request_bytes_count",
"perSeriesAligner": "ALIGN_RATE",
"projectName": "$project",
"unit": "By",
"valueType": "INT64"
},
"queryType": "metrics",
"refId": "A"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Backend Request Bytes by Path",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "bytes",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "$datasource",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 32
},
"hiddenSeries": false,
"id": 9,
"legend": {
"alignAsTable": false,
"avg": false,
"current": false,
"max": false,
"min": false,
"rightSide": false,
"show": true,
"sideWidth": 220,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "7.4.2",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"metricQuery": {
"aliasBy": "",
"alignmentPeriod": "$alignmentPeriod",
"crossSeriesReducer": "REDUCE_SUM",
"filters": [
"resource.type",
"=",
"https_lb_rule",
"AND",
"resource.label.backend_target_name",
"=",
"$backend"
],
"groupBys": ["resource.label.url_map_name", "resource.label.backend_target_name"],
"metricKind": "DELTA",
"metricType": "loadbalancing.googleapis.com/https/backend_response_bytes_count",
"perSeriesAligner": "ALIGN_RATE",
"projectName": "$project",
"unit": "By",
"valueType": "INT64"
},
"queryType": "metrics",
"refId": "A"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Backend Response Bytes",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "bytes",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "$datasource",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 32
},
"hiddenSeries": false,
"id": 10,
"legend": {
"alignAsTable": false,
"avg": false,
"current": false,
"max": false,
"min": false,
"rightSide": false,
"show": true,
"sideWidth": 220,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"options": {
"alertThreshold": true
},
"percentage": false,
"pluginVersion": "7.4.2",
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"metricQuery": {
"aliasBy": "",
"alignmentPeriod": "$alignmentPeriod",
"crossSeriesReducer": "REDUCE_SUM",
"filters": [
"resource.type",
"=",
"https_lb_rule",
"AND",
"resource.label.backend_target_name",
"=",
"$backend"
],
"groupBys": [
"resource.label.url_map_name",
"resource.label.backend_target_name",
"resource.label.matched_url_path_rule"
],
"metricKind": "DELTA",
"metricType": "loadbalancing.googleapis.com/https/backend_response_bytes_count",
"perSeriesAligner": "ALIGN_RATE",
"projectName": "$project",
"unit": "By",
"valueType": "INT64"
},
"queryType": "metrics",
"refId": "A"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Backend Response Bytes by Path",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "bytes",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
}
],
"schemaVersion": 27,
"style": "dark",
"tags": ["Networking", "Cloud Monitoring", "GCP"],
"templating": {
"list": [
{
"current": {
"selected": false,
"text": "Google Cloud Monitoring",
"value": "Google Cloud Monitoring"
},
"description": null,
"error": null,
"hide": 0,
"includeAll": false,
"label": "Datasource",
"multi": false,
"name": "datasource",
"options": [],
"query": "stackdriver",
"queryValue": "",
"refresh": 1,
"regex": "",
"skipUrlSync": false,
"type": "datasource"
},
{
"allValue": null,
"current": {},
"datasource": "$datasource",
"definition": "Google Cloud Monitoring - Projects",
"description": null,
"error": null,
"hide": 0,
"includeAll": false,
"label": "Project",
"multi": false,
"name": "project",
"options": [],
"query": {
"labelKey": "",
"loading": false,
"projectName": "$project",
"projects": [],
"selectedMetricType": "actions.googleapis.com/smarthome_action/num_active_users",
"selectedQueryType": "projects",
"selectedSLOService": "",
"selectedService": "actions.googleapis.com",
"sloServices": []
},
"refresh": 1,
"regex": "",
"skipUrlSync": false,
"sort": 0,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": false
},
{
"allValue": null,
"current": {},
"datasource": "${datasource}",
"definition": "",
"description": null,
"error": null,
"hide": 0,
"includeAll": false,
"label": "Alignment Period",
"multi": false,
"name": "alignmentPeriod",
"options": [],
"query": {
"labelKey": "",
"loading": false,
"projectName": "$project",
"projects": [],
"refId": "CloudMonitoringVariableQueryEditor-VariableQuery",
"selectedMetricType": "actions.googleapis.com/smarthome_action/num_active_users",
"selectedQueryType": "alignmentPeriods",
"selectedSLOService": "",
"selectedService": "actions.googleapis.com",
"sloServices": []
},
"refresh": 1,
"regex": "",
"skipUrlSync": false,
"sort": 0,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": false
},
{
"allValue": null,
"current": {},
"datasource": "${datasource}",
"definition": "",
"description": null,
"error": null,
"hide": 0,
"includeAll": false,
"label": null,
"multi": false,
"name": "backend",
"options": [],
"query": {
"labelKey": "resource.label.backend_target_name",
"loading": false,
"projectName": "$project",
"projects": [],
"refId": "CloudMonitoringVariableQueryEditor-VariableQuery",
"selectedMetricType": "loadbalancing.googleapis.com/https/backend_latencies",
"selectedQueryType": "labelValues",
"selectedSLOService": "",
"selectedService": "loadbalancing.googleapis.com",
"sloServices": []
},
"refresh": 1,
"regex": "",
"skipUrlSync": false,
"sort": 1,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": false
}
]
},
"time": {
"from": "now-24h",
"to": "now"
},
"timepicker": {},
"timezone": "",
"title": "HTTP/S LB Backend Services",
"uid": "",
"version": 6
}
| public/app/plugins/datasource/cloud-monitoring/dashboards/https-lb-backend-services-monitoring.json | 0 | https://github.com/grafana/grafana/commit/a811d7d76fda5809d58ea43c56b7f372719acca1 | [
0.00018765941786114126,
0.00017129488696809858,
0.00016436073929071426,
0.00017175600805785507,
0.0000025513752461847616
]
|
{
"id": 0,
"code_window": [
"\t\t\tprefRoute.Post(\"/set-home-dash\", bind(models.SavePreferencesCommand{}), routing.Wrap(SetHomeDashboard))\n",
"\t\t})\n",
"\n",
"\t\t// Data sources\n",
"\t\tapiRoute.Group(\"/datasources\", func(datasourceRoute routing.RouteRegister) {\n",
"\t\t\tdatasourceRoute.Get(\"/\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesRead)), routing.Wrap(hs.GetDataSources))\n",
"\t\t\tdatasourceRoute.Post(\"/\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesCreate)), quota(\"data_source\"), bind(models.AddDataSourceCommand{}), routing.Wrap(AddDataSource))\n",
"\t\t\tdatasourceRoute.Put(\"/:id\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesWrite, ScopeDatasourceID)), bind(models.UpdateDataSourceCommand{}), routing.Wrap(hs.UpdateDataSource))\n",
"\t\t\tdatasourceRoute.Delete(\"/:id\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesDelete, ScopeDatasourceID)), routing.Wrap(hs.DeleteDataSourceById))\n",
"\t\t\tdatasourceRoute.Delete(\"/uid/:uid\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesDelete, ScopeDatasourceUID)), routing.Wrap(hs.DeleteDataSourceByUID))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tdatasourceRoute.Get(\"/\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesRead, ScopeDatasourcesAll)), routing.Wrap(hs.GetDataSources))\n"
],
"file_path": "pkg/api/api.go",
"type": "replace",
"edit_start_line_idx": 268
} | package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
)
func hello(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return
}
line := fmt.Sprintf("webbhook: -> %s", string(body))
fmt.Println(line)
if _, err := io.WriteString(w, line); err != nil {
log.Printf("Failed to write: %v", err)
}
}
func main() {
http.HandleFunc("/", hello)
log.Fatal(http.ListenAndServe(":3010", nil))
}
| devenv/docker/blocks/alert_webhook_listener/main.go | 0 | https://github.com/grafana/grafana/commit/a811d7d76fda5809d58ea43c56b7f372719acca1 | [
0.000170695930137299,
0.00016871069965418428,
0.00016696244711056352,
0.0001684737071627751,
0.0000015333723695221124
]
|
{
"id": 0,
"code_window": [
"\t\t\tprefRoute.Post(\"/set-home-dash\", bind(models.SavePreferencesCommand{}), routing.Wrap(SetHomeDashboard))\n",
"\t\t})\n",
"\n",
"\t\t// Data sources\n",
"\t\tapiRoute.Group(\"/datasources\", func(datasourceRoute routing.RouteRegister) {\n",
"\t\t\tdatasourceRoute.Get(\"/\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesRead)), routing.Wrap(hs.GetDataSources))\n",
"\t\t\tdatasourceRoute.Post(\"/\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesCreate)), quota(\"data_source\"), bind(models.AddDataSourceCommand{}), routing.Wrap(AddDataSource))\n",
"\t\t\tdatasourceRoute.Put(\"/:id\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesWrite, ScopeDatasourceID)), bind(models.UpdateDataSourceCommand{}), routing.Wrap(hs.UpdateDataSource))\n",
"\t\t\tdatasourceRoute.Delete(\"/:id\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesDelete, ScopeDatasourceID)), routing.Wrap(hs.DeleteDataSourceById))\n",
"\t\t\tdatasourceRoute.Delete(\"/uid/:uid\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesDelete, ScopeDatasourceUID)), routing.Wrap(hs.DeleteDataSourceByUID))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tdatasourceRoute.Get(\"/\", authorize(reqOrgAdmin, ac.EvalPermission(ActionDatasourcesRead, ScopeDatasourcesAll)), routing.Wrap(hs.GetDataSources))\n"
],
"file_path": "pkg/api/api.go",
"type": "replace",
"edit_start_line_idx": 268
} | import React, { ChangeEvent } from 'react';
import { EditorProps } from '../QueryEditor';
import { InlineField, InlineFieldRow, Input } from '@grafana/ui';
import { PulseWaveQuery } from '../types';
const fields = [
{ label: 'Step', id: 'timeStep', placeholder: '60', tooltip: 'The number of seconds between datapoints.' },
{
label: 'On Count',
id: 'onCount',
placeholder: '3',
tooltip: 'The number of values within a cycle, at the start of the cycle, that should have the onValue.',
},
{ label: 'Off Count', id: 'offCount', placeholder: '6', tooltip: 'The number of offValues within the cycle.' },
{
label: 'On Value',
id: 'onValue',
placeholder: '1',
tooltip: 'The value for "on values", may be an int, float, or null.',
},
{
label: 'Off Value',
id: 'offValue',
placeholder: '1',
tooltip: 'The value for "off values", may be a int, float, or null.',
},
];
export const PredictablePulseEditor = ({ onChange, query }: EditorProps) => {
// Convert values to numbers before saving
const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;
onChange({ target: { name, value: Number(value) } });
};
return (
<InlineFieldRow>
{fields.map(({ label, id, placeholder, tooltip }) => {
return (
<InlineField label={label} labelWidth={14} key={id} tooltip={tooltip}>
<Input
width={32}
type="number"
name={id}
id={`pulseWave.${id}-${query.refId}`}
value={query.pulseWave?.[id as keyof PulseWaveQuery]}
placeholder={placeholder}
onChange={onInputChange}
/>
</InlineField>
);
})}
</InlineFieldRow>
);
};
| public/app/plugins/datasource/testdata/components/PredictablePulseEditor.tsx | 0 | https://github.com/grafana/grafana/commit/a811d7d76fda5809d58ea43c56b7f372719acca1 | [
0.00017336171003989875,
0.00016953427984844893,
0.00016468812827952206,
0.00017029469017870724,
0.000002683479578990955
]
|
{
"id": 1,
"code_window": [
"\t\t\t\texpectedCode: http.StatusOK,\n",
"\t\t\t\tdesc: \"DatasourcesGet should return 200 for user with correct permissions\",\n",
"\t\t\t\turl: \"/api/datasources/\",\n",
"\t\t\t\tmethod: http.MethodGet,\n",
"\t\t\t\tpermissions: []*accesscontrol.Permission{{Action: ActionDatasourcesRead}},\n",
"\t\t\t},\n",
"\t\t},\n",
"\t\t{\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tpermissions: []*accesscontrol.Permission{{Action: ActionDatasourcesRead, Scope: ScopeDatasourcesAll}},\n"
],
"file_path": "pkg/api/datasources_test.go",
"type": "replace",
"edit_start_line_idx": 236
} | package mock
import (
"context"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol"
)
type fullAccessControl interface {
accesscontrol.AccessControl
GetUserBuiltInRoles(user *models.SignedInUser) []string
RegisterFixedRoles() error
}
type Calls struct {
Evaluate []interface{}
GetUserPermissions []interface{}
IsDisabled []interface{}
DeclareFixedRoles []interface{}
GetUserBuiltInRoles []interface{}
RegisterFixedRoles []interface{}
}
type Mock struct {
// Unless an override is provided, permissions will be returned by GetUserPermissions
permissions []*accesscontrol.Permission
// Unless an override is provided, disabled will be returned by IsDisabled
disabled bool
// Unless an override is provided, builtInRoles will be returned by GetUserBuiltInRoles
builtInRoles []string
// Track the list of calls
Calls Calls
// Override functions
EvaluateFunc func(context.Context, *models.SignedInUser, accesscontrol.Evaluator) (bool, error)
GetUserPermissionsFunc func(context.Context, *models.SignedInUser) ([]*accesscontrol.Permission, error)
IsDisabledFunc func() bool
DeclareFixedRolesFunc func(...accesscontrol.RoleRegistration) error
GetUserBuiltInRolesFunc func(user *models.SignedInUser) []string
RegisterFixedRolesFunc func() error
}
type MockOptions func(*Mock)
// Ensure the mock stays in line with the interface
var _ fullAccessControl = New()
func New() *Mock {
mock := &Mock{
Calls: Calls{},
disabled: false,
permissions: []*accesscontrol.Permission{},
builtInRoles: []string{},
}
return mock
}
func (m Mock) WithPermissions(permissions []*accesscontrol.Permission) *Mock {
m.permissions = permissions
return &m
}
func (m Mock) WithDisabled() *Mock {
m.disabled = true
return &m
}
func (m Mock) WithBuiltInRoles(builtInRoles []string) *Mock {
m.builtInRoles = builtInRoles
return &m
}
// Evaluate evaluates access to the given resource.
// This mock uses GetUserPermissions to then call the evaluator Evaluate function.
func (m *Mock) Evaluate(ctx context.Context, user *models.SignedInUser, evaluator accesscontrol.Evaluator) (bool, error) {
m.Calls.Evaluate = append(m.Calls.Evaluate, []interface{}{ctx, user, evaluator})
// Use override if provided
if m.EvaluateFunc != nil {
return m.EvaluateFunc(ctx, user, evaluator)
}
// Otherwise perform an actual evaluation of the permissions
permissions, err := m.GetUserPermissions(ctx, user)
if err != nil {
return false, err
}
return evaluator.Evaluate(accesscontrol.GroupScopesByAction(permissions))
}
// GetUserPermissions returns user permissions.
// This mock return m.permissions unless an override is provided.
func (m *Mock) GetUserPermissions(ctx context.Context, user *models.SignedInUser) ([]*accesscontrol.Permission, error) {
m.Calls.GetUserPermissions = append(m.Calls.GetUserPermissions, []interface{}{ctx, user})
// Use override if provided
if m.GetUserPermissionsFunc != nil {
return m.GetUserPermissionsFunc(ctx, user)
}
// Otherwise return the Permissions list
return m.permissions, nil
}
// Middleware checks if service disabled or not to switch to fallback authorization.
// This mock return m.disabled unless an override is provided.
func (m *Mock) IsDisabled() bool {
m.Calls.IsDisabled = append(m.Calls.IsDisabled, struct{}{})
// Use override if provided
if m.IsDisabledFunc != nil {
return m.IsDisabledFunc()
}
// Otherwise return the Disabled bool
return m.disabled
}
// DeclareFixedRoles allow the caller to declare, to the service, fixed roles and their
// assignments to organization roles ("Viewer", "Editor", "Admin") or "Grafana Admin"
// This mock returns no error unless an override is provided.
func (m *Mock) DeclareFixedRoles(registrations ...accesscontrol.RoleRegistration) error {
m.Calls.DeclareFixedRoles = append(m.Calls.DeclareFixedRoles, []interface{}{registrations})
// Use override if provided
if m.DeclareFixedRolesFunc != nil {
return m.DeclareFixedRolesFunc(registrations...)
}
return nil
}
// GetUserBuiltInRoles returns the list of organizational roles ("Viewer", "Editor", "Admin")
// or "Grafana Admin" associated to a user
// This mock returns m.builtInRoles unless an override is provided.
func (m *Mock) GetUserBuiltInRoles(user *models.SignedInUser) []string {
m.Calls.GetUserBuiltInRoles = append(m.Calls.GetUserBuiltInRoles, []interface{}{user})
// Use override if provided
if m.GetUserBuiltInRolesFunc != nil {
return m.GetUserBuiltInRolesFunc(user)
}
// Otherwise return the BuiltInRoles list
return m.builtInRoles
}
// RegisterFixedRoles registers all roles declared to AccessControl
// This mock returns no error unless an override is provided.
func (m *Mock) RegisterFixedRoles() error {
m.Calls.RegisterFixedRoles = append(m.Calls.RegisterFixedRoles, []struct{}{})
// Use override if provided
if m.RegisterFixedRolesFunc != nil {
return m.RegisterFixedRolesFunc()
}
return nil
}
| pkg/services/accesscontrol/mock/mock.go | 1 | https://github.com/grafana/grafana/commit/a811d7d76fda5809d58ea43c56b7f372719acca1 | [
0.02639332227408886,
0.0028925950173288584,
0.00016498252807650715,
0.0002738683542702347,
0.006427320186048746
]
|
{
"id": 1,
"code_window": [
"\t\t\t\texpectedCode: http.StatusOK,\n",
"\t\t\t\tdesc: \"DatasourcesGet should return 200 for user with correct permissions\",\n",
"\t\t\t\turl: \"/api/datasources/\",\n",
"\t\t\t\tmethod: http.MethodGet,\n",
"\t\t\t\tpermissions: []*accesscontrol.Permission{{Action: ActionDatasourcesRead}},\n",
"\t\t\t},\n",
"\t\t},\n",
"\t\t{\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tpermissions: []*accesscontrol.Permission{{Action: ActionDatasourcesRead, Scope: ScopeDatasourcesAll}},\n"
],
"file_path": "pkg/api/datasources_test.go",
"type": "replace",
"edit_start_line_idx": 236
} | import {
toDataFrame,
FieldType,
FieldCache,
FieldColorModeId,
Field,
getColorForTheme,
applyFieldOverrides,
createTheme,
DataFrame,
} from '@grafana/data';
import { getTheme } from '../../themes';
import { getMultiSeriesGraphHoverInfo, findHoverIndexFromData, graphTimeFormat } from './utils';
const mockResult = (
value: string,
datapointIndex: number,
seriesIndex: number,
color?: string,
label?: string,
time?: string
) => ({
value,
datapointIndex,
seriesIndex,
color,
label,
time,
});
function passThroughFieldOverrides(frame: DataFrame) {
return applyFieldOverrides({
data: [frame],
fieldConfig: {
defaults: {},
overrides: [],
},
replaceVariables: (val: string) => val,
timeZone: 'utc',
theme: createTheme(),
});
}
// A and B series have the same x-axis range and the datapoints are x-axis aligned
const aSeries = passThroughFieldOverrides(
toDataFrame({
fields: [
{ name: 'time', type: FieldType.time, values: [10000, 20000, 30000, 80000] },
{
name: 'value',
type: FieldType.number,
values: [10, 20, 10, 25],
config: { color: { mode: FieldColorModeId.Fixed, fixedColor: 'red' } },
},
],
})
)[0];
const bSeries = passThroughFieldOverrides(
toDataFrame({
fields: [
{ name: 'time', type: FieldType.time, values: [10000, 20000, 30000, 80000] },
{
name: 'value',
type: FieldType.number,
values: [30, 60, 30, 40],
config: { color: { mode: FieldColorModeId.Fixed, fixedColor: 'blue' } },
},
],
})
)[0];
// C-series has the same x-axis range as A and B but is missing the middle point
const cSeries = passThroughFieldOverrides(
toDataFrame({
fields: [
{ name: 'time', type: FieldType.time, values: [10000, 30000, 80000] },
{
name: 'value',
type: FieldType.number,
values: [30, 30, 30],
config: { color: { mode: FieldColorModeId.Fixed, fixedColor: 'yellow' } },
},
],
})
)[0];
function getFixedThemedColor(field: Field): string {
return getColorForTheme(field.config.color!.fixedColor!, getTheme());
}
describe('Graph utils', () => {
describe('getMultiSeriesGraphHoverInfo', () => {
describe('when series datapoints are x-axis aligned', () => {
it('returns a datapoints that user hovers over', () => {
const aCache = new FieldCache(aSeries);
const aValueField = aCache.getFieldByName('value');
const aTimeField = aCache.getFieldByName('time');
const bCache = new FieldCache(bSeries);
const bValueField = bCache.getFieldByName('value');
const bTimeField = bCache.getFieldByName('time');
const result = getMultiSeriesGraphHoverInfo([aValueField!, bValueField!], [aTimeField!, bTimeField!], 0);
expect(result.time).toBe('1970-01-01 00:00:10');
expect(result.results[0]).toEqual(
mockResult('10', 0, 0, getFixedThemedColor(aValueField!), aValueField!.name, '1970-01-01 00:00:10')
);
expect(result.results[1]).toEqual(
mockResult('30', 0, 1, getFixedThemedColor(bValueField!), bValueField!.name, '1970-01-01 00:00:10')
);
});
describe('returns the closest datapoints before the hover position', () => {
it('when hovering right before a datapoint', () => {
const aCache = new FieldCache(aSeries);
const aValueField = aCache.getFieldByName('value');
const aTimeField = aCache.getFieldByName('time');
const bCache = new FieldCache(bSeries);
const bValueField = bCache.getFieldByName('value');
const bTimeField = bCache.getFieldByName('time');
// hovering right before middle point
const result = getMultiSeriesGraphHoverInfo([aValueField!, bValueField!], [aTimeField!, bTimeField!], 19900);
expect(result.time).toBe('1970-01-01 00:00:10');
expect(result.results[0]).toEqual(
mockResult('10', 0, 0, getFixedThemedColor(aValueField!), aValueField!.name, '1970-01-01 00:00:10')
);
expect(result.results[1]).toEqual(
mockResult('30', 0, 1, getFixedThemedColor(bValueField!), bValueField!.name, '1970-01-01 00:00:10')
);
});
it('when hovering right after a datapoint', () => {
const aCache = new FieldCache(aSeries);
const aValueField = aCache.getFieldByName('value');
const aTimeField = aCache.getFieldByName('time');
const bCache = new FieldCache(bSeries);
const bValueField = bCache.getFieldByName('value');
const bTimeField = bCache.getFieldByName('time');
// hovering right after middle point
const result = getMultiSeriesGraphHoverInfo([aValueField!, bValueField!], [aTimeField!, bTimeField!], 20100);
expect(result.time).toBe('1970-01-01 00:00:20');
expect(result.results[0]).toEqual(
mockResult('20', 1, 0, getFixedThemedColor(aValueField!), aValueField!.name, '1970-01-01 00:00:20')
);
expect(result.results[1]).toEqual(
mockResult('60', 1, 1, getFixedThemedColor(bValueField!), bValueField!.name, '1970-01-01 00:00:20')
);
});
});
});
describe('when series x-axes are not aligned', () => {
// aSeries and cSeries are not aligned
// cSeries is missing a middle point
it('hovering over a middle point', () => {
const aCache = new FieldCache(aSeries);
const aValueField = aCache.getFieldByName('value');
const aTimeField = aCache.getFieldByName('time');
const cCache = new FieldCache(cSeries);
const cValueField = cCache.getFieldByName('value');
const cTimeField = cCache.getFieldByName('time');
// hovering on a middle point
// aSeries has point at that time, cSeries doesn't
const result = getMultiSeriesGraphHoverInfo([aValueField!, cValueField!], [aTimeField!, cTimeField!], 20000);
// we expect a time of the hovered point
expect(result.time).toBe('1970-01-01 00:00:20');
// we expect middle point from aSeries (the one we are hovering over)
expect(result.results[0]).toEqual(
mockResult('20', 1, 0, getFixedThemedColor(aValueField!), aValueField!.name, '1970-01-01 00:00:20')
);
// we expect closest point before hovered point from cSeries (1st point)
expect(result.results[1]).toEqual(
mockResult('30', 0, 1, getFixedThemedColor(cValueField!), cValueField!.name, '1970-01-01 00:00:10')
);
});
it('hovering right after over the middle point', () => {
const aCache = new FieldCache(aSeries);
const aValueField = aCache.getFieldByName('value');
const aTimeField = aCache.getFieldByName('time');
const cCache = new FieldCache(cSeries);
const cValueField = cCache.getFieldByName('value');
const cTimeField = cCache.getFieldByName('time');
// aSeries has point at that time, cSeries doesn't
const result = getMultiSeriesGraphHoverInfo([aValueField!, cValueField!], [aTimeField!, cTimeField!], 20100);
// we expect the time of the closest point before hover
expect(result.time).toBe('1970-01-01 00:00:20');
// we expect the closest datapoint before hover from aSeries
expect(result.results[0]).toEqual(
mockResult('20', 1, 0, getFixedThemedColor(aValueField!), aValueField!.name, '1970-01-01 00:00:20')
);
// we expect the closest datapoint before hover from cSeries (1st point)
expect(result.results[1]).toEqual(
mockResult('30', 0, 1, getFixedThemedColor(cValueField!), cValueField!.name, '1970-01-01 00:00:10')
);
});
});
});
describe('findHoverIndexFromData', () => {
it('returns index of the closest datapoint before hover position', () => {
const cache = new FieldCache(aSeries);
const timeField = cache.getFieldByName('time');
// hovering over 1st datapoint
expect(findHoverIndexFromData(timeField!, 0)).toBe(0);
// hovering over right before 2nd datapoint
expect(findHoverIndexFromData(timeField!, 19900)).toBe(0);
// hovering over 2nd datapoint
expect(findHoverIndexFromData(timeField!, 20000)).toBe(1);
// hovering over right before 3rd datapoint
expect(findHoverIndexFromData(timeField!, 29900)).toBe(1);
// hovering over 3rd datapoint
expect(findHoverIndexFromData(timeField!, 30000)).toBe(2);
});
});
describe('graphTimeFormat', () => {
it('graphTimeFormat', () => {
expect(graphTimeFormat(5, 1, 45 * 5 * 1000)).toBe('HH:mm:ss');
expect(graphTimeFormat(5, 1, 7200 * 5 * 1000)).toBe('HH:mm');
expect(graphTimeFormat(5, 1, 80000 * 5 * 1000)).toBe('MM/DD HH:mm');
expect(graphTimeFormat(5, 1, 2419200 * 5 * 1000)).toBe('MM/DD');
expect(graphTimeFormat(5, 1, 12419200 * 5 * 1000)).toBe('YYYY-MM');
});
});
});
| packages/grafana-ui/src/components/Graph/utils.test.ts | 0 | https://github.com/grafana/grafana/commit/a811d7d76fda5809d58ea43c56b7f372719acca1 | [
0.00017799714987631887,
0.00017410625878255814,
0.00017001094238366932,
0.00017386834952048957,
0.000002228777020718553
]
|
{
"id": 1,
"code_window": [
"\t\t\t\texpectedCode: http.StatusOK,\n",
"\t\t\t\tdesc: \"DatasourcesGet should return 200 for user with correct permissions\",\n",
"\t\t\t\turl: \"/api/datasources/\",\n",
"\t\t\t\tmethod: http.MethodGet,\n",
"\t\t\t\tpermissions: []*accesscontrol.Permission{{Action: ActionDatasourcesRead}},\n",
"\t\t\t},\n",
"\t\t},\n",
"\t\t{\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tpermissions: []*accesscontrol.Permission{{Action: ActionDatasourcesRead, Scope: ScopeDatasourcesAll}},\n"
],
"file_path": "pkg/api/datasources_test.go",
"type": "replace",
"edit_start_line_idx": 236
} | <?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 20.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="64px" height="64px" viewBox="0 0 64 64" style="enable-background:new 0 0 64 64;" xml:space="preserve">
<style type="text/css">
.st0{fill:#52545c;}
</style>
<path class="st0" d="M59.5,50.8L28.4,19.6C32.2,15,32,8.2,27.6,3.9c-2.3-2.3-5.3-3.4-8.3-3.4s-6,1.1-8.3,3.4L5.7,9.3
c-4.6,4.6-4.6,12,0,16.6C8,28.1,11,29.2,14,29.2c2.6,0,5.3-0.9,7.5-2.7l20.9,20.9L35.8,54c-0.5,0.5-0.5,1.3,0,1.8l2.1,2.1
c0.3,0.3,0.6,0.4,0.9,0.4s0.7-0.1,0.9-0.4l1.7-1.7l2.1,2.1L41.8,60c-0.5,0.5-0.5,1.3,0,1.8l2.1,2.1c0.3,0.3,0.6,0.4,0.9,0.4
c0.3,0,0.7-0.1,0.9-0.4l6.6-6.6l0.2,0.2c0.4,0.4,0.9,0.6,1.5,0.6c0.5,0,1.1-0.2,1.5-0.6l4-4C60.3,52.9,60.3,51.6,59.5,50.8z M14,22
c-1.2,0-2.3-0.5-3.2-1.3C9,19,9,16.1,10.8,14.3L16.2,9c0.9-0.9,2-1.3,3.2-1.3s2.3,0.5,3.2,1.3c0.9,0.9,1.3,2,1.3,3.2
s-0.5,2.3-1.3,3.2l-5.4,5.4C16.3,21.6,15.2,22,14,22z"/>
</svg>
| public/img/icons_light_theme/icon_apikeys.svg | 0 | https://github.com/grafana/grafana/commit/a811d7d76fda5809d58ea43c56b7f372719acca1 | [
0.000170356739545241,
0.00016706142923794687,
0.00016376611893065274,
0.00016706142923794687,
0.0000032953103072941303
]
|
{
"id": 1,
"code_window": [
"\t\t\t\texpectedCode: http.StatusOK,\n",
"\t\t\t\tdesc: \"DatasourcesGet should return 200 for user with correct permissions\",\n",
"\t\t\t\turl: \"/api/datasources/\",\n",
"\t\t\t\tmethod: http.MethodGet,\n",
"\t\t\t\tpermissions: []*accesscontrol.Permission{{Action: ActionDatasourcesRead}},\n",
"\t\t\t},\n",
"\t\t},\n",
"\t\t{\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tpermissions: []*accesscontrol.Permission{{Action: ActionDatasourcesRead, Scope: ScopeDatasourcesAll}},\n"
],
"file_path": "pkg/api/datasources_test.go",
"type": "replace",
"edit_start_line_idx": 236
} | <?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 20.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="64px" height="64px" viewBox="0 0 64 64" style="enable-background:new 0 0 64 64;" xml:space="preserve">
<style type="text/css">
.st0{fill:#E3E2E2;}
.st1{fill:url(#SVGID_1_);}
</style>
<g>
<path class="st0" d="M20.7,0.6H5.2C2.3,0.6,0,2.9,0,5.8v15.6c0,2.8,2.3,5.2,5.2,5.2h15.6c2.8,0,5.2-2.3,5.2-5.2V5.8
C25.9,2.9,23.6,0.6,20.7,0.6z"/>
<path class="st0" d="M33.4,26.5H49c2.8,0,5.2-2.3,5.2-5.2V5.8c0-2.8-2.3-5.2-5.2-5.2H33.4c-2.8,0-5.2,2.3-5.2,5.2v15.6
C28.2,24.2,30.6,26.5,33.4,26.5z"/>
<path class="st0" d="M20.7,28.2H5.2c-2.8,0-5.2,2.3-5.2,5.2v15.6c0,2.8,2.3,5.2,5.2,5.2h15.6c2.8,0,5.2-2.3,5.2-5.2V33.3
C25.9,30.5,23.6,28.2,20.7,28.2z"/>
<path class="st0" d="M35.1,39.2h4.1v-4.1c0-3.2,2.6-5.8,5.8-5.8h7.1c-0.9-0.7-2-1.1-3.2-1.1H33.4c-2.8,0-5.2,2.3-5.2,5.2v15.6
c0,1.2,0.4,2.3,1.1,3.1v-7C29.3,41.8,31.9,39.2,35.1,39.2z"/>
<linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="49.157" y1="90.4824" x2="49.157" y2="15.655">
<stop offset="0" style="stop-color:#FFF23A"/>
<stop offset="4.010540e-02" style="stop-color:#FEE62D"/>
<stop offset="0.1171" style="stop-color:#FED41A"/>
<stop offset="0.1964" style="stop-color:#FDC90F"/>
<stop offset="0.2809" style="stop-color:#FDC60B"/>
<stop offset="0.6685" style="stop-color:#F28F3F"/>
<stop offset="0.8876" style="stop-color:#ED693C"/>
<stop offset="1" style="stop-color:#E83E39"/>
</linearGradient>
<path class="st1" d="M63.2,44.2h-5h-0.4h-3.7h0v-0.7v-8.4c0-0.4-0.4-0.8-0.8-0.8H45c-0.4,0-0.8,0.4-0.8,0.8v9.1h-9.1
c-0.4,0-0.8,0.4-0.8,0.8v8.3c0,0.2,0.1,0.4,0.3,0.6c0.1,0.1,0.3,0.2,0.5,0.2c0,0,0,0,0.1,0h9.1v3.2v1.3v4.6c0,0.4,0.4,0.8,0.8,0.8
h8.3c0.4,0,0.8-0.4,0.8-0.8v-9.1h9.1c0.4,0,0.8-0.4,0.8-0.8V45C64,44.6,63.6,44.2,63.2,44.2z"/>
</g>
</svg>
| public/img/icons_dark_theme/icon_new_dashboard.svg | 0 | https://github.com/grafana/grafana/commit/a811d7d76fda5809d58ea43c56b7f372719acca1 | [
0.00017430367006454617,
0.00017004337860271335,
0.00016402961045969278,
0.00017092011694330722,
0.000003771934871110716
]
|
{
"id": 2,
"code_window": [
"\tRegisterFixedRolesFunc func() error\n",
"}\n",
"\n",
"type MockOptions func(*Mock)\n",
"\n",
"// Ensure the mock stays in line with the interface\n",
"var _ fullAccessControl = New()\n",
"\n",
"func New() *Mock {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/services/accesscontrol/mock/mock.go",
"type": "replace",
"edit_start_line_idx": 44
} | package mock
import (
"context"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/accesscontrol"
)
type fullAccessControl interface {
accesscontrol.AccessControl
GetUserBuiltInRoles(user *models.SignedInUser) []string
RegisterFixedRoles() error
}
type Calls struct {
Evaluate []interface{}
GetUserPermissions []interface{}
IsDisabled []interface{}
DeclareFixedRoles []interface{}
GetUserBuiltInRoles []interface{}
RegisterFixedRoles []interface{}
}
type Mock struct {
// Unless an override is provided, permissions will be returned by GetUserPermissions
permissions []*accesscontrol.Permission
// Unless an override is provided, disabled will be returned by IsDisabled
disabled bool
// Unless an override is provided, builtInRoles will be returned by GetUserBuiltInRoles
builtInRoles []string
// Track the list of calls
Calls Calls
// Override functions
EvaluateFunc func(context.Context, *models.SignedInUser, accesscontrol.Evaluator) (bool, error)
GetUserPermissionsFunc func(context.Context, *models.SignedInUser) ([]*accesscontrol.Permission, error)
IsDisabledFunc func() bool
DeclareFixedRolesFunc func(...accesscontrol.RoleRegistration) error
GetUserBuiltInRolesFunc func(user *models.SignedInUser) []string
RegisterFixedRolesFunc func() error
}
type MockOptions func(*Mock)
// Ensure the mock stays in line with the interface
var _ fullAccessControl = New()
func New() *Mock {
mock := &Mock{
Calls: Calls{},
disabled: false,
permissions: []*accesscontrol.Permission{},
builtInRoles: []string{},
}
return mock
}
func (m Mock) WithPermissions(permissions []*accesscontrol.Permission) *Mock {
m.permissions = permissions
return &m
}
func (m Mock) WithDisabled() *Mock {
m.disabled = true
return &m
}
func (m Mock) WithBuiltInRoles(builtInRoles []string) *Mock {
m.builtInRoles = builtInRoles
return &m
}
// Evaluate evaluates access to the given resource.
// This mock uses GetUserPermissions to then call the evaluator Evaluate function.
func (m *Mock) Evaluate(ctx context.Context, user *models.SignedInUser, evaluator accesscontrol.Evaluator) (bool, error) {
m.Calls.Evaluate = append(m.Calls.Evaluate, []interface{}{ctx, user, evaluator})
// Use override if provided
if m.EvaluateFunc != nil {
return m.EvaluateFunc(ctx, user, evaluator)
}
// Otherwise perform an actual evaluation of the permissions
permissions, err := m.GetUserPermissions(ctx, user)
if err != nil {
return false, err
}
return evaluator.Evaluate(accesscontrol.GroupScopesByAction(permissions))
}
// GetUserPermissions returns user permissions.
// This mock return m.permissions unless an override is provided.
func (m *Mock) GetUserPermissions(ctx context.Context, user *models.SignedInUser) ([]*accesscontrol.Permission, error) {
m.Calls.GetUserPermissions = append(m.Calls.GetUserPermissions, []interface{}{ctx, user})
// Use override if provided
if m.GetUserPermissionsFunc != nil {
return m.GetUserPermissionsFunc(ctx, user)
}
// Otherwise return the Permissions list
return m.permissions, nil
}
// Middleware checks if service disabled or not to switch to fallback authorization.
// This mock return m.disabled unless an override is provided.
func (m *Mock) IsDisabled() bool {
m.Calls.IsDisabled = append(m.Calls.IsDisabled, struct{}{})
// Use override if provided
if m.IsDisabledFunc != nil {
return m.IsDisabledFunc()
}
// Otherwise return the Disabled bool
return m.disabled
}
// DeclareFixedRoles allow the caller to declare, to the service, fixed roles and their
// assignments to organization roles ("Viewer", "Editor", "Admin") or "Grafana Admin"
// This mock returns no error unless an override is provided.
func (m *Mock) DeclareFixedRoles(registrations ...accesscontrol.RoleRegistration) error {
m.Calls.DeclareFixedRoles = append(m.Calls.DeclareFixedRoles, []interface{}{registrations})
// Use override if provided
if m.DeclareFixedRolesFunc != nil {
return m.DeclareFixedRolesFunc(registrations...)
}
return nil
}
// GetUserBuiltInRoles returns the list of organizational roles ("Viewer", "Editor", "Admin")
// or "Grafana Admin" associated to a user
// This mock returns m.builtInRoles unless an override is provided.
func (m *Mock) GetUserBuiltInRoles(user *models.SignedInUser) []string {
m.Calls.GetUserBuiltInRoles = append(m.Calls.GetUserBuiltInRoles, []interface{}{user})
// Use override if provided
if m.GetUserBuiltInRolesFunc != nil {
return m.GetUserBuiltInRolesFunc(user)
}
// Otherwise return the BuiltInRoles list
return m.builtInRoles
}
// RegisterFixedRoles registers all roles declared to AccessControl
// This mock returns no error unless an override is provided.
func (m *Mock) RegisterFixedRoles() error {
m.Calls.RegisterFixedRoles = append(m.Calls.RegisterFixedRoles, []struct{}{})
// Use override if provided
if m.RegisterFixedRolesFunc != nil {
return m.RegisterFixedRolesFunc()
}
return nil
}
| pkg/services/accesscontrol/mock/mock.go | 1 | https://github.com/grafana/grafana/commit/a811d7d76fda5809d58ea43c56b7f372719acca1 | [
0.9980377554893494,
0.1720094084739685,
0.00016648251039441675,
0.0033079530112445354,
0.3252783417701721
]
|
{
"id": 2,
"code_window": [
"\tRegisterFixedRolesFunc func() error\n",
"}\n",
"\n",
"type MockOptions func(*Mock)\n",
"\n",
"// Ensure the mock stays in line with the interface\n",
"var _ fullAccessControl = New()\n",
"\n",
"func New() *Mock {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/services/accesscontrol/mock/mock.go",
"type": "replace",
"edit_start_line_idx": 44
} | {
"annotations": {
"list": [
{
"builtIn": 1,
"datasource": "-- Grafana --",
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations & Alerts",
"type": "dashboard"
}
]
},
"editable": true,
"gnetId": null,
"graphTooltip": 0,
"iteration": 1591027621672,
"links": [
{
"asDropdown": true,
"icon": "external link",
"tags": ["gdev", "elasticsearch", "datasource-test"],
"title": "Dashboards",
"type": "dashboards"
}
],
"panels": [
{
"aliasColors": {
"error": "red"
},
"bars": true,
"dashLength": 10,
"dashes": false,
"datasource": "gdev-elasticsearch-v6-filebeat",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 5,
"w": 24,
"x": 0,
"y": 0
},
"hiddenSeries": false,
"id": 4,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": false,
"linewidth": 1,
"nullPointMode": "null",
"options": {
"dataLinks": []
},
"percentage": false,
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": true,
"steppedLine": false,
"targets": [
{
"bucketAggs": [
{
"fake": true,
"field": "fields.level",
"id": "3",
"settings": {
"min_doc_count": 1,
"order": "desc",
"orderBy": "_term",
"size": "10"
},
"type": "terms"
},
{
"field": "@timestamp",
"id": "2",
"settings": {
"interval": "5m",
"min_doc_count": 1,
"trimEdges": 0
},
"type": "date_histogram"
}
],
"metrics": [
{
"field": "select field",
"id": "1",
"type": "count"
}
],
"query": "fields.app:grafana",
"refId": "A",
"timeField": "@timestamp"
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Panel Title",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"datasource": "gdev-elasticsearch-v6-filebeat",
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"gridPos": {
"h": 22,
"w": 24,
"x": 0,
"y": 5
},
"id": 2,
"links": [],
"options": {
"showLabels": false,
"showTime": true,
"sortOrder": "Descending",
"wrapLogMessage": true
},
"targets": [
{
"bucketAggs": [
{
"$$hashKey": "object:394",
"field": "@timestamp",
"id": "2",
"settings": {
"interval": "auto",
"min_doc_count": 0,
"trimEdges": 0
},
"type": "date_histogram"
}
],
"metrics": [
{
"$$hashKey": "object:359",
"field": "select field",
"id": "1",
"meta": {},
"settings": {},
"type": "logs"
}
],
"query": "fields.app:grafana",
"refId": "A",
"timeField": "@timestamp"
}
],
"timeFrom": null,
"timeShift": null,
"title": "Panel Title",
"type": "logs"
}
],
"schemaVersion": 25,
"style": "dark",
"tags": ["gdev", "elasticsearch", "datasource-test"],
"templating": {
"list": [
{
"datasource": "gdev-elasticsearch-v6-filebeat",
"filters": [],
"hide": 0,
"label": "",
"name": "Filters",
"skipUrlSync": false,
"type": "adhoc"
}
]
},
"time": {
"from": "now-30m",
"to": "now"
},
"timepicker": {
"refresh_intervals": ["5s", "10s", "30s", "1m", "5m", "15m", "30m", "1h", "2h", "1d"],
"time_options": ["5m", "15m", "1h", "6h", "12h", "24h", "2d", "7d", "30d"]
},
"timezone": "",
"title": "Datasource tests - Elasticsearch v6 Filebeat",
"uid": "06tPt4gZz",
"version": 1
}
| devenv/dev-dashboards/datasource-elasticsearch/elasticsearch_v6_filebeat.json | 0 | https://github.com/grafana/grafana/commit/a811d7d76fda5809d58ea43c56b7f372719acca1 | [
0.0001744546607369557,
0.00017220251902472228,
0.00016807288920972496,
0.00017232555546797812,
0.0000014282634310802678
]
|
{
"id": 2,
"code_window": [
"\tRegisterFixedRolesFunc func() error\n",
"}\n",
"\n",
"type MockOptions func(*Mock)\n",
"\n",
"// Ensure the mock stays in line with the interface\n",
"var _ fullAccessControl = New()\n",
"\n",
"func New() *Mock {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/services/accesscontrol/mock/mock.go",
"type": "replace",
"edit_start_line_idx": 44
} | import React, { PureComponent } from 'react';
import { dateTimeFormat } from '@grafana/data';
import { AccessControlAction, SyncInfo, UserDTO } from 'app/types';
import { Button, LinkButton } from '@grafana/ui';
import { contextSrv } from 'app/core/core';
interface Props {
ldapSyncInfo: SyncInfo;
user: UserDTO;
onUserSync: () => void;
}
interface State {}
const format = 'dddd YYYY-MM-DD HH:mm zz';
const debugLDAPMappingBaseURL = '/admin/ldap';
export class UserLdapSyncInfo extends PureComponent<Props, State> {
onUserSync = () => {
this.props.onUserSync();
};
render() {
const { ldapSyncInfo, user } = this.props;
const nextSyncSuccessful = ldapSyncInfo && ldapSyncInfo.nextSync;
const nextSyncTime = nextSyncSuccessful ? dateTimeFormat(ldapSyncInfo.nextSync, { format }) : '';
const debugLDAPMappingURL = `${debugLDAPMappingBaseURL}?user=${user && user.login}`;
const canReadLDAPUser = contextSrv.hasPermission(AccessControlAction.LDAPUsersRead);
const canSyncLDAPUser = contextSrv.hasPermission(AccessControlAction.LDAPUsersSync);
return (
<>
<h3 className="page-heading">LDAP Synchronisation</h3>
<div className="gf-form-group">
<div className="gf-form">
<table className="filter-table form-inline">
<tbody>
<tr>
<td>External sync</td>
<td>User synced via LDAP. Some changes must be done in LDAP or mappings.</td>
<td>
<span className="label label-tag">LDAP</span>
</td>
</tr>
<tr>
{ldapSyncInfo.enabled ? (
<>
<td>Next scheduled synchronization</td>
<td colSpan={2}>{nextSyncTime}</td>
</>
) : (
<>
<td>Next scheduled synchronization</td>
<td colSpan={2}>Not enabled</td>
</>
)}
</tr>
</tbody>
</table>
</div>
<div className="gf-form-button-row">
{canSyncLDAPUser && (
<Button variant="secondary" onClick={this.onUserSync}>
Sync user
</Button>
)}
{canReadLDAPUser && (
<LinkButton variant="secondary" href={debugLDAPMappingURL}>
Debug LDAP Mapping
</LinkButton>
)}
</div>
</div>
</>
);
}
}
| public/app/features/admin/UserLdapSyncInfo.tsx | 0 | https://github.com/grafana/grafana/commit/a811d7d76fda5809d58ea43c56b7f372719acca1 | [
0.00017331675917375833,
0.00017043118714354932,
0.0001660137641010806,
0.00017115964146796614,
0.0000023371972019958775
]
|
{
"id": 2,
"code_window": [
"\tRegisterFixedRolesFunc func() error\n",
"}\n",
"\n",
"type MockOptions func(*Mock)\n",
"\n",
"// Ensure the mock stays in line with the interface\n",
"var _ fullAccessControl = New()\n",
"\n",
"func New() *Mock {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/services/accesscontrol/mock/mock.go",
"type": "replace",
"edit_start_line_idx": 44
} | package authinfoservice
import (
"github.com/grafana/grafana/pkg/models"
)
type OSSUserProtectionImpl struct {
}
func ProvideOSSUserProtectionService() *OSSUserProtectionImpl {
return &OSSUserProtectionImpl{}
}
func (*OSSUserProtectionImpl) AllowUserMapping(_ *models.User, _ string) error {
return nil
}
| pkg/services/login/authinfoservice/userprotection.go | 0 | https://github.com/grafana/grafana/commit/a811d7d76fda5809d58ea43c56b7f372719acca1 | [
0.00031602507806383073,
0.0002447183651383966,
0.00017341163766104728,
0.0002447183651383966,
0.00007130672020139173
]
|
{
"id": 0,
"code_window": [
"import { ComponentType, useEffect } from 'react'\n",
"import Head from 'next/head'\n",
"import { NextRouter, useRouter } from 'next/router'\n",
"\n",
"import { STORAGE_KEY } from 'lib/gotrue'\n",
"import { IS_PLATFORM } from 'lib/constants'\n",
"import { useProfile, useStore, usePermissions } from 'hooks'\n",
"import Error500 from '../../pages/500'\n",
"import { NextPageWithLayout } from 'types'\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { getNextPath, STORAGE_KEY } from 'lib/gotrue'\n"
],
"file_path": "studio/hooks/misc/withAuth.tsx",
"type": "replace",
"edit_start_line_idx": 4
} | import { GoTrueClient, User } from '@supabase/gotrue-js'
export const STORAGE_KEY = process.env.NEXT_PUBLIC_STORAGE_KEY || 'supabase.dashboard.auth.token'
export const auth = new GoTrueClient({
url: process.env.NEXT_PUBLIC_GOTRUE_URL,
storageKey: STORAGE_KEY,
detectSessionInUrl: true,
})
export const getAuthUser = async (token: String): Promise<any> => {
try {
const {
data: { user },
error,
} = await auth.getUser(token.replace('Bearer ', ''))
if (error) throw error
return { user, error: null }
} catch (err) {
console.log(err)
return { user: null, error: err }
}
}
export const getAuth0Id = (provider: String, providerId: String): String => {
return `${provider}|${providerId}`
}
export const getIdentity = (gotrueUser: User) => {
try {
if (gotrueUser !== undefined && gotrueUser.identities !== undefined) {
return { identity: gotrueUser.identities[0], error: null }
}
throw 'Missing identity'
} catch (err) {
return { identity: null, error: err }
}
}
// NOTE: do not use any imports in this function,
// as it is use standalone in the documents head
export const getNextPath = () => {
if (typeof window === 'undefined') {
// make sure this method is SSR safe
return '/projects'
}
const searchParams = new URLSearchParams(location.search)
const returnTo = searchParams.get('next')
searchParams.delete('next')
const next = returnTo ?? '/projects'
const remainingSearchParams = searchParams.toString()
if (next === 'new-project') {
return '/new/new-project' + (remainingSearchParams ? `?${remainingSearchParams}` : '')
}
return next + (remainingSearchParams ? `?${remainingSearchParams}` : '')
}
| studio/lib/gotrue.ts | 1 | https://github.com/supabase/supabase/commit/ec9cd56e27b914d51f679fe2be28bdd574e9dd2c | [
0.003922575619071722,
0.0007159422966651618,
0.00016550434520468116,
0.00016965370741672814,
0.0013093684101477265
]
|
{
"id": 0,
"code_window": [
"import { ComponentType, useEffect } from 'react'\n",
"import Head from 'next/head'\n",
"import { NextRouter, useRouter } from 'next/router'\n",
"\n",
"import { STORAGE_KEY } from 'lib/gotrue'\n",
"import { IS_PLATFORM } from 'lib/constants'\n",
"import { useProfile, useStore, usePermissions } from 'hooks'\n",
"import Error500 from '../../pages/500'\n",
"import { NextPageWithLayout } from 'types'\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { getNextPath, STORAGE_KEY } from 'lib/gotrue'\n"
],
"file_path": "studio/hooks/misc/withAuth.tsx",
"type": "replace",
"edit_start_line_idx": 4
} | import { FC, useState } from 'react'
import { observer } from 'mobx-react-lite'
import { Button, Input, IconChevronLeft, IconSearch, IconAlertCircle } from 'ui'
import { PostgresPublication } from '@supabase/postgres-meta'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { checkPermissions, useStore } from 'hooks'
import PublicationsTableItem from './PublicationsTableItem'
import Table from 'components/to-be-cleaned/Table'
import NoSearchResults from 'components/to-be-cleaned/NoSearchResults'
import InformationBox from 'components/ui/InformationBox'
interface Props {
selectedPublication: PostgresPublication
onSelectBack: () => void
}
const PublicationsTables: FC<Props> = ({ selectedPublication, onSelectBack }) => {
const { meta } = useStore()
const [filterString, setFilterString] = useState<string>('')
const canUpdatePublications = checkPermissions(
PermissionAction.TENANT_SQL_ADMIN_WRITE,
'publications'
)
const tables =
filterString.length === 0
? meta.tables.list((table: any) => !meta.excludedSchemas.includes(table.schema))
: meta.tables.list(
(table: any) =>
!meta.excludedSchemas.includes(table.schema) && table.name.includes(filterString)
)
// const publication = selectedPublication
// const enabledForAllTables = publication.tables == null
// const toggleReplicationForAllTables = async (publication: any, disable: boolean) => {
// const toggle = disable ? 'disable' : 'enable'
// confirmAlert({
// title: 'Confirm',
// type: 'warn',
// message: `Are you sure you want to ${toggle} replication for all tables in ${publication.name}?`,
// onAsyncConfirm: async () => {
// try {
// const res: any = await meta.publications.recreate(publication.id)
// if (res.error) {
// throw res.error
// } else {
// onPublicationUpdated(res)
// }
// } catch (error: any) {
// ui.setNotification({
// category: 'error',
// message: `Failed to toggle replication for all tables: ${error.message}`,
// })
// }
// },
// })
// }
return (
<>
<div className="mb-4">
<div className="flex items-center justify-between">
<div className="flex items-center space-x-3">
<Button
type="outline"
onClick={() => onSelectBack()}
icon={<IconChevronLeft />}
style={{ padding: '5px' }}
/>
<div>
<Input
size="small"
placeholder={'Filter'}
value={filterString}
onChange={(e) => setFilterString(e.target.value)}
icon={<IconSearch size="tiny" />}
/>
</div>
</div>
{!canUpdatePublications && (
<div className="w-[500px]">
<InformationBox
icon={<IconAlertCircle className="text-scale-1100" strokeWidth={2} />}
title="You need additional permissions to update database replications"
/>
</div>
)}
</div>
</div>
{tables.length === 0 ? (
<NoSearchResults />
) : (
<div>
<Table
head={[
<Table.th key="header-name">Name</Table.th>,
<Table.th key="header-schema">Schema</Table.th>,
<Table.th key="header-desc" className="hidden text-left lg:table-cell">
Description
</Table.th>,
<Table.th key="header-all">
{/* Temporarily disable All tables toggle for publications. See https://github.com/supabase/supabase/pull/7233.
<div className="flex flex-row space-x-3 items-center justify-end">
<div className="text-xs leading-4 font-medium text-gray-400 text-right ">
All Tables
</div>
<Toggle
size="tiny"
align="right"
error=""
className="m-0 p-0 ml-2 mt-1 -mb-1"
checked={enabledForAllTables}
onChange={() => toggleReplicationForAllTables(publication, enabledForAllTables)}
/>
</div> */}
</Table.th>,
]}
body={tables.map((table: any, i: number) => (
<PublicationsTableItem
key={table.id}
table={table}
selectedPublication={selectedPublication}
/>
))}
/>
</div>
)}
</>
)
}
export default observer(PublicationsTables)
| studio/components/interfaces/Database/Publications/PublicationsTables.tsx | 0 | https://github.com/supabase/supabase/commit/ec9cd56e27b914d51f679fe2be28bdd574e9dd2c | [
0.0002617609570734203,
0.0001800306054065004,
0.00016576526104472578,
0.00017327233217656612,
0.000024086213670670986
]
|
{
"id": 0,
"code_window": [
"import { ComponentType, useEffect } from 'react'\n",
"import Head from 'next/head'\n",
"import { NextRouter, useRouter } from 'next/router'\n",
"\n",
"import { STORAGE_KEY } from 'lib/gotrue'\n",
"import { IS_PLATFORM } from 'lib/constants'\n",
"import { useProfile, useStore, usePermissions } from 'hooks'\n",
"import Error500 from '../../pages/500'\n",
"import { NextPageWithLayout } from 'types'\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { getNextPath, STORAGE_KEY } from 'lib/gotrue'\n"
],
"file_path": "studio/hooks/misc/withAuth.tsx",
"type": "replace",
"edit_start_line_idx": 4
} | export { default as IconToggleLeft } from './IconToggleLeft' | packages/ui/src/components/Icon/icons/IconToggleLeft/index.tsx | 0 | https://github.com/supabase/supabase/commit/ec9cd56e27b914d51f679fe2be28bdd574e9dd2c | [
0.00016581348609179258,
0.00016581348609179258,
0.00016581348609179258,
0.00016581348609179258,
0
]
|
{
"id": 0,
"code_window": [
"import { ComponentType, useEffect } from 'react'\n",
"import Head from 'next/head'\n",
"import { NextRouter, useRouter } from 'next/router'\n",
"\n",
"import { STORAGE_KEY } from 'lib/gotrue'\n",
"import { IS_PLATFORM } from 'lib/constants'\n",
"import { useProfile, useStore, usePermissions } from 'hooks'\n",
"import Error500 from '../../pages/500'\n",
"import { NextPageWithLayout } from 'types'\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { getNextPath, STORAGE_KEY } from 'lib/gotrue'\n"
],
"file_path": "studio/hooks/misc/withAuth.tsx",
"type": "replace",
"edit_start_line_idx": 4
} | import * as React from 'react'
import { IconKey, IconLink } from 'ui'
import { useDrag, useDrop, DropTargetMonitor } from 'react-dnd'
import { XYCoord } from 'dnd-core'
import { useDispatch } from '../../store'
import { ColumnHeaderProps, ColumnType, DragItem } from '../../types'
import { ColumnMenu } from '../menu'
import { useTrackedState } from '../../store'
export function ColumnHeader<R>({
column,
columnType,
isPrimaryKey,
format,
}: ColumnHeaderProps<R>) {
const ref = React.useRef<HTMLDivElement>(null)
const dispatch = useDispatch()
const columnIdx = column.idx
const columnKey = column.key
const columnFormat = getColumnFormat(columnType, format)
const state = useTrackedState()
const hoverValue = column.name as string
// keep state.gridColumns' order in sync with data grid component
if (state.gridColumns[columnIdx].key != columnKey) {
dispatch({
type: 'UPDATE_COLUMN_IDX',
payload: { columnKey, columnIdx },
})
}
const [{ isDragging }, drag] = useDrag({
type: 'column-header',
item: () => {
return { key: columnKey, index: columnIdx }
},
canDrag: () => !column.frozen,
collect: (monitor: any) => ({
isDragging: monitor.isDragging(),
}),
})
const [{ handlerId }, drop] = useDrop({
accept: 'column-header',
collect(monitor) {
return {
handlerId: monitor.getHandlerId(),
}
},
hover(item: DragItem, monitor: DropTargetMonitor) {
if (!ref.current) {
return
}
if (column.frozen) {
return
}
const dragIndex = item.index
const dragKey = item.key
const hoverIndex = columnIdx
const hoverKey = columnKey
// Don't replace items with themselves
if (dragIndex === hoverIndex) {
return
}
// Determine rectangle on screen
const hoverBoundingRect = ref.current?.getBoundingClientRect()
// Get horizontal middle
const hoverMiddleX = (hoverBoundingRect.right - hoverBoundingRect.left) / 2
// Determine mouse position
const clientOffset = monitor.getClientOffset()
// Get pixels to the top
const hoverClientX = (clientOffset as XYCoord).x - hoverBoundingRect.left
// Only perform the move when the mouse has crossed half of the items width
// Dragging left
if (dragIndex < hoverIndex && hoverClientX < hoverMiddleX) {
return
}
// Dragging right
if (dragIndex > hoverIndex && hoverClientX > hoverMiddleX) {
return
}
// Time to actually perform the action
moveColumn(dragKey, hoverKey)
// Note: we're mutating the monitor item here!
// Generally it's better to avoid mutations,
// but it's good here for the sake of performance
// to avoid expensive index searches.
item.index = hoverIndex
},
})
const moveColumn = (fromKey: string, toKey: string) => {
if (fromKey == toKey) return
dispatch({
type: 'MOVE_COLUMN',
payload: { fromKey, toKey },
})
}
const opacity = isDragging ? 0 : 1
const cursor = column.frozen ? 'sb-grid-column-header--cursor' : ''
drag(drop(ref))
return (
<div ref={ref} data-handler-id={handlerId} style={{ opacity }} className="w-full">
<div className={`sb-grid-column-header ${cursor}`}>
<div className="sb-grid-column-header__inner">
{renderColumnIcon(columnType)}
{isPrimaryKey && (
<div className="sb-grid-column-header__inner__primary-key">
<IconKey size="tiny" strokeWidth={2} />
</div>
)}
<span className="sb-grid-column-header__inner__name" title={hoverValue}>
{column.name}
</span>
<span className="sb-grid-column-header__inner__format">{columnFormat}</span>
</div>
<ColumnMenu column={column} />
</div>
</div>
)
}
function renderColumnIcon(type: ColumnType) {
switch (type) {
case 'foreign_key':
return (
<div>
<IconLink size="tiny" strokeWidth={2} />
</div>
)
default:
return null
}
}
function getColumnFormat(type: ColumnType, format: string) {
if (type == 'array') {
return `${format.replace('_', '')}[]`
} else return format
}
| studio/components/grid/components/grid/ColumnHeader.tsx | 0 | https://github.com/supabase/supabase/commit/ec9cd56e27b914d51f679fe2be28bdd574e9dd2c | [
0.0001753440301399678,
0.00017110964108724147,
0.00016510589921381325,
0.00017166248289868236,
0.000002757054289759253
]
|
{
"id": 1,
"code_window": [
" to the login page if they are guaranteed (no token at all) to not be logged in. */}\n",
" <script\n",
" dangerouslySetInnerHTML={{\n",
" __html: `if (!localStorage.getItem('${STORAGE_KEY}') && !location.hash) {location.replace('/sign-in?next=' + (new URLSearchParams(location.search).get('next') || encodeURIComponent(location.pathname + location.search + location.hash)))}`,\n",
" }}\n",
" />\n",
" </Head>\n",
" <WrappedComponent {...props} />\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" __html: `window._getNextPath = ${getNextPath.toString()};if (!localStorage.getItem('${STORAGE_KEY}') && !location.hash) {location.replace('/sign-in?next=' + window._getNextPath(location.pathname))}`,\n"
],
"file_path": "studio/hooks/misc/withAuth.tsx",
"type": "replace",
"edit_start_line_idx": 88
} | import { GoTrueClient, User } from '@supabase/gotrue-js'
export const STORAGE_KEY = process.env.NEXT_PUBLIC_STORAGE_KEY || 'supabase.dashboard.auth.token'
export const auth = new GoTrueClient({
url: process.env.NEXT_PUBLIC_GOTRUE_URL,
storageKey: STORAGE_KEY,
detectSessionInUrl: true,
})
export const getAuthUser = async (token: String): Promise<any> => {
try {
const {
data: { user },
error,
} = await auth.getUser(token.replace('Bearer ', ''))
if (error) throw error
return { user, error: null }
} catch (err) {
console.log(err)
return { user: null, error: err }
}
}
export const getAuth0Id = (provider: String, providerId: String): String => {
return `${provider}|${providerId}`
}
export const getIdentity = (gotrueUser: User) => {
try {
if (gotrueUser !== undefined && gotrueUser.identities !== undefined) {
return { identity: gotrueUser.identities[0], error: null }
}
throw 'Missing identity'
} catch (err) {
return { identity: null, error: err }
}
}
// NOTE: do not use any imports in this function,
// as it is use standalone in the documents head
export const getNextPath = () => {
if (typeof window === 'undefined') {
// make sure this method is SSR safe
return '/projects'
}
const searchParams = new URLSearchParams(location.search)
const returnTo = searchParams.get('next')
searchParams.delete('next')
const next = returnTo ?? '/projects'
const remainingSearchParams = searchParams.toString()
if (next === 'new-project') {
return '/new/new-project' + (remainingSearchParams ? `?${remainingSearchParams}` : '')
}
return next + (remainingSearchParams ? `?${remainingSearchParams}` : '')
}
| studio/lib/gotrue.ts | 1 | https://github.com/supabase/supabase/commit/ec9cd56e27b914d51f679fe2be28bdd574e9dd2c | [
0.006234088446944952,
0.0018946712370961905,
0.0001663241710048169,
0.0004897098406217992,
0.0022783707827329636
]
|
{
"id": 1,
"code_window": [
" to the login page if they are guaranteed (no token at all) to not be logged in. */}\n",
" <script\n",
" dangerouslySetInnerHTML={{\n",
" __html: `if (!localStorage.getItem('${STORAGE_KEY}') && !location.hash) {location.replace('/sign-in?next=' + (new URLSearchParams(location.search).get('next') || encodeURIComponent(location.pathname + location.search + location.hash)))}`,\n",
" }}\n",
" />\n",
" </Head>\n",
" <WrappedComponent {...props} />\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" __html: `window._getNextPath = ${getNextPath.toString()};if (!localStorage.getItem('${STORAGE_KEY}') && !location.hash) {location.replace('/sign-in?next=' + window._getNextPath(location.pathname))}`,\n"
],
"file_path": "studio/hooks/misc/withAuth.tsx",
"type": "replace",
"edit_start_line_idx": 88
} | ---
id: careers
title: Work at Supabase
description: We're hiring. Start your career at Supabase.
---
[Browse open roles](https://boards.greenhouse.io/supabase).
| about/docs/careers.mdx | 0 | https://github.com/supabase/supabase/commit/ec9cd56e27b914d51f679fe2be28bdd574e9dd2c | [
0.00017070666945073754,
0.00017070666945073754,
0.00017070666945073754,
0.00017070666945073754,
0
]
|
{
"id": 1,
"code_window": [
" to the login page if they are guaranteed (no token at all) to not be logged in. */}\n",
" <script\n",
" dangerouslySetInnerHTML={{\n",
" __html: `if (!localStorage.getItem('${STORAGE_KEY}') && !location.hash) {location.replace('/sign-in?next=' + (new URLSearchParams(location.search).get('next') || encodeURIComponent(location.pathname + location.search + location.hash)))}`,\n",
" }}\n",
" />\n",
" </Head>\n",
" <WrappedComponent {...props} />\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" __html: `window._getNextPath = ${getNextPath.toString()};if (!localStorage.getItem('${STORAGE_KEY}') && !location.hash) {location.replace('/sign-in?next=' + window._getNextPath(location.pathname))}`,\n"
],
"file_path": "studio/hooks/misc/withAuth.tsx",
"type": "replace",
"edit_start_line_idx": 88
} | <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-user"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg> | studio/public/img/user.svg | 0 | https://github.com/supabase/supabase/commit/ec9cd56e27b914d51f679fe2be28bdd574e9dd2c | [
0.00017292141274083406,
0.00017292141274083406,
0.00017292141274083406,
0.00017292141274083406,
0
]
|
{
"id": 1,
"code_window": [
" to the login page if they are guaranteed (no token at all) to not be logged in. */}\n",
" <script\n",
" dangerouslySetInnerHTML={{\n",
" __html: `if (!localStorage.getItem('${STORAGE_KEY}') && !location.hash) {location.replace('/sign-in?next=' + (new URLSearchParams(location.search).get('next') || encodeURIComponent(location.pathname + location.search + location.hash)))}`,\n",
" }}\n",
" />\n",
" </Head>\n",
" <WrappedComponent {...props} />\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" __html: `window._getNextPath = ${getNextPath.toString()};if (!localStorage.getItem('${STORAGE_KEY}') && !location.hash) {location.replace('/sign-in?next=' + window._getNextPath(location.pathname))}`,\n"
],
"file_path": "studio/hooks/misc/withAuth.tsx",
"type": "replace",
"edit_start_line_idx": 88
} | import HCaptcha from '@hcaptcha/react-hcaptcha'
import { useStore } from 'hooks'
import { post } from 'lib/common/fetch'
import { API_URL } from 'lib/constants'
import { useRouter } from 'next/router'
import { useRef, useState } from 'react'
import { Button, Form, Input } from 'ui'
import { object, string } from 'yup'
const forgotPasswordSchema = object({
email: string().email('Must be a valid email').required('Email is required'),
})
const ForgotPasswordForm = () => {
const { ui } = useStore()
const router = useRouter()
const [captchaToken, setCaptchaToken] = useState<string | null>(null)
const captchaRef = useRef<HCaptcha>(null)
const onForgotPassword = async ({ email }: { email: string }) => {
const toastId = ui.setNotification({
category: 'loading',
message: `Sending password reset email...`,
})
let token = captchaToken
if (!token) {
const captchaResponse = await captchaRef.current?.execute({ async: true })
token = captchaResponse?.response ?? null
}
const response = await post(`${API_URL}/reset-password`, {
email,
hcaptchaToken: token ?? undefined,
redirectTo: `${
process.env.NEXT_PUBLIC_VERCEL_ENV === 'preview'
? process.env.NEXT_PUBLIC_VERCEL_URL
: process.env.NEXT_PUBLIC_SITE_URL
}/reset-password`,
})
const error = response.error
if (!error) {
ui.setNotification({
id: toastId,
category: 'success',
message: `Password reset email sent successfully! Please check your email`,
})
await router.push('/sign-in')
} else {
setCaptchaToken(null)
captchaRef.current?.resetCaptcha()
ui.setNotification({
id: toastId,
category: 'error',
message: error.message,
})
}
}
return (
<Form
validateOnBlur
id="forgot-password-form"
initialValues={{ email: '' }}
validationSchema={forgotPasswordSchema}
onSubmit={onForgotPassword}
>
{({ isSubmitting }: { isSubmitting: boolean }) => {
return (
<div className="flex flex-col space-y-4 pt-4">
<Input
id="email"
name="email"
type="email"
label="Email"
placeholder="[email protected]"
disabled={isSubmitting}
autoComplete="email"
/>
<div className="self-center">
<HCaptcha
ref={captchaRef}
sitekey={process.env.NEXT_PUBLIC_HCAPTCHA_SITE_KEY!}
size="invisible"
onVerify={(token) => {
setCaptchaToken(token)
}}
onExpire={() => {
setCaptchaToken(null)
}}
/>
</div>
<div className="border-overlay-border border-t" />
<Button
block
form="forgot-password-form"
htmlType="submit"
size="medium"
disabled={isSubmitting}
loading={isSubmitting}
>
Send Reset Email
</Button>
</div>
)
}}
</Form>
)
}
export default ForgotPasswordForm
| studio/components/interfaces/SignIn/ForgotPasswordForm.tsx | 0 | https://github.com/supabase/supabase/commit/ec9cd56e27b914d51f679fe2be28bdd574e9dd2c | [
0.0003583058132790029,
0.00019813929975498468,
0.00016396875435020775,
0.00016829004744067788,
0.000067482927988749
]
|
{
"id": 2,
"code_window": [
" }\n",
"}\n",
"\n",
"// NOTE: do not use any imports in this function,\n",
"// as it is use standalone in the documents head\n",
"export const getNextPath = () => {\n",
" if (typeof window === 'undefined') {\n",
" // make sure this method is SSR safe\n",
" return '/projects'\n",
" }\n",
"\n",
" const searchParams = new URLSearchParams(location.search)\n",
" const returnTo = searchParams.get('next')\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export const getNextPath = (fallback = '/projects') => {\n"
],
"file_path": "studio/lib/gotrue.ts",
"type": "replace",
"edit_start_line_idx": 42
} | import { ComponentType, useEffect } from 'react'
import Head from 'next/head'
import { NextRouter, useRouter } from 'next/router'
import { STORAGE_KEY } from 'lib/gotrue'
import { IS_PLATFORM } from 'lib/constants'
import { useProfile, useStore, usePermissions } from 'hooks'
import Error500 from '../../pages/500'
import { NextPageWithLayout } from 'types'
const PLATFORM_ONLY_PAGES = ['reports', 'settings']
export function withAuth<T>(
WrappedComponent: ComponentType<T> | NextPageWithLayout<T, T>,
options?: {
redirectTo: string
redirectIfFound?: boolean
}
) {
const WithAuthHOC: ComponentType<T> = (props: any) => {
const router = useRouter()
const rootStore = useStore()
const { ref, slug } = router.query
const { app, ui } = rootStore
const page = router.pathname.split('/')[3]
const redirectTo = options?.redirectTo ?? defaultRedirectTo(ref)
const redirectIfFound = options?.redirectIfFound
const returning =
app.projects.isInitialized && app.organizations.isInitialized ? 'minimal' : undefined
const { profile, isLoading, error } = useProfile(returning)
const {
permissions,
isLoading: isPermissionLoading,
mutate: mutatePermissions,
} = usePermissions(profile, returning)
const isAccessingBlockedPage = !IS_PLATFORM && PLATFORM_ONLY_PAGES.includes(page)
const isRedirecting =
isAccessingBlockedPage ||
checkRedirectTo(isLoading, router, profile, error, redirectTo, redirectIfFound)
useEffect(() => {
// This should run before redirecting
if (!isLoading) {
if (!profile) {
ui.setProfile(undefined)
} else if (returning !== 'minimal') {
ui.setProfile(profile)
if (!app.organizations.isInitialized) app.organizations.load()
if (!app.projects.isInitialized) app.projects.load()
mutatePermissions()
}
}
if (!isPermissionLoading) {
ui.setPermissions(permissions)
}
// This should run after setting store data
if (isRedirecting) {
router.push(redirectTo)
}
}, [isLoading, isPermissionLoading, isRedirecting, profile, permissions])
useEffect(() => {
if (!isLoading && router.isReady) {
if (ref) {
rootStore.setProjectRef(Array.isArray(ref) ? ref[0] : ref)
}
rootStore.setOrganizationSlug(slug ? String(slug) : undefined)
}
}, [isLoading, router.isReady, ref, slug])
if (!isLoading && !isRedirecting && !profile && error) {
return <Error500 />
}
return (
<>
<Head>
{/* This script will quickly (before the main JS loads) redirect the user
to the login page if they are guaranteed (no token at all) to not be logged in. */}
<script
dangerouslySetInnerHTML={{
__html: `if (!localStorage.getItem('${STORAGE_KEY}') && !location.hash) {location.replace('/sign-in?next=' + (new URLSearchParams(location.search).get('next') || encodeURIComponent(location.pathname + location.search + location.hash)))}`,
}}
/>
</Head>
<WrappedComponent {...props} />
</>
)
}
WithAuthHOC.displayName = `WithAuth(${WrappedComponent.displayName})`
if ('getLayout' in WrappedComponent) {
;(WithAuthHOC as any).getLayout = WrappedComponent.getLayout
}
return WithAuthHOC
}
function defaultRedirectTo(ref: string | string[] | undefined) {
return IS_PLATFORM ? '/sign-in' : ref !== undefined ? `/project/${ref}` : '/sign-in'
}
function checkRedirectTo(
loading: boolean,
router: NextRouter,
profile: any,
profileError: any,
redirectTo: string,
redirectIfFound?: boolean
) {
if (loading) return false
if (router.pathname == redirectTo) return false
// If redirectTo is set, redirect if the user is not logged in.
if (redirectTo && !redirectIfFound && profileError?.code === 401) return true
// If redirectIfFound is also set, redirect if the user was found
if (redirectIfFound && profile) return true
return false
}
| studio/hooks/misc/withAuth.tsx | 1 | https://github.com/supabase/supabase/commit/ec9cd56e27b914d51f679fe2be28bdd574e9dd2c | [
0.002347517292946577,
0.0003485110937617719,
0.00016429445531684905,
0.00017186168406624347,
0.0005778018967248499
]
|
{
"id": 2,
"code_window": [
" }\n",
"}\n",
"\n",
"// NOTE: do not use any imports in this function,\n",
"// as it is use standalone in the documents head\n",
"export const getNextPath = () => {\n",
" if (typeof window === 'undefined') {\n",
" // make sure this method is SSR safe\n",
" return '/projects'\n",
" }\n",
"\n",
" const searchParams = new URLSearchParams(location.search)\n",
" const returnTo = searchParams.get('next')\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export const getNextPath = (fallback = '/projects') => {\n"
],
"file_path": "studio/lib/gotrue.ts",
"type": "replace",
"edit_start_line_idx": 42
} | // DO NOT EDIT
// this file is generated by /internals/populate-icons script
import * as React from 'react'
// @ts-ignore
import { Sunset } from 'react-feather'
import IconBase from './../../IconBase'
function IconSunset(props: any) {
return <IconBase icon={Sunset} {...props} />
}
export default IconSunset
| packages/ui/src/components/Icon/icons/IconSunset/IconSunset.tsx | 0 | https://github.com/supabase/supabase/commit/ec9cd56e27b914d51f679fe2be28bdd574e9dd2c | [
0.00017709078383632004,
0.00017390963330399245,
0.00017072848277166486,
0.00017390963330399245,
0.0000031811505323275924
]
|
{
"id": 2,
"code_window": [
" }\n",
"}\n",
"\n",
"// NOTE: do not use any imports in this function,\n",
"// as it is use standalone in the documents head\n",
"export const getNextPath = () => {\n",
" if (typeof window === 'undefined') {\n",
" // make sure this method is SSR safe\n",
" return '/projects'\n",
" }\n",
"\n",
" const searchParams = new URLSearchParams(location.search)\n",
" const returnTo = searchParams.get('next')\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export const getNextPath = (fallback = '/projects') => {\n"
],
"file_path": "studio/lib/gotrue.ts",
"type": "replace",
"edit_start_line_idx": 42
} | import { useState, useEffect } from 'react'
import { observer } from 'mobx-react-lite'
import { useRouter } from 'next/router'
import { useStore, useFlag } from 'hooks'
import { get } from 'lib/common/fetch'
import { API_URL, PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
import { NextPageWithLayout } from 'types'
import { BillingLayout } from 'components/layouts'
import Connecting from 'components/ui/Loading/Loading'
import { StripeSubscription } from 'components/interfaces/Billing'
import { ProUpgrade } from 'components/interfaces/Billing'
import { PaymentMethod } from 'components/interfaces/Billing/Billing.types'
import { DatabaseAddon } from 'components/interfaces/Billing/AddOns/AddOns.types'
const BillingUpdatePro: NextPageWithLayout = () => {
const { ui } = useStore()
const router = useRouter()
const projectRef = ui.selectedProject?.ref
const orgSlug = ui.selectedOrganization?.slug
const projectUpdateDisabled = useFlag('disableProjectCreationAndUpdate')
const [subscription, setSubscription] = useState<StripeSubscription>()
const [products, setProducts] = useState<{ tiers: any[]; addons: DatabaseAddon[] }>()
const [paymentMethods, setPaymentMethods] = useState<PaymentMethod[]>()
const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(false)
const isEnterprise =
subscription && subscription.tier.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.ENTERPRISE
useEffect(() => {
// User added a new payment method
if (router.query.setup_intent && router.query.redirect_status) {
ui.setNotification({ category: 'success', message: 'Successfully added new payment method' })
}
}, [])
useEffect(() => {
if (projectUpdateDisabled) {
router.push(`/project/${projectRef}/settings/billing/update`)
} else if (projectRef) {
getStripeProducts()
getSubscription()
}
}, [projectRef])
useEffect(() => {
if (orgSlug) {
getPaymentMethods()
}
}, [orgSlug])
useEffect(() => {
if (isEnterprise) {
router.push(`/project/${projectRef}/settings/billing/update/enterprise`)
}
}, [subscription])
const getStripeProducts = async () => {
try {
const products = await get(`${API_URL}/stripe/products`)
setProducts(products)
} catch (error: any) {
ui.setNotification({
error,
category: 'error',
message: `Failed to get products: ${error.message}`,
})
}
}
const getPaymentMethods = async () => {
const orgSlug = ui.selectedOrganization?.slug ?? ''
try {
setIsLoadingPaymentMethods(true)
const { data: paymentMethods, error } = await get(
`${API_URL}/organizations/${orgSlug}/payments`
)
if (error) throw error
setIsLoadingPaymentMethods(false)
setPaymentMethods(paymentMethods)
} catch (error: any) {
ui.setNotification({
error,
category: 'error',
message: `Failed to get available payment methods: ${error.message}`,
})
}
}
const getSubscription = async () => {
try {
if (!ui.selectedProject?.subscription_id) {
throw new Error('Unable to get subscription ID of project')
}
const subscription = await get(`${API_URL}/projects/${projectRef}/subscription`)
if (subscription.error) throw subscription.error
setSubscription(subscription)
} catch (error: any) {
ui.setNotification({
error,
category: 'error',
message: `Failed to get subscription: ${error.message}`,
})
}
}
if (!products || !subscription || isEnterprise)
return (
<div className="flex h-full w-full items-center justify-center">
<Connecting />
</div>
)
return (
<ProUpgrade
products={products}
currentSubscription={subscription}
isLoadingPaymentMethods={isLoadingPaymentMethods}
paymentMethods={paymentMethods || []}
onSelectBack={() => router.push(`/project/${projectRef}/settings/billing/update`)}
/>
)
}
BillingUpdatePro.getLayout = (page) => <BillingLayout>{page}</BillingLayout>
export default observer(BillingUpdatePro)
| studio/pages/project/[ref]/settings/billing/update/pro.tsx | 0 | https://github.com/supabase/supabase/commit/ec9cd56e27b914d51f679fe2be28bdd574e9dd2c | [
0.00017694529378786683,
0.00017081483383663,
0.00016465765656903386,
0.00017099260003305972,
0.0000032630998703098157
]
|
{
"id": 2,
"code_window": [
" }\n",
"}\n",
"\n",
"// NOTE: do not use any imports in this function,\n",
"// as it is use standalone in the documents head\n",
"export const getNextPath = () => {\n",
" if (typeof window === 'undefined') {\n",
" // make sure this method is SSR safe\n",
" return '/projects'\n",
" }\n",
"\n",
" const searchParams = new URLSearchParams(location.search)\n",
" const returnTo = searchParams.get('next')\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export const getNextPath = (fallback = '/projects') => {\n"
],
"file_path": "studio/lib/gotrue.ts",
"type": "replace",
"edit_start_line_idx": 42
} | import { Dictionary } from 'components/grid'
import { Suggestion } from './ColumnEditor.types'
const defaultTimeBasedExpressions: Suggestion[] = [
{
name: 'now()',
value: 'now()',
description: 'Returns the current date and time',
},
{
name: "(now() at time zone 'utc')",
value: "(now() at time zone 'utc')",
description: 'Returns the current date and time based on the specified timezone',
},
]
const defaultTextBasedValues: Suggestion[] = [
{
name: 'Set as NULL',
value: null,
description: 'Set the default value as NULL value',
},
{
name: 'Set as empty string',
value: '',
description: 'Set the default value as an empty string',
},
]
// [Joshen] For now this is a curate mapping, ideally we could look into
// using meta-store's extensions to generate this partially on top of vanilla expressions
export const typeExpressionSuggestions: Dictionary<Suggestion[]> = {
uuid: [
{
name: 'uuid_generate_v4()',
value: 'uuid_generate_v4()',
description: 'Generates a version 4 UUID',
},
],
time: [...defaultTimeBasedExpressions],
timetz: [...defaultTimeBasedExpressions],
timestamp: [...defaultTimeBasedExpressions],
timestamptz: [...defaultTimeBasedExpressions],
text: [...defaultTextBasedValues],
varchar: [...defaultTextBasedValues],
}
| studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.constants.ts | 0 | https://github.com/supabase/supabase/commit/ec9cd56e27b914d51f679fe2be28bdd574e9dd2c | [
0.00017737977032084018,
0.00017078168457373977,
0.00016470022092107683,
0.0001710649812594056,
0.000004092303242941853
]
|
{
"id": 3,
"code_window": [
" const returnTo = searchParams.get('next')\n",
"\n",
" searchParams.delete('next')\n",
"\n",
" const next = returnTo ?? '/projects'\n",
" const remainingSearchParams = searchParams.toString()\n",
"\n",
" if (next === 'new-project') {\n",
" return '/new/new-project' + (remainingSearchParams ? `?${remainingSearchParams}` : '')\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const next = returnTo ?? fallback\n"
],
"file_path": "studio/lib/gotrue.ts",
"type": "replace",
"edit_start_line_idx": 53
} | import { ComponentType, useEffect } from 'react'
import Head from 'next/head'
import { NextRouter, useRouter } from 'next/router'
import { STORAGE_KEY } from 'lib/gotrue'
import { IS_PLATFORM } from 'lib/constants'
import { useProfile, useStore, usePermissions } from 'hooks'
import Error500 from '../../pages/500'
import { NextPageWithLayout } from 'types'
const PLATFORM_ONLY_PAGES = ['reports', 'settings']
export function withAuth<T>(
WrappedComponent: ComponentType<T> | NextPageWithLayout<T, T>,
options?: {
redirectTo: string
redirectIfFound?: boolean
}
) {
const WithAuthHOC: ComponentType<T> = (props: any) => {
const router = useRouter()
const rootStore = useStore()
const { ref, slug } = router.query
const { app, ui } = rootStore
const page = router.pathname.split('/')[3]
const redirectTo = options?.redirectTo ?? defaultRedirectTo(ref)
const redirectIfFound = options?.redirectIfFound
const returning =
app.projects.isInitialized && app.organizations.isInitialized ? 'minimal' : undefined
const { profile, isLoading, error } = useProfile(returning)
const {
permissions,
isLoading: isPermissionLoading,
mutate: mutatePermissions,
} = usePermissions(profile, returning)
const isAccessingBlockedPage = !IS_PLATFORM && PLATFORM_ONLY_PAGES.includes(page)
const isRedirecting =
isAccessingBlockedPage ||
checkRedirectTo(isLoading, router, profile, error, redirectTo, redirectIfFound)
useEffect(() => {
// This should run before redirecting
if (!isLoading) {
if (!profile) {
ui.setProfile(undefined)
} else if (returning !== 'minimal') {
ui.setProfile(profile)
if (!app.organizations.isInitialized) app.organizations.load()
if (!app.projects.isInitialized) app.projects.load()
mutatePermissions()
}
}
if (!isPermissionLoading) {
ui.setPermissions(permissions)
}
// This should run after setting store data
if (isRedirecting) {
router.push(redirectTo)
}
}, [isLoading, isPermissionLoading, isRedirecting, profile, permissions])
useEffect(() => {
if (!isLoading && router.isReady) {
if (ref) {
rootStore.setProjectRef(Array.isArray(ref) ? ref[0] : ref)
}
rootStore.setOrganizationSlug(slug ? String(slug) : undefined)
}
}, [isLoading, router.isReady, ref, slug])
if (!isLoading && !isRedirecting && !profile && error) {
return <Error500 />
}
return (
<>
<Head>
{/* This script will quickly (before the main JS loads) redirect the user
to the login page if they are guaranteed (no token at all) to not be logged in. */}
<script
dangerouslySetInnerHTML={{
__html: `if (!localStorage.getItem('${STORAGE_KEY}') && !location.hash) {location.replace('/sign-in?next=' + (new URLSearchParams(location.search).get('next') || encodeURIComponent(location.pathname + location.search + location.hash)))}`,
}}
/>
</Head>
<WrappedComponent {...props} />
</>
)
}
WithAuthHOC.displayName = `WithAuth(${WrappedComponent.displayName})`
if ('getLayout' in WrappedComponent) {
;(WithAuthHOC as any).getLayout = WrappedComponent.getLayout
}
return WithAuthHOC
}
function defaultRedirectTo(ref: string | string[] | undefined) {
return IS_PLATFORM ? '/sign-in' : ref !== undefined ? `/project/${ref}` : '/sign-in'
}
function checkRedirectTo(
loading: boolean,
router: NextRouter,
profile: any,
profileError: any,
redirectTo: string,
redirectIfFound?: boolean
) {
if (loading) return false
if (router.pathname == redirectTo) return false
// If redirectTo is set, redirect if the user is not logged in.
if (redirectTo && !redirectIfFound && profileError?.code === 401) return true
// If redirectIfFound is also set, redirect if the user was found
if (redirectIfFound && profile) return true
return false
}
| studio/hooks/misc/withAuth.tsx | 1 | https://github.com/supabase/supabase/commit/ec9cd56e27b914d51f679fe2be28bdd574e9dd2c | [
0.012622898444533348,
0.0011445463169366121,
0.0001663523871684447,
0.00017518276581540704,
0.0033136149868369102
]
|
{
"id": 3,
"code_window": [
" const returnTo = searchParams.get('next')\n",
"\n",
" searchParams.delete('next')\n",
"\n",
" const next = returnTo ?? '/projects'\n",
" const remainingSearchParams = searchParams.toString()\n",
"\n",
" if (next === 'new-project') {\n",
" return '/new/new-project' + (remainingSearchParams ? `?${remainingSearchParams}` : '')\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const next = returnTo ?? fallback\n"
],
"file_path": "studio/lib/gotrue.ts",
"type": "replace",
"edit_start_line_idx": 53
} | # PLUGINS
**This directory is not required, you can delete it if you don't want to use it.**
This directory contains JavaScript plugins that you want to run before mounting the root Vue.js application.
More information about the usage of this directory in [the documentation](https://nuxtjs.org/guide/plugins).
| examples/user-management/nuxtjs-user-management/plugins/README.md | 0 | https://github.com/supabase/supabase/commit/ec9cd56e27b914d51f679fe2be28bdd574e9dd2c | [
0.00016262225108221173,
0.00016262225108221173,
0.00016262225108221173,
0.00016262225108221173,
0
]
|
{
"id": 3,
"code_window": [
" const returnTo = searchParams.get('next')\n",
"\n",
" searchParams.delete('next')\n",
"\n",
" const next = returnTo ?? '/projects'\n",
" const remainingSearchParams = searchParams.toString()\n",
"\n",
" if (next === 'new-project') {\n",
" return '/new/new-project' + (remainingSearchParams ? `?${remainingSearchParams}` : '')\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const next = returnTo ?? fallback\n"
],
"file_path": "studio/lib/gotrue.ts",
"type": "replace",
"edit_start_line_idx": 53
} | // Check if heading has custom anchor first, before forming the anchor based on the title
export const getAnchor = (text: any): string | undefined => {
if (typeof text === 'object') {
if (Array.isArray(text)) {
const customAnchor = text.find(
(x) => typeof x === 'string' && x.includes('{#') && x.endsWith('}')
)
if (customAnchor !== undefined) return customAnchor.slice(3, customAnchor.indexOf('}'))
const formattedText = text
.map((x) => {
if (typeof x !== 'string') return x.props.children
else return x.trim()
})
.map((x) => {
if (typeof x !== 'string') return x
else
return x
.toLowerCase()
.replace(/[^a-z0-9- ]/g, '')
.replace(/[ ]/g, '-')
})
return formattedText.join('-').toLowerCase()
} else {
const anchor = text.props.children
if (typeof anchor === 'string') {
return anchor
.toLowerCase()
.replace(/[^a-z0-9- ]/g, '')
.replace(/[ ]/g, '-')
}
return anchor
}
} else if (typeof text === 'string') {
if (text.includes('{#') && text.endsWith('}')) {
return text.slice(text.indexOf('{#') + 2, text.indexOf('}'))
} else {
return text
.toLowerCase()
.replace(/[^a-z0-9- ]/g, '')
.replace(/[ ]/g, '-')
}
} else {
return undefined
}
}
export const removeAnchor = (text: any) => {
if (typeof text === 'object' && Array.isArray(text)) {
return text.filter((x) => !(typeof x === 'string' && x.includes('{#') && x.endsWith('}')))
} else if (typeof text === 'string') {
if (text.indexOf('{#') > 0) return text.slice(0, text.indexOf('{#'))
else return text
}
return text
}
export const highlightSelectedTocItem = (id: string) => {
const tocMenuItems = document.querySelectorAll('.toc-menu a')
// find any currently active items and remove them
const currentActiveItem = document.querySelector('.toc-menu .toc__menu-item--active')
currentActiveItem?.classList.remove('toc__menu-item--active')
// Add active class to the current item
tocMenuItems.forEach((item) => {
// @ts-ignore
if (item.href.split('#')[1] === id) {
item.classList.add('toc__menu-item--active')
}
})
}
// find any currently active items and remove them on route change
export const unHighlightSelectedTocItems = () => {
const currentActiveItem = document.querySelector('.toc-menu .toc__menu-item--active')
currentActiveItem?.classList.remove('toc__menu-item--active')
}
| apps/docs/components/CustomHTMLElements/CustomHTMLElements.utils.ts | 0 | https://github.com/supabase/supabase/commit/ec9cd56e27b914d51f679fe2be28bdd574e9dd2c | [
0.00017207450582645833,
0.00016903781215660274,
0.0001666011376073584,
0.0001693944213911891,
0.0000017048982954293024
]
|
{
"id": 3,
"code_window": [
" const returnTo = searchParams.get('next')\n",
"\n",
" searchParams.delete('next')\n",
"\n",
" const next = returnTo ?? '/projects'\n",
" const remainingSearchParams = searchParams.toString()\n",
"\n",
" if (next === 'new-project') {\n",
" return '/new/new-project' + (remainingSearchParams ? `?${remainingSearchParams}` : '')\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const next = returnTo ?? fallback\n"
],
"file_path": "studio/lib/gotrue.ts",
"type": "replace",
"edit_start_line_idx": 53
} | module.exports = require('config/tailwind.config')
| apps/temp-community-tutorials/tailwind.config.js | 0 | https://github.com/supabase/supabase/commit/ec9cd56e27b914d51f679fe2be28bdd574e9dd2c | [
0.00016948393022175878,
0.00016948393022175878,
0.00016948393022175878,
0.00016948393022175878,
0
]
|
{
"id": 0,
"code_window": [
" if (isClientCanceled) {\n",
" return;\n",
" }\n",
" }\n",
" return observer.error(this.serializeError(error));\n",
" }\n",
" observer.next(data);\n",
" observer.complete();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return observer.error(this.serializeError(error));\n"
],
"file_path": "packages/microservices/client/client-grpc.ts",
"type": "replace",
"edit_start_line_idx": 228
} | import { Logger } from '@nestjs/common';
import { expect } from 'chai';
import { join } from 'path';
import { Observable, Subject } from 'rxjs';
import * as sinon from 'sinon';
import { ClientGrpcProxy } from '../../client/client-grpc';
import { InvalidGrpcPackageException } from '../../errors/invalid-grpc-package.exception';
import { InvalidGrpcServiceException } from '../../errors/invalid-grpc-service.exception';
import { InvalidProtoDefinitionException } from '../../errors/invalid-proto-definition.exception';
class NoopLogger extends Logger {
log(message: any, context?: string): void {}
error(message: any, trace?: string, context?: string): void {}
warn(message: any, context?: string): void {}
}
class GrpcService {
test = null;
test2 = null;
}
describe('ClientGrpcProxy', () => {
let client: ClientGrpcProxy;
let clientMulti: ClientGrpcProxy;
beforeEach(() => {
client = new ClientGrpcProxy({
protoPath: join(__dirname, './test.proto'),
package: 'test',
});
clientMulti = new ClientGrpcProxy({
protoPath: ['test.proto', 'test2.proto'],
package: ['test', 'test2'],
loader: {
includeDirs: [join(__dirname, '.')],
},
});
});
describe('getService', () => {
describe('when "grpcClient[name]" is nil', () => {
it('should throw "InvalidGrpcServiceException"', () => {
(client as any).grpcClient = {};
expect(() => client.getService('test')).to.throw(
InvalidGrpcServiceException,
);
});
it('should throw "InvalidGrpcServiceException" (multiple proto)', () => {
(clientMulti as any).grpcClient = {};
expect(() => clientMulti.getService('test')).to.throw(
InvalidGrpcServiceException,
);
expect(() => clientMulti.getService('test2')).to.throw(
InvalidGrpcServiceException,
);
});
});
describe('when "grpcClient[name]" is not nil', () => {
it('should create grpcService', () => {
(client as any).grpcClients[0] = {
test: GrpcService,
};
expect(() => client.getService('test')).to.not.throw(
InvalidGrpcServiceException,
);
});
describe('when "grpcClient[name]" is not nil (multiple proto)', () => {
it('should create grpcService', () => {
(clientMulti as any).grpcClients[0] = {
test: GrpcService,
test2: GrpcService,
};
expect(() => clientMulti.getService('test')).to.not.throw(
InvalidGrpcServiceException,
);
expect(() => clientMulti.getService('test2')).to.not.throw(
InvalidGrpcServiceException,
);
});
});
});
});
describe('createServiceMethod', () => {
const methodName = 'test';
describe('when method is a response stream', () => {
it('should call "createStreamServiceMethod"', () => {
const cln = { [methodName]: { responseStream: true } };
const spy = sinon.spy(client, 'createStreamServiceMethod');
client.createServiceMethod(cln, methodName);
expect(spy.called).to.be.true;
});
});
describe('when method is not a response stream', () => {
it('should call "createUnaryServiceMethod"', () => {
const cln = { [methodName]: { responseStream: false } };
const spy = sinon.spy(client, 'createUnaryServiceMethod');
client.createServiceMethod(cln, methodName);
expect(spy.called).to.be.true;
});
});
});
describe('createStreamServiceMethod', () => {
it('should return observable', () => {
const methodKey = 'method';
const fn = client.createStreamServiceMethod(
{ [methodKey]: {} },
methodKey,
);
expect(fn()).to.be.instanceof(Observable);
});
describe('on subscribe', () => {
const methodName = 'm';
const obj = { [methodName]: () => ({ on: (type, fn) => fn() }) };
let stream$: Observable<any>;
beforeEach(() => {
stream$ = client.createStreamServiceMethod(obj, methodName)();
});
it('should call native method', () => {
const spy = sinon.spy(obj, methodName);
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
expect(spy.called).to.be.true;
});
});
describe('when stream request', () => {
const methodName = 'm';
const writeSpy = sinon.spy();
const obj = {
[methodName]: () => ({ on: (type, fn) => fn(), write: writeSpy }),
};
let stream$: Observable<any>;
let upstream: Subject<unknown>;
beforeEach(() => {
upstream = new Subject();
(obj[methodName] as any).requestStream = true;
stream$ = client.createStreamServiceMethod(obj, methodName)(upstream);
});
it('should subscribe to request upstream', () => {
const upstreamSubscribe = sinon.spy(upstream, 'subscribe');
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
upstream.next({ test: true });
expect(writeSpy.called).to.be.true;
expect(upstreamSubscribe.called).to.be.true;
});
});
describe('flow-control', () => {
const methodName = 'm';
type EvtCallback = (...args: any[]) => void;
let callMock: {
on: (type: string, fn: EvtCallback) => void;
cancel: sinon.SinonSpy;
finished: boolean;
destroy: sinon.SinonSpy;
removeAllListeners: sinon.SinonSpy;
};
let eventCallbacks: { [type: string]: EvtCallback };
let obj, dataSpy, errorSpy, completeSpy;
let stream$: Observable<any>;
beforeEach(() => {
dataSpy = sinon.spy();
errorSpy = sinon.spy();
completeSpy = sinon.spy();
eventCallbacks = {};
callMock = {
on: (type, fn) => (eventCallbacks[type] = fn),
cancel: sinon.spy(),
finished: false,
destroy: sinon.spy(),
removeAllListeners: sinon.spy(),
};
obj = { [methodName]: () => callMock };
stream$ = client.createStreamServiceMethod(obj, methodName)();
});
it('propagates server errors', () => {
const err = new Error('something happened');
stream$.subscribe({
next: dataSpy,
error: errorSpy,
complete: completeSpy,
});
eventCallbacks.data('a');
eventCallbacks.data('b');
callMock.finished = true;
eventCallbacks.error(err);
eventCallbacks.data('c');
expect(Object.keys(eventCallbacks).length).to.eq(3);
expect(dataSpy.args).to.eql([['a'], ['b']]);
expect(errorSpy.args[0][0]).to.eql(err);
expect(completeSpy.called).to.be.false;
expect(callMock.cancel.called).to.be.false;
});
it('handles client side cancel', () => {
const grpcServerCancelErrMock = {
details: 'Cancelled',
};
const subscription = stream$.subscribe({
next: dataSpy,
error: errorSpy,
});
eventCallbacks.data('a');
eventCallbacks.data('b');
subscription.unsubscribe();
eventCallbacks.error(grpcServerCancelErrMock);
eventCallbacks.end();
eventCallbacks.data('c');
expect(callMock.cancel.called, 'should call call.cancel()').to.be.true;
expect(callMock.destroy.called, 'should call call.destroy()').to.be
.true;
expect(dataSpy.args).to.eql([['a'], ['b']]);
expect(errorSpy.called, 'should not error if client canceled').to.be
.false;
});
});
});
describe('createUnaryServiceMethod', () => {
it('should return observable', () => {
const methodKey = 'method';
const fn = client.createUnaryServiceMethod(
{ [methodKey]: {} },
methodKey,
);
expect(fn()).to.be.instanceof(Observable);
});
describe('on subscribe', () => {
const methodName = 'm';
const obj = {
[methodName]: callback => {
callback(null, {});
return {
finished: true,
};
},
};
let stream$: Observable<any>;
beforeEach(() => {
stream$ = client.createUnaryServiceMethod(obj, methodName)();
});
it('should call native method', () => {
const spy = sinon.spy(obj, methodName);
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
expect(spy.called).to.be.true;
});
});
describe('when stream request', () => {
let clientCallback: (
err: Error | null | undefined,
response: any,
) => void;
const writeSpy = sinon.spy();
const methodName = 'm';
const obj = {
[methodName]: callback => {
clientCallback = callback;
return {
write: writeSpy,
};
},
};
let stream$: Observable<any>;
let upstream: Subject<unknown>;
beforeEach(() => {
upstream = new Subject();
(obj[methodName] as any).requestStream = true;
stream$ = client.createUnaryServiceMethod(obj, methodName)(upstream);
});
it('should subscribe to request upstream', () => {
const upstreamSubscribe = sinon.spy(upstream, 'subscribe');
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
upstream.next({ test: true });
expect(writeSpy.called).to.be.true;
expect(upstreamSubscribe.called).to.be.true;
});
});
describe('flow-control', () => {
it('should cancel call on client unsubscribe', () => {
const methodName = 'm';
const dataSpy = sinon.spy();
const errorSpy = sinon.spy();
const completeSpy = sinon.spy();
const callMock = {
cancel: sinon.spy(),
finished: false,
};
let handler: (error: any, data: any) => void;
const obj = {
[methodName]: (callback, ...args) => {
handler = callback;
return callMock;
},
};
const stream$ = client.createUnaryServiceMethod(obj, methodName)();
const subscription = stream$.subscribe({
next: dataSpy,
error: errorSpy,
complete: completeSpy,
});
subscription.unsubscribe();
handler(null, 'a');
expect(dataSpy.called).to.be.false;
expect(errorSpy.called).to.be.false;
expect(completeSpy.called).to.be.false;
expect(callMock.cancel.called).to.be.true;
});
it('should cancel call on client unsubscribe case client streaming', () => {
const methodName = 'm';
const dataSpy = sinon.spy();
const errorSpy = sinon.spy();
const completeSpy = sinon.spy();
const writeSpy = sinon.spy();
const callMock = {
cancel: sinon.spy(),
finished: false,
write: writeSpy,
};
let handler: (error: any, data: any) => void;
const obj = {
[methodName]: callback => {
handler = callback;
return callMock;
},
};
(obj[methodName] as any).requestStream = true;
const upstream: Subject<unknown> = new Subject();
const stream$: Observable<any> = client.createUnaryServiceMethod(obj, methodName)(upstream);
const upstreamSubscribe = sinon.spy(upstream, 'subscribe');
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
upstream.next({ test: true });
const subscription = stream$.subscribe({
next: dataSpy,
error: errorSpy,
complete: completeSpy,
});
subscription.unsubscribe();
handler(null, 'a');
expect(dataSpy.called).to.be.false;
expect(writeSpy.called).to.be.true;
expect(errorSpy.called).to.be.false;
expect(completeSpy.called).to.be.false;
expect(callMock.cancel.called).to.be.true;
expect(upstreamSubscribe.called).to.be.true;
});
});
});
describe('createClients', () => {
describe('when package does not exist', () => {
it('should throw "InvalidGrpcPackageException"', () => {
sinon.stub(client, 'lookupPackage').callsFake(() => null);
(client as any).logger = new NoopLogger();
try {
client.createClients();
} catch (err) {
expect(err).to.be.instanceof(InvalidGrpcPackageException);
}
});
});
});
describe('loadProto', () => {
describe('when proto is invalid', () => {
it('should throw InvalidProtoDefinitionException', () => {
sinon.stub(client, 'getOptionsProp' as any).callsFake(() => {
throw new Error();
});
(client as any).logger = new NoopLogger();
expect(() => client.loadProto()).to.throws(
InvalidProtoDefinitionException,
);
});
});
});
describe('close', () => {
it('should call "close" method', () => {
const grpcClient = { close: sinon.spy() };
(client as any).grpcClients[0] = grpcClient;
client.close();
expect(grpcClient.close.called).to.be.true;
});
});
describe('publish', () => {
it('should throw exception', () => {
expect(() => client['publish'](null, null)).to.throws(Error);
});
});
describe('send', () => {
it('should throw exception', () => {
expect(() => client.send(null, null)).to.throws(Error);
});
});
describe('connect', () => {
it('should throw exception', () => {
client.connect().catch(error => expect(error).to.be.instanceof(Error));
});
});
describe('dispatchEvent', () => {
it('should throw exception', () => {
client['dispatchEvent'](null).catch(error =>
expect(error).to.be.instanceof(Error),
);
});
});
describe('lookupPackage', () => {
it('should return root package in case package name is not defined', () => {
const root = {};
expect(client.lookupPackage(root, undefined)).to.be.equal(root);
expect(client.lookupPackage(root, '')).to.be.equal(root);
});
});
});
| packages/microservices/test/client/client-grpc.spec.ts | 1 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.001206384040415287,
0.00019519882334861904,
0.0001628632307983935,
0.00016812258400022984,
0.00015163971693255007
]
|
{
"id": 0,
"code_window": [
" if (isClientCanceled) {\n",
" return;\n",
" }\n",
" }\n",
" return observer.error(this.serializeError(error));\n",
" }\n",
" observer.next(data);\n",
" observer.complete();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return observer.error(this.serializeError(error));\n"
],
"file_path": "packages/microservices/client/client-grpc.ts",
"type": "replace",
"edit_start_line_idx": 228
} | import { expect } from 'chai';
import * as sinon from 'sinon';
import { NestContainer } from '../../injector/container';
import { ReplContext } from '../../repl/repl-context';
describe('ReplContext', () => {
let replContext: ReplContext;
let mockApp: {
container: NestContainer;
get: sinon.SinonStub;
resolve: sinon.SinonSpy;
select: sinon.SinonSpy;
};
before(async () => {
const container = new NestContainer();
mockApp = {
container,
get: sinon.stub(),
resolve: sinon.spy(),
select: sinon.spy(),
};
replContext = new ReplContext(mockApp as any);
});
afterEach(() => sinon.restore());
it('writeToStdout', () => {
const stdOutWrite = sinon.stub(process.stdout, 'write');
const text = sinon.stub() as unknown as string;
replContext.writeToStdout(text);
expect(stdOutWrite.calledOnce).to.be.true;
expect(stdOutWrite.calledWith(text)).to.be.true;
});
});
| packages/core/test/repl/repl-context.spec.ts | 0 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.00017532362835481763,
0.0001723308814689517,
0.00016824991325847805,
0.0001728750066831708,
0.0000025955014280043542
]
|
{
"id": 0,
"code_window": [
" if (isClientCanceled) {\n",
" return;\n",
" }\n",
" }\n",
" return observer.error(this.serializeError(error));\n",
" }\n",
" observer.next(data);\n",
" observer.complete();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return observer.error(this.serializeError(error));\n"
],
"file_path": "packages/microservices/client/client-grpc.ts",
"type": "replace",
"edit_start_line_idx": 228
} | import { expect } from 'chai';
import { VERSION_METADATA, CONTROLLER_WATERMARK } from '../../constants';
import { Controller } from '../../decorators/core/controller.decorator';
describe('@Controller', () => {
const reflectedPath = 'test';
const reflectedHost = 'api.example.com';
const reflectedHostArray = ['api1.example.com', 'api2.example.com'];
const reflectedVersion = '1';
const reflectedVersionWithDuplicates = ['1', '2', '2', '1', '2', '1'];
const reflectedVersionWithoutDuplicates = ['1', '2'];
@Controller()
class EmptyDecorator {}
@Controller(reflectedPath)
class Test {}
@Controller({ path: reflectedPath, host: reflectedHost })
class PathAndHostDecorator {}
@Controller({ path: reflectedPath, host: reflectedHostArray })
class PathAndHostArrayDecorator {}
@Controller({ host: reflectedHost })
class HostOnlyDecorator {}
@Controller({
path: reflectedPath,
host: reflectedHost,
version: reflectedVersion,
})
class PathAndHostAndVersionDecorator {}
@Controller({ version: reflectedVersion })
class VersionOnlyDecorator {}
@Controller({ version: reflectedVersionWithDuplicates })
class VersionOnlyArrayDecorator {}
it(`should enhance component with "${CONTROLLER_WATERMARK}" metadata`, () => {
const controllerWatermark = Reflect.getMetadata(
CONTROLLER_WATERMARK,
EmptyDecorator,
);
expect(controllerWatermark).to.be.true;
});
it('should enhance controller with expected path metadata', () => {
const path = Reflect.getMetadata('path', Test);
expect(path).to.be.eql(reflectedPath);
const path2 = Reflect.getMetadata('path', PathAndHostDecorator);
expect(path2).to.be.eql(reflectedPath);
const path3 = Reflect.getMetadata('path', PathAndHostAndVersionDecorator);
expect(path3).to.be.eql(reflectedPath);
});
it('should enhance controller with expected host metadata', () => {
const host = Reflect.getMetadata('host', PathAndHostDecorator);
expect(host).to.be.eql(reflectedHost);
const host2 = Reflect.getMetadata('host', HostOnlyDecorator);
expect(host2).to.be.eql(reflectedHost);
const host3 = Reflect.getMetadata('host', PathAndHostArrayDecorator);
expect(host3).to.be.eql(reflectedHostArray);
const host4 = Reflect.getMetadata('host', PathAndHostAndVersionDecorator);
expect(host4).to.be.eql(reflectedHost);
});
it('should enhance controller with expected version metadata', () => {
const version = Reflect.getMetadata(
VERSION_METADATA,
PathAndHostAndVersionDecorator,
);
expect(version).to.be.eql(reflectedVersion);
const version2 = Reflect.getMetadata(
VERSION_METADATA,
VersionOnlyDecorator,
);
expect(version2).to.be.eql(reflectedVersion);
const version3 = Reflect.getMetadata(
VERSION_METADATA,
VersionOnlyArrayDecorator,
);
expect(version3).to.be.eql(reflectedVersionWithoutDuplicates);
});
it('should set default path when no object passed as param', () => {
const path = Reflect.getMetadata('path', EmptyDecorator);
expect(path).to.be.eql('/');
const path2 = Reflect.getMetadata('path', HostOnlyDecorator);
expect(path2).to.be.eql('/');
const path3 = Reflect.getMetadata('path', VersionOnlyDecorator);
expect(path3).to.be.eql('/');
});
it('should not set host when no host passed as param', () => {
const host = Reflect.getMetadata('host', Test);
expect(host).to.be.undefined;
const host2 = Reflect.getMetadata('host', EmptyDecorator);
expect(host2).to.be.undefined;
});
it('should not set version when no version passed as param', () => {
const version = Reflect.getMetadata(VERSION_METADATA, Test);
expect(version).to.be.undefined;
const version2 = Reflect.getMetadata(VERSION_METADATA, EmptyDecorator);
expect(version2).to.be.undefined;
});
});
| packages/common/test/decorators/controller.decorator.spec.ts | 0 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.00017670486704446375,
0.00017227545322384685,
0.00016589113511145115,
0.00017245693015865982,
0.0000028474787541199476
]
|
{
"id": 0,
"code_window": [
" if (isClientCanceled) {\n",
" return;\n",
" }\n",
" }\n",
" return observer.error(this.serializeError(error));\n",
" }\n",
" observer.next(data);\n",
" observer.complete();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return observer.error(this.serializeError(error));\n"
],
"file_path": "packages/microservices/client/client-grpc.ts",
"type": "replace",
"edit_start_line_idx": 228
} | /**
* @publicApi
*/
export interface WsResponse<T = any> {
event: string;
data: T;
}
| packages/websockets/interfaces/ws-response.interface.ts | 0 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.00016837878501974046,
0.00016837878501974046,
0.00016837878501974046,
0.00016837878501974046,
0
]
|
{
"id": 1,
"code_window": [
" response: any,\n",
" ) => void;\n",
" const writeSpy = sinon.spy();\n",
" const methodName = 'm';\n",
" const obj = {\n",
" [methodName]: callback => {\n",
" clientCallback = callback;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" const callMock = {\n",
" cancel: sinon.spy(),\n",
" finished: false,\n",
" write: writeSpy,\n",
" };\n",
"\n"
],
"file_path": "packages/microservices/test/client/client-grpc.spec.ts",
"type": "add",
"edit_start_line_idx": 292
} | import { Logger } from '@nestjs/common';
import { expect } from 'chai';
import { join } from 'path';
import { Observable, Subject } from 'rxjs';
import * as sinon from 'sinon';
import { ClientGrpcProxy } from '../../client/client-grpc';
import { InvalidGrpcPackageException } from '../../errors/invalid-grpc-package.exception';
import { InvalidGrpcServiceException } from '../../errors/invalid-grpc-service.exception';
import { InvalidProtoDefinitionException } from '../../errors/invalid-proto-definition.exception';
class NoopLogger extends Logger {
log(message: any, context?: string): void {}
error(message: any, trace?: string, context?: string): void {}
warn(message: any, context?: string): void {}
}
class GrpcService {
test = null;
test2 = null;
}
describe('ClientGrpcProxy', () => {
let client: ClientGrpcProxy;
let clientMulti: ClientGrpcProxy;
beforeEach(() => {
client = new ClientGrpcProxy({
protoPath: join(__dirname, './test.proto'),
package: 'test',
});
clientMulti = new ClientGrpcProxy({
protoPath: ['test.proto', 'test2.proto'],
package: ['test', 'test2'],
loader: {
includeDirs: [join(__dirname, '.')],
},
});
});
describe('getService', () => {
describe('when "grpcClient[name]" is nil', () => {
it('should throw "InvalidGrpcServiceException"', () => {
(client as any).grpcClient = {};
expect(() => client.getService('test')).to.throw(
InvalidGrpcServiceException,
);
});
it('should throw "InvalidGrpcServiceException" (multiple proto)', () => {
(clientMulti as any).grpcClient = {};
expect(() => clientMulti.getService('test')).to.throw(
InvalidGrpcServiceException,
);
expect(() => clientMulti.getService('test2')).to.throw(
InvalidGrpcServiceException,
);
});
});
describe('when "grpcClient[name]" is not nil', () => {
it('should create grpcService', () => {
(client as any).grpcClients[0] = {
test: GrpcService,
};
expect(() => client.getService('test')).to.not.throw(
InvalidGrpcServiceException,
);
});
describe('when "grpcClient[name]" is not nil (multiple proto)', () => {
it('should create grpcService', () => {
(clientMulti as any).grpcClients[0] = {
test: GrpcService,
test2: GrpcService,
};
expect(() => clientMulti.getService('test')).to.not.throw(
InvalidGrpcServiceException,
);
expect(() => clientMulti.getService('test2')).to.not.throw(
InvalidGrpcServiceException,
);
});
});
});
});
describe('createServiceMethod', () => {
const methodName = 'test';
describe('when method is a response stream', () => {
it('should call "createStreamServiceMethod"', () => {
const cln = { [methodName]: { responseStream: true } };
const spy = sinon.spy(client, 'createStreamServiceMethod');
client.createServiceMethod(cln, methodName);
expect(spy.called).to.be.true;
});
});
describe('when method is not a response stream', () => {
it('should call "createUnaryServiceMethod"', () => {
const cln = { [methodName]: { responseStream: false } };
const spy = sinon.spy(client, 'createUnaryServiceMethod');
client.createServiceMethod(cln, methodName);
expect(spy.called).to.be.true;
});
});
});
describe('createStreamServiceMethod', () => {
it('should return observable', () => {
const methodKey = 'method';
const fn = client.createStreamServiceMethod(
{ [methodKey]: {} },
methodKey,
);
expect(fn()).to.be.instanceof(Observable);
});
describe('on subscribe', () => {
const methodName = 'm';
const obj = { [methodName]: () => ({ on: (type, fn) => fn() }) };
let stream$: Observable<any>;
beforeEach(() => {
stream$ = client.createStreamServiceMethod(obj, methodName)();
});
it('should call native method', () => {
const spy = sinon.spy(obj, methodName);
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
expect(spy.called).to.be.true;
});
});
describe('when stream request', () => {
const methodName = 'm';
const writeSpy = sinon.spy();
const obj = {
[methodName]: () => ({ on: (type, fn) => fn(), write: writeSpy }),
};
let stream$: Observable<any>;
let upstream: Subject<unknown>;
beforeEach(() => {
upstream = new Subject();
(obj[methodName] as any).requestStream = true;
stream$ = client.createStreamServiceMethod(obj, methodName)(upstream);
});
it('should subscribe to request upstream', () => {
const upstreamSubscribe = sinon.spy(upstream, 'subscribe');
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
upstream.next({ test: true });
expect(writeSpy.called).to.be.true;
expect(upstreamSubscribe.called).to.be.true;
});
});
describe('flow-control', () => {
const methodName = 'm';
type EvtCallback = (...args: any[]) => void;
let callMock: {
on: (type: string, fn: EvtCallback) => void;
cancel: sinon.SinonSpy;
finished: boolean;
destroy: sinon.SinonSpy;
removeAllListeners: sinon.SinonSpy;
};
let eventCallbacks: { [type: string]: EvtCallback };
let obj, dataSpy, errorSpy, completeSpy;
let stream$: Observable<any>;
beforeEach(() => {
dataSpy = sinon.spy();
errorSpy = sinon.spy();
completeSpy = sinon.spy();
eventCallbacks = {};
callMock = {
on: (type, fn) => (eventCallbacks[type] = fn),
cancel: sinon.spy(),
finished: false,
destroy: sinon.spy(),
removeAllListeners: sinon.spy(),
};
obj = { [methodName]: () => callMock };
stream$ = client.createStreamServiceMethod(obj, methodName)();
});
it('propagates server errors', () => {
const err = new Error('something happened');
stream$.subscribe({
next: dataSpy,
error: errorSpy,
complete: completeSpy,
});
eventCallbacks.data('a');
eventCallbacks.data('b');
callMock.finished = true;
eventCallbacks.error(err);
eventCallbacks.data('c');
expect(Object.keys(eventCallbacks).length).to.eq(3);
expect(dataSpy.args).to.eql([['a'], ['b']]);
expect(errorSpy.args[0][0]).to.eql(err);
expect(completeSpy.called).to.be.false;
expect(callMock.cancel.called).to.be.false;
});
it('handles client side cancel', () => {
const grpcServerCancelErrMock = {
details: 'Cancelled',
};
const subscription = stream$.subscribe({
next: dataSpy,
error: errorSpy,
});
eventCallbacks.data('a');
eventCallbacks.data('b');
subscription.unsubscribe();
eventCallbacks.error(grpcServerCancelErrMock);
eventCallbacks.end();
eventCallbacks.data('c');
expect(callMock.cancel.called, 'should call call.cancel()').to.be.true;
expect(callMock.destroy.called, 'should call call.destroy()').to.be
.true;
expect(dataSpy.args).to.eql([['a'], ['b']]);
expect(errorSpy.called, 'should not error if client canceled').to.be
.false;
});
});
});
describe('createUnaryServiceMethod', () => {
it('should return observable', () => {
const methodKey = 'method';
const fn = client.createUnaryServiceMethod(
{ [methodKey]: {} },
methodKey,
);
expect(fn()).to.be.instanceof(Observable);
});
describe('on subscribe', () => {
const methodName = 'm';
const obj = {
[methodName]: callback => {
callback(null, {});
return {
finished: true,
};
},
};
let stream$: Observable<any>;
beforeEach(() => {
stream$ = client.createUnaryServiceMethod(obj, methodName)();
});
it('should call native method', () => {
const spy = sinon.spy(obj, methodName);
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
expect(spy.called).to.be.true;
});
});
describe('when stream request', () => {
let clientCallback: (
err: Error | null | undefined,
response: any,
) => void;
const writeSpy = sinon.spy();
const methodName = 'm';
const obj = {
[methodName]: callback => {
clientCallback = callback;
return {
write: writeSpy,
};
},
};
let stream$: Observable<any>;
let upstream: Subject<unknown>;
beforeEach(() => {
upstream = new Subject();
(obj[methodName] as any).requestStream = true;
stream$ = client.createUnaryServiceMethod(obj, methodName)(upstream);
});
it('should subscribe to request upstream', () => {
const upstreamSubscribe = sinon.spy(upstream, 'subscribe');
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
upstream.next({ test: true });
expect(writeSpy.called).to.be.true;
expect(upstreamSubscribe.called).to.be.true;
});
});
describe('flow-control', () => {
it('should cancel call on client unsubscribe', () => {
const methodName = 'm';
const dataSpy = sinon.spy();
const errorSpy = sinon.spy();
const completeSpy = sinon.spy();
const callMock = {
cancel: sinon.spy(),
finished: false,
};
let handler: (error: any, data: any) => void;
const obj = {
[methodName]: (callback, ...args) => {
handler = callback;
return callMock;
},
};
const stream$ = client.createUnaryServiceMethod(obj, methodName)();
const subscription = stream$.subscribe({
next: dataSpy,
error: errorSpy,
complete: completeSpy,
});
subscription.unsubscribe();
handler(null, 'a');
expect(dataSpy.called).to.be.false;
expect(errorSpy.called).to.be.false;
expect(completeSpy.called).to.be.false;
expect(callMock.cancel.called).to.be.true;
});
it('should cancel call on client unsubscribe case client streaming', () => {
const methodName = 'm';
const dataSpy = sinon.spy();
const errorSpy = sinon.spy();
const completeSpy = sinon.spy();
const writeSpy = sinon.spy();
const callMock = {
cancel: sinon.spy(),
finished: false,
write: writeSpy,
};
let handler: (error: any, data: any) => void;
const obj = {
[methodName]: callback => {
handler = callback;
return callMock;
},
};
(obj[methodName] as any).requestStream = true;
const upstream: Subject<unknown> = new Subject();
const stream$: Observable<any> = client.createUnaryServiceMethod(obj, methodName)(upstream);
const upstreamSubscribe = sinon.spy(upstream, 'subscribe');
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
upstream.next({ test: true });
const subscription = stream$.subscribe({
next: dataSpy,
error: errorSpy,
complete: completeSpy,
});
subscription.unsubscribe();
handler(null, 'a');
expect(dataSpy.called).to.be.false;
expect(writeSpy.called).to.be.true;
expect(errorSpy.called).to.be.false;
expect(completeSpy.called).to.be.false;
expect(callMock.cancel.called).to.be.true;
expect(upstreamSubscribe.called).to.be.true;
});
});
});
describe('createClients', () => {
describe('when package does not exist', () => {
it('should throw "InvalidGrpcPackageException"', () => {
sinon.stub(client, 'lookupPackage').callsFake(() => null);
(client as any).logger = new NoopLogger();
try {
client.createClients();
} catch (err) {
expect(err).to.be.instanceof(InvalidGrpcPackageException);
}
});
});
});
describe('loadProto', () => {
describe('when proto is invalid', () => {
it('should throw InvalidProtoDefinitionException', () => {
sinon.stub(client, 'getOptionsProp' as any).callsFake(() => {
throw new Error();
});
(client as any).logger = new NoopLogger();
expect(() => client.loadProto()).to.throws(
InvalidProtoDefinitionException,
);
});
});
});
describe('close', () => {
it('should call "close" method', () => {
const grpcClient = { close: sinon.spy() };
(client as any).grpcClients[0] = grpcClient;
client.close();
expect(grpcClient.close.called).to.be.true;
});
});
describe('publish', () => {
it('should throw exception', () => {
expect(() => client['publish'](null, null)).to.throws(Error);
});
});
describe('send', () => {
it('should throw exception', () => {
expect(() => client.send(null, null)).to.throws(Error);
});
});
describe('connect', () => {
it('should throw exception', () => {
client.connect().catch(error => expect(error).to.be.instanceof(Error));
});
});
describe('dispatchEvent', () => {
it('should throw exception', () => {
client['dispatchEvent'](null).catch(error =>
expect(error).to.be.instanceof(Error),
);
});
});
describe('lookupPackage', () => {
it('should return root package in case package name is not defined', () => {
const root = {};
expect(client.lookupPackage(root, undefined)).to.be.equal(root);
expect(client.lookupPackage(root, '')).to.be.equal(root);
});
});
});
| packages/microservices/test/client/client-grpc.spec.ts | 1 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.9991173148155212,
0.4395294189453125,
0.00016386482457164675,
0.0048125083558261395,
0.48512035608291626
]
|
{
"id": 1,
"code_window": [
" response: any,\n",
" ) => void;\n",
" const writeSpy = sinon.spy();\n",
" const methodName = 'm';\n",
" const obj = {\n",
" [methodName]: callback => {\n",
" clientCallback = callback;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" const callMock = {\n",
" cancel: sinon.spy(),\n",
" finished: false,\n",
" write: writeSpy,\n",
" };\n",
"\n"
],
"file_path": "packages/microservices/test/client/client-grpc.spec.ts",
"type": "add",
"edit_start_line_idx": 292
} | import {
CanActivate,
ExceptionFilter,
NestInterceptor,
PipeTransform,
VersioningOptions,
WebSocketAdapter,
} from '@nestjs/common';
import { GlobalPrefixOptions } from '@nestjs/common/interfaces';
import { InstanceWrapper } from './injector/instance-wrapper';
import { ExcludeRouteMetadata } from './router/interfaces/exclude-route-metadata.interface';
export class ApplicationConfig {
private globalPrefix = '';
private globalPrefixOptions: GlobalPrefixOptions<ExcludeRouteMetadata> = {};
private globalPipes: Array<PipeTransform> = [];
private globalFilters: Array<ExceptionFilter> = [];
private globalInterceptors: Array<NestInterceptor> = [];
private globalGuards: Array<CanActivate> = [];
private versioningOptions: VersioningOptions;
private readonly globalRequestPipes: InstanceWrapper<PipeTransform>[] = [];
private readonly globalRequestFilters: InstanceWrapper<ExceptionFilter>[] =
[];
private readonly globalRequestInterceptors: InstanceWrapper<NestInterceptor>[] =
[];
private readonly globalRequestGuards: InstanceWrapper<CanActivate>[] = [];
constructor(private ioAdapter: WebSocketAdapter | null = null) {}
public setGlobalPrefix(prefix: string) {
this.globalPrefix = prefix;
}
public getGlobalPrefix() {
return this.globalPrefix;
}
public setGlobalPrefixOptions(
options: GlobalPrefixOptions<ExcludeRouteMetadata>,
) {
this.globalPrefixOptions = options;
}
public getGlobalPrefixOptions(): GlobalPrefixOptions<ExcludeRouteMetadata> {
return this.globalPrefixOptions;
}
public setIoAdapter(ioAdapter: WebSocketAdapter) {
this.ioAdapter = ioAdapter;
}
public getIoAdapter(): WebSocketAdapter {
return this.ioAdapter;
}
public addGlobalPipe(pipe: PipeTransform<any>) {
this.globalPipes.push(pipe);
}
public useGlobalPipes(...pipes: PipeTransform<any>[]) {
this.globalPipes = this.globalPipes.concat(pipes);
}
public getGlobalFilters(): ExceptionFilter[] {
return this.globalFilters;
}
public addGlobalFilter(filter: ExceptionFilter) {
this.globalFilters.push(filter);
}
public useGlobalFilters(...filters: ExceptionFilter[]) {
this.globalFilters = this.globalFilters.concat(filters);
}
public getGlobalPipes(): PipeTransform<any>[] {
return this.globalPipes;
}
public getGlobalInterceptors(): NestInterceptor[] {
return this.globalInterceptors;
}
public addGlobalInterceptor(interceptor: NestInterceptor) {
this.globalInterceptors.push(interceptor);
}
public useGlobalInterceptors(...interceptors: NestInterceptor[]) {
this.globalInterceptors = this.globalInterceptors.concat(interceptors);
}
public getGlobalGuards(): CanActivate[] {
return this.globalGuards;
}
public addGlobalGuard(guard: CanActivate) {
this.globalGuards.push(guard);
}
public useGlobalGuards(...guards: CanActivate[]) {
this.globalGuards = this.globalGuards.concat(guards);
}
public addGlobalRequestInterceptor(
wrapper: InstanceWrapper<NestInterceptor>,
) {
this.globalRequestInterceptors.push(wrapper);
}
public getGlobalRequestInterceptors(): InstanceWrapper<NestInterceptor>[] {
return this.globalRequestInterceptors;
}
public addGlobalRequestPipe(wrapper: InstanceWrapper<PipeTransform>) {
this.globalRequestPipes.push(wrapper);
}
public getGlobalRequestPipes(): InstanceWrapper<PipeTransform>[] {
return this.globalRequestPipes;
}
public addGlobalRequestFilter(wrapper: InstanceWrapper<ExceptionFilter>) {
this.globalRequestFilters.push(wrapper);
}
public getGlobalRequestFilters(): InstanceWrapper<ExceptionFilter>[] {
return this.globalRequestFilters;
}
public addGlobalRequestGuard(wrapper: InstanceWrapper<CanActivate>) {
this.globalRequestGuards.push(wrapper);
}
public getGlobalRequestGuards(): InstanceWrapper<CanActivate>[] {
return this.globalRequestGuards;
}
public enableVersioning(options: VersioningOptions): void {
if (Array.isArray(options.defaultVersion)) {
// Drop duplicated versions
options.defaultVersion = Array.from(new Set(options.defaultVersion));
}
this.versioningOptions = options;
}
public getVersioning(): VersioningOptions | undefined {
return this.versioningOptions;
}
}
| packages/core/application-config.ts | 0 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.00017605283937882632,
0.00017301694606430829,
0.0001668372133281082,
0.00017358419427182525,
0.0000023778404738550307
]
|
{
"id": 1,
"code_window": [
" response: any,\n",
" ) => void;\n",
" const writeSpy = sinon.spy();\n",
" const methodName = 'm';\n",
" const obj = {\n",
" [methodName]: callback => {\n",
" clientCallback = callback;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" const callMock = {\n",
" cancel: sinon.spy(),\n",
" finished: false,\n",
" write: writeSpy,\n",
" };\n",
"\n"
],
"file_path": "packages/microservices/test/client/client-grpc.spec.ts",
"type": "add",
"edit_start_line_idx": 292
} | import { Module } from '@nestjs/common';
import { DogsService } from './dogs.service';
import { DogsController } from './dogs.controller';
@Module({
controllers: [DogsController],
providers: [DogsService],
})
export class DogsModule {}
| integration/inspector/src/dogs/dogs.module.ts | 0 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.00017683733312878758,
0.00017683733312878758,
0.00017683733312878758,
0.00017683733312878758,
0
]
|
{
"id": 1,
"code_window": [
" response: any,\n",
" ) => void;\n",
" const writeSpy = sinon.spy();\n",
" const methodName = 'm';\n",
" const obj = {\n",
" [methodName]: callback => {\n",
" clientCallback = callback;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" const callMock = {\n",
" cancel: sinon.spy(),\n",
" finished: false,\n",
" write: writeSpy,\n",
" };\n",
"\n"
],
"file_path": "packages/microservices/test/client/client-grpc.spec.ts",
"type": "add",
"edit_start_line_idx": 292
} | import { uid } from 'uid';
import { ROUTE_ARGS_METADATA } from '../../constants';
import { PipeTransform } from '../../index';
import { Type } from '../../interfaces';
import { CustomParamFactory } from '../../interfaces/features/custom-route-param-factory.interface';
import { assignCustomParameterMetadata } from '../../utils/assign-custom-metadata.util';
import { isFunction, isNil } from '../../utils/shared.utils';
export type ParamDecoratorEnhancer = ParameterDecorator;
/**
* Defines HTTP route param decorator
*
* @param factory
*
* @publicApi
*/
export function createParamDecorator<
FactoryData = any,
FactoryInput = any,
FactoryOutput = any,
>(
factory: CustomParamFactory<FactoryData, FactoryInput, FactoryOutput>,
enhancers: ParamDecoratorEnhancer[] = [],
): (
...dataOrPipes: (Type<PipeTransform> | PipeTransform | FactoryData)[]
) => ParameterDecorator {
const paramtype = uid(21);
return (
data?,
...pipes: (Type<PipeTransform> | PipeTransform | FactoryData)[]
): ParameterDecorator =>
(target, key, index) => {
const args =
Reflect.getMetadata(ROUTE_ARGS_METADATA, target.constructor, key) || {};
const isPipe = (pipe: any) =>
pipe &&
((isFunction(pipe) &&
pipe.prototype &&
isFunction(pipe.prototype.transform)) ||
isFunction(pipe.transform));
const hasParamData = isNil(data) || !isPipe(data);
const paramData = hasParamData ? (data as any) : undefined;
const paramPipes = hasParamData ? pipes : [data, ...pipes];
Reflect.defineMetadata(
ROUTE_ARGS_METADATA,
assignCustomParameterMetadata(
args,
paramtype,
index,
factory,
paramData,
...(paramPipes as PipeTransform[]),
),
target.constructor,
key,
);
enhancers.forEach(fn => fn(target, key, index));
};
}
| packages/common/decorators/http/create-route-param-metadata.decorator.ts | 0 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.001489801099523902,
0.0003807131724897772,
0.00016492071154061705,
0.000175394510733895,
0.00045546883484348655
]
|
{
"id": 2,
"code_window": [
" const obj = {\n",
" [methodName]: callback => {\n",
" clientCallback = callback;\n",
" return {\n",
" write: writeSpy,\n",
" };\n",
" },\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return callMock;\n"
],
"file_path": "packages/microservices/test/client/client-grpc.spec.ts",
"type": "replace",
"edit_start_line_idx": 295
} | import { Logger } from '@nestjs/common';
import { expect } from 'chai';
import { join } from 'path';
import { Observable, Subject } from 'rxjs';
import * as sinon from 'sinon';
import { ClientGrpcProxy } from '../../client/client-grpc';
import { InvalidGrpcPackageException } from '../../errors/invalid-grpc-package.exception';
import { InvalidGrpcServiceException } from '../../errors/invalid-grpc-service.exception';
import { InvalidProtoDefinitionException } from '../../errors/invalid-proto-definition.exception';
class NoopLogger extends Logger {
log(message: any, context?: string): void {}
error(message: any, trace?: string, context?: string): void {}
warn(message: any, context?: string): void {}
}
class GrpcService {
test = null;
test2 = null;
}
describe('ClientGrpcProxy', () => {
let client: ClientGrpcProxy;
let clientMulti: ClientGrpcProxy;
beforeEach(() => {
client = new ClientGrpcProxy({
protoPath: join(__dirname, './test.proto'),
package: 'test',
});
clientMulti = new ClientGrpcProxy({
protoPath: ['test.proto', 'test2.proto'],
package: ['test', 'test2'],
loader: {
includeDirs: [join(__dirname, '.')],
},
});
});
describe('getService', () => {
describe('when "grpcClient[name]" is nil', () => {
it('should throw "InvalidGrpcServiceException"', () => {
(client as any).grpcClient = {};
expect(() => client.getService('test')).to.throw(
InvalidGrpcServiceException,
);
});
it('should throw "InvalidGrpcServiceException" (multiple proto)', () => {
(clientMulti as any).grpcClient = {};
expect(() => clientMulti.getService('test')).to.throw(
InvalidGrpcServiceException,
);
expect(() => clientMulti.getService('test2')).to.throw(
InvalidGrpcServiceException,
);
});
});
describe('when "grpcClient[name]" is not nil', () => {
it('should create grpcService', () => {
(client as any).grpcClients[0] = {
test: GrpcService,
};
expect(() => client.getService('test')).to.not.throw(
InvalidGrpcServiceException,
);
});
describe('when "grpcClient[name]" is not nil (multiple proto)', () => {
it('should create grpcService', () => {
(clientMulti as any).grpcClients[0] = {
test: GrpcService,
test2: GrpcService,
};
expect(() => clientMulti.getService('test')).to.not.throw(
InvalidGrpcServiceException,
);
expect(() => clientMulti.getService('test2')).to.not.throw(
InvalidGrpcServiceException,
);
});
});
});
});
describe('createServiceMethod', () => {
const methodName = 'test';
describe('when method is a response stream', () => {
it('should call "createStreamServiceMethod"', () => {
const cln = { [methodName]: { responseStream: true } };
const spy = sinon.spy(client, 'createStreamServiceMethod');
client.createServiceMethod(cln, methodName);
expect(spy.called).to.be.true;
});
});
describe('when method is not a response stream', () => {
it('should call "createUnaryServiceMethod"', () => {
const cln = { [methodName]: { responseStream: false } };
const spy = sinon.spy(client, 'createUnaryServiceMethod');
client.createServiceMethod(cln, methodName);
expect(spy.called).to.be.true;
});
});
});
describe('createStreamServiceMethod', () => {
it('should return observable', () => {
const methodKey = 'method';
const fn = client.createStreamServiceMethod(
{ [methodKey]: {} },
methodKey,
);
expect(fn()).to.be.instanceof(Observable);
});
describe('on subscribe', () => {
const methodName = 'm';
const obj = { [methodName]: () => ({ on: (type, fn) => fn() }) };
let stream$: Observable<any>;
beforeEach(() => {
stream$ = client.createStreamServiceMethod(obj, methodName)();
});
it('should call native method', () => {
const spy = sinon.spy(obj, methodName);
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
expect(spy.called).to.be.true;
});
});
describe('when stream request', () => {
const methodName = 'm';
const writeSpy = sinon.spy();
const obj = {
[methodName]: () => ({ on: (type, fn) => fn(), write: writeSpy }),
};
let stream$: Observable<any>;
let upstream: Subject<unknown>;
beforeEach(() => {
upstream = new Subject();
(obj[methodName] as any).requestStream = true;
stream$ = client.createStreamServiceMethod(obj, methodName)(upstream);
});
it('should subscribe to request upstream', () => {
const upstreamSubscribe = sinon.spy(upstream, 'subscribe');
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
upstream.next({ test: true });
expect(writeSpy.called).to.be.true;
expect(upstreamSubscribe.called).to.be.true;
});
});
describe('flow-control', () => {
const methodName = 'm';
type EvtCallback = (...args: any[]) => void;
let callMock: {
on: (type: string, fn: EvtCallback) => void;
cancel: sinon.SinonSpy;
finished: boolean;
destroy: sinon.SinonSpy;
removeAllListeners: sinon.SinonSpy;
};
let eventCallbacks: { [type: string]: EvtCallback };
let obj, dataSpy, errorSpy, completeSpy;
let stream$: Observable<any>;
beforeEach(() => {
dataSpy = sinon.spy();
errorSpy = sinon.spy();
completeSpy = sinon.spy();
eventCallbacks = {};
callMock = {
on: (type, fn) => (eventCallbacks[type] = fn),
cancel: sinon.spy(),
finished: false,
destroy: sinon.spy(),
removeAllListeners: sinon.spy(),
};
obj = { [methodName]: () => callMock };
stream$ = client.createStreamServiceMethod(obj, methodName)();
});
it('propagates server errors', () => {
const err = new Error('something happened');
stream$.subscribe({
next: dataSpy,
error: errorSpy,
complete: completeSpy,
});
eventCallbacks.data('a');
eventCallbacks.data('b');
callMock.finished = true;
eventCallbacks.error(err);
eventCallbacks.data('c');
expect(Object.keys(eventCallbacks).length).to.eq(3);
expect(dataSpy.args).to.eql([['a'], ['b']]);
expect(errorSpy.args[0][0]).to.eql(err);
expect(completeSpy.called).to.be.false;
expect(callMock.cancel.called).to.be.false;
});
it('handles client side cancel', () => {
const grpcServerCancelErrMock = {
details: 'Cancelled',
};
const subscription = stream$.subscribe({
next: dataSpy,
error: errorSpy,
});
eventCallbacks.data('a');
eventCallbacks.data('b');
subscription.unsubscribe();
eventCallbacks.error(grpcServerCancelErrMock);
eventCallbacks.end();
eventCallbacks.data('c');
expect(callMock.cancel.called, 'should call call.cancel()').to.be.true;
expect(callMock.destroy.called, 'should call call.destroy()').to.be
.true;
expect(dataSpy.args).to.eql([['a'], ['b']]);
expect(errorSpy.called, 'should not error if client canceled').to.be
.false;
});
});
});
describe('createUnaryServiceMethod', () => {
it('should return observable', () => {
const methodKey = 'method';
const fn = client.createUnaryServiceMethod(
{ [methodKey]: {} },
methodKey,
);
expect(fn()).to.be.instanceof(Observable);
});
describe('on subscribe', () => {
const methodName = 'm';
const obj = {
[methodName]: callback => {
callback(null, {});
return {
finished: true,
};
},
};
let stream$: Observable<any>;
beforeEach(() => {
stream$ = client.createUnaryServiceMethod(obj, methodName)();
});
it('should call native method', () => {
const spy = sinon.spy(obj, methodName);
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
expect(spy.called).to.be.true;
});
});
describe('when stream request', () => {
let clientCallback: (
err: Error | null | undefined,
response: any,
) => void;
const writeSpy = sinon.spy();
const methodName = 'm';
const obj = {
[methodName]: callback => {
clientCallback = callback;
return {
write: writeSpy,
};
},
};
let stream$: Observable<any>;
let upstream: Subject<unknown>;
beforeEach(() => {
upstream = new Subject();
(obj[methodName] as any).requestStream = true;
stream$ = client.createUnaryServiceMethod(obj, methodName)(upstream);
});
it('should subscribe to request upstream', () => {
const upstreamSubscribe = sinon.spy(upstream, 'subscribe');
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
upstream.next({ test: true });
expect(writeSpy.called).to.be.true;
expect(upstreamSubscribe.called).to.be.true;
});
});
describe('flow-control', () => {
it('should cancel call on client unsubscribe', () => {
const methodName = 'm';
const dataSpy = sinon.spy();
const errorSpy = sinon.spy();
const completeSpy = sinon.spy();
const callMock = {
cancel: sinon.spy(),
finished: false,
};
let handler: (error: any, data: any) => void;
const obj = {
[methodName]: (callback, ...args) => {
handler = callback;
return callMock;
},
};
const stream$ = client.createUnaryServiceMethod(obj, methodName)();
const subscription = stream$.subscribe({
next: dataSpy,
error: errorSpy,
complete: completeSpy,
});
subscription.unsubscribe();
handler(null, 'a');
expect(dataSpy.called).to.be.false;
expect(errorSpy.called).to.be.false;
expect(completeSpy.called).to.be.false;
expect(callMock.cancel.called).to.be.true;
});
it('should cancel call on client unsubscribe case client streaming', () => {
const methodName = 'm';
const dataSpy = sinon.spy();
const errorSpy = sinon.spy();
const completeSpy = sinon.spy();
const writeSpy = sinon.spy();
const callMock = {
cancel: sinon.spy(),
finished: false,
write: writeSpy,
};
let handler: (error: any, data: any) => void;
const obj = {
[methodName]: callback => {
handler = callback;
return callMock;
},
};
(obj[methodName] as any).requestStream = true;
const upstream: Subject<unknown> = new Subject();
const stream$: Observable<any> = client.createUnaryServiceMethod(obj, methodName)(upstream);
const upstreamSubscribe = sinon.spy(upstream, 'subscribe');
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
upstream.next({ test: true });
const subscription = stream$.subscribe({
next: dataSpy,
error: errorSpy,
complete: completeSpy,
});
subscription.unsubscribe();
handler(null, 'a');
expect(dataSpy.called).to.be.false;
expect(writeSpy.called).to.be.true;
expect(errorSpy.called).to.be.false;
expect(completeSpy.called).to.be.false;
expect(callMock.cancel.called).to.be.true;
expect(upstreamSubscribe.called).to.be.true;
});
});
});
describe('createClients', () => {
describe('when package does not exist', () => {
it('should throw "InvalidGrpcPackageException"', () => {
sinon.stub(client, 'lookupPackage').callsFake(() => null);
(client as any).logger = new NoopLogger();
try {
client.createClients();
} catch (err) {
expect(err).to.be.instanceof(InvalidGrpcPackageException);
}
});
});
});
describe('loadProto', () => {
describe('when proto is invalid', () => {
it('should throw InvalidProtoDefinitionException', () => {
sinon.stub(client, 'getOptionsProp' as any).callsFake(() => {
throw new Error();
});
(client as any).logger = new NoopLogger();
expect(() => client.loadProto()).to.throws(
InvalidProtoDefinitionException,
);
});
});
});
describe('close', () => {
it('should call "close" method', () => {
const grpcClient = { close: sinon.spy() };
(client as any).grpcClients[0] = grpcClient;
client.close();
expect(grpcClient.close.called).to.be.true;
});
});
describe('publish', () => {
it('should throw exception', () => {
expect(() => client['publish'](null, null)).to.throws(Error);
});
});
describe('send', () => {
it('should throw exception', () => {
expect(() => client.send(null, null)).to.throws(Error);
});
});
describe('connect', () => {
it('should throw exception', () => {
client.connect().catch(error => expect(error).to.be.instanceof(Error));
});
});
describe('dispatchEvent', () => {
it('should throw exception', () => {
client['dispatchEvent'](null).catch(error =>
expect(error).to.be.instanceof(Error),
);
});
});
describe('lookupPackage', () => {
it('should return root package in case package name is not defined', () => {
const root = {};
expect(client.lookupPackage(root, undefined)).to.be.equal(root);
expect(client.lookupPackage(root, '')).to.be.equal(root);
});
});
});
| packages/microservices/test/client/client-grpc.spec.ts | 1 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.9979118704795837,
0.13113199174404144,
0.00016551429871469736,
0.00023789757688064128,
0.2939889430999756
]
|
{
"id": 2,
"code_window": [
" const obj = {\n",
" [methodName]: callback => {\n",
" clientCallback = callback;\n",
" return {\n",
" write: writeSpy,\n",
" };\n",
" },\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return callMock;\n"
],
"file_path": "packages/microservices/test/client/client-grpc.spec.ts",
"type": "replace",
"edit_start_line_idx": 295
} | import { Module, Injectable } from '@nestjs/common';
import { AppController } from './app.controller';
import {
ClientsModule,
Transport,
ClientsModuleOptionsFactory,
ClientOptions,
ClientTCP,
RpcException,
} from '@nestjs/microservices';
import * as fs from 'fs';
import * as path from 'path';
const caCert = fs.readFileSync(path.join(__dirname, 'ca.cert.pem')).toString();
class ErrorHandlingProxy extends ClientTCP {
constructor() {
super({
tlsOptions: { ca: caCert },
});
}
serializeError(err) {
return new RpcException(err);
}
}
@Injectable()
class ConfigService {
private readonly config = {
transport: Transport.TCP,
};
get(key: string, defaultValue?: any) {
return this.config[key] || defaultValue;
}
}
@Module({
providers: [ConfigService],
exports: [ConfigService],
})
class ConfigModule {}
@Injectable()
class ClientOptionService implements ClientsModuleOptionsFactory {
constructor(private readonly configService: ConfigService) {}
createClientOptions(): Promise<ClientOptions> | ClientOptions {
return {
transport: this.configService.get('transport'),
options: {
tlsOptions: { ca: caCert },
},
};
}
}
@Module({
imports: [
ClientsModule.registerAsync([
{
imports: [ConfigModule],
name: 'USE_FACTORY_CLIENT',
useFactory: (configService: ConfigService) => ({
transport: configService.get('transport'),
options: {
tlsOptions: { ca: caCert },
},
}),
inject: [ConfigService],
},
{
imports: [ConfigModule],
name: 'USE_CLASS_CLIENT',
useClass: ClientOptionService,
inject: [ConfigService],
},
{
imports: [ConfigModule],
inject: [ConfigService],
name: 'CUSTOM_PROXY_CLIENT',
useFactory: (config: ConfigService) => ({
customClass: ErrorHandlingProxy,
}),
},
]),
],
controllers: [AppController],
})
export class ApplicationModule {}
| integration/microservices/src/tcp-tls/app.module.ts | 0 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.00019325978064443916,
0.0001724161847960204,
0.00016526749823242426,
0.00016797229181975126,
0.000010009062862081919
]
|
{
"id": 2,
"code_window": [
" const obj = {\n",
" [methodName]: callback => {\n",
" clientCallback = callback;\n",
" return {\n",
" write: writeSpy,\n",
" };\n",
" },\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return callMock;\n"
],
"file_path": "packages/microservices/test/client/client-grpc.spec.ts",
"type": "replace",
"edit_start_line_idx": 295
} | export interface Resolver {
resolve(instance: any, basePath: string): void;
registerNotFoundHandler(): void;
registerExceptionHandler(): void;
}
| packages/core/router/interfaces/resolver.interface.ts | 0 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.00016578708891756833,
0.00016578708891756833,
0.00016578708891756833,
0.00016578708891756833,
0
]
|
{
"id": 2,
"code_window": [
" const obj = {\n",
" [methodName]: callback => {\n",
" clientCallback = callback;\n",
" return {\n",
" write: writeSpy,\n",
" };\n",
" },\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return callMock;\n"
],
"file_path": "packages/microservices/test/client/client-grpc.spec.ts",
"type": "replace",
"edit_start_line_idx": 295
} | import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface';
import { isFunction, isUndefined } from '@nestjs/common/utils/shared.utils';
import { MetadataScanner } from '@nestjs/core/metadata-scanner';
import {
CLIENT_CONFIGURATION_METADATA,
CLIENT_METADATA,
PATTERN_EXTRAS_METADATA,
PATTERN_HANDLER_METADATA,
PATTERN_METADATA,
TRANSPORT_METADATA,
} from './constants';
import { Transport } from './enums';
import { PatternHandler } from './enums/pattern-handler.enum';
import { ClientOptions, PatternMetadata } from './interfaces';
export interface ClientProperties {
property: string;
metadata: ClientOptions;
}
export interface EventOrMessageListenerDefinition {
patterns: PatternMetadata[];
methodKey: string;
isEventHandler: boolean;
targetCallback: (...args: any[]) => any;
transport?: Transport;
extras?: Record<string, any>;
}
export interface MessageRequestProperties {
requestPattern: PatternMetadata;
replyPattern: PatternMetadata;
}
export class ListenerMetadataExplorer {
constructor(private readonly metadataScanner: MetadataScanner) {}
public explore(instance: Controller): EventOrMessageListenerDefinition[] {
const instancePrototype = Object.getPrototypeOf(instance);
return this.metadataScanner
.getAllMethodNames(instancePrototype)
.map(method => this.exploreMethodMetadata(instancePrototype, method))
.filter(metadata => metadata);
}
public exploreMethodMetadata(
instancePrototype: object,
methodKey: string,
): EventOrMessageListenerDefinition {
const targetCallback = instancePrototype[methodKey];
const handlerType = Reflect.getMetadata(
PATTERN_HANDLER_METADATA,
targetCallback,
);
if (isUndefined(handlerType)) {
return;
}
const patterns = Reflect.getMetadata(PATTERN_METADATA, targetCallback);
const transport = Reflect.getMetadata(TRANSPORT_METADATA, targetCallback);
const extras = Reflect.getMetadata(PATTERN_EXTRAS_METADATA, targetCallback);
return {
methodKey,
targetCallback,
patterns,
transport,
extras,
isEventHandler: handlerType === PatternHandler.EVENT,
};
}
public *scanForClientHooks(
instance: Controller,
): IterableIterator<ClientProperties> {
for (const propertyKey in instance) {
if (isFunction(propertyKey)) {
continue;
}
const property = String(propertyKey);
const isClient = Reflect.getMetadata(CLIENT_METADATA, instance, property);
if (isUndefined(isClient)) {
continue;
}
const metadata = Reflect.getMetadata(
CLIENT_CONFIGURATION_METADATA,
instance,
property,
);
yield { property, metadata };
}
}
}
| packages/microservices/listener-metadata-explorer.ts | 0 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.0023905558045953512,
0.00040421061567030847,
0.00016618291556369513,
0.00018003728473559022,
0.0006624046945944428
]
|
{
"id": 3,
"code_window": [
" (obj[methodName] as any).requestStream = true;\n",
" stream$ = client.createUnaryServiceMethod(obj, methodName)(upstream);\n",
" });\n",
"\n",
" it('should subscribe to request upstream', () => {\n",
" const upstreamSubscribe = sinon.spy(upstream, 'subscribe');\n",
" stream$.subscribe({\n",
" next: () => ({}),\n",
" error: () => ({}),\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" afterEach(() => {\n",
" clientCallback(null, {});\n",
" });\n",
"\n"
],
"file_path": "packages/microservices/test/client/client-grpc.spec.ts",
"type": "add",
"edit_start_line_idx": 310
} | import { Logger } from '@nestjs/common';
import { expect } from 'chai';
import { join } from 'path';
import { Observable, Subject } from 'rxjs';
import * as sinon from 'sinon';
import { ClientGrpcProxy } from '../../client/client-grpc';
import { InvalidGrpcPackageException } from '../../errors/invalid-grpc-package.exception';
import { InvalidGrpcServiceException } from '../../errors/invalid-grpc-service.exception';
import { InvalidProtoDefinitionException } from '../../errors/invalid-proto-definition.exception';
class NoopLogger extends Logger {
log(message: any, context?: string): void {}
error(message: any, trace?: string, context?: string): void {}
warn(message: any, context?: string): void {}
}
class GrpcService {
test = null;
test2 = null;
}
describe('ClientGrpcProxy', () => {
let client: ClientGrpcProxy;
let clientMulti: ClientGrpcProxy;
beforeEach(() => {
client = new ClientGrpcProxy({
protoPath: join(__dirname, './test.proto'),
package: 'test',
});
clientMulti = new ClientGrpcProxy({
protoPath: ['test.proto', 'test2.proto'],
package: ['test', 'test2'],
loader: {
includeDirs: [join(__dirname, '.')],
},
});
});
describe('getService', () => {
describe('when "grpcClient[name]" is nil', () => {
it('should throw "InvalidGrpcServiceException"', () => {
(client as any).grpcClient = {};
expect(() => client.getService('test')).to.throw(
InvalidGrpcServiceException,
);
});
it('should throw "InvalidGrpcServiceException" (multiple proto)', () => {
(clientMulti as any).grpcClient = {};
expect(() => clientMulti.getService('test')).to.throw(
InvalidGrpcServiceException,
);
expect(() => clientMulti.getService('test2')).to.throw(
InvalidGrpcServiceException,
);
});
});
describe('when "grpcClient[name]" is not nil', () => {
it('should create grpcService', () => {
(client as any).grpcClients[0] = {
test: GrpcService,
};
expect(() => client.getService('test')).to.not.throw(
InvalidGrpcServiceException,
);
});
describe('when "grpcClient[name]" is not nil (multiple proto)', () => {
it('should create grpcService', () => {
(clientMulti as any).grpcClients[0] = {
test: GrpcService,
test2: GrpcService,
};
expect(() => clientMulti.getService('test')).to.not.throw(
InvalidGrpcServiceException,
);
expect(() => clientMulti.getService('test2')).to.not.throw(
InvalidGrpcServiceException,
);
});
});
});
});
describe('createServiceMethod', () => {
const methodName = 'test';
describe('when method is a response stream', () => {
it('should call "createStreamServiceMethod"', () => {
const cln = { [methodName]: { responseStream: true } };
const spy = sinon.spy(client, 'createStreamServiceMethod');
client.createServiceMethod(cln, methodName);
expect(spy.called).to.be.true;
});
});
describe('when method is not a response stream', () => {
it('should call "createUnaryServiceMethod"', () => {
const cln = { [methodName]: { responseStream: false } };
const spy = sinon.spy(client, 'createUnaryServiceMethod');
client.createServiceMethod(cln, methodName);
expect(spy.called).to.be.true;
});
});
});
describe('createStreamServiceMethod', () => {
it('should return observable', () => {
const methodKey = 'method';
const fn = client.createStreamServiceMethod(
{ [methodKey]: {} },
methodKey,
);
expect(fn()).to.be.instanceof(Observable);
});
describe('on subscribe', () => {
const methodName = 'm';
const obj = { [methodName]: () => ({ on: (type, fn) => fn() }) };
let stream$: Observable<any>;
beforeEach(() => {
stream$ = client.createStreamServiceMethod(obj, methodName)();
});
it('should call native method', () => {
const spy = sinon.spy(obj, methodName);
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
expect(spy.called).to.be.true;
});
});
describe('when stream request', () => {
const methodName = 'm';
const writeSpy = sinon.spy();
const obj = {
[methodName]: () => ({ on: (type, fn) => fn(), write: writeSpy }),
};
let stream$: Observable<any>;
let upstream: Subject<unknown>;
beforeEach(() => {
upstream = new Subject();
(obj[methodName] as any).requestStream = true;
stream$ = client.createStreamServiceMethod(obj, methodName)(upstream);
});
it('should subscribe to request upstream', () => {
const upstreamSubscribe = sinon.spy(upstream, 'subscribe');
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
upstream.next({ test: true });
expect(writeSpy.called).to.be.true;
expect(upstreamSubscribe.called).to.be.true;
});
});
describe('flow-control', () => {
const methodName = 'm';
type EvtCallback = (...args: any[]) => void;
let callMock: {
on: (type: string, fn: EvtCallback) => void;
cancel: sinon.SinonSpy;
finished: boolean;
destroy: sinon.SinonSpy;
removeAllListeners: sinon.SinonSpy;
};
let eventCallbacks: { [type: string]: EvtCallback };
let obj, dataSpy, errorSpy, completeSpy;
let stream$: Observable<any>;
beforeEach(() => {
dataSpy = sinon.spy();
errorSpy = sinon.spy();
completeSpy = sinon.spy();
eventCallbacks = {};
callMock = {
on: (type, fn) => (eventCallbacks[type] = fn),
cancel: sinon.spy(),
finished: false,
destroy: sinon.spy(),
removeAllListeners: sinon.spy(),
};
obj = { [methodName]: () => callMock };
stream$ = client.createStreamServiceMethod(obj, methodName)();
});
it('propagates server errors', () => {
const err = new Error('something happened');
stream$.subscribe({
next: dataSpy,
error: errorSpy,
complete: completeSpy,
});
eventCallbacks.data('a');
eventCallbacks.data('b');
callMock.finished = true;
eventCallbacks.error(err);
eventCallbacks.data('c');
expect(Object.keys(eventCallbacks).length).to.eq(3);
expect(dataSpy.args).to.eql([['a'], ['b']]);
expect(errorSpy.args[0][0]).to.eql(err);
expect(completeSpy.called).to.be.false;
expect(callMock.cancel.called).to.be.false;
});
it('handles client side cancel', () => {
const grpcServerCancelErrMock = {
details: 'Cancelled',
};
const subscription = stream$.subscribe({
next: dataSpy,
error: errorSpy,
});
eventCallbacks.data('a');
eventCallbacks.data('b');
subscription.unsubscribe();
eventCallbacks.error(grpcServerCancelErrMock);
eventCallbacks.end();
eventCallbacks.data('c');
expect(callMock.cancel.called, 'should call call.cancel()').to.be.true;
expect(callMock.destroy.called, 'should call call.destroy()').to.be
.true;
expect(dataSpy.args).to.eql([['a'], ['b']]);
expect(errorSpy.called, 'should not error if client canceled').to.be
.false;
});
});
});
describe('createUnaryServiceMethod', () => {
it('should return observable', () => {
const methodKey = 'method';
const fn = client.createUnaryServiceMethod(
{ [methodKey]: {} },
methodKey,
);
expect(fn()).to.be.instanceof(Observable);
});
describe('on subscribe', () => {
const methodName = 'm';
const obj = {
[methodName]: callback => {
callback(null, {});
return {
finished: true,
};
},
};
let stream$: Observable<any>;
beforeEach(() => {
stream$ = client.createUnaryServiceMethod(obj, methodName)();
});
it('should call native method', () => {
const spy = sinon.spy(obj, methodName);
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
expect(spy.called).to.be.true;
});
});
describe('when stream request', () => {
let clientCallback: (
err: Error | null | undefined,
response: any,
) => void;
const writeSpy = sinon.spy();
const methodName = 'm';
const obj = {
[methodName]: callback => {
clientCallback = callback;
return {
write: writeSpy,
};
},
};
let stream$: Observable<any>;
let upstream: Subject<unknown>;
beforeEach(() => {
upstream = new Subject();
(obj[methodName] as any).requestStream = true;
stream$ = client.createUnaryServiceMethod(obj, methodName)(upstream);
});
it('should subscribe to request upstream', () => {
const upstreamSubscribe = sinon.spy(upstream, 'subscribe');
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
upstream.next({ test: true });
expect(writeSpy.called).to.be.true;
expect(upstreamSubscribe.called).to.be.true;
});
});
describe('flow-control', () => {
it('should cancel call on client unsubscribe', () => {
const methodName = 'm';
const dataSpy = sinon.spy();
const errorSpy = sinon.spy();
const completeSpy = sinon.spy();
const callMock = {
cancel: sinon.spy(),
finished: false,
};
let handler: (error: any, data: any) => void;
const obj = {
[methodName]: (callback, ...args) => {
handler = callback;
return callMock;
},
};
const stream$ = client.createUnaryServiceMethod(obj, methodName)();
const subscription = stream$.subscribe({
next: dataSpy,
error: errorSpy,
complete: completeSpy,
});
subscription.unsubscribe();
handler(null, 'a');
expect(dataSpy.called).to.be.false;
expect(errorSpy.called).to.be.false;
expect(completeSpy.called).to.be.false;
expect(callMock.cancel.called).to.be.true;
});
it('should cancel call on client unsubscribe case client streaming', () => {
const methodName = 'm';
const dataSpy = sinon.spy();
const errorSpy = sinon.spy();
const completeSpy = sinon.spy();
const writeSpy = sinon.spy();
const callMock = {
cancel: sinon.spy(),
finished: false,
write: writeSpy,
};
let handler: (error: any, data: any) => void;
const obj = {
[methodName]: callback => {
handler = callback;
return callMock;
},
};
(obj[methodName] as any).requestStream = true;
const upstream: Subject<unknown> = new Subject();
const stream$: Observable<any> = client.createUnaryServiceMethod(obj, methodName)(upstream);
const upstreamSubscribe = sinon.spy(upstream, 'subscribe');
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
upstream.next({ test: true });
const subscription = stream$.subscribe({
next: dataSpy,
error: errorSpy,
complete: completeSpy,
});
subscription.unsubscribe();
handler(null, 'a');
expect(dataSpy.called).to.be.false;
expect(writeSpy.called).to.be.true;
expect(errorSpy.called).to.be.false;
expect(completeSpy.called).to.be.false;
expect(callMock.cancel.called).to.be.true;
expect(upstreamSubscribe.called).to.be.true;
});
});
});
describe('createClients', () => {
describe('when package does not exist', () => {
it('should throw "InvalidGrpcPackageException"', () => {
sinon.stub(client, 'lookupPackage').callsFake(() => null);
(client as any).logger = new NoopLogger();
try {
client.createClients();
} catch (err) {
expect(err).to.be.instanceof(InvalidGrpcPackageException);
}
});
});
});
describe('loadProto', () => {
describe('when proto is invalid', () => {
it('should throw InvalidProtoDefinitionException', () => {
sinon.stub(client, 'getOptionsProp' as any).callsFake(() => {
throw new Error();
});
(client as any).logger = new NoopLogger();
expect(() => client.loadProto()).to.throws(
InvalidProtoDefinitionException,
);
});
});
});
describe('close', () => {
it('should call "close" method', () => {
const grpcClient = { close: sinon.spy() };
(client as any).grpcClients[0] = grpcClient;
client.close();
expect(grpcClient.close.called).to.be.true;
});
});
describe('publish', () => {
it('should throw exception', () => {
expect(() => client['publish'](null, null)).to.throws(Error);
});
});
describe('send', () => {
it('should throw exception', () => {
expect(() => client.send(null, null)).to.throws(Error);
});
});
describe('connect', () => {
it('should throw exception', () => {
client.connect().catch(error => expect(error).to.be.instanceof(Error));
});
});
describe('dispatchEvent', () => {
it('should throw exception', () => {
client['dispatchEvent'](null).catch(error =>
expect(error).to.be.instanceof(Error),
);
});
});
describe('lookupPackage', () => {
it('should return root package in case package name is not defined', () => {
const root = {};
expect(client.lookupPackage(root, undefined)).to.be.equal(root);
expect(client.lookupPackage(root, '')).to.be.equal(root);
});
});
});
| packages/microservices/test/client/client-grpc.spec.ts | 1 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.999081015586853,
0.12509039044380188,
0.00016259541735053062,
0.0016378990840166807,
0.3218151926994324
]
|
{
"id": 3,
"code_window": [
" (obj[methodName] as any).requestStream = true;\n",
" stream$ = client.createUnaryServiceMethod(obj, methodName)(upstream);\n",
" });\n",
"\n",
" it('should subscribe to request upstream', () => {\n",
" const upstreamSubscribe = sinon.spy(upstream, 'subscribe');\n",
" stream$.subscribe({\n",
" next: () => ({}),\n",
" error: () => ({}),\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" afterEach(() => {\n",
" clientCallback(null, {});\n",
" });\n",
"\n"
],
"file_path": "packages/microservices/test/client/client-grpc.spec.ts",
"type": "add",
"edit_start_line_idx": 310
} | {
"extends": "./tsconfig.json",
"exclude": ["node_modules", "dist", "test", "**/*spec.ts"]
}
| sample/02-gateways/tsconfig.build.json | 0 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.00017237420252058655,
0.00017237420252058655,
0.00017237420252058655,
0.00017237420252058655,
0
]
|
{
"id": 3,
"code_window": [
" (obj[methodName] as any).requestStream = true;\n",
" stream$ = client.createUnaryServiceMethod(obj, methodName)(upstream);\n",
" });\n",
"\n",
" it('should subscribe to request upstream', () => {\n",
" const upstreamSubscribe = sinon.spy(upstream, 'subscribe');\n",
" stream$.subscribe({\n",
" next: () => ({}),\n",
" error: () => ({}),\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" afterEach(() => {\n",
" clientCallback(null, {});\n",
" });\n",
"\n"
],
"file_path": "packages/microservices/test/client/client-grpc.spec.ts",
"type": "add",
"edit_start_line_idx": 310
} | {
"language": "ts",
"collection": "@nestjs/schematics",
"sourceRoot": "src"
}
| sample/19-auth-jwt/nest-cli.json | 0 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.0001742378663038835,
0.0001742378663038835,
0.0001742378663038835,
0.0001742378663038835,
0
]
|
{
"id": 3,
"code_window": [
" (obj[methodName] as any).requestStream = true;\n",
" stream$ = client.createUnaryServiceMethod(obj, methodName)(upstream);\n",
" });\n",
"\n",
" it('should subscribe to request upstream', () => {\n",
" const upstreamSubscribe = sinon.spy(upstream, 'subscribe');\n",
" stream$.subscribe({\n",
" next: () => ({}),\n",
" error: () => ({}),\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" afterEach(() => {\n",
" clientCallback(null, {});\n",
" });\n",
"\n"
],
"file_path": "packages/microservices/test/client/client-grpc.spec.ts",
"type": "add",
"edit_start_line_idx": 310
} | import { logLevel } from '../external/kafka.interface';
export const KafkaLogger =
(logger: any) =>
({ namespace, level, label, log }) => {
let loggerMethod: string;
switch (level) {
case logLevel.ERROR:
case logLevel.NOTHING:
loggerMethod = 'error';
break;
case logLevel.WARN:
loggerMethod = 'warn';
break;
case logLevel.INFO:
loggerMethod = 'log';
break;
case logLevel.DEBUG:
default:
loggerMethod = 'debug';
break;
}
const { message, ...others } = log;
if (logger[loggerMethod]) {
logger[loggerMethod](
`${label} [${namespace}] ${message} ${JSON.stringify(others)}`,
);
}
};
| packages/microservices/helpers/kafka-logger.ts | 0 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.00017100154946092516,
0.00016888254322111607,
0.00016567723650950938,
0.00016942567890509963,
0.000002064078444163897
]
|
{
"id": 4,
"code_window": [
" [methodName]: callback => {\n",
" handler = callback;\n",
" return callMock;\n",
" },\n",
" };\n",
" \n",
" (obj[methodName] as any).requestStream = true;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "packages/microservices/test/client/client-grpc.spec.ts",
"type": "replace",
"edit_start_line_idx": 384
} | import { Logger } from '@nestjs/common';
import { expect } from 'chai';
import { join } from 'path';
import { Observable, Subject } from 'rxjs';
import * as sinon from 'sinon';
import { ClientGrpcProxy } from '../../client/client-grpc';
import { InvalidGrpcPackageException } from '../../errors/invalid-grpc-package.exception';
import { InvalidGrpcServiceException } from '../../errors/invalid-grpc-service.exception';
import { InvalidProtoDefinitionException } from '../../errors/invalid-proto-definition.exception';
class NoopLogger extends Logger {
log(message: any, context?: string): void {}
error(message: any, trace?: string, context?: string): void {}
warn(message: any, context?: string): void {}
}
class GrpcService {
test = null;
test2 = null;
}
describe('ClientGrpcProxy', () => {
let client: ClientGrpcProxy;
let clientMulti: ClientGrpcProxy;
beforeEach(() => {
client = new ClientGrpcProxy({
protoPath: join(__dirname, './test.proto'),
package: 'test',
});
clientMulti = new ClientGrpcProxy({
protoPath: ['test.proto', 'test2.proto'],
package: ['test', 'test2'],
loader: {
includeDirs: [join(__dirname, '.')],
},
});
});
describe('getService', () => {
describe('when "grpcClient[name]" is nil', () => {
it('should throw "InvalidGrpcServiceException"', () => {
(client as any).grpcClient = {};
expect(() => client.getService('test')).to.throw(
InvalidGrpcServiceException,
);
});
it('should throw "InvalidGrpcServiceException" (multiple proto)', () => {
(clientMulti as any).grpcClient = {};
expect(() => clientMulti.getService('test')).to.throw(
InvalidGrpcServiceException,
);
expect(() => clientMulti.getService('test2')).to.throw(
InvalidGrpcServiceException,
);
});
});
describe('when "grpcClient[name]" is not nil', () => {
it('should create grpcService', () => {
(client as any).grpcClients[0] = {
test: GrpcService,
};
expect(() => client.getService('test')).to.not.throw(
InvalidGrpcServiceException,
);
});
describe('when "grpcClient[name]" is not nil (multiple proto)', () => {
it('should create grpcService', () => {
(clientMulti as any).grpcClients[0] = {
test: GrpcService,
test2: GrpcService,
};
expect(() => clientMulti.getService('test')).to.not.throw(
InvalidGrpcServiceException,
);
expect(() => clientMulti.getService('test2')).to.not.throw(
InvalidGrpcServiceException,
);
});
});
});
});
describe('createServiceMethod', () => {
const methodName = 'test';
describe('when method is a response stream', () => {
it('should call "createStreamServiceMethod"', () => {
const cln = { [methodName]: { responseStream: true } };
const spy = sinon.spy(client, 'createStreamServiceMethod');
client.createServiceMethod(cln, methodName);
expect(spy.called).to.be.true;
});
});
describe('when method is not a response stream', () => {
it('should call "createUnaryServiceMethod"', () => {
const cln = { [methodName]: { responseStream: false } };
const spy = sinon.spy(client, 'createUnaryServiceMethod');
client.createServiceMethod(cln, methodName);
expect(spy.called).to.be.true;
});
});
});
describe('createStreamServiceMethod', () => {
it('should return observable', () => {
const methodKey = 'method';
const fn = client.createStreamServiceMethod(
{ [methodKey]: {} },
methodKey,
);
expect(fn()).to.be.instanceof(Observable);
});
describe('on subscribe', () => {
const methodName = 'm';
const obj = { [methodName]: () => ({ on: (type, fn) => fn() }) };
let stream$: Observable<any>;
beforeEach(() => {
stream$ = client.createStreamServiceMethod(obj, methodName)();
});
it('should call native method', () => {
const spy = sinon.spy(obj, methodName);
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
expect(spy.called).to.be.true;
});
});
describe('when stream request', () => {
const methodName = 'm';
const writeSpy = sinon.spy();
const obj = {
[methodName]: () => ({ on: (type, fn) => fn(), write: writeSpy }),
};
let stream$: Observable<any>;
let upstream: Subject<unknown>;
beforeEach(() => {
upstream = new Subject();
(obj[methodName] as any).requestStream = true;
stream$ = client.createStreamServiceMethod(obj, methodName)(upstream);
});
it('should subscribe to request upstream', () => {
const upstreamSubscribe = sinon.spy(upstream, 'subscribe');
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
upstream.next({ test: true });
expect(writeSpy.called).to.be.true;
expect(upstreamSubscribe.called).to.be.true;
});
});
describe('flow-control', () => {
const methodName = 'm';
type EvtCallback = (...args: any[]) => void;
let callMock: {
on: (type: string, fn: EvtCallback) => void;
cancel: sinon.SinonSpy;
finished: boolean;
destroy: sinon.SinonSpy;
removeAllListeners: sinon.SinonSpy;
};
let eventCallbacks: { [type: string]: EvtCallback };
let obj, dataSpy, errorSpy, completeSpy;
let stream$: Observable<any>;
beforeEach(() => {
dataSpy = sinon.spy();
errorSpy = sinon.spy();
completeSpy = sinon.spy();
eventCallbacks = {};
callMock = {
on: (type, fn) => (eventCallbacks[type] = fn),
cancel: sinon.spy(),
finished: false,
destroy: sinon.spy(),
removeAllListeners: sinon.spy(),
};
obj = { [methodName]: () => callMock };
stream$ = client.createStreamServiceMethod(obj, methodName)();
});
it('propagates server errors', () => {
const err = new Error('something happened');
stream$.subscribe({
next: dataSpy,
error: errorSpy,
complete: completeSpy,
});
eventCallbacks.data('a');
eventCallbacks.data('b');
callMock.finished = true;
eventCallbacks.error(err);
eventCallbacks.data('c');
expect(Object.keys(eventCallbacks).length).to.eq(3);
expect(dataSpy.args).to.eql([['a'], ['b']]);
expect(errorSpy.args[0][0]).to.eql(err);
expect(completeSpy.called).to.be.false;
expect(callMock.cancel.called).to.be.false;
});
it('handles client side cancel', () => {
const grpcServerCancelErrMock = {
details: 'Cancelled',
};
const subscription = stream$.subscribe({
next: dataSpy,
error: errorSpy,
});
eventCallbacks.data('a');
eventCallbacks.data('b');
subscription.unsubscribe();
eventCallbacks.error(grpcServerCancelErrMock);
eventCallbacks.end();
eventCallbacks.data('c');
expect(callMock.cancel.called, 'should call call.cancel()').to.be.true;
expect(callMock.destroy.called, 'should call call.destroy()').to.be
.true;
expect(dataSpy.args).to.eql([['a'], ['b']]);
expect(errorSpy.called, 'should not error if client canceled').to.be
.false;
});
});
});
describe('createUnaryServiceMethod', () => {
it('should return observable', () => {
const methodKey = 'method';
const fn = client.createUnaryServiceMethod(
{ [methodKey]: {} },
methodKey,
);
expect(fn()).to.be.instanceof(Observable);
});
describe('on subscribe', () => {
const methodName = 'm';
const obj = {
[methodName]: callback => {
callback(null, {});
return {
finished: true,
};
},
};
let stream$: Observable<any>;
beforeEach(() => {
stream$ = client.createUnaryServiceMethod(obj, methodName)();
});
it('should call native method', () => {
const spy = sinon.spy(obj, methodName);
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
expect(spy.called).to.be.true;
});
});
describe('when stream request', () => {
let clientCallback: (
err: Error | null | undefined,
response: any,
) => void;
const writeSpy = sinon.spy();
const methodName = 'm';
const obj = {
[methodName]: callback => {
clientCallback = callback;
return {
write: writeSpy,
};
},
};
let stream$: Observable<any>;
let upstream: Subject<unknown>;
beforeEach(() => {
upstream = new Subject();
(obj[methodName] as any).requestStream = true;
stream$ = client.createUnaryServiceMethod(obj, methodName)(upstream);
});
it('should subscribe to request upstream', () => {
const upstreamSubscribe = sinon.spy(upstream, 'subscribe');
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
upstream.next({ test: true });
expect(writeSpy.called).to.be.true;
expect(upstreamSubscribe.called).to.be.true;
});
});
describe('flow-control', () => {
it('should cancel call on client unsubscribe', () => {
const methodName = 'm';
const dataSpy = sinon.spy();
const errorSpy = sinon.spy();
const completeSpy = sinon.spy();
const callMock = {
cancel: sinon.spy(),
finished: false,
};
let handler: (error: any, data: any) => void;
const obj = {
[methodName]: (callback, ...args) => {
handler = callback;
return callMock;
},
};
const stream$ = client.createUnaryServiceMethod(obj, methodName)();
const subscription = stream$.subscribe({
next: dataSpy,
error: errorSpy,
complete: completeSpy,
});
subscription.unsubscribe();
handler(null, 'a');
expect(dataSpy.called).to.be.false;
expect(errorSpy.called).to.be.false;
expect(completeSpy.called).to.be.false;
expect(callMock.cancel.called).to.be.true;
});
it('should cancel call on client unsubscribe case client streaming', () => {
const methodName = 'm';
const dataSpy = sinon.spy();
const errorSpy = sinon.spy();
const completeSpy = sinon.spy();
const writeSpy = sinon.spy();
const callMock = {
cancel: sinon.spy(),
finished: false,
write: writeSpy,
};
let handler: (error: any, data: any) => void;
const obj = {
[methodName]: callback => {
handler = callback;
return callMock;
},
};
(obj[methodName] as any).requestStream = true;
const upstream: Subject<unknown> = new Subject();
const stream$: Observable<any> = client.createUnaryServiceMethod(obj, methodName)(upstream);
const upstreamSubscribe = sinon.spy(upstream, 'subscribe');
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
upstream.next({ test: true });
const subscription = stream$.subscribe({
next: dataSpy,
error: errorSpy,
complete: completeSpy,
});
subscription.unsubscribe();
handler(null, 'a');
expect(dataSpy.called).to.be.false;
expect(writeSpy.called).to.be.true;
expect(errorSpy.called).to.be.false;
expect(completeSpy.called).to.be.false;
expect(callMock.cancel.called).to.be.true;
expect(upstreamSubscribe.called).to.be.true;
});
});
});
describe('createClients', () => {
describe('when package does not exist', () => {
it('should throw "InvalidGrpcPackageException"', () => {
sinon.stub(client, 'lookupPackage').callsFake(() => null);
(client as any).logger = new NoopLogger();
try {
client.createClients();
} catch (err) {
expect(err).to.be.instanceof(InvalidGrpcPackageException);
}
});
});
});
describe('loadProto', () => {
describe('when proto is invalid', () => {
it('should throw InvalidProtoDefinitionException', () => {
sinon.stub(client, 'getOptionsProp' as any).callsFake(() => {
throw new Error();
});
(client as any).logger = new NoopLogger();
expect(() => client.loadProto()).to.throws(
InvalidProtoDefinitionException,
);
});
});
});
describe('close', () => {
it('should call "close" method', () => {
const grpcClient = { close: sinon.spy() };
(client as any).grpcClients[0] = grpcClient;
client.close();
expect(grpcClient.close.called).to.be.true;
});
});
describe('publish', () => {
it('should throw exception', () => {
expect(() => client['publish'](null, null)).to.throws(Error);
});
});
describe('send', () => {
it('should throw exception', () => {
expect(() => client.send(null, null)).to.throws(Error);
});
});
describe('connect', () => {
it('should throw exception', () => {
client.connect().catch(error => expect(error).to.be.instanceof(Error));
});
});
describe('dispatchEvent', () => {
it('should throw exception', () => {
client['dispatchEvent'](null).catch(error =>
expect(error).to.be.instanceof(Error),
);
});
});
describe('lookupPackage', () => {
it('should return root package in case package name is not defined', () => {
const root = {};
expect(client.lookupPackage(root, undefined)).to.be.equal(root);
expect(client.lookupPackage(root, '')).to.be.equal(root);
});
});
});
| packages/microservices/test/client/client-grpc.spec.ts | 1 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.9971707463264465,
0.05767207592725754,
0.00016575719928368926,
0.0002820399822667241,
0.21628114581108093
]
|
{
"id": 4,
"code_window": [
" [methodName]: callback => {\n",
" handler = callback;\n",
" return callMock;\n",
" },\n",
" };\n",
" \n",
" (obj[methodName] as any).requestStream = true;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "packages/microservices/test/client/client-grpc.spec.ts",
"type": "replace",
"edit_start_line_idx": 384
} | export function compareElementAt(
prev: unknown[],
curr: unknown[],
index: number,
) {
return prev && curr && prev[index] === curr[index];
}
| packages/websockets/utils/compare-element.util.ts | 0 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.00017278922314289957,
0.00017278922314289957,
0.00017278922314289957,
0.00017278922314289957,
0
]
|
{
"id": 4,
"code_window": [
" [methodName]: callback => {\n",
" handler = callback;\n",
" return callMock;\n",
" },\n",
" };\n",
" \n",
" (obj[methodName] as any).requestStream = true;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "packages/microservices/test/client/client-grpc.spec.ts",
"type": "replace",
"edit_start_line_idx": 384
} | import { Type } from '../type.interface';
import { ClassTransformOptions } from './class-transform-options.interface';
export interface TransformerPackage {
plainToClass<T>(
cls: Type<T>,
plain: unknown,
options?: ClassTransformOptions,
): T | T[];
classToPlain(
object: unknown,
options?: ClassTransformOptions,
): Record<string, any> | Record<string, any>[];
}
| packages/common/interfaces/external/transformer-package.interface.ts | 0 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.00018654600717127323,
0.0001803663617465645,
0.00017418671632185578,
0.0001803663617465645,
0.000006179645424708724
]
|
{
"id": 4,
"code_window": [
" [methodName]: callback => {\n",
" handler = callback;\n",
" return callMock;\n",
" },\n",
" };\n",
" \n",
" (obj[methodName] as any).requestStream = true;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "packages/microservices/test/client/client-grpc.spec.ts",
"type": "replace",
"edit_start_line_idx": 384
} | /**
* @publicApi
*/
export type RawBodyRequest<T> = T & { rawBody?: Buffer };
| packages/common/interfaces/http/raw-body-request.interface.ts | 0 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.0001692507357802242,
0.0001692507357802242,
0.0001692507357802242,
0.0001692507357802242,
0
]
|
{
"id": 5,
"code_window": [
" (obj[methodName] as any).requestStream = true;\n",
" const upstream: Subject<unknown> = new Subject();\n",
" const stream$: Observable<any> = client.createUnaryServiceMethod(obj, methodName)(upstream);\n",
"\n",
" const upstreamSubscribe = sinon.spy(upstream, 'subscribe');\n",
" stream$.subscribe({\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" let upstream: Subject<unknown> = new Subject();\n",
" let stream$: Observable<any> = client.createUnaryServiceMethod(\n",
" obj,\n",
" methodName,\n",
" )(upstream);\n"
],
"file_path": "packages/microservices/test/client/client-grpc.spec.ts",
"type": "replace",
"edit_start_line_idx": 386
} | import { Logger } from '@nestjs/common';
import { expect } from 'chai';
import { join } from 'path';
import { Observable, Subject } from 'rxjs';
import * as sinon from 'sinon';
import { ClientGrpcProxy } from '../../client/client-grpc';
import { InvalidGrpcPackageException } from '../../errors/invalid-grpc-package.exception';
import { InvalidGrpcServiceException } from '../../errors/invalid-grpc-service.exception';
import { InvalidProtoDefinitionException } from '../../errors/invalid-proto-definition.exception';
class NoopLogger extends Logger {
log(message: any, context?: string): void {}
error(message: any, trace?: string, context?: string): void {}
warn(message: any, context?: string): void {}
}
class GrpcService {
test = null;
test2 = null;
}
describe('ClientGrpcProxy', () => {
let client: ClientGrpcProxy;
let clientMulti: ClientGrpcProxy;
beforeEach(() => {
client = new ClientGrpcProxy({
protoPath: join(__dirname, './test.proto'),
package: 'test',
});
clientMulti = new ClientGrpcProxy({
protoPath: ['test.proto', 'test2.proto'],
package: ['test', 'test2'],
loader: {
includeDirs: [join(__dirname, '.')],
},
});
});
describe('getService', () => {
describe('when "grpcClient[name]" is nil', () => {
it('should throw "InvalidGrpcServiceException"', () => {
(client as any).grpcClient = {};
expect(() => client.getService('test')).to.throw(
InvalidGrpcServiceException,
);
});
it('should throw "InvalidGrpcServiceException" (multiple proto)', () => {
(clientMulti as any).grpcClient = {};
expect(() => clientMulti.getService('test')).to.throw(
InvalidGrpcServiceException,
);
expect(() => clientMulti.getService('test2')).to.throw(
InvalidGrpcServiceException,
);
});
});
describe('when "grpcClient[name]" is not nil', () => {
it('should create grpcService', () => {
(client as any).grpcClients[0] = {
test: GrpcService,
};
expect(() => client.getService('test')).to.not.throw(
InvalidGrpcServiceException,
);
});
describe('when "grpcClient[name]" is not nil (multiple proto)', () => {
it('should create grpcService', () => {
(clientMulti as any).grpcClients[0] = {
test: GrpcService,
test2: GrpcService,
};
expect(() => clientMulti.getService('test')).to.not.throw(
InvalidGrpcServiceException,
);
expect(() => clientMulti.getService('test2')).to.not.throw(
InvalidGrpcServiceException,
);
});
});
});
});
describe('createServiceMethod', () => {
const methodName = 'test';
describe('when method is a response stream', () => {
it('should call "createStreamServiceMethod"', () => {
const cln = { [methodName]: { responseStream: true } };
const spy = sinon.spy(client, 'createStreamServiceMethod');
client.createServiceMethod(cln, methodName);
expect(spy.called).to.be.true;
});
});
describe('when method is not a response stream', () => {
it('should call "createUnaryServiceMethod"', () => {
const cln = { [methodName]: { responseStream: false } };
const spy = sinon.spy(client, 'createUnaryServiceMethod');
client.createServiceMethod(cln, methodName);
expect(spy.called).to.be.true;
});
});
});
describe('createStreamServiceMethod', () => {
it('should return observable', () => {
const methodKey = 'method';
const fn = client.createStreamServiceMethod(
{ [methodKey]: {} },
methodKey,
);
expect(fn()).to.be.instanceof(Observable);
});
describe('on subscribe', () => {
const methodName = 'm';
const obj = { [methodName]: () => ({ on: (type, fn) => fn() }) };
let stream$: Observable<any>;
beforeEach(() => {
stream$ = client.createStreamServiceMethod(obj, methodName)();
});
it('should call native method', () => {
const spy = sinon.spy(obj, methodName);
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
expect(spy.called).to.be.true;
});
});
describe('when stream request', () => {
const methodName = 'm';
const writeSpy = sinon.spy();
const obj = {
[methodName]: () => ({ on: (type, fn) => fn(), write: writeSpy }),
};
let stream$: Observable<any>;
let upstream: Subject<unknown>;
beforeEach(() => {
upstream = new Subject();
(obj[methodName] as any).requestStream = true;
stream$ = client.createStreamServiceMethod(obj, methodName)(upstream);
});
it('should subscribe to request upstream', () => {
const upstreamSubscribe = sinon.spy(upstream, 'subscribe');
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
upstream.next({ test: true });
expect(writeSpy.called).to.be.true;
expect(upstreamSubscribe.called).to.be.true;
});
});
describe('flow-control', () => {
const methodName = 'm';
type EvtCallback = (...args: any[]) => void;
let callMock: {
on: (type: string, fn: EvtCallback) => void;
cancel: sinon.SinonSpy;
finished: boolean;
destroy: sinon.SinonSpy;
removeAllListeners: sinon.SinonSpy;
};
let eventCallbacks: { [type: string]: EvtCallback };
let obj, dataSpy, errorSpy, completeSpy;
let stream$: Observable<any>;
beforeEach(() => {
dataSpy = sinon.spy();
errorSpy = sinon.spy();
completeSpy = sinon.spy();
eventCallbacks = {};
callMock = {
on: (type, fn) => (eventCallbacks[type] = fn),
cancel: sinon.spy(),
finished: false,
destroy: sinon.spy(),
removeAllListeners: sinon.spy(),
};
obj = { [methodName]: () => callMock };
stream$ = client.createStreamServiceMethod(obj, methodName)();
});
it('propagates server errors', () => {
const err = new Error('something happened');
stream$.subscribe({
next: dataSpy,
error: errorSpy,
complete: completeSpy,
});
eventCallbacks.data('a');
eventCallbacks.data('b');
callMock.finished = true;
eventCallbacks.error(err);
eventCallbacks.data('c');
expect(Object.keys(eventCallbacks).length).to.eq(3);
expect(dataSpy.args).to.eql([['a'], ['b']]);
expect(errorSpy.args[0][0]).to.eql(err);
expect(completeSpy.called).to.be.false;
expect(callMock.cancel.called).to.be.false;
});
it('handles client side cancel', () => {
const grpcServerCancelErrMock = {
details: 'Cancelled',
};
const subscription = stream$.subscribe({
next: dataSpy,
error: errorSpy,
});
eventCallbacks.data('a');
eventCallbacks.data('b');
subscription.unsubscribe();
eventCallbacks.error(grpcServerCancelErrMock);
eventCallbacks.end();
eventCallbacks.data('c');
expect(callMock.cancel.called, 'should call call.cancel()').to.be.true;
expect(callMock.destroy.called, 'should call call.destroy()').to.be
.true;
expect(dataSpy.args).to.eql([['a'], ['b']]);
expect(errorSpy.called, 'should not error if client canceled').to.be
.false;
});
});
});
describe('createUnaryServiceMethod', () => {
it('should return observable', () => {
const methodKey = 'method';
const fn = client.createUnaryServiceMethod(
{ [methodKey]: {} },
methodKey,
);
expect(fn()).to.be.instanceof(Observable);
});
describe('on subscribe', () => {
const methodName = 'm';
const obj = {
[methodName]: callback => {
callback(null, {});
return {
finished: true,
};
},
};
let stream$: Observable<any>;
beforeEach(() => {
stream$ = client.createUnaryServiceMethod(obj, methodName)();
});
it('should call native method', () => {
const spy = sinon.spy(obj, methodName);
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
expect(spy.called).to.be.true;
});
});
describe('when stream request', () => {
let clientCallback: (
err: Error | null | undefined,
response: any,
) => void;
const writeSpy = sinon.spy();
const methodName = 'm';
const obj = {
[methodName]: callback => {
clientCallback = callback;
return {
write: writeSpy,
};
},
};
let stream$: Observable<any>;
let upstream: Subject<unknown>;
beforeEach(() => {
upstream = new Subject();
(obj[methodName] as any).requestStream = true;
stream$ = client.createUnaryServiceMethod(obj, methodName)(upstream);
});
it('should subscribe to request upstream', () => {
const upstreamSubscribe = sinon.spy(upstream, 'subscribe');
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
upstream.next({ test: true });
expect(writeSpy.called).to.be.true;
expect(upstreamSubscribe.called).to.be.true;
});
});
describe('flow-control', () => {
it('should cancel call on client unsubscribe', () => {
const methodName = 'm';
const dataSpy = sinon.spy();
const errorSpy = sinon.spy();
const completeSpy = sinon.spy();
const callMock = {
cancel: sinon.spy(),
finished: false,
};
let handler: (error: any, data: any) => void;
const obj = {
[methodName]: (callback, ...args) => {
handler = callback;
return callMock;
},
};
const stream$ = client.createUnaryServiceMethod(obj, methodName)();
const subscription = stream$.subscribe({
next: dataSpy,
error: errorSpy,
complete: completeSpy,
});
subscription.unsubscribe();
handler(null, 'a');
expect(dataSpy.called).to.be.false;
expect(errorSpy.called).to.be.false;
expect(completeSpy.called).to.be.false;
expect(callMock.cancel.called).to.be.true;
});
it('should cancel call on client unsubscribe case client streaming', () => {
const methodName = 'm';
const dataSpy = sinon.spy();
const errorSpy = sinon.spy();
const completeSpy = sinon.spy();
const writeSpy = sinon.spy();
const callMock = {
cancel: sinon.spy(),
finished: false,
write: writeSpy,
};
let handler: (error: any, data: any) => void;
const obj = {
[methodName]: callback => {
handler = callback;
return callMock;
},
};
(obj[methodName] as any).requestStream = true;
const upstream: Subject<unknown> = new Subject();
const stream$: Observable<any> = client.createUnaryServiceMethod(obj, methodName)(upstream);
const upstreamSubscribe = sinon.spy(upstream, 'subscribe');
stream$.subscribe({
next: () => ({}),
error: () => ({}),
});
upstream.next({ test: true });
const subscription = stream$.subscribe({
next: dataSpy,
error: errorSpy,
complete: completeSpy,
});
subscription.unsubscribe();
handler(null, 'a');
expect(dataSpy.called).to.be.false;
expect(writeSpy.called).to.be.true;
expect(errorSpy.called).to.be.false;
expect(completeSpy.called).to.be.false;
expect(callMock.cancel.called).to.be.true;
expect(upstreamSubscribe.called).to.be.true;
});
});
});
describe('createClients', () => {
describe('when package does not exist', () => {
it('should throw "InvalidGrpcPackageException"', () => {
sinon.stub(client, 'lookupPackage').callsFake(() => null);
(client as any).logger = new NoopLogger();
try {
client.createClients();
} catch (err) {
expect(err).to.be.instanceof(InvalidGrpcPackageException);
}
});
});
});
describe('loadProto', () => {
describe('when proto is invalid', () => {
it('should throw InvalidProtoDefinitionException', () => {
sinon.stub(client, 'getOptionsProp' as any).callsFake(() => {
throw new Error();
});
(client as any).logger = new NoopLogger();
expect(() => client.loadProto()).to.throws(
InvalidProtoDefinitionException,
);
});
});
});
describe('close', () => {
it('should call "close" method', () => {
const grpcClient = { close: sinon.spy() };
(client as any).grpcClients[0] = grpcClient;
client.close();
expect(grpcClient.close.called).to.be.true;
});
});
describe('publish', () => {
it('should throw exception', () => {
expect(() => client['publish'](null, null)).to.throws(Error);
});
});
describe('send', () => {
it('should throw exception', () => {
expect(() => client.send(null, null)).to.throws(Error);
});
});
describe('connect', () => {
it('should throw exception', () => {
client.connect().catch(error => expect(error).to.be.instanceof(Error));
});
});
describe('dispatchEvent', () => {
it('should throw exception', () => {
client['dispatchEvent'](null).catch(error =>
expect(error).to.be.instanceof(Error),
);
});
});
describe('lookupPackage', () => {
it('should return root package in case package name is not defined', () => {
const root = {};
expect(client.lookupPackage(root, undefined)).to.be.equal(root);
expect(client.lookupPackage(root, '')).to.be.equal(root);
});
});
});
| packages/microservices/test/client/client-grpc.spec.ts | 1 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.9987844824790955,
0.20352685451507568,
0.00016237726958934218,
0.0013884902000427246,
0.39845308661460876
]
|
{
"id": 5,
"code_window": [
" (obj[methodName] as any).requestStream = true;\n",
" const upstream: Subject<unknown> = new Subject();\n",
" const stream$: Observable<any> = client.createUnaryServiceMethod(obj, methodName)(upstream);\n",
"\n",
" const upstreamSubscribe = sinon.spy(upstream, 'subscribe');\n",
" stream$.subscribe({\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" let upstream: Subject<unknown> = new Subject();\n",
" let stream$: Observable<any> = client.createUnaryServiceMethod(\n",
" obj,\n",
" methodName,\n",
" )(upstream);\n"
],
"file_path": "packages/microservices/test/client/client-grpc.spec.ts",
"type": "replace",
"edit_start_line_idx": 386
} | export declare class AppController {
root(): string;
}
| benchmarks/nest/app.controller.d.ts | 0 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.00016828601656015962,
0.00016828601656015962,
0.00016828601656015962,
0.00016828601656015962,
0
]
|
{
"id": 5,
"code_window": [
" (obj[methodName] as any).requestStream = true;\n",
" const upstream: Subject<unknown> = new Subject();\n",
" const stream$: Observable<any> = client.createUnaryServiceMethod(obj, methodName)(upstream);\n",
"\n",
" const upstreamSubscribe = sinon.spy(upstream, 'subscribe');\n",
" stream$.subscribe({\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" let upstream: Subject<unknown> = new Subject();\n",
" let stream$: Observable<any> = client.createUnaryServiceMethod(\n",
" obj,\n",
" methodName,\n",
" )(upstream);\n"
],
"file_path": "packages/microservices/test/client/client-grpc.spec.ts",
"type": "replace",
"edit_start_line_idx": 386
} | {
"singleQuote": true,
"arrowParens": "avoid",
"trailingComma": "all"
}
| .prettierrc | 0 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.00017448244034312665,
0.00017448244034312665,
0.00017448244034312665,
0.00017448244034312665,
0
]
|
{
"id": 5,
"code_window": [
" (obj[methodName] as any).requestStream = true;\n",
" const upstream: Subject<unknown> = new Subject();\n",
" const stream$: Observable<any> = client.createUnaryServiceMethod(obj, methodName)(upstream);\n",
"\n",
" const upstreamSubscribe = sinon.spy(upstream, 'subscribe');\n",
" stream$.subscribe({\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" let upstream: Subject<unknown> = new Subject();\n",
" let stream$: Observable<any> = client.createUnaryServiceMethod(\n",
" obj,\n",
" methodName,\n",
" )(upstream);\n"
],
"file_path": "packages/microservices/test/client/client-grpc.spec.ts",
"type": "replace",
"edit_start_line_idx": 386
} | /**
* @publicApi
*/
export interface RmqUrl {
protocol?: string;
hostname?: string;
port?: number;
username?: string;
password?: string;
locale?: string;
frameMax?: number;
heartbeat?: number;
vhost?: string;
}
/**
* @publicApi
*/
export interface AmqpConnectionManagerSocketOptions {
reconnectTimeInSeconds?: number;
heartbeatIntervalInSeconds?: number;
findServers?: () => string | string[];
connectionOptions?: any;
}
/**
* @publicApi
*/
export interface AmqplibQueueOptions {
durable?: boolean;
autoDelete?: boolean;
arguments?: any;
messageTtl?: number;
expires?: number;
deadLetterExchange?: string;
deadLetterRoutingKey?: string;
maxLength?: number;
maxPriority?: number;
}
| packages/microservices/external/rmq-url.interface.ts | 0 | https://github.com/nestjs/nest/commit/9f3d1c9c76d9cf6efd83d4fa84b0d2c28027a581 | [
0.00017731162370182574,
0.00017078017117455602,
0.0001644047733861953,
0.00017070214380510151,
0.000004590095613821177
]
|
{
"id": 0,
"code_window": [
" } else {\n",
" node.value = null;\n",
" }\n",
" if (!this.eat(tt.semi)) {\n",
" this.raise(this.state.start, \"A semicolon is required after a class property\");\n",
" }\n",
" return this.finishNode(node, \"ClassProperty\");\n",
"};\n",
"\n",
"pp.parseClassMethod = function (classBody, method, isGenerator, isAsync) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.raise(node.value && node.value.end || node.key.end, \"A semicolon is required after a class property\");\n"
],
"file_path": "packages/babylon/src/parser/statement.js",
"type": "replace",
"edit_start_line_idx": 750
} | import { types as tt } from "../tokenizer/types";
import Parser from "./index";
import { lineBreak } from "../util/whitespace";
const pp = Parser.prototype;
// ### Statement parsing
// Parse a program. Initializes the parser, reads any number of
// statements, and wraps them in a Program node. Optionally takes a
// `program` argument. If present, the statements will be appended
// to its body instead of creating a new node.
pp.parseTopLevel = function (file, program) {
program.sourceType = this.options.sourceType;
this.parseBlockBody(program, true, true, tt.eof);
file.program = this.finishNode(program, "Program");
file.comments = this.state.comments;
file.tokens = this.state.tokens;
return this.finishNode(file, "File");
};
const loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
// TODO
pp.stmtToDirective = function (stmt) {
let expr = stmt.expression;
let directiveLiteral = this.startNodeAt(expr.start, expr.loc.start);
let directive = this.startNodeAt(stmt.start, stmt.loc.start);
let raw = this.input.slice(expr.start, expr.end);
let val = directiveLiteral.value = raw.slice(1, -1); // remove quotes
this.addExtra(directiveLiteral, "raw", raw);
this.addExtra(directiveLiteral, "rawValue", val);
directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end);
return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end);
};
// Parse a single statement.
//
// If expecting a statement and finding a slash operator, parse a
// regular expression literal. This is to handle cases like
// `if (foo) /blah/.exec(foo)`, where looking at the previous token
// does not help.
pp.parseStatement = function (declaration, topLevel) {
if (this.match(tt.at)) {
this.parseDecorators(true);
}
let starttype = this.state.type, node = this.startNode();
// Most types of statements are recognized by the keyword they
// start with. Many are trivial to parse, some require a bit of
// complexity.
switch (starttype) {
case tt._break: case tt._continue: return this.parseBreakContinueStatement(node, starttype.keyword);
case tt._debugger: return this.parseDebuggerStatement(node);
case tt._do: return this.parseDoStatement(node);
case tt._for: return this.parseForStatement(node);
case tt._function:
if (!declaration) this.unexpected();
return this.parseFunctionStatement(node);
case tt._class:
if (!declaration) this.unexpected();
this.takeDecorators(node);
return this.parseClass(node, true);
case tt._if: return this.parseIfStatement(node);
case tt._return: return this.parseReturnStatement(node);
case tt._switch: return this.parseSwitchStatement(node);
case tt._throw: return this.parseThrowStatement(node);
case tt._try: return this.parseTryStatement(node);
case tt._let:
case tt._const:
if (!declaration) this.unexpected(); // NOTE: falls through to _var
case tt._var:
return this.parseVarStatement(node, starttype);
case tt._while: return this.parseWhileStatement(node);
case tt._with: return this.parseWithStatement(node);
case tt.braceL: return this.parseBlock();
case tt.semi: return this.parseEmptyStatement(node);
case tt._export:
case tt._import:
if (!this.options.allowImportExportEverywhere) {
if (!topLevel) {
this.raise(this.state.start, "'import' and 'export' may only appear at the top level");
}
if (!this.inModule) {
this.raise(this.state.start, "'import' and 'export' may appear only with 'sourceType: module'");
}
}
return starttype === tt._import ? this.parseImport(node) : this.parseExport(node);
case tt.name:
if (this.hasPlugin("asyncFunctions") && this.state.value === "async") {
// peek ahead and see if next token is a function
let state = this.state.clone();
this.next();
if (this.match(tt._function) && !this.canInsertSemicolon()) {
this.expect(tt._function);
return this.parseFunction(node, true, false, true);
} else {
this.state = state;
}
}
}
// If the statement does not start with a statement keyword or a
// brace, it's an ExpressionStatement or LabeledStatement. We
// simply start parsing an expression, and afterwards, if the
// next token is a colon and the expression was a simple
// Identifier node, we switch to interpreting it as a label.
let maybeName = this.state.value;
let expr = this.parseExpression();
if (starttype === tt.name && expr.type === "Identifier" && this.eat(tt.colon)) {
return this.parseLabeledStatement(node, maybeName, expr);
} else {
return this.parseExpressionStatement(node, expr);
}
};
pp.takeDecorators = function (node) {
if (this.state.decorators.length) {
node.decorators = this.state.decorators;
this.state.decorators = [];
}
};
pp.parseDecorators = function (allowExport) {
while (this.match(tt.at)) {
this.state.decorators.push(this.parseDecorator());
}
if (allowExport && this.match(tt._export)) {
return;
}
if (!this.match(tt._class)) {
this.raise(this.state.start, "Leading decorators must be attached to a class declaration");
}
};
pp.parseDecorator = function () {
if (!this.hasPlugin("decorators")) {
this.unexpected();
}
let node = this.startNode();
this.next();
node.expression = this.parseMaybeAssign();
return this.finishNode(node, "Decorator");
};
pp.parseBreakContinueStatement = function (node, keyword) {
let isBreak = keyword === "break";
this.next();
if (this.isLineTerminator()) {
node.label = null;
} else if (!this.match(tt.name)) {
this.unexpected();
} else {
node.label = this.parseIdentifier();
this.semicolon();
}
// Verify that there is an actual destination to break or
// continue to.
let i;
for (i = 0; i < this.state.labels.length; ++i) {
let lab = this.state.labels[i];
if (node.label == null || lab.name === node.label.name) {
if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
if (node.label && isBreak) break;
}
}
if (i === this.state.labels.length) this.raise(node.start, "Unsyntactic " + keyword);
return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
};
pp.parseDebuggerStatement = function (node) {
this.next();
this.semicolon();
return this.finishNode(node, "DebuggerStatement");
};
pp.parseDoStatement = function (node) {
this.next();
this.state.labels.push(loopLabel);
node.body = this.parseStatement(false);
this.state.labels.pop();
this.expect(tt._while);
node.test = this.parseParenExpression();
this.eat(tt.semi);
return this.finishNode(node, "DoWhileStatement");
};
// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
// loop is non-trivial. Basically, we have to parse the init `var`
// statement or expression, disallowing the `in` operator (see
// the second parameter to `parseExpression`), and then check
// whether the next token is `in` or `of`. When there is no init
// part (semicolon immediately after the opening parenthesis), it
// is a regular `for` loop.
pp.parseForStatement = function (node) {
this.next();
this.state.labels.push(loopLabel);
this.expect(tt.parenL);
if (this.match(tt.semi)) {
return this.parseFor(node, null);
}
if (this.match(tt._var) || this.match(tt._let) || this.match(tt._const)) {
let init = this.startNode(), varKind = this.state.type;
this.next();
this.parseVar(init, true, varKind);
this.finishNode(init, "VariableDeclaration");
if (this.match(tt._in) || this.isContextual("of")) {
if (init.declarations.length === 1 && !init.declarations[0].init) {
return this.parseForIn(node, init);
}
}
return this.parseFor(node, init);
}
let refShorthandDefaultPos = {start: 0};
let init = this.parseExpression(true, refShorthandDefaultPos);
if (this.match(tt._in) || this.isContextual("of")) {
this.toAssignable(init);
this.checkLVal(init);
return this.parseForIn(node, init);
} else if (refShorthandDefaultPos.start) {
this.unexpected(refShorthandDefaultPos.start);
}
return this.parseFor(node, init);
};
pp.parseFunctionStatement = function (node) {
this.next();
return this.parseFunction(node, true);
};
pp.parseIfStatement = function (node) {
this.next();
node.test = this.parseParenExpression();
node.consequent = this.parseStatement(false);
node.alternate = this.eat(tt._else) ? this.parseStatement(false) : null;
return this.finishNode(node, "IfStatement");
};
pp.parseReturnStatement = function (node) {
if (!this.state.inFunction && !this.options.allowReturnOutsideFunction) {
this.raise(this.state.start, "'return' outside of function");
}
this.next();
// In `return` (and `break`/`continue`), the keywords with
// optional arguments, we eagerly look for a semicolon or the
// possibility to insert one.
if (this.isLineTerminator()) {
node.argument = null;
} else {
node.argument = this.parseExpression();
this.semicolon();
}
return this.finishNode(node, "ReturnStatement");
};
pp.parseSwitchStatement = function (node) {
this.next();
node.discriminant = this.parseParenExpression();
node.cases = [];
this.expect(tt.braceL);
this.state.labels.push(switchLabel);
// Statements under must be grouped (by label) in SwitchCase
// nodes. `cur` is used to keep the node that we are currently
// adding statements to.
let cur;
for (let sawDefault; !this.match(tt.braceR); ) {
if (this.match(tt._case) || this.match(tt._default)) {
let isCase = this.match(tt._case);
if (cur) this.finishNode(cur, "SwitchCase");
node.cases.push(cur = this.startNode());
cur.consequent = [];
this.next();
if (isCase) {
cur.test = this.parseExpression();
} else {
if (sawDefault) this.raise(this.state.lastTokStart, "Multiple default clauses");
sawDefault = true;
cur.test = null;
}
this.expect(tt.colon);
} else {
if (cur) {
cur.consequent.push(this.parseStatement(true));
} else {
this.unexpected();
}
}
}
if (cur) this.finishNode(cur, "SwitchCase");
this.next(); // Closing brace
this.state.labels.pop();
return this.finishNode(node, "SwitchStatement");
};
pp.parseThrowStatement = function (node) {
this.next();
if (lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start)))
this.raise(this.state.lastTokEnd, "Illegal newline after throw");
node.argument = this.parseExpression();
this.semicolon();
return this.finishNode(node, "ThrowStatement");
};
// Reused empty array added for node fields that are always empty.
let empty = [];
pp.parseTryStatement = function (node) {
this.next();
node.block = this.parseBlock();
node.handler = null;
if (this.match(tt._catch)) {
let clause = this.startNode();
this.next();
this.expect(tt.parenL);
clause.param = this.parseBindingAtom();
this.checkLVal(clause.param, true, Object.create(null));
this.expect(tt.parenR);
clause.body = this.parseBlock();
node.handler = this.finishNode(clause, "CatchClause");
}
node.guardedHandlers = empty;
node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null;
if (!node.handler && !node.finalizer) {
this.raise(node.start, "Missing catch or finally clause");
}
return this.finishNode(node, "TryStatement");
};
pp.parseVarStatement = function (node, kind) {
this.next();
this.parseVar(node, false, kind);
this.semicolon();
return this.finishNode(node, "VariableDeclaration");
};
pp.parseWhileStatement = function (node) {
this.next();
node.test = this.parseParenExpression();
this.state.labels.push(loopLabel);
node.body = this.parseStatement(false);
this.state.labels.pop();
return this.finishNode(node, "WhileStatement");
};
pp.parseWithStatement = function (node) {
if (this.state.strict) this.raise(this.state.start, "'with' in strict mode");
this.next();
node.object = this.parseParenExpression();
node.body = this.parseStatement(false);
return this.finishNode(node, "WithStatement");
};
pp.parseEmptyStatement = function (node) {
this.next();
return this.finishNode(node, "EmptyStatement");
};
pp.parseLabeledStatement = function (node, maybeName, expr) {
for (let label of (this.state.labels: Array<Object>)){
if (label.name === maybeName) {
this.raise(expr.start, `Label '${maybeName}' is already declared`);
}
}
let kind = this.state.type.isLoop ? "loop" : this.match(tt._switch) ? "switch" : null;
for (let i = this.state.labels.length - 1; i >= 0; i--) {
let label = this.state.labels[i];
if (label.statementStart === node.start) {
label.statementStart = this.state.start;
label.kind = kind;
} else {
break;
}
}
this.state.labels.push({name: maybeName, kind: kind, statementStart: this.state.start});
node.body = this.parseStatement(true);
this.state.labels.pop();
node.label = expr;
return this.finishNode(node, "LabeledStatement");
};
pp.parseExpressionStatement = function (node, expr) {
node.expression = expr;
this.semicolon();
return this.finishNode(node, "ExpressionStatement");
};
// Parse a semicolon-enclosed block of statements, handling `"use
// strict"` declarations when `allowStrict` is true (used for
// function bodies).
pp.parseBlock = function (allowDirectives?) {
let node = this.startNode();
this.expect(tt.braceL);
this.parseBlockBody(node, allowDirectives, false, tt.braceR);
return this.finishNode(node, "BlockStatement");
};
// TODO
pp.parseBlockBody = function (node, allowDirectives, topLevel, end) {
node.body = [];
node.directives = [];
let parsedNonDirective = false;
let oldStrict;
let octalPosition;
while (!this.eat(end)) {
if (!parsedNonDirective && this.state.containsOctal && !octalPosition) {
octalPosition = this.state.octalPosition;
}
let stmt = this.parseStatement(true, topLevel);
if (allowDirectives && !parsedNonDirective &&
stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" &&
!stmt.expression.extra.parenthesized) {
let directive = this.stmtToDirective(stmt);
node.directives.push(directive);
if (oldStrict === undefined && directive.value.value === "use strict") {
oldStrict = this.state.strict;
this.setStrict(true);
if (octalPosition) {
this.raise(octalPosition, "Octal literal in strict mode");
}
}
continue;
}
parsedNonDirective = true;
node.body.push(stmt);
}
if (oldStrict === false) {
this.setStrict(false);
}
};
// Parse a regular `for` loop. The disambiguation code in
// `parseStatement` will already have parsed the init statement or
// expression.
pp.parseFor = function (node, init) {
node.init = init;
this.expect(tt.semi);
node.test = this.match(tt.semi) ? null : this.parseExpression();
this.expect(tt.semi);
node.update = this.match(tt.parenR) ? null : this.parseExpression();
this.expect(tt.parenR);
node.body = this.parseStatement(false);
this.state.labels.pop();
return this.finishNode(node, "ForStatement");
};
// Parse a `for`/`in` and `for`/`of` loop, which are almost
// same from parser's perspective.
pp.parseForIn = function (node, init) {
let type = this.match(tt._in) ? "ForInStatement" : "ForOfStatement";
this.next();
node.left = init;
node.right = this.parseExpression();
this.expect(tt.parenR);
node.body = this.parseStatement(false);
this.state.labels.pop();
return this.finishNode(node, type);
};
// Parse a list of variable declarations.
pp.parseVar = function (node, isFor, kind) {
node.declarations = [];
node.kind = kind.keyword;
for (;;) {
let decl = this.startNode();
this.parseVarHead(decl);
if (this.eat(tt.eq)) {
decl.init = this.parseMaybeAssign(isFor);
} else if (kind === tt._const && !(this.match(tt._in) || this.isContextual("of"))) {
this.unexpected();
} else if (decl.id.type !== "Identifier" && !(isFor && (this.match(tt._in) || this.isContextual("of")))) {
this.raise(this.state.lastTokEnd, "Complex binding patterns require an initialization value");
} else {
decl.init = null;
}
node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
if (!this.eat(tt.comma)) break;
}
return node;
};
pp.parseVarHead = function (decl) {
decl.id = this.parseBindingAtom();
this.checkLVal(decl.id, true);
};
// Parse a function declaration or literal (depending on the
// `isStatement` parameter).
pp.parseFunction = function (node, isStatement, allowExpressionBody, isAsync, optionalId) {
let oldInMethod = this.state.inMethod;
this.state.inMethod = false;
this.initFunction(node, isAsync);
if (this.match(tt.star)) {
if (node.async && !this.hasPlugin("asyncGenerators")) {
this.unexpected();
} else {
node.generator = true;
this.next();
}
}
if (isStatement && !optionalId && !this.match(tt.name) && !this.match(tt._yield)) {
this.unexpected();
}
if (this.match(tt.name) || this.match(tt._yield)) {
node.id = this.parseBindingIdentifier();
}
this.parseFunctionParams(node);
this.parseFunctionBody(node, allowExpressionBody);
this.state.inMethod = oldInMethod;
return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
};
pp.parseFunctionParams = function (node) {
this.expect(tt.parenL);
node.params = this.parseBindingList(tt.parenR, false, this.hasPlugin("trailingFunctionCommas"));
};
// Parse a class declaration or literal (depending on the
// `isStatement` parameter).
pp.parseClass = function (node, isStatement, optionalId) {
this.next();
this.parseClassId(node, isStatement, optionalId);
this.parseClassSuper(node);
this.parseClassBody(node);
return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
};
pp.isClassProperty = function () {
return this.match(tt.eq) || this.match(tt.semi) || this.canInsertSemicolon();
};
pp.parseClassBody = function (node) {
// class bodies are implicitly strict
let oldStrict = this.state.strict;
this.state.strict = true;
let hadConstructorCall = false;
let hadConstructor = false;
let decorators = [];
let classBody = this.startNode();
classBody.body = [];
this.expect(tt.braceL);
while (!this.eat(tt.braceR)) {
if (this.eat(tt.semi)) {
continue;
}
if (this.match(tt.at)) {
decorators.push(this.parseDecorator());
continue;
}
let method = this.startNode();
// steal the decorators if there are any
if (decorators.length) {
method.decorators = decorators;
decorators = [];
}
let isConstructorCall = false;
let isMaybeStatic = this.match(tt.name) && this.state.value === "static";
let isGenerator = this.eat(tt.star);
let isGetSet = false;
let isAsync = false;
this.parsePropertyName(method);
method.static = isMaybeStatic && !this.match(tt.parenL);
if (method.static) {
if (isGenerator) this.unexpected();
isGenerator = this.eat(tt.star);
this.parsePropertyName(method);
}
if (!isGenerator && method.key.type === "Identifier" && !method.computed) {
if (this.isClassProperty()) {
classBody.body.push(this.parseClassProperty(method));
continue;
}
if (this.hasPlugin("classConstructorCall") && method.key.name === "call" && this.match(tt.name) && this.state.value === "constructor") {
isConstructorCall = true;
this.parsePropertyName(method);
}
}
let isAsyncMethod = this.hasPlugin("asyncFunctions") && !this.match(tt.parenL) && !method.computed && method.key.type === "Identifier" && method.key.name === "async";
if (isAsyncMethod) {
if (this.hasPlugin("asyncGenerators") && this.eat(tt.star)) isGenerator = true;
isAsync = true;
this.parsePropertyName(method);
}
method.kind = "method";
if (!method.computed) {
let { key } = method;
// handle get/set methods
// eg. class Foo { get bar() {} set bar() {} }
if (!isAsync && !isGenerator && key.type === "Identifier" && !this.match(tt.parenL) && (key.name === "get" || key.name === "set")) {
isGetSet = true;
method.kind = key.name;
key = this.parsePropertyName(method);
}
// disallow invalid constructors
let isConstructor = !isConstructorCall && !method.static && (
(key.type === "Identifier" && key.name === "constructor") ||
(key.type === "StringLiteral" && key.value === "constructor")
);
if (isConstructor) {
if (hadConstructor) this.raise(key.start, "Duplicate constructor in the same class");
if (isGetSet) this.raise(key.start, "Constructor can't have get/set modifier");
if (isGenerator) this.raise(key.start, "Constructor can't be a generator");
if (isAsync) this.raise(key.start, "Constructor can't be an async function");
method.kind = "constructor";
hadConstructor = true;
}
// disallow static prototype method
let isStaticPrototype = method.static && (
(key.type === "Identifier" && key.name === "prototype") ||
(key.type === "StringLiteral" && key.value === "prototype")
);
if (isStaticPrototype) {
this.raise(key.start, "Classes may not have static property named prototype");
}
}
// convert constructor to a constructor call
if (isConstructorCall) {
if (hadConstructorCall) this.raise(method.start, "Duplicate constructor call in the same class");
method.kind = "constructorCall";
hadConstructorCall = true;
}
// disallow decorators on class constructors
if ((method.kind === "constructor" || method.kind === "constructorCall") && method.decorators) {
this.raise(method.start, "You can't attach decorators to a class constructor");
}
this.parseClassMethod(classBody, method, isGenerator, isAsync);
// get methods aren't allowed to have any parameters
// set methods must have exactly 1 parameter
if (isGetSet) {
let paramCount = method.kind === "get" ? 0 : 1;
if (method.params.length !== paramCount) {
let start = method.start;
if (method.kind === "get") {
this.raise(start, "getter should have no params");
} else {
this.raise(start, "setter should have exactly one param");
}
}
}
}
if (decorators.length) {
this.raise(this.state.start, "You have trailing decorators with no method");
}
node.body = this.finishNode(classBody, "ClassBody");
this.state.strict = oldStrict;
};
pp.parseClassProperty = function (node) {
if (this.match(tt.eq)) {
if (!this.hasPlugin("classProperties")) this.unexpected();
this.next();
node.value = this.parseMaybeAssign();
} else {
node.value = null;
}
if (!this.eat(tt.semi)) {
this.raise(this.state.start, "A semicolon is required after a class property");
}
return this.finishNode(node, "ClassProperty");
};
pp.parseClassMethod = function (classBody, method, isGenerator, isAsync) {
this.parseMethod(method, isGenerator, isAsync);
classBody.body.push(this.finishNode(method, "ClassMethod"));
};
pp.parseClassId = function (node, isStatement, optionalId) {
if (this.match(tt.name)) {
node.id = this.parseIdentifier();
} else {
if (optionalId || !isStatement) {
node.id = null;
} else {
this.unexpected();
}
}
};
pp.parseClassSuper = function (node) {
node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null;
};
// Parses module export declaration.
pp.parseExport = function (node) {
this.next();
// export * from '...'
if (this.match(tt.star)) {
let specifier = this.startNode();
this.next();
if (this.hasPlugin("exportExtensions") && this.eatContextual("as")) {
specifier.exported = this.parseIdentifier();
node.specifiers = [this.finishNode(specifier, "ExportNamespaceSpecifier")];
this.parseExportSpecifiersMaybe(node);
this.parseExportFrom(node, true);
} else {
this.parseExportFrom(node, true);
return this.finishNode(node, "ExportAllDeclaration");
}
} else if (this.hasPlugin("exportExtensions") && this.isExportDefaultSpecifier()) {
let specifier = this.startNode();
specifier.exported = this.parseIdentifier(true);
node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
if (this.match(tt.comma) && this.lookahead().type === tt.star) {
this.expect(tt.comma);
let specifier = this.startNode();
this.expect(tt.star);
this.expectContextual("as");
specifier.exported = this.parseIdentifier();
node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
} else {
this.parseExportSpecifiersMaybe(node);
}
this.parseExportFrom(node, true);
} else if (this.eat(tt._default)) { // export default ...
let expr = this.startNode();
let needsSemi = false;
if (this.eat(tt._function)) {
expr = this.parseFunction(expr, true, false, false, true);
} else if (this.match(tt._class)) {
expr = this.parseClass(expr, true, true);
} else {
needsSemi = true;
expr = this.parseMaybeAssign();
}
node.declaration = expr;
if (needsSemi) this.semicolon();
this.checkExport(node);
return this.finishNode(node, "ExportDefaultDeclaration");
} else if (this.state.type.keyword || this.shouldParseExportDeclaration()) {
node.specifiers = [];
node.source = null;
node.declaration = this.parseExportDeclaration(node);
} else { // export { x, y as z } [from '...']
node.declaration = null;
node.specifiers = this.parseExportSpecifiers();
this.parseExportFrom(node);
}
this.checkExport(node);
return this.finishNode(node, "ExportNamedDeclaration");
};
pp.parseExportDeclaration = function () {
return this.parseStatement(true);
};
pp.isExportDefaultSpecifier = function () {
if (this.match(tt.name)) {
return this.state.value !== "type"
&& this.state.value !== "async"
&& this.state.value !== "interface";
}
if (!this.match(tt._default)) {
return false;
}
let lookahead = this.lookahead();
return lookahead.type === tt.comma || (lookahead.type === tt.name && lookahead.value === "from");
};
pp.parseExportSpecifiersMaybe = function (node) {
if (this.eat(tt.comma)) {
node.specifiers = node.specifiers.concat(this.parseExportSpecifiers());
}
};
pp.parseExportFrom = function (node, expect?) {
if (this.eatContextual("from")) {
node.source = this.match(tt.string) ? this.parseExprAtom() : this.unexpected();
this.checkExport(node);
} else {
if (expect) {
this.unexpected();
} else {
node.source = null;
}
}
this.semicolon();
};
pp.shouldParseExportDeclaration = function () {
return this.hasPlugin("asyncFunctions") && this.isContextual("async");
};
pp.checkExport = function (node) {
if (this.state.decorators.length) {
let isClass = node.declaration && (node.declaration.type === "ClassDeclaration" || node.declaration.type === "ClassExpression");
if (!node.declaration || !isClass) {
this.raise(node.start, "You can only use decorators on an export when exporting a class");
}
this.takeDecorators(node.declaration);
}
};
// Parses a comma-separated list of module exports.
pp.parseExportSpecifiers = function () {
let nodes = [];
let first = true;
let needsFrom;
// export { x, y as z } [from '...']
this.expect(tt.braceL);
while (!this.eat(tt.braceR)) {
if (first) {
first = false;
} else {
this.expect(tt.comma);
if (this.eat(tt.braceR)) break;
}
let isDefault = this.match(tt._default);
if (isDefault && !needsFrom) needsFrom = true;
let node = this.startNode();
node.local = this.parseIdentifier(isDefault);
node.exported = this.eatContextual("as") ? this.parseIdentifier(true) : node.local.__clone();
nodes.push(this.finishNode(node, "ExportSpecifier"));
}
// https://github.com/ember-cli/ember-cli/pull/3739
if (needsFrom && !this.isContextual("from")) {
this.unexpected();
}
return nodes;
};
// Parses import declaration.
pp.parseImport = function (node) {
this.next();
// import '...'
if (this.match(tt.string)) {
node.specifiers = [];
node.source = this.parseExprAtom();
} else {
node.specifiers = [];
this.parseImportSpecifiers(node);
this.expectContextual("from");
node.source = this.match(tt.string) ? this.parseExprAtom() : this.unexpected();
}
this.semicolon();
return this.finishNode(node, "ImportDeclaration");
};
// Parses a comma-separated list of module imports.
pp.parseImportSpecifiers = function (node) {
let first = true;
if (this.match(tt.name)) {
// import defaultObj, { x, y as z } from '...'
let startPos = this.state.start, startLoc = this.state.startLoc;
node.specifiers.push(this.parseImportSpecifierDefault(this.parseIdentifier(), startPos, startLoc));
if (!this.eat(tt.comma)) return;
}
if (this.match(tt.star)) {
let specifier = this.startNode();
this.next();
this.expectContextual("as");
specifier.local = this.parseIdentifier();
this.checkLVal(specifier.local, true);
node.specifiers.push(this.finishNode(specifier, "ImportNamespaceSpecifier"));
return;
}
this.expect(tt.braceL);
while (!this.eat(tt.braceR)) {
if (first) {
first = false;
} else {
this.expect(tt.comma);
if (this.eat(tt.braceR)) break;
}
let specifier = this.startNode();
specifier.imported = this.parseIdentifier(true);
specifier.local = this.eatContextual("as") ? this.parseIdentifier() : specifier.imported.__clone();
this.checkLVal(specifier.local, true);
node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
}
};
pp.parseImportSpecifierDefault = function (id, startPos, startLoc) {
let node = this.startNodeAt(startPos, startLoc);
node.local = id;
this.checkLVal(node.local, true);
return this.finishNode(node, "ImportDefaultSpecifier");
};
| packages/babylon/src/parser/statement.js | 1 | https://github.com/babel/babel/commit/f31099f383b52cf4fe1786188f6421529dea865b | [
0.9964736104011536,
0.035932570695877075,
0.00016615947242826223,
0.0019694450311362743,
0.1662714034318924
]
|
{
"id": 0,
"code_window": [
" } else {\n",
" node.value = null;\n",
" }\n",
" if (!this.eat(tt.semi)) {\n",
" this.raise(this.state.start, \"A semicolon is required after a class property\");\n",
" }\n",
" return this.finishNode(node, \"ClassProperty\");\n",
"};\n",
"\n",
"pp.parseClassMethod = function (classBody, method, isGenerator, isAsync) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.raise(node.value && node.value.end || node.key.end, \"A semicolon is required after a class property\");\n"
],
"file_path": "packages/babylon/src/parser/statement.js",
"type": "replace",
"edit_start_line_idx": 750
} | import _regeneratorRuntime from "babel-runtime/regenerator";
void _regeneratorRuntime.mark(function _callee() {
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
case "end":
return _context.stop();
}
}, _callee, this);
});
| packages/babel-plugin-transform-runtime/test/fixtures/runtime/regenerator-runtime/expected.js | 0 | https://github.com/babel/babel/commit/f31099f383b52cf4fe1786188f6421529dea865b | [
0.00017585318710189313,
0.00017388700507581234,
0.00017192083760164678,
0.00017388700507581234,
0.000001966174750123173
]
|
{
"id": 0,
"code_window": [
" } else {\n",
" node.value = null;\n",
" }\n",
" if (!this.eat(tt.semi)) {\n",
" this.raise(this.state.start, \"A semicolon is required after a class property\");\n",
" }\n",
" return this.finishNode(node, \"ClassProperty\");\n",
"};\n",
"\n",
"pp.parseClassMethod = function (classBody, method, isGenerator, isAsync) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.raise(node.value && node.value.end || node.key.end, \"A semicolon is required after a class property\");\n"
],
"file_path": "packages/babylon/src/parser/statement.js",
"type": "replace",
"edit_start_line_idx": 750
} | class A {set constructor(m){}}
| packages/babylon/test/fixtures/esprima/invalid-syntax/migrated_0273/actual.js | 0 | https://github.com/babel/babel/commit/f31099f383b52cf4fe1786188f6421529dea865b | [
0.0005581675795838237,
0.0005581675795838237,
0.0005581675795838237,
0.0005581675795838237,
0
]
|
{
"id": 0,
"code_window": [
" } else {\n",
" node.value = null;\n",
" }\n",
" if (!this.eat(tt.semi)) {\n",
" this.raise(this.state.start, \"A semicolon is required after a class property\");\n",
" }\n",
" return this.finishNode(node, \"ClassProperty\");\n",
"};\n",
"\n",
"pp.parseClassMethod = function (classBody, method, isGenerator, isAsync) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.raise(node.value && node.value.end || node.key.end, \"A semicolon is required after a class property\");\n"
],
"file_path": "packages/babylon/src/parser/statement.js",
"type": "replace",
"edit_start_line_idx": 750
} | {
"throws": "Binding arguments in strict mode (1:48)"
} | packages/babylon/test/fixtures/esprima/invalid-syntax/migrated_0215/options.json | 0 | https://github.com/babel/babel/commit/f31099f383b52cf4fe1786188f6421529dea865b | [
0.00017291052790824324,
0.00017291052790824324,
0.00017291052790824324,
0.00017291052790824324,
0
]
|
{
"id": 1,
"code_window": [
"{\n",
" \"throws\": \"A semicolon is required after a class property (3:0)\",\n",
" \"plugins\": [\"classProperties\"]\n",
"}"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"throws\": \"A semicolon is required after a class property (2:10)\",\n"
],
"file_path": "packages/babylon/test/fixtures/experimental/class-properties/semicolons-required-with-value/options.json",
"type": "replace",
"edit_start_line_idx": 1
} | {
"throws": "A semicolon is required after a class property (3:0)",
"plugins": ["classProperties"]
}
| packages/babylon/test/fixtures/experimental/class-properties/semicolons-required-with-value/options.json | 1 | https://github.com/babel/babel/commit/f31099f383b52cf4fe1786188f6421529dea865b | [
0.996871292591095,
0.996871292591095,
0.996871292591095,
0.996871292591095,
0
]
|
{
"id": 1,
"code_window": [
"{\n",
" \"throws\": \"A semicolon is required after a class property (3:0)\",\n",
" \"plugins\": [\"classProperties\"]\n",
"}"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"throws\": \"A semicolon is required after a class property (2:10)\",\n"
],
"file_path": "packages/babylon/test/fixtures/experimental/class-properties/semicolons-required-with-value/options.json",
"type": "replace",
"edit_start_line_idx": 1
} | {
"throws": "Unexpected token (1:9)"
} | packages/babylon/test/fixtures/esprima/invalid-syntax/migrated_0108/options.json | 0 | https://github.com/babel/babel/commit/f31099f383b52cf4fe1786188f6421529dea865b | [
0.000178426897036843,
0.000178426897036843,
0.000178426897036843,
0.000178426897036843,
0
]
|
{
"id": 1,
"code_window": [
"{\n",
" \"throws\": \"A semicolon is required after a class property (3:0)\",\n",
" \"plugins\": [\"classProperties\"]\n",
"}"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"throws\": \"A semicolon is required after a class property (2:10)\",\n"
],
"file_path": "packages/babylon/test/fixtures/experimental/class-properties/semicolons-required-with-value/options.json",
"type": "replace",
"edit_start_line_idx": 1
} | function x(...{ a }){}
| packages/babylon/test/fixtures/esprima/invalid-syntax/migrated_0259/actual.js | 0 | https://github.com/babel/babel/commit/f31099f383b52cf4fe1786188f6421529dea865b | [
0.00017275463324040174,
0.00017275463324040174,
0.00017275463324040174,
0.00017275463324040174,
0
]
|
{
"id": 1,
"code_window": [
"{\n",
" \"throws\": \"A semicolon is required after a class property (3:0)\",\n",
" \"plugins\": [\"classProperties\"]\n",
"}"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"throws\": \"A semicolon is required after a class property (2:10)\",\n"
],
"file_path": "packages/babylon/test/fixtures/experimental/class-properties/semicolons-required-with-value/options.json",
"type": "replace",
"edit_start_line_idx": 1
} | x = {} | packages/babylon/test/fixtures/core/uncategorised/20/actual.js | 0 | https://github.com/babel/babel/commit/f31099f383b52cf4fe1786188f6421529dea865b | [
0.00017144512094091624,
0.00017144512094091624,
0.00017144512094091624,
0.00017144512094091624,
0
]
|
{
"id": 2,
"code_window": [
"{\n",
" \"throws\": \"A semicolon is required after a class property (3:0)\",\n",
" \"plugins\": [\"classProperties\"]\n",
"}"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"throws\": \"A semicolon is required after a class property (2:6)\",\n"
],
"file_path": "packages/babylon/test/fixtures/experimental/class-properties/semicolons-required-without-value/options.json",
"type": "replace",
"edit_start_line_idx": 1
} | import { types as tt } from "../tokenizer/types";
import Parser from "./index";
import { lineBreak } from "../util/whitespace";
const pp = Parser.prototype;
// ### Statement parsing
// Parse a program. Initializes the parser, reads any number of
// statements, and wraps them in a Program node. Optionally takes a
// `program` argument. If present, the statements will be appended
// to its body instead of creating a new node.
pp.parseTopLevel = function (file, program) {
program.sourceType = this.options.sourceType;
this.parseBlockBody(program, true, true, tt.eof);
file.program = this.finishNode(program, "Program");
file.comments = this.state.comments;
file.tokens = this.state.tokens;
return this.finishNode(file, "File");
};
const loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
// TODO
pp.stmtToDirective = function (stmt) {
let expr = stmt.expression;
let directiveLiteral = this.startNodeAt(expr.start, expr.loc.start);
let directive = this.startNodeAt(stmt.start, stmt.loc.start);
let raw = this.input.slice(expr.start, expr.end);
let val = directiveLiteral.value = raw.slice(1, -1); // remove quotes
this.addExtra(directiveLiteral, "raw", raw);
this.addExtra(directiveLiteral, "rawValue", val);
directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end);
return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end);
};
// Parse a single statement.
//
// If expecting a statement and finding a slash operator, parse a
// regular expression literal. This is to handle cases like
// `if (foo) /blah/.exec(foo)`, where looking at the previous token
// does not help.
pp.parseStatement = function (declaration, topLevel) {
if (this.match(tt.at)) {
this.parseDecorators(true);
}
let starttype = this.state.type, node = this.startNode();
// Most types of statements are recognized by the keyword they
// start with. Many are trivial to parse, some require a bit of
// complexity.
switch (starttype) {
case tt._break: case tt._continue: return this.parseBreakContinueStatement(node, starttype.keyword);
case tt._debugger: return this.parseDebuggerStatement(node);
case tt._do: return this.parseDoStatement(node);
case tt._for: return this.parseForStatement(node);
case tt._function:
if (!declaration) this.unexpected();
return this.parseFunctionStatement(node);
case tt._class:
if (!declaration) this.unexpected();
this.takeDecorators(node);
return this.parseClass(node, true);
case tt._if: return this.parseIfStatement(node);
case tt._return: return this.parseReturnStatement(node);
case tt._switch: return this.parseSwitchStatement(node);
case tt._throw: return this.parseThrowStatement(node);
case tt._try: return this.parseTryStatement(node);
case tt._let:
case tt._const:
if (!declaration) this.unexpected(); // NOTE: falls through to _var
case tt._var:
return this.parseVarStatement(node, starttype);
case tt._while: return this.parseWhileStatement(node);
case tt._with: return this.parseWithStatement(node);
case tt.braceL: return this.parseBlock();
case tt.semi: return this.parseEmptyStatement(node);
case tt._export:
case tt._import:
if (!this.options.allowImportExportEverywhere) {
if (!topLevel) {
this.raise(this.state.start, "'import' and 'export' may only appear at the top level");
}
if (!this.inModule) {
this.raise(this.state.start, "'import' and 'export' may appear only with 'sourceType: module'");
}
}
return starttype === tt._import ? this.parseImport(node) : this.parseExport(node);
case tt.name:
if (this.hasPlugin("asyncFunctions") && this.state.value === "async") {
// peek ahead and see if next token is a function
let state = this.state.clone();
this.next();
if (this.match(tt._function) && !this.canInsertSemicolon()) {
this.expect(tt._function);
return this.parseFunction(node, true, false, true);
} else {
this.state = state;
}
}
}
// If the statement does not start with a statement keyword or a
// brace, it's an ExpressionStatement or LabeledStatement. We
// simply start parsing an expression, and afterwards, if the
// next token is a colon and the expression was a simple
// Identifier node, we switch to interpreting it as a label.
let maybeName = this.state.value;
let expr = this.parseExpression();
if (starttype === tt.name && expr.type === "Identifier" && this.eat(tt.colon)) {
return this.parseLabeledStatement(node, maybeName, expr);
} else {
return this.parseExpressionStatement(node, expr);
}
};
pp.takeDecorators = function (node) {
if (this.state.decorators.length) {
node.decorators = this.state.decorators;
this.state.decorators = [];
}
};
pp.parseDecorators = function (allowExport) {
while (this.match(tt.at)) {
this.state.decorators.push(this.parseDecorator());
}
if (allowExport && this.match(tt._export)) {
return;
}
if (!this.match(tt._class)) {
this.raise(this.state.start, "Leading decorators must be attached to a class declaration");
}
};
pp.parseDecorator = function () {
if (!this.hasPlugin("decorators")) {
this.unexpected();
}
let node = this.startNode();
this.next();
node.expression = this.parseMaybeAssign();
return this.finishNode(node, "Decorator");
};
pp.parseBreakContinueStatement = function (node, keyword) {
let isBreak = keyword === "break";
this.next();
if (this.isLineTerminator()) {
node.label = null;
} else if (!this.match(tt.name)) {
this.unexpected();
} else {
node.label = this.parseIdentifier();
this.semicolon();
}
// Verify that there is an actual destination to break or
// continue to.
let i;
for (i = 0; i < this.state.labels.length; ++i) {
let lab = this.state.labels[i];
if (node.label == null || lab.name === node.label.name) {
if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
if (node.label && isBreak) break;
}
}
if (i === this.state.labels.length) this.raise(node.start, "Unsyntactic " + keyword);
return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
};
pp.parseDebuggerStatement = function (node) {
this.next();
this.semicolon();
return this.finishNode(node, "DebuggerStatement");
};
pp.parseDoStatement = function (node) {
this.next();
this.state.labels.push(loopLabel);
node.body = this.parseStatement(false);
this.state.labels.pop();
this.expect(tt._while);
node.test = this.parseParenExpression();
this.eat(tt.semi);
return this.finishNode(node, "DoWhileStatement");
};
// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
// loop is non-trivial. Basically, we have to parse the init `var`
// statement or expression, disallowing the `in` operator (see
// the second parameter to `parseExpression`), and then check
// whether the next token is `in` or `of`. When there is no init
// part (semicolon immediately after the opening parenthesis), it
// is a regular `for` loop.
pp.parseForStatement = function (node) {
this.next();
this.state.labels.push(loopLabel);
this.expect(tt.parenL);
if (this.match(tt.semi)) {
return this.parseFor(node, null);
}
if (this.match(tt._var) || this.match(tt._let) || this.match(tt._const)) {
let init = this.startNode(), varKind = this.state.type;
this.next();
this.parseVar(init, true, varKind);
this.finishNode(init, "VariableDeclaration");
if (this.match(tt._in) || this.isContextual("of")) {
if (init.declarations.length === 1 && !init.declarations[0].init) {
return this.parseForIn(node, init);
}
}
return this.parseFor(node, init);
}
let refShorthandDefaultPos = {start: 0};
let init = this.parseExpression(true, refShorthandDefaultPos);
if (this.match(tt._in) || this.isContextual("of")) {
this.toAssignable(init);
this.checkLVal(init);
return this.parseForIn(node, init);
} else if (refShorthandDefaultPos.start) {
this.unexpected(refShorthandDefaultPos.start);
}
return this.parseFor(node, init);
};
pp.parseFunctionStatement = function (node) {
this.next();
return this.parseFunction(node, true);
};
pp.parseIfStatement = function (node) {
this.next();
node.test = this.parseParenExpression();
node.consequent = this.parseStatement(false);
node.alternate = this.eat(tt._else) ? this.parseStatement(false) : null;
return this.finishNode(node, "IfStatement");
};
pp.parseReturnStatement = function (node) {
if (!this.state.inFunction && !this.options.allowReturnOutsideFunction) {
this.raise(this.state.start, "'return' outside of function");
}
this.next();
// In `return` (and `break`/`continue`), the keywords with
// optional arguments, we eagerly look for a semicolon or the
// possibility to insert one.
if (this.isLineTerminator()) {
node.argument = null;
} else {
node.argument = this.parseExpression();
this.semicolon();
}
return this.finishNode(node, "ReturnStatement");
};
pp.parseSwitchStatement = function (node) {
this.next();
node.discriminant = this.parseParenExpression();
node.cases = [];
this.expect(tt.braceL);
this.state.labels.push(switchLabel);
// Statements under must be grouped (by label) in SwitchCase
// nodes. `cur` is used to keep the node that we are currently
// adding statements to.
let cur;
for (let sawDefault; !this.match(tt.braceR); ) {
if (this.match(tt._case) || this.match(tt._default)) {
let isCase = this.match(tt._case);
if (cur) this.finishNode(cur, "SwitchCase");
node.cases.push(cur = this.startNode());
cur.consequent = [];
this.next();
if (isCase) {
cur.test = this.parseExpression();
} else {
if (sawDefault) this.raise(this.state.lastTokStart, "Multiple default clauses");
sawDefault = true;
cur.test = null;
}
this.expect(tt.colon);
} else {
if (cur) {
cur.consequent.push(this.parseStatement(true));
} else {
this.unexpected();
}
}
}
if (cur) this.finishNode(cur, "SwitchCase");
this.next(); // Closing brace
this.state.labels.pop();
return this.finishNode(node, "SwitchStatement");
};
pp.parseThrowStatement = function (node) {
this.next();
if (lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start)))
this.raise(this.state.lastTokEnd, "Illegal newline after throw");
node.argument = this.parseExpression();
this.semicolon();
return this.finishNode(node, "ThrowStatement");
};
// Reused empty array added for node fields that are always empty.
let empty = [];
pp.parseTryStatement = function (node) {
this.next();
node.block = this.parseBlock();
node.handler = null;
if (this.match(tt._catch)) {
let clause = this.startNode();
this.next();
this.expect(tt.parenL);
clause.param = this.parseBindingAtom();
this.checkLVal(clause.param, true, Object.create(null));
this.expect(tt.parenR);
clause.body = this.parseBlock();
node.handler = this.finishNode(clause, "CatchClause");
}
node.guardedHandlers = empty;
node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null;
if (!node.handler && !node.finalizer) {
this.raise(node.start, "Missing catch or finally clause");
}
return this.finishNode(node, "TryStatement");
};
pp.parseVarStatement = function (node, kind) {
this.next();
this.parseVar(node, false, kind);
this.semicolon();
return this.finishNode(node, "VariableDeclaration");
};
pp.parseWhileStatement = function (node) {
this.next();
node.test = this.parseParenExpression();
this.state.labels.push(loopLabel);
node.body = this.parseStatement(false);
this.state.labels.pop();
return this.finishNode(node, "WhileStatement");
};
pp.parseWithStatement = function (node) {
if (this.state.strict) this.raise(this.state.start, "'with' in strict mode");
this.next();
node.object = this.parseParenExpression();
node.body = this.parseStatement(false);
return this.finishNode(node, "WithStatement");
};
pp.parseEmptyStatement = function (node) {
this.next();
return this.finishNode(node, "EmptyStatement");
};
pp.parseLabeledStatement = function (node, maybeName, expr) {
for (let label of (this.state.labels: Array<Object>)){
if (label.name === maybeName) {
this.raise(expr.start, `Label '${maybeName}' is already declared`);
}
}
let kind = this.state.type.isLoop ? "loop" : this.match(tt._switch) ? "switch" : null;
for (let i = this.state.labels.length - 1; i >= 0; i--) {
let label = this.state.labels[i];
if (label.statementStart === node.start) {
label.statementStart = this.state.start;
label.kind = kind;
} else {
break;
}
}
this.state.labels.push({name: maybeName, kind: kind, statementStart: this.state.start});
node.body = this.parseStatement(true);
this.state.labels.pop();
node.label = expr;
return this.finishNode(node, "LabeledStatement");
};
pp.parseExpressionStatement = function (node, expr) {
node.expression = expr;
this.semicolon();
return this.finishNode(node, "ExpressionStatement");
};
// Parse a semicolon-enclosed block of statements, handling `"use
// strict"` declarations when `allowStrict` is true (used for
// function bodies).
pp.parseBlock = function (allowDirectives?) {
let node = this.startNode();
this.expect(tt.braceL);
this.parseBlockBody(node, allowDirectives, false, tt.braceR);
return this.finishNode(node, "BlockStatement");
};
// TODO
pp.parseBlockBody = function (node, allowDirectives, topLevel, end) {
node.body = [];
node.directives = [];
let parsedNonDirective = false;
let oldStrict;
let octalPosition;
while (!this.eat(end)) {
if (!parsedNonDirective && this.state.containsOctal && !octalPosition) {
octalPosition = this.state.octalPosition;
}
let stmt = this.parseStatement(true, topLevel);
if (allowDirectives && !parsedNonDirective &&
stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" &&
!stmt.expression.extra.parenthesized) {
let directive = this.stmtToDirective(stmt);
node.directives.push(directive);
if (oldStrict === undefined && directive.value.value === "use strict") {
oldStrict = this.state.strict;
this.setStrict(true);
if (octalPosition) {
this.raise(octalPosition, "Octal literal in strict mode");
}
}
continue;
}
parsedNonDirective = true;
node.body.push(stmt);
}
if (oldStrict === false) {
this.setStrict(false);
}
};
// Parse a regular `for` loop. The disambiguation code in
// `parseStatement` will already have parsed the init statement or
// expression.
pp.parseFor = function (node, init) {
node.init = init;
this.expect(tt.semi);
node.test = this.match(tt.semi) ? null : this.parseExpression();
this.expect(tt.semi);
node.update = this.match(tt.parenR) ? null : this.parseExpression();
this.expect(tt.parenR);
node.body = this.parseStatement(false);
this.state.labels.pop();
return this.finishNode(node, "ForStatement");
};
// Parse a `for`/`in` and `for`/`of` loop, which are almost
// same from parser's perspective.
pp.parseForIn = function (node, init) {
let type = this.match(tt._in) ? "ForInStatement" : "ForOfStatement";
this.next();
node.left = init;
node.right = this.parseExpression();
this.expect(tt.parenR);
node.body = this.parseStatement(false);
this.state.labels.pop();
return this.finishNode(node, type);
};
// Parse a list of variable declarations.
pp.parseVar = function (node, isFor, kind) {
node.declarations = [];
node.kind = kind.keyword;
for (;;) {
let decl = this.startNode();
this.parseVarHead(decl);
if (this.eat(tt.eq)) {
decl.init = this.parseMaybeAssign(isFor);
} else if (kind === tt._const && !(this.match(tt._in) || this.isContextual("of"))) {
this.unexpected();
} else if (decl.id.type !== "Identifier" && !(isFor && (this.match(tt._in) || this.isContextual("of")))) {
this.raise(this.state.lastTokEnd, "Complex binding patterns require an initialization value");
} else {
decl.init = null;
}
node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
if (!this.eat(tt.comma)) break;
}
return node;
};
pp.parseVarHead = function (decl) {
decl.id = this.parseBindingAtom();
this.checkLVal(decl.id, true);
};
// Parse a function declaration or literal (depending on the
// `isStatement` parameter).
pp.parseFunction = function (node, isStatement, allowExpressionBody, isAsync, optionalId) {
let oldInMethod = this.state.inMethod;
this.state.inMethod = false;
this.initFunction(node, isAsync);
if (this.match(tt.star)) {
if (node.async && !this.hasPlugin("asyncGenerators")) {
this.unexpected();
} else {
node.generator = true;
this.next();
}
}
if (isStatement && !optionalId && !this.match(tt.name) && !this.match(tt._yield)) {
this.unexpected();
}
if (this.match(tt.name) || this.match(tt._yield)) {
node.id = this.parseBindingIdentifier();
}
this.parseFunctionParams(node);
this.parseFunctionBody(node, allowExpressionBody);
this.state.inMethod = oldInMethod;
return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
};
pp.parseFunctionParams = function (node) {
this.expect(tt.parenL);
node.params = this.parseBindingList(tt.parenR, false, this.hasPlugin("trailingFunctionCommas"));
};
// Parse a class declaration or literal (depending on the
// `isStatement` parameter).
pp.parseClass = function (node, isStatement, optionalId) {
this.next();
this.parseClassId(node, isStatement, optionalId);
this.parseClassSuper(node);
this.parseClassBody(node);
return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
};
pp.isClassProperty = function () {
return this.match(tt.eq) || this.match(tt.semi) || this.canInsertSemicolon();
};
pp.parseClassBody = function (node) {
// class bodies are implicitly strict
let oldStrict = this.state.strict;
this.state.strict = true;
let hadConstructorCall = false;
let hadConstructor = false;
let decorators = [];
let classBody = this.startNode();
classBody.body = [];
this.expect(tt.braceL);
while (!this.eat(tt.braceR)) {
if (this.eat(tt.semi)) {
continue;
}
if (this.match(tt.at)) {
decorators.push(this.parseDecorator());
continue;
}
let method = this.startNode();
// steal the decorators if there are any
if (decorators.length) {
method.decorators = decorators;
decorators = [];
}
let isConstructorCall = false;
let isMaybeStatic = this.match(tt.name) && this.state.value === "static";
let isGenerator = this.eat(tt.star);
let isGetSet = false;
let isAsync = false;
this.parsePropertyName(method);
method.static = isMaybeStatic && !this.match(tt.parenL);
if (method.static) {
if (isGenerator) this.unexpected();
isGenerator = this.eat(tt.star);
this.parsePropertyName(method);
}
if (!isGenerator && method.key.type === "Identifier" && !method.computed) {
if (this.isClassProperty()) {
classBody.body.push(this.parseClassProperty(method));
continue;
}
if (this.hasPlugin("classConstructorCall") && method.key.name === "call" && this.match(tt.name) && this.state.value === "constructor") {
isConstructorCall = true;
this.parsePropertyName(method);
}
}
let isAsyncMethod = this.hasPlugin("asyncFunctions") && !this.match(tt.parenL) && !method.computed && method.key.type === "Identifier" && method.key.name === "async";
if (isAsyncMethod) {
if (this.hasPlugin("asyncGenerators") && this.eat(tt.star)) isGenerator = true;
isAsync = true;
this.parsePropertyName(method);
}
method.kind = "method";
if (!method.computed) {
let { key } = method;
// handle get/set methods
// eg. class Foo { get bar() {} set bar() {} }
if (!isAsync && !isGenerator && key.type === "Identifier" && !this.match(tt.parenL) && (key.name === "get" || key.name === "set")) {
isGetSet = true;
method.kind = key.name;
key = this.parsePropertyName(method);
}
// disallow invalid constructors
let isConstructor = !isConstructorCall && !method.static && (
(key.type === "Identifier" && key.name === "constructor") ||
(key.type === "StringLiteral" && key.value === "constructor")
);
if (isConstructor) {
if (hadConstructor) this.raise(key.start, "Duplicate constructor in the same class");
if (isGetSet) this.raise(key.start, "Constructor can't have get/set modifier");
if (isGenerator) this.raise(key.start, "Constructor can't be a generator");
if (isAsync) this.raise(key.start, "Constructor can't be an async function");
method.kind = "constructor";
hadConstructor = true;
}
// disallow static prototype method
let isStaticPrototype = method.static && (
(key.type === "Identifier" && key.name === "prototype") ||
(key.type === "StringLiteral" && key.value === "prototype")
);
if (isStaticPrototype) {
this.raise(key.start, "Classes may not have static property named prototype");
}
}
// convert constructor to a constructor call
if (isConstructorCall) {
if (hadConstructorCall) this.raise(method.start, "Duplicate constructor call in the same class");
method.kind = "constructorCall";
hadConstructorCall = true;
}
// disallow decorators on class constructors
if ((method.kind === "constructor" || method.kind === "constructorCall") && method.decorators) {
this.raise(method.start, "You can't attach decorators to a class constructor");
}
this.parseClassMethod(classBody, method, isGenerator, isAsync);
// get methods aren't allowed to have any parameters
// set methods must have exactly 1 parameter
if (isGetSet) {
let paramCount = method.kind === "get" ? 0 : 1;
if (method.params.length !== paramCount) {
let start = method.start;
if (method.kind === "get") {
this.raise(start, "getter should have no params");
} else {
this.raise(start, "setter should have exactly one param");
}
}
}
}
if (decorators.length) {
this.raise(this.state.start, "You have trailing decorators with no method");
}
node.body = this.finishNode(classBody, "ClassBody");
this.state.strict = oldStrict;
};
pp.parseClassProperty = function (node) {
if (this.match(tt.eq)) {
if (!this.hasPlugin("classProperties")) this.unexpected();
this.next();
node.value = this.parseMaybeAssign();
} else {
node.value = null;
}
if (!this.eat(tt.semi)) {
this.raise(this.state.start, "A semicolon is required after a class property");
}
return this.finishNode(node, "ClassProperty");
};
pp.parseClassMethod = function (classBody, method, isGenerator, isAsync) {
this.parseMethod(method, isGenerator, isAsync);
classBody.body.push(this.finishNode(method, "ClassMethod"));
};
pp.parseClassId = function (node, isStatement, optionalId) {
if (this.match(tt.name)) {
node.id = this.parseIdentifier();
} else {
if (optionalId || !isStatement) {
node.id = null;
} else {
this.unexpected();
}
}
};
pp.parseClassSuper = function (node) {
node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null;
};
// Parses module export declaration.
pp.parseExport = function (node) {
this.next();
// export * from '...'
if (this.match(tt.star)) {
let specifier = this.startNode();
this.next();
if (this.hasPlugin("exportExtensions") && this.eatContextual("as")) {
specifier.exported = this.parseIdentifier();
node.specifiers = [this.finishNode(specifier, "ExportNamespaceSpecifier")];
this.parseExportSpecifiersMaybe(node);
this.parseExportFrom(node, true);
} else {
this.parseExportFrom(node, true);
return this.finishNode(node, "ExportAllDeclaration");
}
} else if (this.hasPlugin("exportExtensions") && this.isExportDefaultSpecifier()) {
let specifier = this.startNode();
specifier.exported = this.parseIdentifier(true);
node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
if (this.match(tt.comma) && this.lookahead().type === tt.star) {
this.expect(tt.comma);
let specifier = this.startNode();
this.expect(tt.star);
this.expectContextual("as");
specifier.exported = this.parseIdentifier();
node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
} else {
this.parseExportSpecifiersMaybe(node);
}
this.parseExportFrom(node, true);
} else if (this.eat(tt._default)) { // export default ...
let expr = this.startNode();
let needsSemi = false;
if (this.eat(tt._function)) {
expr = this.parseFunction(expr, true, false, false, true);
} else if (this.match(tt._class)) {
expr = this.parseClass(expr, true, true);
} else {
needsSemi = true;
expr = this.parseMaybeAssign();
}
node.declaration = expr;
if (needsSemi) this.semicolon();
this.checkExport(node);
return this.finishNode(node, "ExportDefaultDeclaration");
} else if (this.state.type.keyword || this.shouldParseExportDeclaration()) {
node.specifiers = [];
node.source = null;
node.declaration = this.parseExportDeclaration(node);
} else { // export { x, y as z } [from '...']
node.declaration = null;
node.specifiers = this.parseExportSpecifiers();
this.parseExportFrom(node);
}
this.checkExport(node);
return this.finishNode(node, "ExportNamedDeclaration");
};
pp.parseExportDeclaration = function () {
return this.parseStatement(true);
};
pp.isExportDefaultSpecifier = function () {
if (this.match(tt.name)) {
return this.state.value !== "type"
&& this.state.value !== "async"
&& this.state.value !== "interface";
}
if (!this.match(tt._default)) {
return false;
}
let lookahead = this.lookahead();
return lookahead.type === tt.comma || (lookahead.type === tt.name && lookahead.value === "from");
};
pp.parseExportSpecifiersMaybe = function (node) {
if (this.eat(tt.comma)) {
node.specifiers = node.specifiers.concat(this.parseExportSpecifiers());
}
};
pp.parseExportFrom = function (node, expect?) {
if (this.eatContextual("from")) {
node.source = this.match(tt.string) ? this.parseExprAtom() : this.unexpected();
this.checkExport(node);
} else {
if (expect) {
this.unexpected();
} else {
node.source = null;
}
}
this.semicolon();
};
pp.shouldParseExportDeclaration = function () {
return this.hasPlugin("asyncFunctions") && this.isContextual("async");
};
pp.checkExport = function (node) {
if (this.state.decorators.length) {
let isClass = node.declaration && (node.declaration.type === "ClassDeclaration" || node.declaration.type === "ClassExpression");
if (!node.declaration || !isClass) {
this.raise(node.start, "You can only use decorators on an export when exporting a class");
}
this.takeDecorators(node.declaration);
}
};
// Parses a comma-separated list of module exports.
pp.parseExportSpecifiers = function () {
let nodes = [];
let first = true;
let needsFrom;
// export { x, y as z } [from '...']
this.expect(tt.braceL);
while (!this.eat(tt.braceR)) {
if (first) {
first = false;
} else {
this.expect(tt.comma);
if (this.eat(tt.braceR)) break;
}
let isDefault = this.match(tt._default);
if (isDefault && !needsFrom) needsFrom = true;
let node = this.startNode();
node.local = this.parseIdentifier(isDefault);
node.exported = this.eatContextual("as") ? this.parseIdentifier(true) : node.local.__clone();
nodes.push(this.finishNode(node, "ExportSpecifier"));
}
// https://github.com/ember-cli/ember-cli/pull/3739
if (needsFrom && !this.isContextual("from")) {
this.unexpected();
}
return nodes;
};
// Parses import declaration.
pp.parseImport = function (node) {
this.next();
// import '...'
if (this.match(tt.string)) {
node.specifiers = [];
node.source = this.parseExprAtom();
} else {
node.specifiers = [];
this.parseImportSpecifiers(node);
this.expectContextual("from");
node.source = this.match(tt.string) ? this.parseExprAtom() : this.unexpected();
}
this.semicolon();
return this.finishNode(node, "ImportDeclaration");
};
// Parses a comma-separated list of module imports.
pp.parseImportSpecifiers = function (node) {
let first = true;
if (this.match(tt.name)) {
// import defaultObj, { x, y as z } from '...'
let startPos = this.state.start, startLoc = this.state.startLoc;
node.specifiers.push(this.parseImportSpecifierDefault(this.parseIdentifier(), startPos, startLoc));
if (!this.eat(tt.comma)) return;
}
if (this.match(tt.star)) {
let specifier = this.startNode();
this.next();
this.expectContextual("as");
specifier.local = this.parseIdentifier();
this.checkLVal(specifier.local, true);
node.specifiers.push(this.finishNode(specifier, "ImportNamespaceSpecifier"));
return;
}
this.expect(tt.braceL);
while (!this.eat(tt.braceR)) {
if (first) {
first = false;
} else {
this.expect(tt.comma);
if (this.eat(tt.braceR)) break;
}
let specifier = this.startNode();
specifier.imported = this.parseIdentifier(true);
specifier.local = this.eatContextual("as") ? this.parseIdentifier() : specifier.imported.__clone();
this.checkLVal(specifier.local, true);
node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
}
};
pp.parseImportSpecifierDefault = function (id, startPos, startLoc) {
let node = this.startNodeAt(startPos, startLoc);
node.local = id;
this.checkLVal(node.local, true);
return this.finishNode(node, "ImportDefaultSpecifier");
};
| packages/babylon/src/parser/statement.js | 1 | https://github.com/babel/babel/commit/f31099f383b52cf4fe1786188f6421529dea865b | [
0.008027584291994572,
0.0003010464133694768,
0.00016412987315561622,
0.0001698680134722963,
0.0008169294451363385
]
|
{
"id": 2,
"code_window": [
"{\n",
" \"throws\": \"A semicolon is required after a class property (3:0)\",\n",
" \"plugins\": [\"classProperties\"]\n",
"}"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"throws\": \"A semicolon is required after a class property (2:6)\",\n"
],
"file_path": "packages/babylon/test/fixtures/experimental/class-properties/semicolons-required-without-value/options.json",
"type": "replace",
"edit_start_line_idx": 1
} | var single = 'quotes';
var outnumber = 'double';
var moreSingleQuotesThanDouble = '!';
React.createClass({
render() {
return <View multiple="attributes" attribute="If parent is JSX keep double quote" />;
}
});
| packages/babel-generator/test/fixtures/auto-string/jsx/expected.js | 0 | https://github.com/babel/babel/commit/f31099f383b52cf4fe1786188f6421529dea865b | [
0.00018515263218432665,
0.00018515263218432665,
0.00018515263218432665,
0.00018515263218432665,
0
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.