hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 5,
"code_window": [
"\t| ICustomRendererMessage\n",
"\t| IClickedDataUrlMessage\n",
"\t| IFocusMarkdownPreviewMessage\n",
"\t| IToggleMarkdownPreviewMessage\n",
"\t| ICellDragStartMessage\n",
"\t| ICellDragMessage\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t| IMouseEnterMarkdownPreviewMessage\n",
"\t| IMouseLeaveMarkdownPreviewMessage\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView.ts",
"type": "add",
"edit_start_line_idx": 273
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
//@ts-check
'use strict';
/**
* Add support for redirecting the loading of node modules
*
* @param {string} injectPath
*/
exports.injectNodeModuleLookupPath = function (injectPath) {
if (!injectPath) {
throw new Error('Missing injectPath');
}
const Module = require('module');
const path = require('path');
const nodeModulesPath = path.join(__dirname, '../node_modules');
// @ts-ignore
const originalResolveLookupPaths = Module._resolveLookupPaths;
// @ts-ignore
Module._resolveLookupPaths = function (moduleName, parent) {
const paths = originalResolveLookupPaths(moduleName, parent);
if (Array.isArray(paths)) {
for (let i = 0, len = paths.length; i < len; i++) {
if (paths[i] === nodeModulesPath) {
paths.splice(i, 0, injectPath);
break;
}
}
}
return paths;
};
};
exports.removeGlobalNodeModuleLookupPaths = function () {
const Module = require('module');
// @ts-ignore
const globalPaths = Module.globalPaths;
// @ts-ignore
const originalResolveLookupPaths = Module._resolveLookupPaths;
// @ts-ignore
Module._resolveLookupPaths = function (moduleName, parent) {
const paths = originalResolveLookupPaths(moduleName, parent);
let commonSuffixLength = 0;
while (commonSuffixLength < paths.length && paths[paths.length - 1 - commonSuffixLength] === globalPaths[globalPaths.length - 1 - commonSuffixLength]) {
commonSuffixLength++;
}
return paths.slice(0, paths.length - commonSuffixLength);
};
};
/**
* Helper to enable portable mode.
*
* @param {Partial<import('./vs/platform/product/common/productService').IProductConfiguration>} product
* @returns {{ portableDataPath: string; isPortable: boolean; }}
*/
exports.configurePortable = function (product) {
const fs = require('fs');
const path = require('path');
const appRoot = path.dirname(__dirname);
/**
* @param {import('path')} path
*/
function getApplicationPath(path) {
if (process.env['VSCODE_DEV']) {
return appRoot;
}
if (process.platform === 'darwin') {
return path.dirname(path.dirname(path.dirname(appRoot)));
}
return path.dirname(path.dirname(appRoot));
}
/**
* @param {import('path')} path
*/
function getPortableDataPath(path) {
if (process.env['VSCODE_PORTABLE']) {
return process.env['VSCODE_PORTABLE'];
}
if (process.platform === 'win32' || process.platform === 'linux') {
return path.join(getApplicationPath(path), 'data');
}
// @ts-ignore
const portableDataName = product.portable || `${product.applicationName}-portable-data`;
return path.join(path.dirname(getApplicationPath(path)), portableDataName);
}
const portableDataPath = getPortableDataPath(path);
const isPortable = !('target' in product) && fs.existsSync(portableDataPath);
const portableTempPath = path.join(portableDataPath, 'tmp');
const isTempPortable = isPortable && fs.existsSync(portableTempPath);
if (isPortable) {
process.env['VSCODE_PORTABLE'] = portableDataPath;
} else {
delete process.env['VSCODE_PORTABLE'];
}
if (isTempPortable) {
if (process.platform === 'win32') {
process.env['TMP'] = portableTempPath;
process.env['TEMP'] = portableTempPath;
} else {
process.env['TMPDIR'] = portableTempPath;
}
}
return {
portableDataPath,
isPortable
};
};
| src/bootstrap-node.js | 0 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.00019714310474228114,
0.00017227914941031486,
0.00016593985492363572,
0.00017000189109239727,
0.000007342701792367734
] |
{
"id": 5,
"code_window": [
"\t| ICustomRendererMessage\n",
"\t| IClickedDataUrlMessage\n",
"\t| IFocusMarkdownPreviewMessage\n",
"\t| IToggleMarkdownPreviewMessage\n",
"\t| ICellDragStartMessage\n",
"\t| ICellDragMessage\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t| IMouseEnterMarkdownPreviewMessage\n",
"\t| IMouseLeaveMarkdownPreviewMessage\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView.ts",
"type": "add",
"edit_start_line_idx": 273
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as objects from 'vs/base/common/objects';
import * as types from 'vs/base/common/types';
import { URI, UriComponents } from 'vs/base/common/uri';
import { Event } from 'vs/base/common/event';
import { Registry } from 'vs/platform/registry/common/platform';
import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IConfigurationRegistry, Extensions, OVERRIDE_PROPERTY_PATTERN, overrideIdentifierFromKey } from 'vs/platform/configuration/common/configurationRegistry';
import { IStringDictionary } from 'vs/base/common/collections';
export const IConfigurationService = createDecorator<IConfigurationService>('configurationService');
export function isConfigurationOverrides(thing: any): thing is IConfigurationOverrides {
return thing
&& typeof thing === 'object'
&& (!thing.overrideIdentifier || typeof thing.overrideIdentifier === 'string')
&& (!thing.resource || thing.resource instanceof URI);
}
export interface IConfigurationOverrides {
overrideIdentifier?: string | null;
resource?: URI | null;
}
export const enum ConfigurationTarget {
USER = 1,
USER_LOCAL,
USER_REMOTE,
WORKSPACE,
WORKSPACE_FOLDER,
DEFAULT,
MEMORY
}
export function ConfigurationTargetToString(configurationTarget: ConfigurationTarget) {
switch (configurationTarget) {
case ConfigurationTarget.USER: return 'USER';
case ConfigurationTarget.USER_LOCAL: return 'USER_LOCAL';
case ConfigurationTarget.USER_REMOTE: return 'USER_REMOTE';
case ConfigurationTarget.WORKSPACE: return 'WORKSPACE';
case ConfigurationTarget.WORKSPACE_FOLDER: return 'WORKSPACE_FOLDER';
case ConfigurationTarget.DEFAULT: return 'DEFAULT';
case ConfigurationTarget.MEMORY: return 'MEMORY';
}
}
export interface IConfigurationChange {
keys: string[];
overrides: [string, string[]][];
}
export interface IConfigurationChangeEvent {
readonly source: ConfigurationTarget;
readonly affectedKeys: string[];
readonly change: IConfigurationChange;
affectsConfiguration(configuration: string, overrides?: IConfigurationOverrides): boolean;
// Following data is used for telemetry
readonly sourceConfig: any;
}
export interface IConfigurationValue<T> {
readonly defaultValue?: T;
readonly userValue?: T;
readonly userLocalValue?: T;
readonly userRemoteValue?: T;
readonly workspaceValue?: T;
readonly workspaceFolderValue?: T;
readonly memoryValue?: T;
readonly value?: T;
readonly default?: { value?: T, override?: T };
readonly user?: { value?: T, override?: T };
readonly userLocal?: { value?: T, override?: T };
readonly userRemote?: { value?: T, override?: T };
readonly workspace?: { value?: T, override?: T };
readonly workspaceFolder?: { value?: T, override?: T };
readonly memory?: { value?: T, override?: T };
readonly overrideIdentifiers?: string[];
}
export interface IConfigurationService {
readonly _serviceBrand: undefined;
onDidChangeConfiguration: Event<IConfigurationChangeEvent>;
getConfigurationData(): IConfigurationData | null;
/**
* Fetches the value of the section for the given overrides.
* Value can be of native type or an object keyed off the section name.
*
* @param section - Section of the configuraion. Can be `null` or `undefined`.
* @param overrides - Overrides that has to be applied while fetching
*
*/
getValue<T>(): T;
getValue<T>(section: string): T;
getValue<T>(overrides: IConfigurationOverrides): T;
getValue<T>(section: string, overrides: IConfigurationOverrides): T;
updateValue(key: string, value: any): Promise<void>;
updateValue(key: string, value: any, overrides: IConfigurationOverrides): Promise<void>;
updateValue(key: string, value: any, target: ConfigurationTarget): Promise<void>;
updateValue(key: string, value: any, overrides: IConfigurationOverrides, target: ConfigurationTarget, donotNotifyError?: boolean): Promise<void>;
inspect<T>(key: string, overrides?: IConfigurationOverrides): IConfigurationValue<T>;
reloadConfiguration(target?: ConfigurationTarget | IWorkspaceFolder): Promise<void>;
keys(): {
default: string[];
user: string[];
workspace: string[];
workspaceFolder: string[];
memory?: string[];
};
}
export interface IConfigurationModel {
contents: any;
keys: string[];
overrides: IOverrides[];
}
export interface IOverrides {
keys: string[];
contents: any;
identifiers: string[];
}
export interface IConfigurationData {
defaults: IConfigurationModel;
user: IConfigurationModel;
workspace: IConfigurationModel;
folders: [UriComponents, IConfigurationModel][];
}
export interface IConfigurationCompareResult {
added: string[];
removed: string[];
updated: string[];
overrides: [string, string[]][];
}
export function compare(from: IConfigurationModel | undefined, to: IConfigurationModel | undefined): IConfigurationCompareResult {
const added = to
? from ? to.keys.filter(key => from.keys.indexOf(key) === -1) : [...to.keys]
: [];
const removed = from
? to ? from.keys.filter(key => to.keys.indexOf(key) === -1) : [...from.keys]
: [];
const updated: string[] = [];
if (to && from) {
for (const key of from.keys) {
if (to.keys.indexOf(key) !== -1) {
const value1 = getConfigurationValue(from.contents, key);
const value2 = getConfigurationValue(to.contents, key);
if (!objects.equals(value1, value2)) {
updated.push(key);
}
}
}
}
const overrides: [string, string[]][] = [];
const byOverrideIdentifier = (overrides: IOverrides[]): IStringDictionary<IOverrides> => {
const result: IStringDictionary<IOverrides> = {};
for (const override of overrides) {
for (const identifier of override.identifiers) {
result[keyFromOverrideIdentifier(identifier)] = override;
}
}
return result;
};
const toOverridesByIdentifier: IStringDictionary<IOverrides> = to ? byOverrideIdentifier(to.overrides) : {};
const fromOverridesByIdentifier: IStringDictionary<IOverrides> = from ? byOverrideIdentifier(from.overrides) : {};
if (Object.keys(toOverridesByIdentifier).length) {
for (const key of added) {
const override = toOverridesByIdentifier[key];
if (override) {
overrides.push([overrideIdentifierFromKey(key), override.keys]);
}
}
}
if (Object.keys(fromOverridesByIdentifier).length) {
for (const key of removed) {
const override = fromOverridesByIdentifier[key];
if (override) {
overrides.push([overrideIdentifierFromKey(key), override.keys]);
}
}
}
if (Object.keys(toOverridesByIdentifier).length && Object.keys(fromOverridesByIdentifier).length) {
for (const key of updated) {
const fromOverride = fromOverridesByIdentifier[key];
const toOverride = toOverridesByIdentifier[key];
if (fromOverride && toOverride) {
const result = compare({ contents: fromOverride.contents, keys: fromOverride.keys, overrides: [] }, { contents: toOverride.contents, keys: toOverride.keys, overrides: [] });
overrides.push([overrideIdentifierFromKey(key), [...result.added, ...result.removed, ...result.updated]]);
}
}
}
return { added, removed, updated, overrides };
}
export function toOverrides(raw: any, conflictReporter: (message: string) => void): IOverrides[] {
const overrides: IOverrides[] = [];
for (const key of Object.keys(raw)) {
if (OVERRIDE_PROPERTY_PATTERN.test(key)) {
const overrideRaw: any = {};
for (const keyInOverrideRaw in raw[key]) {
overrideRaw[keyInOverrideRaw] = raw[key][keyInOverrideRaw];
}
overrides.push({
identifiers: [overrideIdentifierFromKey(key).trim()],
keys: Object.keys(overrideRaw),
contents: toValuesTree(overrideRaw, conflictReporter)
});
}
}
return overrides;
}
export function toValuesTree(properties: { [qualifiedKey: string]: any }, conflictReporter: (message: string) => void): any {
const root = Object.create(null);
for (let key in properties) {
addToValueTree(root, key, properties[key], conflictReporter);
}
return root;
}
export function addToValueTree(settingsTreeRoot: any, key: string, value: any, conflictReporter: (message: string) => void): void {
const segments = key.split('.');
const last = segments.pop()!;
let curr = settingsTreeRoot;
for (let i = 0; i < segments.length; i++) {
let s = segments[i];
let obj = curr[s];
switch (typeof obj) {
case 'undefined':
obj = curr[s] = Object.create(null);
break;
case 'object':
break;
default:
conflictReporter(`Ignoring ${key} as ${segments.slice(0, i + 1).join('.')} is ${JSON.stringify(obj)}`);
return;
}
curr = obj;
}
if (typeof curr === 'object' && curr !== null) {
try {
curr[last] = value; // workaround https://github.com/microsoft/vscode/issues/13606
} catch (e) {
conflictReporter(`Ignoring ${key} as ${segments.join('.')} is ${JSON.stringify(curr)}`);
}
} else {
conflictReporter(`Ignoring ${key} as ${segments.join('.')} is ${JSON.stringify(curr)}`);
}
}
export function removeFromValueTree(valueTree: any, key: string): void {
const segments = key.split('.');
doRemoveFromValueTree(valueTree, segments);
}
function doRemoveFromValueTree(valueTree: any, segments: string[]): void {
const first = segments.shift()!;
if (segments.length === 0) {
// Reached last segment
delete valueTree[first];
return;
}
if (Object.keys(valueTree).indexOf(first) !== -1) {
const value = valueTree[first];
if (typeof value === 'object' && !Array.isArray(value)) {
doRemoveFromValueTree(value, segments);
if (Object.keys(value).length === 0) {
delete valueTree[first];
}
}
}
}
/**
* A helper function to get the configuration value with a specific settings path (e.g. config.some.setting)
*/
export function getConfigurationValue<T>(config: any, settingPath: string, defaultValue?: T): T {
function accessSetting(config: any, path: string[]): any {
let current = config;
for (const component of path) {
if (typeof current !== 'object' || current === null) {
return undefined;
}
current = current[component];
}
return <T>current;
}
const path = settingPath.split('.');
const result = accessSetting(config, path);
return typeof result === 'undefined' ? defaultValue : result;
}
export function merge(base: any, add: any, overwrite: boolean): void {
Object.keys(add).forEach(key => {
if (key !== '__proto__') {
if (key in base) {
if (types.isObject(base[key]) && types.isObject(add[key])) {
merge(base[key], add[key], overwrite);
} else if (overwrite) {
base[key] = add[key];
}
} else {
base[key] = add[key];
}
}
});
}
export function getConfigurationKeys(): string[] {
const properties = Registry.as<IConfigurationRegistry>(Extensions.Configuration).getConfigurationProperties();
return Object.keys(properties);
}
export function getDefaultValues(): any {
const valueTreeRoot: any = Object.create(null);
const properties = Registry.as<IConfigurationRegistry>(Extensions.Configuration).getConfigurationProperties();
for (let key in properties) {
let value = properties[key].default;
addToValueTree(valueTreeRoot, key, value, message => console.error(`Conflict in default settings: ${message}`));
}
return valueTreeRoot;
}
export function keyFromOverrideIdentifier(overrideIdentifier: string): string {
return `[${overrideIdentifier}]`;
}
export function getMigratedSettingValue<T>(configurationService: IConfigurationService, currentSettingName: string, legacySettingName: string): T {
const setting = configurationService.inspect<T>(currentSettingName);
const legacySetting = configurationService.inspect<T>(legacySettingName);
if (typeof setting.userValue !== 'undefined' || typeof setting.workspaceValue !== 'undefined' || typeof setting.workspaceFolderValue !== 'undefined') {
return setting.value!;
} else if (typeof legacySetting.userValue !== 'undefined' || typeof legacySetting.workspaceValue !== 'undefined' || typeof legacySetting.workspaceFolderValue !== 'undefined') {
return legacySetting.value!;
} else {
return setting.defaultValue!;
}
}
| src/vs/platform/configuration/common/configuration.ts | 0 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.00018589702085591853,
0.00016992590099107474,
0.00016478396719321609,
0.00016924520605243742,
0.000003577349616534775
] |
{
"id": 6,
"code_window": [
"\t\t\t\t\tif (cell) {\n",
"\t\t\t\t\t\tthis.notebookEditor.focusNotebookCell(cell, 'container');\n",
"\t\t\t\t\t}\n",
"\t\t\t\t} else if (data.type === 'toggleMarkdownPreview') {\n",
"\t\t\t\t\tthis.notebookEditor.setMarkdownCellEditState(data.cellId, CellEditState.Editing);\n",
"\t\t\t\t} else if (data.type === 'cell-drag-start') {\n",
"\t\t\t\t\tthis.notebookEditor.markdownCellDragStart(data.cellId, data.position);\n",
"\t\t\t\t} else if (data.type === 'cell-drag') {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t} else if (data.type === 'mouseEnterMarkdownPreview') {\n",
"\t\t\t\t\tconst cell = this.notebookEditor.getCellById(data.cellId);\n",
"\t\t\t\t\tif (cell instanceof MarkdownCellViewModel) {\n",
"\t\t\t\t\t\tcell.cellIsHovered = true;\n",
"\t\t\t\t\t}\n",
"\t\t\t\t} else if (data.type === 'mouseLeaveMarkdownPreview') {\n",
"\t\t\t\t\tconst cell = this.notebookEditor.getCellById(data.cellId);\n",
"\t\t\t\t\tif (cell instanceof MarkdownCellViewModel) {\n",
"\t\t\t\t\t\tcell.cellIsHovered = false;\n",
"\t\t\t\t\t}\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView.ts",
"type": "add",
"edit_start_line_idx": 799
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter, Event } from 'vs/base/common/event';
import * as UUID from 'vs/base/common/uuid';
import * as editorCommon from 'vs/editor/common/editorCommon';
import * as model from 'vs/editor/common/model';
import * as nls from 'vs/nls';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { BOTTOM_CELL_TOOLBAR_GAP, BOTTOM_CELL_TOOLBAR_HEIGHT, CELL_BOTTOM_MARGIN, CELL_MARGIN, CELL_TOP_MARGIN, CODE_CELL_LEFT_MARGIN, COLLAPSED_INDICATOR_HEIGHT } from 'vs/workbench/contrib/notebook/browser/constants';
import { EditorFoldingStateDelegate } from 'vs/workbench/contrib/notebook/browser/contrib/fold/foldingModel';
import { CellFindMatch, ICellOutputViewModel, ICellViewModel, MarkdownCellLayoutChangeEvent, MarkdownCellLayoutInfo, NotebookLayoutInfo } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { MarkdownRenderer } from 'vs/editor/browser/core/markdownRenderer';
import { BaseCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/baseCellViewModel';
import { NotebookCellStateChangedEvent, NotebookEventDispatcher } from 'vs/workbench/contrib/notebook/browser/viewModel/eventDispatcher';
import { NotebookCellTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookCellTextModel';
import { CellKind, INotebookSearchOptions } from 'vs/workbench/contrib/notebook/common/notebookCommon';
export class MarkdownCellViewModel extends BaseCellViewModel implements ICellViewModel {
readonly cellKind = CellKind.Markdown;
private _html: HTMLElement | null = null;
private _layoutInfo: MarkdownCellLayoutInfo;
get layoutInfo() {
return this._layoutInfo;
}
set renderedMarkdownHeight(newHeight: number) {
const newTotalHeight = newHeight + BOTTOM_CELL_TOOLBAR_GAP;
this.totalHeight = newTotalHeight;
}
private set totalHeight(newHeight: number) {
if (newHeight !== this.layoutInfo.totalHeight) {
this.layoutChange({ totalHeight: newHeight });
}
}
private get totalHeight() {
throw new Error('MarkdownCellViewModel.totalHeight is write only');
}
private _editorHeight = 0;
set editorHeight(newHeight: number) {
this._editorHeight = newHeight;
this.totalHeight = this._editorHeight + CELL_TOP_MARGIN + CELL_BOTTOM_MARGIN + BOTTOM_CELL_TOOLBAR_GAP + this.getEditorStatusbarHeight();
}
get editorHeight() {
throw new Error('MarkdownCellViewModel.editorHeight is write only');
}
protected readonly _onDidChangeLayout = new Emitter<MarkdownCellLayoutChangeEvent>();
readonly onDidChangeLayout = this._onDidChangeLayout.event;
get foldingState() {
return this.foldingDelegate.getFoldingState(this.foldingDelegate.getCellIndex(this));
}
private _hoveringOutput: boolean = false;
public get outputIsHovered(): boolean {
return this._hoveringOutput;
}
public set outputIsHovered(v: boolean) {
this._hoveringOutput = v;
}
constructor(
readonly viewType: string,
readonly model: NotebookCellTextModel,
initialNotebookLayoutInfo: NotebookLayoutInfo | null,
readonly foldingDelegate: EditorFoldingStateDelegate,
readonly eventDispatcher: NotebookEventDispatcher,
private readonly _mdRenderer: MarkdownRenderer,
@IConfigurationService configurationService: IConfigurationService
) {
super(viewType, model, UUID.generateUuid(), configurationService);
this._layoutInfo = {
editorHeight: 0,
fontInfo: initialNotebookLayoutInfo?.fontInfo || null,
editorWidth: initialNotebookLayoutInfo?.width ? this.computeEditorWidth(initialNotebookLayoutInfo.width) : 0,
bottomToolbarOffset: BOTTOM_CELL_TOOLBAR_GAP,
totalHeight: 0
};
this._register(this.onDidChangeState(e => {
eventDispatcher.emit([new NotebookCellStateChangedEvent(e, this)]);
}));
}
/**
* we put outputs stuff here to make compiler happy
*/
outputsViewModels: ICellOutputViewModel[] = [];
getOutputOffset(index: number): number {
// throw new Error('Method not implemented.');
return -1;
}
updateOutputHeight(index: number, height: number): void {
// throw new Error('Method not implemented.');
}
triggerfoldingStateChange() {
this._onDidChangeState.fire({ foldingStateChanged: true });
}
private computeEditorWidth(outerWidth: number) {
return outerWidth - (CELL_MARGIN * 2) - CODE_CELL_LEFT_MARGIN;
}
layoutChange(state: MarkdownCellLayoutChangeEvent) {
// recompute
if (!this.metadata?.inputCollapsed) {
const editorWidth = state.outerWidth !== undefined ? this.computeEditorWidth(state.outerWidth) : this._layoutInfo.editorWidth;
const totalHeight = state.totalHeight === undefined ? this._layoutInfo.totalHeight : state.totalHeight;
this._layoutInfo = {
fontInfo: state.font || this._layoutInfo.fontInfo,
editorWidth,
editorHeight: this._editorHeight,
bottomToolbarOffset: totalHeight - BOTTOM_CELL_TOOLBAR_GAP - BOTTOM_CELL_TOOLBAR_HEIGHT / 2,
totalHeight
};
} else {
const editorWidth = state.outerWidth !== undefined ? this.computeEditorWidth(state.outerWidth) : this._layoutInfo.editorWidth;
const totalHeight = CELL_TOP_MARGIN + COLLAPSED_INDICATOR_HEIGHT + BOTTOM_CELL_TOOLBAR_GAP + CELL_BOTTOM_MARGIN;
state.totalHeight = totalHeight;
this._layoutInfo = {
fontInfo: state.font || this._layoutInfo.fontInfo,
editorWidth,
editorHeight: this._editorHeight,
bottomToolbarOffset: totalHeight - BOTTOM_CELL_TOOLBAR_GAP - BOTTOM_CELL_TOOLBAR_HEIGHT / 2,
totalHeight
};
}
this._onDidChangeLayout.fire(state);
}
restoreEditorViewState(editorViewStates: editorCommon.ICodeEditorViewState | null, totalHeight?: number) {
super.restoreEditorViewState(editorViewStates);
if (totalHeight !== undefined) {
this._layoutInfo = {
fontInfo: this._layoutInfo.fontInfo,
editorWidth: this._layoutInfo.editorWidth,
bottomToolbarOffset: this._layoutInfo.bottomToolbarOffset,
totalHeight: totalHeight,
editorHeight: this._editorHeight
};
this.layoutChange({});
}
}
hasDynamicHeight() {
return false;
}
getHeight(lineHeight: number) {
if (this._layoutInfo.totalHeight === 0) {
return 100;
} else {
return this._layoutInfo.totalHeight;
}
}
clearHTML() {
this._html = null;
}
getHTML(): HTMLElement | null {
if (this.cellKind === CellKind.Markdown) {
if (this._html) {
return this._html;
}
const renderer = this.getMarkdownRenderer();
const text = this.getText();
if (text.length === 0) {
const el = document.createElement('p');
el.className = 'emptyMarkdownPlaceholder';
el.innerText = nls.localize('notebook.emptyMarkdownPlaceholder', "Empty markdown cell, double click or press enter to edit.");
this._html = el;
} else {
this._html = renderer.render({ value: this.getText(), isTrusted: true }, undefined, { gfm: true }).element;
}
return this._html;
}
return null;
}
async resolveTextModel(): Promise<model.ITextModel> {
if (!this.textModel) {
const ref = await this.model.resolveTextModelRef();
this.textModel = ref.object.textEditorModel;
this._register(ref);
this._register(this.textModel.onDidChangeContent(() => {
this._html = null;
this._onDidChangeState.fire({ contentChanged: true });
}));
}
return this.textModel;
}
onDeselect() {
}
getMarkdownRenderer() {
return this._mdRenderer;
}
private readonly _hasFindResult = this._register(new Emitter<boolean>());
public readonly hasFindResult: Event<boolean> = this._hasFindResult.event;
startFind(value: string, options: INotebookSearchOptions): CellFindMatch | null {
const matches = super.cellStartFind(value, options);
if (matches === null) {
return null;
}
return {
cell: this,
matches
};
}
}
| src/vs/workbench/contrib/notebook/browser/viewModel/markdownCellViewModel.ts | 1 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.0037673318292945623,
0.00033617063309066,
0.00016370491357520223,
0.00017163169104605913,
0.0007162648253142834
] |
{
"id": 6,
"code_window": [
"\t\t\t\t\tif (cell) {\n",
"\t\t\t\t\t\tthis.notebookEditor.focusNotebookCell(cell, 'container');\n",
"\t\t\t\t\t}\n",
"\t\t\t\t} else if (data.type === 'toggleMarkdownPreview') {\n",
"\t\t\t\t\tthis.notebookEditor.setMarkdownCellEditState(data.cellId, CellEditState.Editing);\n",
"\t\t\t\t} else if (data.type === 'cell-drag-start') {\n",
"\t\t\t\t\tthis.notebookEditor.markdownCellDragStart(data.cellId, data.position);\n",
"\t\t\t\t} else if (data.type === 'cell-drag') {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t} else if (data.type === 'mouseEnterMarkdownPreview') {\n",
"\t\t\t\t\tconst cell = this.notebookEditor.getCellById(data.cellId);\n",
"\t\t\t\t\tif (cell instanceof MarkdownCellViewModel) {\n",
"\t\t\t\t\t\tcell.cellIsHovered = true;\n",
"\t\t\t\t\t}\n",
"\t\t\t\t} else if (data.type === 'mouseLeaveMarkdownPreview') {\n",
"\t\t\t\t\tconst cell = this.notebookEditor.getCellById(data.cellId);\n",
"\t\t\t\t\tif (cell instanceof MarkdownCellViewModel) {\n",
"\t\t\t\t\t\tcell.cellIsHovered = false;\n",
"\t\t\t\t\t}\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView.ts",
"type": "add",
"edit_start_line_idx": 799
} | .PHONY: all
all: echo hello
.PHONY: hello
hello: main.o factorial.o \
hello.o $(first) $($(filter second,second)) \
# This is a long \
comment inside prerequisites.
g++ main.o factorial.o hello.o -o hello
# There are a building steps \
below. And the tab is at the beginning of this line.
main.o: main.cpp
g++ -c main.cpp
factorial.o: factorial.cpp
g++ -c factorial.cpp $(fake_variable)
hello.o: hello.cpp \
$(Colorizing with tabs at the beginning of the second line of prerequisites)
g++ -c hello.cpp -o $@
.PHONY: clean
clean:
rm *o hello
.PHONY: var
var:
# "$$" in a shell means to escape makefile's variable substitution.
some_shell_var=$$(sed -nre 's/some regex with (group)/\1/p')
.PHONY: echo
echo:
echo "#" and '#' in quotes are not comments \
and '\' will be continued
@echo Shell is not printed out, just a message.
@-+-+echo Error will be ignored here; invalidcommand
# And we can see variables are highlited as supposed to be:
@echo '$(CC) $(shell echo "123") -o $@'
@-./point-and-slash-should-not-be-highlighted
define defined
$(info Checking existance of $(1) $(flavor $(1)))
$(if $(filter undefined,$(flavor $(1))),0,1)
endef
ifeq ($(strip $(call defined,TOP_DIR)),0)
$(info TOP_DIR must be set before including paths.mk)
endif
-include $(TOP_DIR)3rdparty.mk
ifeq ($(strip $(call defined,CODIT_DIR)),0)
$(info CODIT_DIR must be set in $(TOP_DIR)3rdparty.mk)
endif
CXXVER_GE480 := $(shell expr `$(CXX) -dumpversion | sed -e 's/\.\([0-9][0-9]\)/\1/g' -e 's/\.\([0-9]\)/0\1/g' -e 's/^[0-9]\{3,4\}$$/&00/'` \>= 40800)
ok := ok
$(info Braces {} in parentheses ({}): ${ok})
${info Parentheses () in braces {()}: $(ok)}
ifeq ("${ok}", "skip")
$(ok))}
${ok}})
endif
result != echo "'$(ok)' $(shell echo "from inlined shell")"
$(info $(result))
# Below is a test of variable assignment without any spacing.
var=val
var?=val
var:=123
var!=echo val
var:=val \
notvar=butval
var:=$(val:.c=.o)
var-$(nested-var)=val
# Spaces in a nested shell will hurt a colorizing of variable,
# but not so much.
var-$(shell printf 2) := val2
$(info Should be 'val2' here: $(var-2))
export a ?= b:c
| extensions/vscode-colorize-tests/test/colorize-fixtures/makefile | 0 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.00017447078425902873,
0.0001714473037282005,
0.0001690670324023813,
0.0001716700498946011,
0.0000018396162886347156
] |
{
"id": 6,
"code_window": [
"\t\t\t\t\tif (cell) {\n",
"\t\t\t\t\t\tthis.notebookEditor.focusNotebookCell(cell, 'container');\n",
"\t\t\t\t\t}\n",
"\t\t\t\t} else if (data.type === 'toggleMarkdownPreview') {\n",
"\t\t\t\t\tthis.notebookEditor.setMarkdownCellEditState(data.cellId, CellEditState.Editing);\n",
"\t\t\t\t} else if (data.type === 'cell-drag-start') {\n",
"\t\t\t\t\tthis.notebookEditor.markdownCellDragStart(data.cellId, data.position);\n",
"\t\t\t\t} else if (data.type === 'cell-drag') {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t} else if (data.type === 'mouseEnterMarkdownPreview') {\n",
"\t\t\t\t\tconst cell = this.notebookEditor.getCellById(data.cellId);\n",
"\t\t\t\t\tif (cell instanceof MarkdownCellViewModel) {\n",
"\t\t\t\t\t\tcell.cellIsHovered = true;\n",
"\t\t\t\t\t}\n",
"\t\t\t\t} else if (data.type === 'mouseLeaveMarkdownPreview') {\n",
"\t\t\t\t\tconst cell = this.notebookEditor.getCellById(data.cellId);\n",
"\t\t\t\t\tif (cell instanceof MarkdownCellViewModel) {\n",
"\t\t\t\t\t\tcell.cellIsHovered = false;\n",
"\t\t\t\t\t}\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView.ts",
"type": "add",
"edit_start_line_idx": 799
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { createDecorator as createServiceDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IDisposable, Disposable } from 'vs/base/common/lifecycle';
import { isWindows } from 'vs/base/common/platform';
import { Event, Emitter } from 'vs/base/common/event';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { URI } from 'vs/base/common/uri';
import { toErrorMessage } from 'vs/base/common/errorMessage';
export const ILogService = createServiceDecorator<ILogService>('logService');
export const ILoggerService = createServiceDecorator<ILoggerService>('loggerService');
function now(): string {
return new Date().toISOString();
}
export enum LogLevel {
Trace,
Debug,
Info,
Warning,
Error,
Critical,
Off
}
export const DEFAULT_LOG_LEVEL: LogLevel = LogLevel.Info;
export interface ILogger extends IDisposable {
onDidChangeLogLevel: Event<LogLevel>;
getLevel(): LogLevel;
setLevel(level: LogLevel): void;
trace(message: string, ...args: any[]): void;
debug(message: string, ...args: any[]): void;
info(message: string, ...args: any[]): void;
warn(message: string, ...args: any[]): void;
error(message: string | Error, ...args: any[]): void;
critical(message: string | Error, ...args: any[]): void;
/**
* An operation to flush the contents. Can be synchronous.
*/
flush(): void;
}
export interface ILogService extends ILogger {
readonly _serviceBrand: undefined;
}
export interface ILoggerOptions {
/**
* Name of the logger.
*/
name?: string;
/**
* Do not create rotating files if max size exceeds.
*/
donotRotate?: boolean;
/**
* Do not use formatters.
*/
donotUseFormatters?: boolean;
/**
* If set, logger logs the message always.
*/
always?: boolean;
}
export interface ILoggerService {
readonly _serviceBrand: undefined;
/**
* Creates a logger
*/
createLogger(file: URI, options?: ILoggerOptions): ILogger;
}
export abstract class AbstractLogger extends Disposable {
private level: LogLevel = DEFAULT_LOG_LEVEL;
private readonly _onDidChangeLogLevel: Emitter<LogLevel> = this._register(new Emitter<LogLevel>());
readonly onDidChangeLogLevel: Event<LogLevel> = this._onDidChangeLogLevel.event;
setLevel(level: LogLevel): void {
if (this.level !== level) {
this.level = level;
this._onDidChangeLogLevel.fire(this.level);
}
}
getLevel(): LogLevel {
return this.level;
}
}
export abstract class AbstractMessageLogger extends AbstractLogger implements ILogger {
protected abstract log(level: LogLevel, message: string): void;
constructor(private readonly logAlways?: boolean) {
super();
}
private checkLogLevel(level: LogLevel): boolean {
return this.logAlways || this.getLevel() <= level;
}
trace(message: string, ...args: any[]): void {
if (this.checkLogLevel(LogLevel.Trace)) {
this.log(LogLevel.Trace, this.format([message, ...args]));
}
}
debug(message: string, ...args: any[]): void {
if (this.checkLogLevel(LogLevel.Debug)) {
this.log(LogLevel.Debug, this.format([message, ...args]));
}
}
info(message: string, ...args: any[]): void {
if (this.checkLogLevel(LogLevel.Info)) {
this.log(LogLevel.Info, this.format([message, ...args]));
}
}
warn(message: string, ...args: any[]): void {
if (this.checkLogLevel(LogLevel.Warning)) {
this.log(LogLevel.Warning, this.format([message, ...args]));
}
}
error(message: string | Error, ...args: any[]): void {
if (this.checkLogLevel(LogLevel.Error)) {
if (message instanceof Error) {
const array = Array.prototype.slice.call(arguments) as any[];
array[0] = message.stack;
this.log(LogLevel.Error, this.format(array));
} else {
this.log(LogLevel.Error, this.format([message, ...args]));
}
}
}
critical(message: string | Error, ...args: any[]): void {
if (this.checkLogLevel(LogLevel.Critical)) {
this.log(LogLevel.Critical, this.format([message, ...args]));
}
}
flush(): void { }
private format(args: any): string {
let result = '';
for (let i = 0; i < args.length; i++) {
let a = args[i];
if (typeof a === 'object') {
try {
a = JSON.stringify(a);
} catch (e) { }
}
result += (i > 0 ? ' ' : '') + a;
}
return result;
}
}
export class ConsoleMainLogger extends AbstractLogger implements ILogger {
private useColors: boolean;
constructor(logLevel: LogLevel = DEFAULT_LOG_LEVEL) {
super();
this.setLevel(logLevel);
this.useColors = !isWindows;
}
trace(message: string, ...args: any[]): void {
if (this.getLevel() <= LogLevel.Trace) {
if (this.useColors) {
console.log(`\x1b[90m[main ${now()}]\x1b[0m`, message, ...args);
} else {
console.log(`[main ${now()}]`, message, ...args);
}
}
}
debug(message: string, ...args: any[]): void {
if (this.getLevel() <= LogLevel.Debug) {
if (this.useColors) {
console.log(`\x1b[90m[main ${now()}]\x1b[0m`, message, ...args);
} else {
console.log(`[main ${now()}]`, message, ...args);
}
}
}
info(message: string, ...args: any[]): void {
if (this.getLevel() <= LogLevel.Info) {
if (this.useColors) {
console.log(`\x1b[90m[main ${now()}]\x1b[0m`, message, ...args);
} else {
console.log(`[main ${now()}]`, message, ...args);
}
}
}
warn(message: string | Error, ...args: any[]): void {
if (this.getLevel() <= LogLevel.Warning) {
if (this.useColors) {
console.warn(`\x1b[93m[main ${now()}]\x1b[0m`, message, ...args);
} else {
console.warn(`[main ${now()}]`, message, ...args);
}
}
}
error(message: string, ...args: any[]): void {
if (this.getLevel() <= LogLevel.Error) {
if (this.useColors) {
console.error(`\x1b[91m[main ${now()}]\x1b[0m`, message, ...args);
} else {
console.error(`[main ${now()}]`, message, ...args);
}
}
}
critical(message: string, ...args: any[]): void {
if (this.getLevel() <= LogLevel.Critical) {
if (this.useColors) {
console.error(`\x1b[90m[main ${now()}]\x1b[0m`, message, ...args);
} else {
console.error(`[main ${now()}]`, message, ...args);
}
}
}
dispose(): void {
// noop
}
flush(): void {
// noop
}
}
export class ConsoleLogger extends AbstractLogger implements ILogger {
constructor(logLevel: LogLevel = DEFAULT_LOG_LEVEL) {
super();
this.setLevel(logLevel);
}
trace(message: string, ...args: any[]): void {
if (this.getLevel() <= LogLevel.Trace) {
console.log('%cTRACE', 'color: #888', message, ...args);
}
}
debug(message: string, ...args: any[]): void {
if (this.getLevel() <= LogLevel.Debug) {
console.log('%cDEBUG', 'background: #eee; color: #888', message, ...args);
}
}
info(message: string, ...args: any[]): void {
if (this.getLevel() <= LogLevel.Info) {
console.log('%c INFO', 'color: #33f', message, ...args);
}
}
warn(message: string | Error, ...args: any[]): void {
if (this.getLevel() <= LogLevel.Warning) {
console.log('%c WARN', 'color: #993', message, ...args);
}
}
error(message: string, ...args: any[]): void {
if (this.getLevel() <= LogLevel.Error) {
console.log('%c ERR', 'color: #f33', message, ...args);
}
}
critical(message: string, ...args: any[]): void {
if (this.getLevel() <= LogLevel.Critical) {
console.log('%cCRITI', 'background: #f33; color: white', message, ...args);
}
}
dispose(): void {
// noop
}
flush(): void {
// noop
}
}
export class AdapterLogger extends AbstractLogger implements ILogger {
constructor(private readonly adapter: { log: (type: string, args: any[]) => void }, logLevel: LogLevel = DEFAULT_LOG_LEVEL) {
super();
this.setLevel(logLevel);
}
trace(message: string, ...args: any[]): void {
if (this.getLevel() <= LogLevel.Trace) {
this.adapter.log('trace', [this.extractMessage(message), ...args]);
}
}
debug(message: string, ...args: any[]): void {
if (this.getLevel() <= LogLevel.Debug) {
this.adapter.log('debug', [this.extractMessage(message), ...args]);
}
}
info(message: string, ...args: any[]): void {
if (this.getLevel() <= LogLevel.Info) {
this.adapter.log('info', [this.extractMessage(message), ...args]);
}
}
warn(message: string | Error, ...args: any[]): void {
if (this.getLevel() <= LogLevel.Warning) {
this.adapter.log('warn', [this.extractMessage(message), ...args]);
}
}
error(message: string | Error, ...args: any[]): void {
if (this.getLevel() <= LogLevel.Error) {
this.adapter.log('error', [this.extractMessage(message), ...args]);
}
}
critical(message: string | Error, ...args: any[]): void {
if (this.getLevel() <= LogLevel.Critical) {
this.adapter.log('critical', [this.extractMessage(message), ...args]);
}
}
private extractMessage(msg: string | Error): string {
if (typeof msg === 'string') {
return msg;
}
return toErrorMessage(msg, this.getLevel() <= LogLevel.Trace);
}
dispose(): void {
// noop
}
flush(): void {
// noop
}
}
export class MultiplexLogService extends AbstractLogger implements ILogService {
declare readonly _serviceBrand: undefined;
constructor(private readonly logServices: ReadonlyArray<ILogger>) {
super();
if (logServices.length) {
this.setLevel(logServices[0].getLevel());
}
}
setLevel(level: LogLevel): void {
for (const logService of this.logServices) {
logService.setLevel(level);
}
super.setLevel(level);
}
trace(message: string, ...args: any[]): void {
for (const logService of this.logServices) {
logService.trace(message, ...args);
}
}
debug(message: string, ...args: any[]): void {
for (const logService of this.logServices) {
logService.debug(message, ...args);
}
}
info(message: string, ...args: any[]): void {
for (const logService of this.logServices) {
logService.info(message, ...args);
}
}
warn(message: string, ...args: any[]): void {
for (const logService of this.logServices) {
logService.warn(message, ...args);
}
}
error(message: string | Error, ...args: any[]): void {
for (const logService of this.logServices) {
logService.error(message, ...args);
}
}
critical(message: string | Error, ...args: any[]): void {
for (const logService of this.logServices) {
logService.critical(message, ...args);
}
}
flush(): void {
for (const logService of this.logServices) {
logService.flush();
}
}
dispose(): void {
for (const logService of this.logServices) {
logService.dispose();
}
}
}
export class LogService extends Disposable implements ILogService {
declare readonly _serviceBrand: undefined;
constructor(private logger: ILogger) {
super();
this._register(logger);
}
get onDidChangeLogLevel(): Event<LogLevel> {
return this.logger.onDidChangeLogLevel;
}
setLevel(level: LogLevel): void {
this.logger.setLevel(level);
}
getLevel(): LogLevel {
return this.logger.getLevel();
}
trace(message: string, ...args: any[]): void {
this.logger.trace(message, ...args);
}
debug(message: string, ...args: any[]): void {
this.logger.debug(message, ...args);
}
info(message: string, ...args: any[]): void {
this.logger.info(message, ...args);
}
warn(message: string, ...args: any[]): void {
this.logger.warn(message, ...args);
}
error(message: string | Error, ...args: any[]): void {
this.logger.error(message, ...args);
}
critical(message: string | Error, ...args: any[]): void {
this.logger.critical(message, ...args);
}
flush(): void {
this.logger.flush();
}
}
export class NullLogService implements ILogService {
declare readonly _serviceBrand: undefined;
readonly onDidChangeLogLevel: Event<LogLevel> = new Emitter<LogLevel>().event;
setLevel(level: LogLevel): void { }
getLevel(): LogLevel { return LogLevel.Info; }
trace(message: string, ...args: any[]): void { }
debug(message: string, ...args: any[]): void { }
info(message: string, ...args: any[]): void { }
warn(message: string, ...args: any[]): void { }
error(message: string | Error, ...args: any[]): void { }
critical(message: string | Error, ...args: any[]): void { }
dispose(): void { }
flush(): void { }
}
export function getLogLevel(environmentService: IEnvironmentService): LogLevel {
if (environmentService.verbose) {
return LogLevel.Trace;
}
if (typeof environmentService.logLevel === 'string') {
const logLevel = parseLogLevel(environmentService.logLevel.toLowerCase());
if (logLevel !== undefined) {
return logLevel;
}
}
return DEFAULT_LOG_LEVEL;
}
export function parseLogLevel(logLevel: string): LogLevel | undefined {
switch (logLevel) {
case 'trace':
return LogLevel.Trace;
case 'debug':
return LogLevel.Debug;
case 'info':
return LogLevel.Info;
case 'warn':
return LogLevel.Warning;
case 'error':
return LogLevel.Error;
case 'critical':
return LogLevel.Critical;
case 'off':
return LogLevel.Off;
}
return undefined;
}
export function LogLevelToString(logLevel: LogLevel): string {
switch (logLevel) {
case LogLevel.Trace: return 'trace';
case LogLevel.Debug: return 'debug';
case LogLevel.Info: return 'info';
case LogLevel.Warning: return 'warn';
case LogLevel.Error: return 'error';
case LogLevel.Critical: return 'critical';
case LogLevel.Off: return 'off';
}
}
| src/vs/platform/log/common/log.ts | 0 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.00017430134175810963,
0.00016945178504101932,
0.00015891976363491267,
0.00017008731083478779,
0.0000031915283216221724
] |
{
"id": 6,
"code_window": [
"\t\t\t\t\tif (cell) {\n",
"\t\t\t\t\t\tthis.notebookEditor.focusNotebookCell(cell, 'container');\n",
"\t\t\t\t\t}\n",
"\t\t\t\t} else if (data.type === 'toggleMarkdownPreview') {\n",
"\t\t\t\t\tthis.notebookEditor.setMarkdownCellEditState(data.cellId, CellEditState.Editing);\n",
"\t\t\t\t} else if (data.type === 'cell-drag-start') {\n",
"\t\t\t\t\tthis.notebookEditor.markdownCellDragStart(data.cellId, data.position);\n",
"\t\t\t\t} else if (data.type === 'cell-drag') {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t} else if (data.type === 'mouseEnterMarkdownPreview') {\n",
"\t\t\t\t\tconst cell = this.notebookEditor.getCellById(data.cellId);\n",
"\t\t\t\t\tif (cell instanceof MarkdownCellViewModel) {\n",
"\t\t\t\t\t\tcell.cellIsHovered = true;\n",
"\t\t\t\t\t}\n",
"\t\t\t\t} else if (data.type === 'mouseLeaveMarkdownPreview') {\n",
"\t\t\t\t\tconst cell = this.notebookEditor.getCellById(data.cellId);\n",
"\t\t\t\t\tif (cell instanceof MarkdownCellViewModel) {\n",
"\t\t\t\t\t\tcell.cellIsHovered = false;\n",
"\t\t\t\t\t}\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView.ts",
"type": "add",
"edit_start_line_idx": 799
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as fs from 'fs';
import { tmpdir } from 'os';
import { join } from 'vs/base/common/path';
export function createWaitMarkerFile(verbose?: boolean): string | undefined {
const randomWaitMarkerPath = join(tmpdir(), Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 10));
try {
fs.writeFileSync(randomWaitMarkerPath, ''); // use built-in fs to avoid dragging in more dependencies
if (verbose) {
console.log(`Marker file for --wait created: ${randomWaitMarkerPath}`);
}
return randomWaitMarkerPath;
} catch (err) {
if (verbose) {
console.error(`Failed to create marker file for --wait: ${err}`);
}
return undefined;
}
}
| src/vs/platform/environment/node/wait.ts | 0 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.00017384176317136735,
0.00017101141565945,
0.00016928849800024182,
0.00016990398580674082,
0.000002017070073634386
] |
{
"id": 7,
"code_window": [
"\t\t\tthis.updateForLayout(element, templateData);\n",
"\t\t}));\n",
"\n",
"\t\t// render toolbar first\n",
"\t\tthis.setupCellToolbarActions(templateData, elementDisposables);\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.updateForHover(element, templateData);\n",
"\t\telementDisposables.add(element.onDidChangeState(e => {\n",
"\t\t\tif (e.cellIsHoveredChanged) {\n",
"\t\t\t\tthis.updateForHover(element, templateData);\n",
"\t\t\t}\n",
"\t\t}));\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer.ts",
"type": "add",
"edit_start_line_idx": 536
} | /*---------------------------------------------------------------------------------------------
* 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 { VSBuffer } from 'vs/base/common/buffer';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable } from 'vs/base/common/lifecycle';
import { getExtensionForMimeType } from 'vs/base/common/mime';
import { FileAccess, Schemas } from 'vs/base/common/network';
import { isWeb } from 'vs/base/common/platform';
import { dirname, joinPath } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import * as UUID from 'vs/base/common/uuid';
import { IFileDialogService } from 'vs/platform/dialogs/common/dialogs';
import { IFileService } from 'vs/platform/files/common/files';
import { IOpenerService, matchesScheme } from 'vs/platform/opener/common/opener';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { CellEditState, ICellOutputViewModel, ICommonCellInfo, ICommonNotebookEditor, IDisplayOutputLayoutUpdateRequest, IDisplayOutputViewModel, IGenericCellViewModel, IInsetRenderOutput, RenderOutputType } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { preloadsScriptStr } from 'vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads';
import { transformWebviewThemeVars } from 'vs/workbench/contrib/notebook/browser/view/renderers/webviewThemeMapping';
import { INotebookRendererInfo } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { IWebviewService, WebviewContentPurpose, WebviewElement } from 'vs/workbench/contrib/webview/browser/webview';
import { asWebviewUri } from 'vs/workbench/contrib/webview/common/webviewUri';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
export interface WebviewIntialized {
__vscode_notebook_message: boolean;
type: 'initialized'
}
export interface IDimensionMessage {
__vscode_notebook_message: boolean;
type: 'dimension';
id: string;
init: boolean;
data: DOM.Dimension;
isOutput: boolean;
}
export interface IMouseEnterMessage {
__vscode_notebook_message: boolean;
type: 'mouseenter';
id: string;
}
export interface IMouseLeaveMessage {
__vscode_notebook_message: boolean;
type: 'mouseleave';
id: string;
}
export interface IWheelMessage {
__vscode_notebook_message: boolean;
type: 'did-scroll-wheel';
payload: any;
}
export interface IScrollAckMessage {
__vscode_notebook_message: boolean;
type: 'scroll-ack';
data: { top: number };
version: number;
}
export interface IBlurOutputMessage {
__vscode_notebook_message: boolean;
type: 'focus-editor';
id: string;
focusNext?: boolean;
}
export interface IClickedDataUrlMessage {
__vscode_notebook_message: boolean;
type: 'clicked-data-url';
data: string;
downloadName?: string;
}
export interface IFocusMarkdownPreviewMessage {
__vscode_notebook_message: boolean;
type: 'focusMarkdownPreview';
cellId: string;
}
export interface IToggleMarkdownPreviewMessage {
__vscode_notebook_message: boolean;
type: 'toggleMarkdownPreview';
cellId: string;
}
export interface ICellDragStartMessage {
__vscode_notebook_message: boolean;
type: 'cell-drag-start';
cellId: string;
position: { clientX: number, clientY: number };
}
export interface ICellDragMessage {
__vscode_notebook_message: boolean;
type: 'cell-drag';
cellId: string;
position: { clientX: number, clientY: number };
}
export interface ICellDragEndMessage {
readonly __vscode_notebook_message: boolean;
readonly type: 'cell-drag-end';
readonly cellId: string;
readonly ctrlKey: boolean
readonly altKey: boolean;
readonly position: {
readonly clientX: number;
readonly clientY: number;
};
}
export interface IClearMessage {
type: 'clear';
}
export interface IOutputRequestMetadata {
/**
* Additional attributes of a cell metadata.
*/
custom?: { [key: string]: unknown };
}
export interface IOutputRequestDto {
/**
* { mime_type: value }
*/
data: { [key: string]: unknown; }
metadata?: IOutputRequestMetadata;
outputId: string;
}
export interface ICreationRequestMessage {
type: 'html';
content:
| { type: RenderOutputType.Html; htmlContent: string }
| { type: RenderOutputType.Extension; output: IOutputRequestDto; mimeType: string };
cellId: string;
outputId: string;
top: number;
left: number;
requiredPreloads: ReadonlyArray<IPreloadResource>;
initiallyHidden?: boolean;
apiNamespace?: string | undefined;
}
export interface IContentWidgetTopRequest {
id: string;
top: number;
left: number;
}
export interface IViewScrollTopRequestMessage {
type: 'view-scroll';
top?: number;
forceDisplay: boolean;
widgets: IContentWidgetTopRequest[];
version: number;
}
export interface IViewScrollMarkdownRequestMessage {
type: 'view-scroll-markdown';
cells: { id: string; top: number }[];
}
export interface IScrollRequestMessage {
type: 'scroll';
id: string;
top: number;
widgetTop?: number;
version: number;
}
export interface IClearOutputRequestMessage {
type: 'clearOutput';
cellId: string;
outputId: string;
cellUri: string;
apiNamespace: string | undefined;
}
export interface IHideOutputMessage {
type: 'hideOutput';
outputId: string;
cellId: string;
}
export interface IShowOutputMessage {
type: 'showOutput';
cellId: string;
outputId: string;
top: number;
}
export interface IFocusOutputMessage {
type: 'focus-output';
cellId: string;
}
export interface IPreloadResource {
originalUri: string;
uri: string;
}
export interface IUpdatePreloadResourceMessage {
type: 'preload';
resources: IPreloadResource[];
source: 'renderer' | 'kernel';
}
export interface IUpdateDecorationsMessage {
type: 'decorations';
cellId: string;
addedClassNames: string[];
removedClassNames: string[];
}
export interface ICustomRendererMessage {
__vscode_notebook_message: boolean;
type: 'customRendererMessage';
rendererId: string;
message: unknown;
}
export interface ICreateMarkdownMessage {
type: 'createMarkdownPreview',
id: string;
content: string;
top: number;
}
export interface IRemoveMarkdownMessage {
type: 'removeMarkdownPreview',
id: string;
}
export interface IHideMarkdownMessage {
type: 'hideMarkdownPreview',
id: string;
}
export interface IShowMarkdownMessage {
type: 'showMarkdownPreview',
id: string;
content: string;
top: number;
}
export interface IInitializeMarkdownMessage {
type: 'initializeMarkdownPreview';
cells: Array<{ cellId: string, content: string }>;
}
export type FromWebviewMessage =
| WebviewIntialized
| IDimensionMessage
| IMouseEnterMessage
| IMouseLeaveMessage
| IWheelMessage
| IScrollAckMessage
| IBlurOutputMessage
| ICustomRendererMessage
| IClickedDataUrlMessage
| IFocusMarkdownPreviewMessage
| IToggleMarkdownPreviewMessage
| ICellDragStartMessage
| ICellDragMessage
| ICellDragEndMessage
;
export type ToWebviewMessage =
| IClearMessage
| IFocusOutputMessage
| ICreationRequestMessage
| IViewScrollTopRequestMessage
| IScrollRequestMessage
| IClearOutputRequestMessage
| IHideOutputMessage
| IShowOutputMessage
| IUpdatePreloadResourceMessage
| IUpdateDecorationsMessage
| ICustomRendererMessage
| ICreateMarkdownMessage
| IRemoveMarkdownMessage
| IShowMarkdownMessage
| IHideMarkdownMessage
| IInitializeMarkdownMessage
| IViewScrollMarkdownRequestMessage;
export type AnyMessage = FromWebviewMessage | ToWebviewMessage;
export interface ICachedInset<K extends ICommonCellInfo> {
outputId: string;
cellInfo: K;
renderer?: INotebookRendererInfo;
cachedCreation: ICreationRequestMessage;
}
function html(strings: TemplateStringsArray, ...values: any[]): string {
let str = '';
strings.forEach((string, i) => {
str += string + (values[i] || '');
});
return str;
}
export interface INotebookWebviewMessage {
message: unknown;
forRenderer?: string;
}
let version = 0;
export class BackLayerWebView<T extends ICommonCellInfo> extends Disposable {
element: HTMLElement;
webview: WebviewElement | undefined = undefined;
insetMapping: Map<IDisplayOutputViewModel, ICachedInset<T>> = new Map();
markdownPreviewMapping: Set<string> = new Set();
hiddenInsetMapping: Set<IDisplayOutputViewModel> = new Set();
reversedInsetMapping: Map<string, IDisplayOutputViewModel> = new Map();
localResourceRootsCache: URI[] | undefined = undefined;
rendererRootsCache: URI[] = [];
kernelRootsCache: URI[] = [];
private readonly _onMessage = this._register(new Emitter<INotebookWebviewMessage>());
private readonly _preloadsCache = new Set<string>();
public readonly onMessage: Event<INotebookWebviewMessage> = this._onMessage.event;
private _loaded!: Promise<void>;
private _initalized?: Promise<void>;
private _disposed = false;
constructor(
public notebookEditor: ICommonNotebookEditor,
public id: string,
public documentUri: URI,
public options: {
outputNodePadding: number,
outputNodeLeftPadding: number
},
@IWebviewService readonly webviewService: IWebviewService,
@IOpenerService readonly openerService: IOpenerService,
@INotebookService private readonly notebookService: INotebookService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
@IFileDialogService private readonly fileDialogService: IFileDialogService,
@IFileService private readonly fileService: IFileService,
) {
super();
this.element = document.createElement('div');
this.element.style.height = '1400px';
this.element.style.position = 'absolute';
}
private generateContent(coreDependencies: string, baseUrl: string) {
const markdownRenderersSrc = this.getMarkdownRendererScripts();
return html`
<html lang="en">
<head>
<meta charset="UTF-8">
<base href="${baseUrl}/"/>
<style>
#container > div > div.output {
width: 100%;
padding: ${this.options.outputNodePadding}px ${this.options.outputNodePadding}px ${this.options.outputNodePadding}px ${this.options.outputNodeLeftPadding}px;
box-sizing: border-box;
background-color: var(--vscode-notebook-outputContainerBackgroundColor);
}
#container > div > div.preview {
width: 100%;
box-sizing: border-box;
white-space: nowrap;
overflow: hidden;
user-select: text;
-webkit-user-select: text;
-ms-user-select: text;
white-space: initial;
padding-left: 0px !important;
}
/* markdown */
#container > div > div.preview img {
max-width: 100%;
max-height: 100%;
}
#container > div > div.preview a {
text-decoration: none;
}
#container > div > div.preview a:hover {
text-decoration: underline;
}
#container > div > div.preview a:focus,
#container > div > div.preview input:focus,
#container > div > div.preview select:focus,
#container > div > div.preview textarea:focus {
outline: 1px solid -webkit-focus-ring-color;
outline-offset: -1px;
}
#container > div > div.preview hr {
border: 0;
height: 2px;
border-bottom: 2px solid;
}
#container > div > div.preview h1 {
padding-bottom: 0.3em;
line-height: 1.2;
border-bottom-width: 1px;
border-bottom-style: solid;
border-color: rgba(255, 255, 255, 0.18);
}
#container > div > div.preview h1 {
border-color: rgba(0, 0, 0, 0.18);
}
#container > div > div.preview h1,
#container > div > div.preview h2,
#container > div > div.preview h3 {
font-weight: normal;
}
#container > div > div.preview div {
width: 100%;
}
/* Adjust margin of first item in markdown cell */
#container > div > div.preview *:first-child {
margin-top: 0px;
}
/* h1 tags don't need top margin */
#container > div > div.preview h1:first-child {
margin-top: 0;
}
/* Removes bottom margin when only one item exists in markdown cell */
#container > div > div.preview *:only-child,
#container > div > div.preview *:last-child {
margin-bottom: 0;
padding-bottom: 0;
}
/* makes all markdown cells consistent */
#container > div > div.preview div {
min-height: 24px;
}
#container > div > div.preview table {
border-collapse: collapse;
border-spacing: 0;
}
#container > div > div.preview table th,
#container > div > div.preview table td {
border: 1px solid;
}
#container > div > div.preview table > thead > tr > th {
text-align: left;
border-bottom: 1px solid;
}
#container > div > div.preview table > thead > tr > th,
#container > div > div.preview table > thead > tr > td,
#container > div > div.preview table > tbody > tr > th,
#container > div > div.preview table > tbody > tr > td {
padding: 5px 10px;
}
#container > div > div.preview table > tbody > tr + tr > td {
border-top: 1px solid;
}
#container > div > div.preview blockquote {
margin: 0 7px 0 5px;
padding: 0 16px 0 10px;
border-left-width: 5px;
border-left-style: solid;
}
#container > div > div.preview code,
#container > div > div.preview .code {
font-family: var(--monaco-monospace-font);
font-size: 1em;
line-height: 1.357em;
}
#container > div > div.preview .code {
white-space: pre-wrap;
}
#container > div > div.preview .latex-block {
display: block;
}
#container > div > div.preview .latex {
vertical-align: middle;
display: inline-block;
}
#container > div > div.preview .latex img,
#container > div > div.preview .latex-block img {
filter: brightness(0) invert(0)
}
#container > div > div.preview.dragging {
background-color: var(--vscode-editor-background);
}
.monaco-workbench.vs-dark .notebookOverlay .cell.markdown .latex img,
.monaco-workbench.vs-dark .notebookOverlay .cell.markdown .latex-block img {
filter: brightness(0) invert(1)
}
#container > div.nb-symbolHighlight > div {
background-color: var(--vscode-notebook-symbolHighlightBackground);
}
#container > div.nb-cellDeleted > div {
background-color: var(--vscode-diffEditor-removedTextBackground);
}
#container > div.nb-cellAdded > div {
background-color: var(--vscode-diffEditor-insertedTextBackground);
}
#container > div > div > div {
overflow-x: scroll;
}
body {
padding: 0px;
height: 100%;
width: 100%;
}
table, thead, tr, th, td, tbody {
border: none !important;
border-color: transparent;
border-spacing: 0;
border-collapse: collapse;
}
table {
width: 100%;
}
table, th, tr {
text-align: left !important;
}
thead {
font-weight: bold;
background-color: rgba(130, 130, 130, 0.16);
}
th, td {
padding: 4px 8px;
}
tr:nth-child(even) {
background-color: rgba(130, 130, 130, 0.08);
}
tbody th {
font-weight: normal;
}
</style>
</head>
<body style="overflow: hidden;">
<script>
self.require = {};
</script>
${coreDependencies}
<div id='container' class="widgetarea" style="position: absolute;width:100%;top: 0px"></div>
<script>${preloadsScriptStr(this.options.outputNodePadding, this.options.outputNodeLeftPadding)}</script>
${markdownRenderersSrc}
</body>
</html>`;
}
private getMarkdownRendererScripts() {
const markdownRenderers = this.notebookService.getMarkdownRendererInfo();
return markdownRenderers
.sort((a, b) => {
// prefer built-in extension
if (a.extensionIsBuiltin) {
return b.extensionIsBuiltin ? 0 : -1;
}
return b.extensionIsBuiltin ? 1 : -1;
})
.map(renderer => {
return asWebviewUri(this.environmentService, this.id, renderer.entrypoint);
})
.map(src => `<script src="${src}"></script>`)
.join('\n');
}
postRendererMessage(rendererId: string, message: any) {
this._sendMessageToWebview({
__vscode_notebook_message: true,
type: 'customRendererMessage',
message,
rendererId
});
}
private resolveOutputId(id: string): { cellInfo: T, output: ICellOutputViewModel } | undefined {
const output = this.reversedInsetMapping.get(id);
if (!output) {
return;
}
const cellInfo = this.insetMapping.get(output)!.cellInfo;
return { cellInfo, output };
}
async createWebview(): Promise<void> {
let coreDependencies = '';
let resolveFunc: () => void;
this._initalized = new Promise<void>((resolve, reject) => {
resolveFunc = resolve;
});
const baseUrl = asWebviewUri(this.environmentService, this.id, dirname(this.documentUri));
if (!isWeb) {
const loaderUri = FileAccess.asFileUri('vs/loader.js', require);
const loader = asWebviewUri(this.environmentService, this.id, loaderUri);
coreDependencies = `<script src="${loader}"></script><script>
var requirejs = (function() {
return require;
}());
</script>`;
const htmlContent = this.generateContent(coreDependencies, baseUrl.toString());
this._initialize(htmlContent);
resolveFunc!();
} else {
const loaderUri = FileAccess.asBrowserUri('vs/loader.js', require);
fetch(loaderUri.toString(true)).then(async response => {
if (response.status !== 200) {
throw new Error(response.statusText);
}
const loaderJs = await response.text();
coreDependencies = `
<script>
${loaderJs}
</script>
<script>
var requirejs = (function() {
return require;
}());
</script>
`;
const htmlContent = this.generateContent(coreDependencies, baseUrl.toString());
this._initialize(htmlContent);
resolveFunc!();
});
}
await this._initalized;
}
private async _initialize(content: string) {
if (!document.body.contains(this.element)) {
throw new Error('Element is already detached from the DOM tree');
}
this.webview = this._createInset(this.webviewService, content);
this.webview.mountTo(this.element);
this._register(this.webview);
this._register(this.webview.onDidClickLink(link => {
if (this._disposed) {
return;
}
if (!link) {
return;
}
if (matchesScheme(link, Schemas.http) || matchesScheme(link, Schemas.https) || matchesScheme(link, Schemas.mailto)
|| matchesScheme(link, Schemas.command)) {
this.openerService.open(link, { fromUserGesture: true, allowContributedOpeners: true });
}
}));
this._register(this.webview.onDidReload(() => {
if (this._disposed) {
return;
}
let renderers = new Set<INotebookRendererInfo>();
for (const inset of this.insetMapping.values()) {
if (inset.renderer) {
renderers.add(inset.renderer);
}
}
this._preloadsCache.clear();
this.updateRendererPreloads(renderers);
for (const [output, inset] of this.insetMapping.entries()) {
this._sendMessageToWebview({ ...inset.cachedCreation, initiallyHidden: this.hiddenInsetMapping.has(output) });
}
}));
this._register(this.webview.onMessage((data: FromWebviewMessage) => {
if (this._disposed) {
return;
}
if (data.__vscode_notebook_message) {
if (data.type === 'dimension') {
if (data.isOutput) {
const height = data.data.height;
const outputHeight = height;
const resolvedResult = this.resolveOutputId(data.id);
if (resolvedResult) {
const { cellInfo, output } = resolvedResult;
this.notebookEditor.updateOutputHeight(cellInfo, output, outputHeight, !!data.init);
}
} else {
const cellId = data.id.substr(0, data.id.length - '_preview'.length);
this.notebookEditor.updateMarkdownCellHeight(cellId, data.data.height, !!data.init);
}
} else if (data.type === 'mouseenter') {
const resolvedResult = this.resolveOutputId(data.id);
if (resolvedResult) {
const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo);
if (latestCell) {
latestCell.outputIsHovered = true;
}
}
} else if (data.type === 'mouseleave') {
const resolvedResult = this.resolveOutputId(data.id);
if (resolvedResult) {
const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo);
if (latestCell) {
latestCell.outputIsHovered = false;
}
}
} else if (data.type === 'scroll-ack') {
// const date = new Date();
// const top = data.data.top;
// console.log('ack top ', top, ' version: ', data.version, ' - ', date.getMinutes() + ':' + date.getSeconds() + ':' + date.getMilliseconds());
} else if (data.type === 'did-scroll-wheel') {
this.notebookEditor.triggerScroll({
...data.payload,
preventDefault: () => { },
stopPropagation: () => { }
});
} else if (data.type === 'focus-editor') {
const resolvedResult = this.resolveOutputId(data.id);
if (resolvedResult) {
const latestCell = this.notebookEditor.getCellByInfo(resolvedResult.cellInfo);
if (!latestCell) {
return;
}
if (data.focusNext) {
this.notebookEditor.focusNextNotebookCell(latestCell, 'editor');
} else {
this.notebookEditor.focusNotebookCell(latestCell, 'editor');
}
}
} else if (data.type === 'clicked-data-url') {
this._onDidClickDataLink(data);
} else if (data.type === 'customRendererMessage') {
this._onMessage.fire({ message: data.message, forRenderer: data.rendererId });
} else if (data.type === 'focusMarkdownPreview') {
const cell = this.notebookEditor.getCellById(data.cellId);
if (cell) {
this.notebookEditor.focusNotebookCell(cell, 'container');
}
} else if (data.type === 'toggleMarkdownPreview') {
this.notebookEditor.setMarkdownCellEditState(data.cellId, CellEditState.Editing);
} else if (data.type === 'cell-drag-start') {
this.notebookEditor.markdownCellDragStart(data.cellId, data.position);
} else if (data.type === 'cell-drag') {
this.notebookEditor.markdownCellDrag(data.cellId, data.position);
} else if (data.type === 'cell-drag-end') {
this.notebookEditor.markdownCellDragEnd(data.cellId, {
clientY: data.position.clientY,
ctrlKey: data.ctrlKey,
altKey: data.altKey,
});
}
return;
}
this._onMessage.fire({ message: data });
}));
}
private async _onDidClickDataLink(event: IClickedDataUrlMessage): Promise<void> {
const [splitStart, splitData] = event.data.split(';base64,');
if (!splitData || !splitStart) {
return;
}
const defaultDir = dirname(this.documentUri);
let defaultName: string;
if (event.downloadName) {
defaultName = event.downloadName;
} else {
const mimeType = splitStart.replace(/^data:/, '');
const candidateExtension = mimeType && getExtensionForMimeType(mimeType);
defaultName = candidateExtension ? `download${candidateExtension}` : 'download';
}
const defaultUri = joinPath(defaultDir, defaultName);
const newFileUri = await this.fileDialogService.showSaveDialog({
defaultUri
});
if (!newFileUri) {
return;
}
const decoded = atob(splitData);
const typedArray = new Uint8Array(decoded.length);
for (let i = 0; i < decoded.length; i++) {
typedArray[i] = decoded.charCodeAt(i);
}
const buff = VSBuffer.wrap(typedArray);
await this.fileService.writeFile(newFileUri, buff);
await this.openerService.open(newFileUri);
}
private _createInset(webviewService: IWebviewService, content: string) {
const rootPath = isWeb ? FileAccess.asBrowserUri('', require) : FileAccess.asFileUri('', require);
const workspaceFolders = this.contextService.getWorkspace().folders.map(x => x.uri);
this.localResourceRootsCache = [
...this.notebookService.getNotebookProviderResourceRoots(),
...this.notebookService.getMarkdownRendererInfo().map(x => dirname(x.entrypoint)),
...workspaceFolders,
rootPath,
];
const webview = webviewService.createWebviewElement(this.id, {
purpose: WebviewContentPurpose.NotebookRenderer,
enableFindWidget: false,
transformCssVariables: transformWebviewThemeVars,
}, {
allowMultipleAPIAcquire: true,
allowScripts: true,
localResourceRoots: this.localResourceRootsCache
}, undefined);
let resolveFunc: () => void;
this._loaded = new Promise<void>((resolve, reject) => {
resolveFunc = resolve;
});
const dispose = webview.onMessage((data: FromWebviewMessage) => {
if (data.__vscode_notebook_message && data.type === 'initialized') {
resolveFunc();
dispose.dispose();
}
});
webview.html = content;
return webview;
}
shouldUpdateInset(cell: IGenericCellViewModel, output: ICellOutputViewModel, cellTop: number) {
if (this._disposed) {
return;
}
if (cell.metadata?.outputCollapsed) {
return false;
}
const outputCache = this.insetMapping.get(output)!;
const outputIndex = cell.outputsViewModels.indexOf(output);
const outputOffset = cellTop + cell.getOutputOffset(outputIndex);
if (this.hiddenInsetMapping.has(output)) {
return true;
}
if (outputOffset === outputCache.cachedCreation.top) {
return false;
}
return true;
}
updateMarkdownScrollTop(items: { id: string, top: number }[]) {
this._sendMessageToWebview({
type: 'view-scroll-markdown',
cells: items
});
}
updateViewScrollTop(top: number, forceDisplay: boolean, items: IDisplayOutputLayoutUpdateRequest[]) {
if (this._disposed) {
return;
}
const widgets: IContentWidgetTopRequest[] = items.map(item => {
const outputCache = this.insetMapping.get(item.output)!;
const id = outputCache.outputId;
const outputOffset = item.outputOffset;
outputCache.cachedCreation.top = outputOffset;
this.hiddenInsetMapping.delete(item.output);
return {
id: id,
top: outputOffset,
left: 0
};
});
this._sendMessageToWebview({
top,
type: 'view-scroll',
version: version++,
forceDisplay,
widgets: widgets
});
}
async createMarkdownPreview(cellId: string, content: string, cellTop: number) {
if (this._disposed) {
return;
}
const initialTop = cellTop;
this.markdownPreviewMapping.add(cellId);
this._sendMessageToWebview({
type: 'createMarkdownPreview',
id: cellId,
content: content,
top: initialTop,
});
}
async showMarkdownPreview(cellId: string, content: string, cellTop: number) {
if (this._disposed) {
return;
}
this._sendMessageToWebview({
type: 'showMarkdownPreview',
id: cellId,
content: content,
top: cellTop
});
}
async hideMarkdownPreview(cellId: string,) {
if (this._disposed) {
return;
}
this._sendMessageToWebview({
type: 'hideMarkdownPreview',
id: cellId
});
}
async removeMarkdownPreview(cellId: string,) {
if (this._disposed) {
return;
}
this.markdownPreviewMapping.delete(cellId);
this._sendMessageToWebview({
type: 'removeMarkdownPreview',
id: cellId
});
}
async initializeMarkdown(cells: Array<{ cellId: string, content: string }>) {
await this._loaded;
// TODO: use proper handler
const p = new Promise<void>(resolve => {
this.webview?.onMessage(e => {
if (e.type === 'initializedMarkdownPreview') {
resolve();
}
});
});
for (const cell of cells) {
this.markdownPreviewMapping.add(cell.cellId);
}
this._sendMessageToWebview({
type: 'initializeMarkdownPreview',
cells: cells,
});
await p;
}
async createInset(cellInfo: T, content: IInsetRenderOutput, cellTop: number, offset: number) {
if (this._disposed) {
return;
}
const initialTop = cellTop + offset;
if (this.insetMapping.has(content.source)) {
const outputCache = this.insetMapping.get(content.source);
if (outputCache) {
this.hiddenInsetMapping.delete(content.source);
this._sendMessageToWebview({
type: 'showOutput',
cellId: outputCache.cellInfo.cellId,
outputId: outputCache.outputId,
top: initialTop
});
return;
}
}
const messageBase = {
type: 'html',
cellId: cellInfo.cellId,
top: initialTop,
left: 0,
requiredPreloads: [],
} as const;
let message: ICreationRequestMessage;
let renderer: INotebookRendererInfo | undefined;
if (content.type === RenderOutputType.Extension) {
const output = content.source.model;
renderer = content.renderer;
let data: { [key: string]: unknown } = {};
let metadata: { [key: string]: unknown } = {};
data[content.mimeType] = output.outputs.find(op => op.mime === content.mimeType)?.value || undefined;
metadata[content.mimeType] = output.outputs.find(op => op.mime === content.mimeType)?.metadata || undefined;
message = {
...messageBase,
outputId: output.outputId,
apiNamespace: content.renderer.id,
requiredPreloads: await this.updateRendererPreloads([content.renderer]),
content: {
type: RenderOutputType.Extension,
mimeType: content.mimeType,
output: {
metadata: metadata,
data: data,
outputId: output.outputId
},
},
};
} else {
message = {
...messageBase,
outputId: UUID.generateUuid(),
content: {
type: content.type,
htmlContent: content.htmlContent,
}
};
}
this._sendMessageToWebview(message);
this.insetMapping.set(content.source, { outputId: message.outputId, cellInfo: cellInfo, renderer, cachedCreation: message });
this.hiddenInsetMapping.delete(content.source);
this.reversedInsetMapping.set(message.outputId, content.source);
}
removeInset(output: ICellOutputViewModel) {
if (this._disposed) {
return;
}
const outputCache = this.insetMapping.get(output);
if (!outputCache) {
return;
}
const id = outputCache.outputId;
this._sendMessageToWebview({
type: 'clearOutput',
apiNamespace: outputCache.cachedCreation.apiNamespace,
cellUri: outputCache.cellInfo.cellUri.toString(),
outputId: id,
cellId: outputCache.cellInfo.cellId
});
this.insetMapping.delete(output);
this.reversedInsetMapping.delete(id);
}
hideInset(output: ICellOutputViewModel) {
if (this._disposed) {
return;
}
const outputCache = this.insetMapping.get(output);
if (!outputCache) {
return;
}
this.hiddenInsetMapping.add(output);
this._sendMessageToWebview({
type: 'hideOutput',
outputId: outputCache.outputId,
cellId: outputCache.cellInfo.cellId,
});
}
clearInsets() {
if (this._disposed) {
return;
}
this._sendMessageToWebview({
type: 'clear'
});
this.insetMapping = new Map();
this.reversedInsetMapping = new Map();
}
focusWebview() {
if (this._disposed) {
return;
}
this.webview?.focus();
}
focusOutput(cellId: string) {
if (this._disposed) {
return;
}
this.webview?.focus();
setTimeout(() => { // Need this, or focus decoration is not shown. No clue.
this._sendMessageToWebview({
type: 'focus-output',
cellId,
});
}, 50);
}
deltaCellOutputContainerClassNames(cellId: string, added: string[], removed: string[]) {
this._sendMessageToWebview({
type: 'decorations',
cellId,
addedClassNames: added,
removedClassNames: removed
});
}
async updateKernelPreloads(extensionLocations: URI[], preloads: URI[]) {
if (this._disposed) {
return;
}
await this._loaded;
const resources: IPreloadResource[] = [];
for (const preload of preloads) {
const uri = this.environmentService.isExtensionDevelopment && (preload.scheme === 'http' || preload.scheme === 'https')
? preload : asWebviewUri(this.environmentService, this.id, preload);
if (!this._preloadsCache.has(uri.toString())) {
resources.push({ uri: uri.toString(), originalUri: preload.toString() });
this._preloadsCache.add(uri.toString());
}
}
if (!resources.length) {
return;
}
this.kernelRootsCache = [...extensionLocations, ...this.kernelRootsCache];
this._updatePreloads(resources, 'kernel');
}
async updateRendererPreloads(renderers: Iterable<INotebookRendererInfo>) {
if (this._disposed) {
return [];
}
await this._loaded;
const requiredPreloads: IPreloadResource[] = [];
const resources: IPreloadResource[] = [];
const extensionLocations: URI[] = [];
for (const rendererInfo of renderers) {
extensionLocations.push(rendererInfo.extensionLocation);
for (const preload of [rendererInfo.entrypoint, ...rendererInfo.preloads]) {
const uri = asWebviewUri(this.environmentService, this.id, preload);
const resource: IPreloadResource = { uri: uri.toString(), originalUri: preload.toString() };
requiredPreloads.push(resource);
if (!this._preloadsCache.has(uri.toString())) {
resources.push(resource);
this._preloadsCache.add(uri.toString());
}
}
}
if (!resources.length) {
return requiredPreloads;
}
this.rendererRootsCache = extensionLocations;
this._updatePreloads(resources, 'renderer');
return requiredPreloads;
}
private _updatePreloads(resources: IPreloadResource[], source: 'renderer' | 'kernel') {
if (!this.webview) {
return;
}
const mixedResourceRoots = [...(this.localResourceRootsCache || []), ...this.rendererRootsCache, ...this.kernelRootsCache];
this.webview.localResourcesRoot = mixedResourceRoots;
this._sendMessageToWebview({
type: 'preload',
resources: resources,
source: source
});
}
private _sendMessageToWebview(message: ToWebviewMessage) {
if (this._disposed) {
return;
}
this.webview?.postMessage(message);
}
clearPreloadsCache() {
this._preloadsCache.clear();
}
dispose() {
this._disposed = true;
this.webview?.dispose();
super.dispose();
}
}
| src/vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView.ts | 1 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.0002676195290405303,
0.0001706857146928087,
0.00016063815564848483,
0.00016951787983998656,
0.00000999362237052992
] |
{
"id": 7,
"code_window": [
"\t\t\tthis.updateForLayout(element, templateData);\n",
"\t\t}));\n",
"\n",
"\t\t// render toolbar first\n",
"\t\tthis.setupCellToolbarActions(templateData, elementDisposables);\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.updateForHover(element, templateData);\n",
"\t\telementDisposables.add(element.onDidChangeState(e => {\n",
"\t\t\tif (e.cellIsHoveredChanged) {\n",
"\t\t\t\tthis.updateForHover(element, templateData);\n",
"\t\t\t}\n",
"\t\t}));\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer.ts",
"type": "add",
"edit_start_line_idx": 536
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.codicon-wrench-subaction {
opacity: 0.5;
}
@keyframes codicon-spin {
100% {
transform:rotate(360deg);
}
}
.codicon-sync.codicon-modifier-spin, .codicon-loading.codicon-modifier-spin .codicon-gear.codicon-modifier-spin {
/* Use steps to throttle FPS to reduce CPU usage */
animation: codicon-spin 1.5s steps(30) infinite;
}
.codicon-modifier-disabled {
opacity: 0.4;
}
/* custom speed & easing for loading icon */
.codicon-loading,
.codicon-tree-item-loading::before {
animation-duration: 1s !important;
animation-timing-function: cubic-bezier(0.53, 0.21, 0.29, 0.67) !important;
}
| src/vs/base/browser/ui/codicons/codicon/codicon-modifiers.css | 0 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.00017845990078058094,
0.0001717057020869106,
0.000165696837939322,
0.00017133302753791213,
0.000005444147973321378
] |
{
"id": 7,
"code_window": [
"\t\t\tthis.updateForLayout(element, templateData);\n",
"\t\t}));\n",
"\n",
"\t\t// render toolbar first\n",
"\t\tthis.setupCellToolbarActions(templateData, elementDisposables);\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.updateForHover(element, templateData);\n",
"\t\telementDisposables.add(element.onDidChangeState(e => {\n",
"\t\t\tif (e.cellIsHoveredChanged) {\n",
"\t\t\t\tthis.updateForHover(element, templateData);\n",
"\t\t\t}\n",
"\t\t}));\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer.ts",
"type": "add",
"edit_start_line_idx": 536
} | <html>
<head>
<meta charset="utf-8">
<title>VSCode Tests</title>
<link href="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css" rel="stylesheet" />
</head>
<body>
<div id="mocha"></div>
<script src="/out/vs/loader.js"></script>
<script src="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script>
<script>
mocha.setup('tdd');
require.config({
baseUrl: '/out',
paths: {
assert: '/test/unit/assert.js',
sinon: '/node_modules/sinon/pkg/sinon-1.17.7.js'
}
});
require({{ modules }}, function () {
mocha.run();
});
</script>
</body>
</html>
| test/unit/node/index.html | 0 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.0001734179095365107,
0.00017127289902418852,
0.000169758393894881,
0.0001706423790892586,
0.0000015590970861012465
] |
{
"id": 7,
"code_window": [
"\t\t\tthis.updateForLayout(element, templateData);\n",
"\t\t}));\n",
"\n",
"\t\t// render toolbar first\n",
"\t\tthis.setupCellToolbarActions(templateData, elementDisposables);\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tthis.updateForHover(element, templateData);\n",
"\t\telementDisposables.add(element.onDidChangeState(e => {\n",
"\t\t\tif (e.cellIsHoveredChanged) {\n",
"\t\t\t\tthis.updateForHover(element, templateData);\n",
"\t\t\t}\n",
"\t\t}));\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer.ts",
"type": "add",
"edit_start_line_idx": 536
} | var x = `Hello ${foo}!`;
console.log(`string text line 1
string text line 2`);
x = tag`Hello ${ a + b } world ${ a * b }`; | extensions/vscode-colorize-tests/test/colorize-fixtures/test-strings.ts | 0 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.00017406234110239893,
0.00017406234110239893,
0.00017406234110239893,
0.00017406234110239893,
0
] |
{
"id": 8,
"code_window": [
"\t\tconst focusSideHeight = element.layoutInfo.totalHeight - BOTTOM_CELL_TOOLBAR_GAP;\n",
"\t\ttemplateData.focusIndicatorLeft.style.height = `${focusSideHeight}px`;\n",
"\t\ttemplateData.focusIndicatorRight.style.height = `${focusSideHeight}px`;\n",
"\t}\n",
"\n",
"\tdisposeTemplate(templateData: MarkdownCellRenderTemplate): void {\n",
"\t\ttemplateData.disposables.clear();\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate updateForHover(element: MarkdownCellViewModel, templateData: MarkdownCellRenderTemplate): void {\n",
"\t\ttemplateData.container.classList.toggle('markdown-cell-hover', element.cellIsHovered);\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer.ts",
"type": "add",
"edit_start_line_idx": 566
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { getPixelRatio, getZoomLevel } from 'vs/base/browser/browser';
import * as DOM from 'vs/base/browser/dom';
import { domEvent } from 'vs/base/browser/event';
import { IListRenderer, IListVirtualDelegate } from 'vs/base/browser/ui/list/list';
import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar';
import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar';
import { IAction } from 'vs/base/common/actions';
import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';
import { Color } from 'vs/base/common/color';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { deepClone } from 'vs/base/common/objects';
import * as platform from 'vs/base/common/platform';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget';
import { EditorOption, EDITOR_FONT_DEFAULTS, IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { BareFontInfo } from 'vs/editor/common/config/fontInfo';
import { Range } from 'vs/editor/common/core/range';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { ITextModel } from 'vs/editor/common/model';
import * as modes from 'vs/editor/common/modes';
import { tokenizeLineToHTML } from 'vs/editor/common/modes/textToHtmlTokenizer';
import { localize } from 'vs/nls';
import { createActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { IMenu, MenuItemAction } from 'vs/platform/actions/common/actions';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { BOTTOM_CELL_TOOLBAR_GAP, CELL_BOTTOM_MARGIN, CELL_TOP_MARGIN, EDITOR_BOTTOM_PADDING, EDITOR_BOTTOM_PADDING_WITHOUT_STATUSBAR, EDITOR_TOOLBAR_HEIGHT } from 'vs/workbench/contrib/notebook/browser/constants';
import { CancelCellAction, DeleteCellAction, ExecuteCellAction, INotebookCellActionContext } from 'vs/workbench/contrib/notebook/browser/contrib/coreActions';
import { BaseCellRenderTemplate, CellEditState, CodeCellRenderTemplate, EditorTopPaddingChangeEvent, EXPAND_CELL_CONTENT_COMMAND_ID, getEditorTopPadding, ICellViewModel, INotebookEditor, isCodeCellRenderTemplate, MarkdownCellRenderTemplate } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { CellContextKeyManager } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellContextKeys';
import { CellMenus } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellMenus';
import { CellEditorStatusBar } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellWidgets';
import { CodeCell } from 'vs/workbench/contrib/notebook/browser/view/renderers/codeCell';
import { CellDragAndDropController, DRAGGING_CLASS } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellDnd';
import { StatefulMarkdownCell } from 'vs/workbench/contrib/notebook/browser/view/renderers/markdownCell';
import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel';
import { MarkdownCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/markdownCellViewModel';
import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModel';
import { CellEditType, CellKind, NotebookCellMetadata, NotebookCellRunState, NotebookCellsChangeType, ShowCellStatusBarKey } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { CodiconActionViewItem, createAndFillInActionBarActionsWithVerticalSeparators, VerticalSeparator, VerticalSeparatorViewItem } from './cellActionView';
import { ThemeIcon } from 'vs/platform/theme/common/themeService';
import { errorStateIcon, successStateIcon, unfoldIcon } from 'vs/workbench/contrib/notebook/browser/notebookIcons';
import { syncing } from 'vs/platform/theme/common/iconRegistry';
const $ = DOM.$;
export class NotebookCellListDelegate implements IListVirtualDelegate<CellViewModel> {
private readonly lineHeight: number;
constructor(
@IConfigurationService private readonly configurationService: IConfigurationService
) {
const editorOptions = this.configurationService.getValue<IEditorOptions>('editor');
this.lineHeight = BareFontInfo.createFromRawSettings(editorOptions, getZoomLevel(), getPixelRatio()).lineHeight;
}
getHeight(element: CellViewModel): number {
return element.getHeight(this.lineHeight);
}
hasDynamicHeight(element: CellViewModel): boolean {
return element.hasDynamicHeight();
}
getTemplateId(element: CellViewModel): string {
if (element.cellKind === CellKind.Markdown) {
return MarkdownCellRenderer.TEMPLATE_ID;
} else {
return CodeCellRenderer.TEMPLATE_ID;
}
}
}
export class CellEditorOptions {
private static fixedEditorOptions: IEditorOptions = {
scrollBeyondLastLine: false,
scrollbar: {
verticalScrollbarSize: 14,
horizontal: 'auto',
useShadows: true,
verticalHasArrows: false,
horizontalHasArrows: false,
alwaysConsumeMouseWheel: false
},
renderLineHighlightOnlyWhenFocus: true,
overviewRulerLanes: 0,
selectOnLineNumbers: false,
lineNumbers: 'off',
lineDecorationsWidth: 0,
glyphMargin: false,
fixedOverflowWidgets: true,
minimap: { enabled: false },
renderValidationDecorations: 'on'
};
private _value: IEditorOptions;
private disposable: IDisposable;
private readonly _onDidChange = new Emitter<IEditorOptions>();
readonly onDidChange: Event<IEditorOptions> = this._onDidChange.event;
constructor(configurationService: IConfigurationService, language: string) {
this.disposable = configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('editor') || e.affectsConfiguration(ShowCellStatusBarKey)) {
this._value = computeEditorOptions();
this._onDidChange.fire(this.value);
}
});
EditorTopPaddingChangeEvent(() => {
this._value = computeEditorOptions();
this._onDidChange.fire(this.value);
});
const computeEditorOptions = () => {
const showCellStatusBar = configurationService.getValue<boolean>(ShowCellStatusBarKey);
const editorPadding = {
top: getEditorTopPadding(),
bottom: showCellStatusBar ? EDITOR_BOTTOM_PADDING : EDITOR_BOTTOM_PADDING_WITHOUT_STATUSBAR
};
const editorOptions = deepClone(configurationService.getValue<IEditorOptions>('editor', { overrideIdentifier: language }));
const computed = {
...editorOptions,
...CellEditorOptions.fixedEditorOptions,
...{ padding: editorPadding }
};
if (!computed.folding) {
computed.lineDecorationsWidth = 16;
}
return computed;
};
this._value = computeEditorOptions();
}
dispose(): void {
this._onDidChange.dispose();
this.disposable.dispose();
}
get value(): IEditorOptions {
return this._value;
}
setGlyphMargin(gm: boolean): void {
if (gm !== this._value.glyphMargin) {
this._value.glyphMargin = gm;
this._onDidChange.fire(this.value);
}
}
}
abstract class AbstractCellRenderer {
protected readonly editorOptions: CellEditorOptions;
protected readonly cellMenus: CellMenus;
constructor(
protected readonly instantiationService: IInstantiationService,
protected readonly notebookEditor: INotebookEditor,
protected readonly contextMenuService: IContextMenuService,
configurationService: IConfigurationService,
private readonly keybindingService: IKeybindingService,
private readonly notificationService: INotificationService,
protected readonly contextKeyServiceProvider: (container: HTMLElement) => IContextKeyService,
language: string,
protected readonly dndController: CellDragAndDropController
) {
this.editorOptions = new CellEditorOptions(configurationService, language);
this.cellMenus = this.instantiationService.createInstance(CellMenus);
}
dispose() {
this.editorOptions.dispose();
}
protected createBetweenCellToolbar(container: HTMLElement, disposables: DisposableStore, contextKeyService: IContextKeyService): ToolBar {
const toolbar = new ToolBar(container, this.contextMenuService, {
actionViewItemProvider: action => {
if (action instanceof MenuItemAction) {
const item = new CodiconActionViewItem(action, this.keybindingService, this.notificationService);
return item;
}
return undefined;
}
});
const cellMenu = this.instantiationService.createInstance(CellMenus);
const menu = disposables.add(cellMenu.getCellInsertionMenu(contextKeyService));
const actions = this.getCellToolbarActions(menu, false);
toolbar.setActions(actions.primary, actions.secondary);
return toolbar;
}
protected setBetweenCellToolbarContext(templateData: BaseCellRenderTemplate, element: CodeCellViewModel | MarkdownCellViewModel, context: INotebookCellActionContext): void {
templateData.betweenCellToolbar.context = context;
const container = templateData.bottomCellContainer;
const bottomToolbarOffset = element.layoutInfo.bottomToolbarOffset;
container.style.top = `${bottomToolbarOffset}px`;
templateData.elementDisposables.add(element.onDidChangeLayout(() => {
const bottomToolbarOffset = element.layoutInfo.bottomToolbarOffset;
container.style.top = `${bottomToolbarOffset}px`;
}));
}
protected createToolbar(container: HTMLElement, elementClass?: string): ToolBar {
const toolbar = new ToolBar(container, this.contextMenuService, {
getKeyBinding: action => this.keybindingService.lookupKeybinding(action.id),
actionViewItemProvider: action => {
if (action.id === VerticalSeparator.ID) {
return new VerticalSeparatorViewItem(undefined, action);
}
return createActionViewItem(this.instantiationService, action);
},
renderDropdownAsChildElement: true
});
if (elementClass) {
toolbar.getElement().classList.add(elementClass);
}
return toolbar;
}
private getCellToolbarActions(menu: IMenu, alwaysFillSecondaryActions: boolean): { primary: IAction[], secondary: IAction[] } {
const primary: IAction[] = [];
const secondary: IAction[] = [];
const result = { primary, secondary };
createAndFillInActionBarActionsWithVerticalSeparators(menu, { shouldForwardArgs: true }, result, alwaysFillSecondaryActions, g => /^inline/.test(g));
return result;
}
protected setupCellToolbarActions(templateData: BaseCellRenderTemplate, disposables: DisposableStore): void {
const updateActions = () => {
const actions = this.getCellToolbarActions(templateData.titleMenu, true);
const hadFocus = DOM.isAncestor(document.activeElement, templateData.toolbar.getElement());
templateData.toolbar.setActions(actions.primary, actions.secondary);
if (hadFocus) {
this.notebookEditor.focus();
}
if (actions.primary.length || actions.secondary.length) {
templateData.container.classList.add('cell-has-toolbar-actions');
if (isCodeCellRenderTemplate(templateData)) {
templateData.focusIndicatorLeft.style.top = `${EDITOR_TOOLBAR_HEIGHT + CELL_TOP_MARGIN}px`;
templateData.focusIndicatorRight.style.top = `${EDITOR_TOOLBAR_HEIGHT + CELL_TOP_MARGIN}px`;
}
} else {
templateData.container.classList.remove('cell-has-toolbar-actions');
if (isCodeCellRenderTemplate(templateData)) {
templateData.focusIndicatorLeft.style.top = `${CELL_TOP_MARGIN}px`;
templateData.focusIndicatorRight.style.top = `${CELL_TOP_MARGIN}px`;
}
}
};
// #103926
let dropdownIsVisible = false;
let deferredUpdate: (() => void) | undefined;
updateActions();
disposables.add(templateData.titleMenu.onDidChange(() => {
if (this.notebookEditor.isDisposed) {
return;
}
if (dropdownIsVisible) {
deferredUpdate = () => updateActions();
return;
}
updateActions();
}));
disposables.add(templateData.toolbar.onDidChangeDropdownVisibility(visible => {
dropdownIsVisible = visible;
if (deferredUpdate && !visible) {
setTimeout(() => {
if (deferredUpdate) {
deferredUpdate();
}
}, 0);
deferredUpdate = undefined;
}
}));
}
protected commonRenderTemplate(templateData: BaseCellRenderTemplate): void {
templateData.disposables.add(DOM.addDisposableListener(templateData.container, DOM.EventType.FOCUS, () => {
if (templateData.currentRenderedCell) {
this.notebookEditor.selectElement(templateData.currentRenderedCell);
}
}, true));
this.addExpandListener(templateData);
}
protected commonRenderElement(element: ICellViewModel, templateData: BaseCellRenderTemplate): void {
if (element.dragging) {
templateData.container.classList.add(DRAGGING_CLASS);
} else {
templateData.container.classList.remove(DRAGGING_CLASS);
}
}
protected addExpandListener(templateData: BaseCellRenderTemplate): void {
templateData.disposables.add(domEvent(templateData.expandButton, DOM.EventType.CLICK)(() => {
if (!templateData.currentRenderedCell) {
return;
}
const textModel = this.notebookEditor.viewModel!.notebookDocument;
const index = textModel.cells.indexOf(templateData.currentRenderedCell.model);
if (index < 0) {
return;
}
if (templateData.currentRenderedCell.metadata?.inputCollapsed) {
textModel.applyEdits(textModel.versionId, [
{ editType: CellEditType.Metadata, index, metadata: { ...templateData.currentRenderedCell.metadata, inputCollapsed: false } }
], true, undefined, () => undefined, undefined);
} else if (templateData.currentRenderedCell.metadata?.outputCollapsed) {
textModel.applyEdits(textModel.versionId, [
{ editType: CellEditType.Metadata, index, metadata: { ...templateData.currentRenderedCell.metadata, outputCollapsed: false } }
], true, undefined, () => undefined, undefined);
}
}));
}
protected setupCollapsedPart(container: HTMLElement): { collapsedPart: HTMLElement, expandButton: HTMLElement } {
const collapsedPart = DOM.append(container, $('.cell.cell-collapsed-part', undefined, $('span.expandButton' + ThemeIcon.asCSSSelector(unfoldIcon))));
const expandButton = collapsedPart.querySelector('.expandButton') as HTMLElement;
const keybinding = this.keybindingService.lookupKeybinding(EXPAND_CELL_CONTENT_COMMAND_ID);
let title = localize('cellExpandButtonLabel', "Expand");
if (keybinding) {
title += ` (${keybinding.getLabel()})`;
}
collapsedPart.title = title;
DOM.hide(collapsedPart);
return { collapsedPart, expandButton };
}
}
export class MarkdownCellRenderer extends AbstractCellRenderer implements IListRenderer<MarkdownCellViewModel, MarkdownCellRenderTemplate> {
static readonly TEMPLATE_ID = 'markdown_cell';
constructor(
notebookEditor: INotebookEditor,
dndController: CellDragAndDropController,
private renderedEditors: Map<ICellViewModel, ICodeEditor | undefined>,
contextKeyServiceProvider: (container: HTMLElement) => IContextKeyService,
@IInstantiationService instantiationService: IInstantiationService,
@IConfigurationService configurationService: IConfigurationService,
@IContextMenuService contextMenuService: IContextMenuService,
@IKeybindingService keybindingService: IKeybindingService,
@INotificationService notificationService: INotificationService,
) {
super(instantiationService, notebookEditor, contextMenuService, configurationService, keybindingService, notificationService, contextKeyServiceProvider, 'markdown', dndController);
}
get templateId() {
return MarkdownCellRenderer.TEMPLATE_ID;
}
renderTemplate(rootContainer: HTMLElement): MarkdownCellRenderTemplate {
rootContainer.classList.add('markdown-cell-row');
const container = DOM.append(rootContainer, DOM.$('.cell-inner-container'));
const disposables = new DisposableStore();
const contextKeyService = disposables.add(this.contextKeyServiceProvider(container));
const decorationContainer = DOM.append(rootContainer, $('.cell-decoration'));
const titleToolbarContainer = DOM.append(container, $('.cell-title-toolbar'));
const toolbar = disposables.add(this.createToolbar(titleToolbarContainer));
const deleteToolbar = disposables.add(this.createToolbar(titleToolbarContainer, 'cell-delete-toolbar'));
deleteToolbar.setActions([this.instantiationService.createInstance(DeleteCellAction)]);
DOM.append(container, $('.cell-focus-indicator.cell-focus-indicator-top'));
const focusIndicatorLeft = DOM.append(container, DOM.$('.cell-focus-indicator.cell-focus-indicator-side.cell-focus-indicator-left'));
const focusIndicatorRight = DOM.append(container, DOM.$('.cell-focus-indicator.cell-focus-indicator-side.cell-focus-indicator-right'));
const codeInnerContent = DOM.append(container, $('.cell.code'));
const editorPart = DOM.append(codeInnerContent, $('.cell-editor-part'));
const editorContainer = DOM.append(editorPart, $('.cell-editor-container'));
editorPart.style.display = 'none';
const innerContent = DOM.append(container, $('.cell.markdown'));
const foldingIndicator = DOM.append(focusIndicatorLeft, DOM.$('.notebook-folding-indicator'));
const { collapsedPart, expandButton } = this.setupCollapsedPart(container);
const bottomCellContainer = DOM.append(container, $('.cell-bottom-toolbar-container'));
const betweenCellToolbar = disposables.add(this.createBetweenCellToolbar(bottomCellContainer, disposables, contextKeyService));
const focusIndicatorBottom = DOM.append(container, $('.cell-focus-indicator.cell-focus-indicator-bottom'));
const statusBar = disposables.add(this.instantiationService.createInstance(CellEditorStatusBar, editorPart));
DOM.hide(statusBar.durationContainer);
DOM.hide(statusBar.cellRunStatusContainer);
const titleMenu = disposables.add(this.cellMenus.getCellTitleMenu(contextKeyService));
const templateData: MarkdownCellRenderTemplate = {
rootContainer,
collapsedPart,
expandButton,
contextKeyService,
container,
decorationContainer,
cellContainer: innerContent,
editorPart,
editorContainer,
focusIndicatorLeft,
focusIndicatorBottom,
focusIndicatorRight,
foldingIndicator,
disposables,
elementDisposables: new DisposableStore(),
toolbar,
deleteToolbar,
betweenCellToolbar,
bottomCellContainer,
titleMenu,
statusBar,
toJSON: () => { return {}; }
};
this.dndController.registerDragHandle(templateData, rootContainer, container, () => this.getDragImage(templateData));
this.commonRenderTemplate(templateData);
return templateData;
}
private getDragImage(templateData: MarkdownCellRenderTemplate): HTMLElement {
if (templateData.currentRenderedCell?.editState === CellEditState.Editing) {
return this.getEditDragImage(templateData);
} else {
return this.getMarkdownDragImage(templateData);
}
}
private getMarkdownDragImage(templateData: MarkdownCellRenderTemplate): HTMLElement {
const dragImageContainer = DOM.$('.cell-drag-image.monaco-list-row.focused.markdown-cell-row');
DOM.reset(dragImageContainer, templateData.container.cloneNode(true));
// Remove all rendered content nodes after the
const markdownContent = dragImageContainer.querySelector('.cell.markdown')!;
const contentNodes = markdownContent.children[0].children;
for (let i = contentNodes.length - 1; i >= 1; i--) {
contentNodes.item(i)!.remove();
}
return dragImageContainer;
}
private getEditDragImage(templateData: MarkdownCellRenderTemplate): HTMLElement {
return new CodeCellDragImageRenderer().getDragImage(templateData, templateData.currentEditor!, 'markdown');
}
renderElement(element: MarkdownCellViewModel, index: number, templateData: MarkdownCellRenderTemplate, height: number | undefined): void {
if (!this.notebookEditor.hasModel()) {
throw new Error('The notebook editor is not attached with view model yet.');
}
const removedClassNames: string[] = [];
templateData.rootContainer.classList.forEach(className => {
if (/^nb\-.*$/.test(className)) {
removedClassNames.push(className);
}
});
removedClassNames.forEach(className => {
templateData.rootContainer.classList.remove(className);
});
templateData.decorationContainer.innerText = '';
this.commonRenderElement(element, templateData);
templateData.currentRenderedCell = element;
templateData.currentEditor = undefined;
templateData.editorPart.style.display = 'none';
templateData.cellContainer.innerText = '';
if (height === undefined) {
return;
}
const elementDisposables = templateData.elementDisposables;
const generateCellTopDecorations = () => {
templateData.decorationContainer.innerText = '';
element.getCellDecorations().filter(options => options.topClassName !== undefined).forEach(options => {
templateData.decorationContainer.append(DOM.$(`.${options.topClassName!}`));
});
};
elementDisposables.add(element.onCellDecorationsChanged((e) => {
const modified = e.added.find(e => e.topClassName) || e.removed.find(e => e.topClassName);
if (modified) {
generateCellTopDecorations();
}
}));
elementDisposables.add(new CellContextKeyManager(templateData.contextKeyService, this.notebookEditor, this.notebookEditor.viewModel.notebookDocument!, element));
this.updateForLayout(element, templateData);
elementDisposables.add(element.onDidChangeLayout(() => {
this.updateForLayout(element, templateData);
}));
// render toolbar first
this.setupCellToolbarActions(templateData, elementDisposables);
const toolbarContext = <INotebookCellActionContext>{
cell: element,
notebookEditor: this.notebookEditor,
$mid: 12
};
templateData.toolbar.context = toolbarContext;
templateData.deleteToolbar.context = toolbarContext;
this.setBetweenCellToolbarContext(templateData, element, toolbarContext);
const scopedInstaService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, templateData.contextKeyService]));
const markdownCell = scopedInstaService.createInstance(StatefulMarkdownCell, this.notebookEditor, element, templateData, this.editorOptions.value, this.renderedEditors);
elementDisposables.add(this.editorOptions.onDidChange(newValue => markdownCell.updateEditorOptions(newValue)));
elementDisposables.add(markdownCell);
templateData.statusBar.update(toolbarContext);
}
private updateForLayout(element: MarkdownCellViewModel, templateData: MarkdownCellRenderTemplate): void {
// templateData.focusIndicatorLeft.style.height = `${element.layoutInfo.indicatorHeight}px`;
templateData.focusIndicatorBottom.style.top = `${element.layoutInfo.totalHeight - BOTTOM_CELL_TOOLBAR_GAP - CELL_BOTTOM_MARGIN}px`;
const focusSideHeight = element.layoutInfo.totalHeight - BOTTOM_CELL_TOOLBAR_GAP;
templateData.focusIndicatorLeft.style.height = `${focusSideHeight}px`;
templateData.focusIndicatorRight.style.height = `${focusSideHeight}px`;
}
disposeTemplate(templateData: MarkdownCellRenderTemplate): void {
templateData.disposables.clear();
}
disposeElement(element: ICellViewModel, _index: number, templateData: MarkdownCellRenderTemplate): void {
templateData.elementDisposables.clear();
element.getCellDecorations().forEach(e => {
if (e.className) {
templateData.container.classList.remove(e.className);
}
});
}
}
class EditorTextRenderer {
private static _ttPolicy = window.trustedTypes?.createPolicy('cellRendererEditorText', {
createHTML(input) { return input; }
});
getRichText(editor: ICodeEditor, modelRange: Range): HTMLElement | null {
const model = editor.getModel();
if (!model) {
return null;
}
const colorMap = this.getDefaultColorMap();
const fontInfo = editor.getOptions().get(EditorOption.fontInfo);
const fontFamily = fontInfo.fontFamily === EDITOR_FONT_DEFAULTS.fontFamily ? fontInfo.fontFamily : `'${fontInfo.fontFamily}', ${EDITOR_FONT_DEFAULTS.fontFamily}`;
const style = ``
+ `color: ${colorMap[modes.ColorId.DefaultForeground]};`
+ `background-color: ${colorMap[modes.ColorId.DefaultBackground]};`
+ `font-family: ${fontFamily};`
+ `font-weight: ${fontInfo.fontWeight};`
+ `font-size: ${fontInfo.fontSize}px;`
+ `line-height: ${fontInfo.lineHeight}px;`
+ `white-space: pre;`;
const element = DOM.$('div', { style });
const linesHtml = this.getRichTextLinesAsHtml(model, modelRange, colorMap);
element.innerHTML = linesHtml as string;
return element;
}
private getRichTextLinesAsHtml(model: ITextModel, modelRange: Range, colorMap: string[]): string | TrustedHTML {
const startLineNumber = modelRange.startLineNumber;
const startColumn = modelRange.startColumn;
const endLineNumber = modelRange.endLineNumber;
const endColumn = modelRange.endColumn;
const tabSize = model.getOptions().tabSize;
let result = '';
for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
const lineTokens = model.getLineTokens(lineNumber);
const lineContent = lineTokens.getLineContent();
const startOffset = (lineNumber === startLineNumber ? startColumn - 1 : 0);
const endOffset = (lineNumber === endLineNumber ? endColumn - 1 : lineContent.length);
if (lineContent === '') {
result += '<br>';
} else {
result += tokenizeLineToHTML(lineContent, lineTokens.inflate(), colorMap, startOffset, endOffset, tabSize, platform.isWindows);
}
}
return EditorTextRenderer._ttPolicy?.createHTML(result) ?? result;
}
private getDefaultColorMap(): string[] {
const colorMap = modes.TokenizationRegistry.getColorMap();
const result: string[] = ['#000000'];
if (colorMap) {
for (let i = 1, len = colorMap.length; i < len; i++) {
result[i] = Color.Format.CSS.formatHex(colorMap[i]);
}
}
return result;
}
}
class CodeCellDragImageRenderer {
getDragImage(templateData: BaseCellRenderTemplate, editor: ICodeEditor, type: 'code' | 'markdown'): HTMLElement {
let dragImage = this.getDragImageImpl(templateData, editor, type);
if (!dragImage) {
// TODO@roblourens I don't think this can happen
dragImage = document.createElement('div');
dragImage.textContent = '1 cell';
}
return dragImage;
}
private getDragImageImpl(templateData: BaseCellRenderTemplate, editor: ICodeEditor, type: 'code' | 'markdown'): HTMLElement | null {
const dragImageContainer = templateData.container.cloneNode(true) as HTMLElement;
dragImageContainer.classList.forEach(c => dragImageContainer.classList.remove(c));
dragImageContainer.classList.add('cell-drag-image', 'monaco-list-row', 'focused', `${type}-cell-row`);
const editorContainer: HTMLElement | null = dragImageContainer.querySelector('.cell-editor-container');
if (!editorContainer) {
return null;
}
const richEditorText = new EditorTextRenderer().getRichText(editor, new Range(1, 1, 1, 1000));
if (!richEditorText) {
return null;
}
DOM.reset(editorContainer, richEditorText);
return dragImageContainer;
}
}
export class CodeCellRenderer extends AbstractCellRenderer implements IListRenderer<CodeCellViewModel, CodeCellRenderTemplate> {
static readonly TEMPLATE_ID = 'code_cell';
constructor(
protected notebookEditor: INotebookEditor,
private renderedEditors: Map<ICellViewModel, ICodeEditor | undefined>,
dndController: CellDragAndDropController,
contextKeyServiceProvider: (container: HTMLElement) => IContextKeyService,
@IContextMenuService contextMenuService: IContextMenuService,
@IConfigurationService configurationService: IConfigurationService,
@IInstantiationService instantiationService: IInstantiationService,
@IKeybindingService keybindingService: IKeybindingService,
@INotificationService notificationService: INotificationService,
) {
super(instantiationService, notebookEditor, contextMenuService, configurationService, keybindingService, notificationService, contextKeyServiceProvider, 'python', dndController);
}
get templateId() {
return CodeCellRenderer.TEMPLATE_ID;
}
renderTemplate(rootContainer: HTMLElement): CodeCellRenderTemplate {
rootContainer.classList.add('code-cell-row');
const container = DOM.append(rootContainer, DOM.$('.cell-inner-container'));
const disposables = new DisposableStore();
const contextKeyService = disposables.add(this.contextKeyServiceProvider(container));
const decorationContainer = DOM.append(rootContainer, $('.cell-decoration'));
DOM.append(container, $('.cell-focus-indicator.cell-focus-indicator-top'));
const titleToolbarContainer = DOM.append(container, $('.cell-title-toolbar'));
const toolbar = disposables.add(this.createToolbar(titleToolbarContainer));
const deleteToolbar = disposables.add(this.createToolbar(titleToolbarContainer, 'cell-delete-toolbar'));
deleteToolbar.setActions([this.instantiationService.createInstance(DeleteCellAction)]);
const focusIndicator = DOM.append(container, DOM.$('.cell-focus-indicator.cell-focus-indicator-side.cell-focus-indicator-left'));
const dragHandle = DOM.append(container, DOM.$('.cell-drag-handle'));
const cellContainer = DOM.append(container, $('.cell.code'));
const runButtonContainer = DOM.append(cellContainer, $('.run-button-container'));
const runToolbar = disposables.add(this.createToolbar(runButtonContainer));
const executionOrderLabel = DOM.append(cellContainer, $('div.execution-count-label'));
const editorPart = DOM.append(cellContainer, $('.cell-editor-part'));
const editorContainer = DOM.append(editorPart, $('.cell-editor-container'));
// create a special context key service that set the inCompositeEditor-contextkey
const editorContextKeyService = disposables.add(this.contextKeyServiceProvider(editorPart));
const editorInstaService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, editorContextKeyService]));
EditorContextKeys.inCompositeEditor.bindTo(editorContextKeyService).set(true);
const editor = editorInstaService.createInstance(CodeEditorWidget, editorContainer, {
...this.editorOptions.value,
dimension: {
width: 0,
height: 0
},
// overflowWidgetsDomNode: this.notebookEditor.getOverflowContainerDomNode()
}, {});
disposables.add(this.editorOptions.onDidChange(newValue => editor.updateOptions(newValue)));
const { collapsedPart, expandButton } = this.setupCollapsedPart(container);
const progressBar = new ProgressBar(editorPart);
progressBar.hide();
disposables.add(progressBar);
const statusBar = disposables.add(this.instantiationService.createInstance(CellEditorStatusBar, editorPart));
const timer = new TimerRenderer(statusBar.durationContainer);
const cellRunState = new RunStateRenderer(statusBar.cellRunStatusContainer, runToolbar, this.instantiationService);
const outputContainer = DOM.append(container, $('.output'));
const outputShowMoreContainer = DOM.append(container, $('.output-show-more-container'));
const focusIndicatorRight = DOM.append(container, DOM.$('.cell-focus-indicator.cell-focus-indicator-side.cell-focus-indicator-right'));
const focusSinkElement = DOM.append(container, $('.cell-editor-focus-sink'));
focusSinkElement.setAttribute('tabindex', '0');
const bottomCellContainer = DOM.append(container, $('.cell-bottom-toolbar-container'));
const focusIndicatorBottom = DOM.append(container, $('.cell-focus-indicator.cell-focus-indicator-bottom'));
const betweenCellToolbar = this.createBetweenCellToolbar(bottomCellContainer, disposables, contextKeyService);
const titleMenu = disposables.add(this.cellMenus.getCellTitleMenu(contextKeyService));
const templateData: CodeCellRenderTemplate = {
rootContainer,
editorPart,
collapsedPart,
expandButton,
contextKeyService,
container,
decorationContainer,
cellContainer,
cellRunState,
progressBar,
statusBar,
focusIndicatorLeft: focusIndicator,
focusIndicatorRight,
focusIndicatorBottom,
toolbar,
deleteToolbar,
betweenCellToolbar,
focusSinkElement,
runToolbar,
runButtonContainer,
executionOrderLabel,
outputContainer,
outputShowMoreContainer,
editor,
disposables,
elementDisposables: new DisposableStore(),
bottomCellContainer,
timer,
titleMenu,
dragHandle,
toJSON: () => { return {}; }
};
this.dndController.registerDragHandle(templateData, rootContainer, dragHandle, () => new CodeCellDragImageRenderer().getDragImage(templateData, templateData.editor, 'code'));
disposables.add(DOM.addDisposableListener(focusSinkElement, DOM.EventType.FOCUS, () => {
if (templateData.currentRenderedCell && (templateData.currentRenderedCell as CodeCellViewModel).outputsViewModels.length) {
this.notebookEditor.focusNotebookCell(templateData.currentRenderedCell, 'output');
}
}));
this.commonRenderTemplate(templateData);
return templateData;
}
private updateForOutputs(element: CodeCellViewModel, templateData: CodeCellRenderTemplate): void {
if (element.outputsViewModels.length) {
DOM.show(templateData.focusSinkElement);
} else {
DOM.hide(templateData.focusSinkElement);
}
}
private updateForMetadata(element: CodeCellViewModel, templateData: CodeCellRenderTemplate): void {
if (!this.notebookEditor.hasModel()) {
return;
}
const metadata = element.getEvaluatedMetadata(this.notebookEditor.viewModel.notebookDocument.metadata);
templateData.container.classList.toggle('runnable', !!metadata.runnable);
this.updateExecutionOrder(metadata, templateData);
templateData.statusBar.cellStatusMessageContainer.textContent = metadata?.statusMessage || '';
templateData.cellRunState.renderState(element.metadata?.runState);
if (metadata.runState === NotebookCellRunState.Running) {
if (metadata.runStartTime) {
templateData.elementDisposables.add(templateData.timer.start(metadata.runStartTime));
} else {
templateData.timer.clear();
}
} else if (typeof metadata.lastRunDuration === 'number') {
templateData.timer.show(metadata.lastRunDuration);
} else {
templateData.timer.clear();
}
if (typeof metadata.breakpointMargin === 'boolean') {
this.editorOptions.setGlyphMargin(metadata.breakpointMargin);
}
if (metadata.runState === NotebookCellRunState.Running) {
templateData.progressBar.infinite().show(500);
} else {
templateData.progressBar.hide();
}
}
private updateExecutionOrder(metadata: NotebookCellMetadata, templateData: CodeCellRenderTemplate): void {
if (metadata.hasExecutionOrder) {
const executionOrderLabel = typeof metadata.executionOrder === 'number' ?
`[${metadata.executionOrder}]` :
'[ ]';
templateData.executionOrderLabel.innerText = executionOrderLabel;
} else {
templateData.executionOrderLabel.innerText = '';
}
}
private updateForHover(element: CodeCellViewModel, templateData: CodeCellRenderTemplate): void {
templateData.container.classList.toggle('cell-output-hover', element.outputIsHovered);
}
private updateForLayout(element: CodeCellViewModel, templateData: CodeCellRenderTemplate): void {
templateData.focusIndicatorLeft.style.height = `${element.layoutInfo.indicatorHeight}px`;
templateData.focusIndicatorRight.style.height = `${element.layoutInfo.indicatorHeight}px`;
templateData.focusIndicatorBottom.style.top = `${element.layoutInfo.totalHeight - BOTTOM_CELL_TOOLBAR_GAP - CELL_BOTTOM_MARGIN}px`;
templateData.outputContainer.style.top = `${element.layoutInfo.outputContainerOffset}px`;
templateData.outputShowMoreContainer.style.top = `${element.layoutInfo.outputShowMoreContainerOffset}px`;
templateData.dragHandle.style.height = `${element.layoutInfo.totalHeight - BOTTOM_CELL_TOOLBAR_GAP}px`;
}
renderElement(element: CodeCellViewModel, index: number, templateData: CodeCellRenderTemplate, height: number | undefined): void {
if (!this.notebookEditor.hasModel()) {
throw new Error('The notebook editor is not attached with view model yet.');
}
const removedClassNames: string[] = [];
templateData.rootContainer.classList.forEach(className => {
if (/^nb\-.*$/.test(className)) {
removedClassNames.push(className);
}
});
removedClassNames.forEach(className => {
templateData.rootContainer.classList.remove(className);
});
templateData.decorationContainer.innerText = '';
this.commonRenderElement(element, templateData);
templateData.currentRenderedCell = element;
if (height === undefined) {
return;
}
templateData.outputContainer.innerText = '';
const elementDisposables = templateData.elementDisposables;
const generateCellTopDecorations = () => {
templateData.decorationContainer.innerText = '';
element.getCellDecorations().filter(options => options.topClassName !== undefined).forEach(options => {
templateData.decorationContainer.append(DOM.$(`.${options.topClassName!}`));
});
};
elementDisposables.add(element.onCellDecorationsChanged((e) => {
const modified = e.added.find(e => e.topClassName) || e.removed.find(e => e.topClassName);
if (modified) {
generateCellTopDecorations();
}
}));
generateCellTopDecorations();
elementDisposables.add(this.instantiationService.createInstance(CodeCell, this.notebookEditor, element, templateData));
this.renderedEditors.set(element, templateData.editor);
elementDisposables.add(new CellContextKeyManager(templateData.contextKeyService, this.notebookEditor, this.notebookEditor.viewModel.notebookDocument!, element));
this.updateForLayout(element, templateData);
elementDisposables.add(element.onDidChangeLayout(() => {
this.updateForLayout(element, templateData);
}));
templateData.cellRunState.clear();
this.updateForMetadata(element, templateData);
this.updateForHover(element, templateData);
elementDisposables.add(element.onDidChangeState((e) => {
if (e.metadataChanged) {
this.updateForMetadata(element, templateData);
}
if (e.outputIsHoveredChanged) {
this.updateForHover(element, templateData);
}
}));
elementDisposables.add(this.notebookEditor.viewModel.notebookDocument.onDidChangeContent(e => {
if (e.rawEvents.find(event => event.kind === NotebookCellsChangeType.ChangeDocumentMetadata)) {
this.updateForMetadata(element, templateData);
}
}));
this.updateForOutputs(element, templateData);
elementDisposables.add(element.onDidChangeOutputs(_e => this.updateForOutputs(element, templateData)));
this.setupCellToolbarActions(templateData, elementDisposables);
const toolbarContext = <INotebookCellActionContext>{
cell: element,
cellTemplate: templateData,
notebookEditor: this.notebookEditor,
$mid: 12
};
templateData.toolbar.context = toolbarContext;
templateData.runToolbar.context = toolbarContext;
templateData.deleteToolbar.context = toolbarContext;
this.setBetweenCellToolbarContext(templateData, element, toolbarContext);
templateData.statusBar.update(toolbarContext);
}
disposeTemplate(templateData: CodeCellRenderTemplate): void {
templateData.disposables.clear();
}
disposeElement(element: ICellViewModel, index: number, templateData: CodeCellRenderTemplate, height: number | undefined): void {
templateData.elementDisposables.clear();
this.renderedEditors.delete(element);
}
}
export class TimerRenderer {
constructor(private readonly container: HTMLElement) {
DOM.hide(container);
}
private intervalTimer: number | undefined;
start(startTime: number): IDisposable {
this.stop();
DOM.show(this.container);
const intervalTimer = setInterval(() => {
const duration = Date.now() - startTime;
this.container.textContent = this.formatDuration(duration);
}, 100);
this.intervalTimer = intervalTimer as unknown as number | undefined;
return toDisposable(() => {
clearInterval(intervalTimer);
});
}
stop() {
if (this.intervalTimer) {
clearInterval(this.intervalTimer);
}
}
show(duration: number) {
this.stop();
DOM.show(this.container);
this.container.textContent = this.formatDuration(duration);
}
clear() {
DOM.hide(this.container);
this.stop();
this.container.textContent = '';
}
private formatDuration(duration: number) {
const seconds = Math.floor(duration / 1000);
const tenths = String(duration - seconds * 1000).charAt(0);
return `${seconds}.${tenths}s`;
}
}
export class RunStateRenderer {
private static readonly MIN_SPINNER_TIME = 200;
private spinnerTimer: any | undefined;
private pendingNewState: NotebookCellRunState | undefined;
constructor(private readonly element: HTMLElement, private readonly runToolbar: ToolBar, private readonly instantiationService: IInstantiationService) {
DOM.hide(element);
}
clear() {
if (this.spinnerTimer) {
clearTimeout(this.spinnerTimer);
this.spinnerTimer = undefined;
}
}
renderState(runState: NotebookCellRunState = NotebookCellRunState.Idle) {
if (this.spinnerTimer) {
this.pendingNewState = runState;
return;
}
if (runState === NotebookCellRunState.Running) {
this.runToolbar.setActions([this.instantiationService.createInstance(CancelCellAction)]);
} else {
this.runToolbar.setActions([this.instantiationService.createInstance(ExecuteCellAction)]);
}
if (runState === NotebookCellRunState.Success) {
DOM.reset(this.element, renderIcon(successStateIcon));
} else if (runState === NotebookCellRunState.Error) {
DOM.reset(this.element, renderIcon(errorStateIcon));
} else if (runState === NotebookCellRunState.Running) {
DOM.reset(this.element, renderIcon(syncing));
this.spinnerTimer = setTimeout(() => {
this.spinnerTimer = undefined;
if (this.pendingNewState) {
this.renderState(this.pendingNewState);
this.pendingNewState = undefined;
}
}, RunStateRenderer.MIN_SPINNER_TIME);
} else {
this.element.innerText = '';
}
if (runState === NotebookCellRunState.Idle) {
DOM.hide(this.element);
} else {
this.element.style.display = 'flex';
}
}
}
export class ListTopCellToolbar extends Disposable {
private topCellToolbar: HTMLElement;
private _modelDisposables = new DisposableStore();
constructor(
protected readonly notebookEditor: INotebookEditor,
insertionIndicatorContainer: HTMLElement,
@IInstantiationService protected readonly instantiationService: IInstantiationService,
@IContextMenuService protected readonly contextMenuService: IContextMenuService,
@IKeybindingService private readonly keybindingService: IKeybindingService,
@INotificationService private readonly notificationService: INotificationService,
@IContextKeyService readonly contextKeyService: IContextKeyService,
) {
super();
this.topCellToolbar = DOM.append(insertionIndicatorContainer, $('.cell-list-top-cell-toolbar-container'));
const toolbar = new ToolBar(this.topCellToolbar, this.contextMenuService, {
actionViewItemProvider: action => {
if (action instanceof MenuItemAction) {
const item = new CodiconActionViewItem(action, this.keybindingService, this.notificationService);
return item;
}
return undefined;
}
});
const cellMenu = this.instantiationService.createInstance(CellMenus);
const menu = this._register(cellMenu.getCellTopInsertionMenu(contextKeyService));
const actions = this.getCellToolbarActions(menu, false);
toolbar.setActions(actions.primary, actions.secondary);
this._register(toolbar);
this._register(this.notebookEditor.onDidChangeModel(() => {
this._modelDisposables.clear();
if (this.notebookEditor.viewModel) {
this._modelDisposables.add(this.notebookEditor.viewModel.onDidChangeViewCells(() => {
this.updateClass();
}));
this.updateClass();
}
}));
this.updateClass();
}
private updateClass() {
if (this.notebookEditor.viewModel?.length === 0) {
this.topCellToolbar.classList.add('emptyNotebook');
} else {
this.topCellToolbar.classList.remove('emptyNotebook');
}
}
private getCellToolbarActions(menu: IMenu, alwaysFillSecondaryActions: boolean): { primary: IAction[], secondary: IAction[] } {
const primary: IAction[] = [];
const secondary: IAction[] = [];
const result = { primary, secondary };
createAndFillInActionBarActionsWithVerticalSeparators(menu, { shouldForwardArgs: true }, result, alwaysFillSecondaryActions, g => /^inline/.test(g));
return result;
}
}
| src/vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer.ts | 1 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.998479425907135,
0.028972923755645752,
0.0001607849553693086,
0.00038325448986142874,
0.15579108893871307
] |
{
"id": 8,
"code_window": [
"\t\tconst focusSideHeight = element.layoutInfo.totalHeight - BOTTOM_CELL_TOOLBAR_GAP;\n",
"\t\ttemplateData.focusIndicatorLeft.style.height = `${focusSideHeight}px`;\n",
"\t\ttemplateData.focusIndicatorRight.style.height = `${focusSideHeight}px`;\n",
"\t}\n",
"\n",
"\tdisposeTemplate(templateData: MarkdownCellRenderTemplate): void {\n",
"\t\ttemplateData.disposables.clear();\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate updateForHover(element: MarkdownCellViewModel, templateData: MarkdownCellRenderTemplate): void {\n",
"\t\ttemplateData.container.classList.toggle('markdown-cell-hover', element.cellIsHovered);\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer.ts",
"type": "add",
"edit_start_line_idx": 566
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
export interface MatcherWithPriority<T> {
matcher: Matcher<T>;
priority: -1 | 0 | 1;
}
export interface Matcher<T> {
(matcherInput: T): number;
}
export function createMatchers<T>(selector: string, matchesName: (names: string[], matcherInput: T) => number, results: MatcherWithPriority<T>[]): void {
const tokenizer = newTokenizer(selector);
let token = tokenizer.next();
while (token !== null) {
let priority: -1 | 0 | 1 = 0;
if (token.length === 2 && token.charAt(1) === ':') {
switch (token.charAt(0)) {
case 'R': priority = 1; break;
case 'L': priority = -1; break;
default:
console.log(`Unknown priority ${token} in scope selector`);
}
token = tokenizer.next();
}
let matcher = parseConjunction();
if (matcher) {
results.push({ matcher, priority });
}
if (token !== ',') {
break;
}
token = tokenizer.next();
}
function parseOperand(): Matcher<T> | null {
if (token === '-') {
token = tokenizer.next();
const expressionToNegate = parseOperand();
if (!expressionToNegate) {
return null;
}
return matcherInput => {
const score = expressionToNegate(matcherInput);
return score < 0 ? 0 : -1;
};
}
if (token === '(') {
token = tokenizer.next();
const expressionInParents = parseInnerExpression();
if (token === ')') {
token = tokenizer.next();
}
return expressionInParents;
}
if (isIdentifier(token)) {
const identifiers: string[] = [];
do {
identifiers.push(token);
token = tokenizer.next();
} while (isIdentifier(token));
return matcherInput => matchesName(identifiers, matcherInput);
}
return null;
}
function parseConjunction(): Matcher<T> | null {
let matcher = parseOperand();
if (!matcher) {
return null;
}
const matchers: Matcher<T>[] = [];
while (matcher) {
matchers.push(matcher);
matcher = parseOperand();
}
return matcherInput => { // and
let min = matchers[0](matcherInput);
for (let i = 1; min >= 0 && i < matchers.length; i++) {
min = Math.min(min, matchers[i](matcherInput));
}
return min;
};
}
function parseInnerExpression(): Matcher<T> | null {
let matcher = parseConjunction();
if (!matcher) {
return null;
}
const matchers: Matcher<T>[] = [];
while (matcher) {
matchers.push(matcher);
if (token === '|' || token === ',') {
do {
token = tokenizer.next();
} while (token === '|' || token === ','); // ignore subsequent commas
} else {
break;
}
matcher = parseConjunction();
}
return matcherInput => { // or
let max = matchers[0](matcherInput);
for (let i = 1; i < matchers.length; i++) {
max = Math.max(max, matchers[i](matcherInput));
}
return max;
};
}
}
function isIdentifier(token: string | null): token is string {
return !!token && !!token.match(/[\w\.:]+/);
}
function newTokenizer(input: string): { next: () => string | null } {
let regex = /([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g;
let match = regex.exec(input);
return {
next: () => {
if (!match) {
return null;
}
const res = match[0];
match = regex.exec(input);
return res;
}
};
}
| src/vs/workbench/services/themes/common/textMateScopeMatcher.ts | 0 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.00017821489018388093,
0.00017450762970838696,
0.00016996766498778015,
0.0001747719943523407,
0.0000017534989638079423
] |
{
"id": 8,
"code_window": [
"\t\tconst focusSideHeight = element.layoutInfo.totalHeight - BOTTOM_CELL_TOOLBAR_GAP;\n",
"\t\ttemplateData.focusIndicatorLeft.style.height = `${focusSideHeight}px`;\n",
"\t\ttemplateData.focusIndicatorRight.style.height = `${focusSideHeight}px`;\n",
"\t}\n",
"\n",
"\tdisposeTemplate(templateData: MarkdownCellRenderTemplate): void {\n",
"\t\ttemplateData.disposables.clear();\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate updateForHover(element: MarkdownCellViewModel, templateData: MarkdownCellRenderTemplate): void {\n",
"\t\ttemplateData.container.classList.toggle('markdown-cell-hover', element.cellIsHovered);\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer.ts",
"type": "add",
"edit_start_line_idx": 566
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter, Event } from 'vs/base/common/event';
import { IDebugAdapter } from 'vs/workbench/contrib/debug/common/debug';
import { timeout } from 'vs/base/common/async';
import { localize } from 'vs/nls';
/**
* Abstract implementation of the low level API for a debug adapter.
* Missing is how this API communicates with the debug adapter.
*/
export abstract class AbstractDebugAdapter implements IDebugAdapter {
private sequence: number;
private pendingRequests = new Map<number, (e: DebugProtocol.Response) => void>();
private requestCallback: ((request: DebugProtocol.Request) => void) | undefined;
private eventCallback: ((request: DebugProtocol.Event) => void) | undefined;
private messageCallback: ((message: DebugProtocol.ProtocolMessage) => void) | undefined;
private queue: DebugProtocol.ProtocolMessage[] = [];
protected readonly _onError = new Emitter<Error>();
protected readonly _onExit = new Emitter<number | null>();
constructor() {
this.sequence = 1;
}
abstract startSession(): Promise<void>;
abstract stopSession(): Promise<void>;
abstract sendMessage(message: DebugProtocol.ProtocolMessage): void;
get onError(): Event<Error> {
return this._onError.event;
}
get onExit(): Event<number | null> {
return this._onExit.event;
}
onMessage(callback: (message: DebugProtocol.ProtocolMessage) => void): void {
if (this.messageCallback) {
this._onError.fire(new Error(`attempt to set more than one 'Message' callback`));
}
this.messageCallback = callback;
}
onEvent(callback: (event: DebugProtocol.Event) => void): void {
if (this.eventCallback) {
this._onError.fire(new Error(`attempt to set more than one 'Event' callback`));
}
this.eventCallback = callback;
}
onRequest(callback: (request: DebugProtocol.Request) => void): void {
if (this.requestCallback) {
this._onError.fire(new Error(`attempt to set more than one 'Request' callback`));
}
this.requestCallback = callback;
}
sendResponse(response: DebugProtocol.Response): void {
if (response.seq > 0) {
this._onError.fire(new Error(`attempt to send more than one response for command ${response.command}`));
} else {
this.internalSend('response', response);
}
}
sendRequest(command: string, args: any, clb: (result: DebugProtocol.Response) => void, timeout?: number): number {
const request: any = {
command: command
};
if (args && Object.keys(args).length > 0) {
request.arguments = args;
}
this.internalSend('request', request);
if (typeof timeout === 'number') {
const timer = setTimeout(() => {
clearTimeout(timer);
const clb = this.pendingRequests.get(request.seq);
if (clb) {
this.pendingRequests.delete(request.seq);
const err: DebugProtocol.Response = {
type: 'response',
seq: 0,
request_seq: request.seq,
success: false,
command,
message: localize('timeout', "Timeout after {0} ms for '{1}'", timeout, command)
};
clb(err);
}
}, timeout);
}
if (clb) {
// store callback for this request
this.pendingRequests.set(request.seq, clb);
}
return request.seq;
}
acceptMessage(message: DebugProtocol.ProtocolMessage): void {
if (this.messageCallback) {
this.messageCallback(message);
} else {
this.queue.push(message);
if (this.queue.length === 1) {
// first item = need to start processing loop
this.processQueue();
}
}
}
/**
* Returns whether we should insert a timeout between processing messageA
* and messageB. Artificially queueing protocol messages guarantees that any
* microtasks for previous message finish before next message is processed.
* This is essential ordering when using promises anywhere along the call path.
*
* For example, take the following, where `chooseAndSendGreeting` returns
* a person name and then emits a greeting event:
*
* ```
* let person: string;
* adapter.onGreeting(() => console.log('hello', person));
* person = await adapter.chooseAndSendGreeting();
* ```
*
* Because the event is dispatched synchronously, it may fire before person
* is assigned if they're processed in the same task. Inserting a task
* boundary avoids this issue.
*/
protected needsTaskBoundaryBetween(messageA: DebugProtocol.ProtocolMessage, messageB: DebugProtocol.ProtocolMessage) {
return messageA.type !== 'event' || messageB.type !== 'event';
}
/**
* Reads and dispatches items from the queue until it is empty.
*/
private async processQueue() {
let message: DebugProtocol.ProtocolMessage | undefined;
while (this.queue.length) {
if (!message || this.needsTaskBoundaryBetween(this.queue[0], message)) {
await timeout(0);
}
message = this.queue.shift();
if (!message) {
return; // may have been disposed of
}
switch (message.type) {
case 'event':
if (this.eventCallback) {
this.eventCallback(<DebugProtocol.Event>message);
}
break;
case 'request':
if (this.requestCallback) {
this.requestCallback(<DebugProtocol.Request>message);
}
break;
case 'response':
const response = <DebugProtocol.Response>message;
const clb = this.pendingRequests.get(response.request_seq);
if (clb) {
this.pendingRequests.delete(response.request_seq);
clb(response);
}
break;
}
}
}
private internalSend(typ: 'request' | 'response' | 'event', message: DebugProtocol.ProtocolMessage): void {
message.type = typ;
message.seq = this.sequence++;
this.sendMessage(message);
}
protected async cancelPendingRequests(): Promise<void> {
if (this.pendingRequests.size === 0) {
return Promise.resolve();
}
const pending = new Map<number, (e: DebugProtocol.Response) => void>();
this.pendingRequests.forEach((value, key) => pending.set(key, value));
await timeout(500);
pending.forEach((callback, request_seq) => {
const err: DebugProtocol.Response = {
type: 'response',
seq: 0,
request_seq,
success: false,
command: 'canceled',
message: 'canceled'
};
callback(err);
this.pendingRequests.delete(request_seq);
});
}
getPendingRequestIds(): number[] {
return Array.from(this.pendingRequests.keys());
}
dispose(): void {
this.queue = [];
}
}
| src/vs/workbench/contrib/debug/common/abstractDebugAdapter.ts | 0 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.0003255670890212059,
0.00017808127449825406,
0.0001628059399081394,
0.00017276557628065348,
0.00003239746001781896
] |
{
"id": 8,
"code_window": [
"\t\tconst focusSideHeight = element.layoutInfo.totalHeight - BOTTOM_CELL_TOOLBAR_GAP;\n",
"\t\ttemplateData.focusIndicatorLeft.style.height = `${focusSideHeight}px`;\n",
"\t\ttemplateData.focusIndicatorRight.style.height = `${focusSideHeight}px`;\n",
"\t}\n",
"\n",
"\tdisposeTemplate(templateData: MarkdownCellRenderTemplate): void {\n",
"\t\ttemplateData.disposables.clear();\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate updateForHover(element: MarkdownCellViewModel, templateData: MarkdownCellRenderTemplate): void {\n",
"\t\ttemplateData.container.classList.toggle('markdown-cell-hover', element.cellIsHovered);\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer.ts",
"type": "add",
"edit_start_line_idx": 566
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-editor .glyph-margin {
position: absolute;
top: 0;
}
/*
Keeping name short for faster parsing.
cgmr = core glyph margin rendering (div)
*/
.monaco-editor .margin-view-overlays .cgmr {
position: absolute;
display: flex;
align-items: center;
justify-content: center;
}
| src/vs/editor/browser/viewParts/glyphMargin/glyphMargin.css | 0 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.0001787262299330905,
0.00017479881353210658,
0.00017195986583828926,
0.00017371034482493997,
0.0000028675767680397257
] |
{
"id": 9,
"code_window": [
"\t\t\t\t\tcellId,\n",
"\t\t\t\t});\n",
"\t\t\t});\n",
"\n",
"\t\t\tpreviewContainerNode.setAttribute('draggable', 'true');\n",
"\n",
"\t\t\tpreviewContainerNode.addEventListener('dragstart', e => {\n",
"\t\t\t\tif (!e.dataTransfer) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tpreviewContainerNode.addEventListener('mouseenter', () => {\n",
"\t\t\t\tvscode.postMessage({\n",
"\t\t\t\t\t__vscode_notebook_message: true,\n",
"\t\t\t\t\ttype: 'mouseEnterMarkdownPreview',\n",
"\t\t\t\t\tcellId,\n",
"\t\t\t\t});\n",
"\t\t\t});\n",
"\t\t\tpreviewContainerNode.addEventListener('mouseleave', () => {\n",
"\t\t\t\tvscode.postMessage({\n",
"\t\t\t\t\t__vscode_notebook_message: true,\n",
"\t\t\t\t\ttype: 'mouseLeaveMarkdownPreview',\n",
"\t\t\t\t\tcellId,\n",
"\t\t\t\t});\n",
"\t\t\t});\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts",
"type": "add",
"edit_start_line_idx": 719
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-workbench .notebookOverlay.notebook-editor {
box-sizing: border-box;
line-height: 22px;
user-select: initial;
-webkit-user-select: initial;
position: relative;
}
.monaco-workbench .cell.markdown {
user-select: text;
-webkit-user-select: text;
-ms-user-select: text;
white-space: initial;
}
.monaco-workbench .cell.markdown p.emptyMarkdownPlaceholder {
font-style: italic;
opacity: 0.6;
}
.monaco-workbench .notebookOverlay .simple-fr-find-part-wrapper.visible {
z-index: 100;
}
.monaco-workbench .notebookOverlay .cell-list-container .overflowingContentWidgets > div {
z-index: 600 !important;
/* @rebornix: larger than the editor title bar */
}
.monaco-workbench .notebookOverlay .cell-list-container .monaco-list-rows {
min-height: 100%;
overflow: visible !important;
}
.monaco-workbench .notebookOverlay .cell-list-container {
position: relative;
}
.monaco-workbench .notebookOverlay.global-drag-active .webview {
pointer-events: none;
}
.monaco-workbench .notebookOverlay .cell-list-container .webview-cover {
position: absolute;
top: 0;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row {
cursor: default;
overflow: visible !important;
width: 100%;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .notebook-gutter > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row {
cursor: default;
overflow: visible !important;
width: 100%;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image {
position: absolute;
top: -500px;
z-index: 1000;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image .execution-count-label {
display: none;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image .cell-editor-container > div {
padding: 12px 16px;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image .cell-drag-handle {
display: none;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image.code-cell-row .cell-focus-indicator-side {
height: 44px !important;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image.code-cell-row .cell-focus-indicator-bottom {
top: 50px !important;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image.markdown-cell-row .cell-focus-indicator {
bottom: 8px;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image.code-cell-row {
padding: 6px 0px;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image .output {
display: none !important;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image .cell-title-toolbar {
display: none;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image .cell-statusbar-container {
display: none;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image .cell-editor-part {
width: 100%;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image .cell-editor-container > div > div {
/* Rendered code content - show a single unwrapped line */
height: 20px;
overflow: hidden;
white-space: pre-wrap;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image.markdown-cell-row .cell.markdown {
white-space: nowrap;
overflow: hidden;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell {
display: flex;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:not(.selected) .monaco-editor .lines-content .selected-text,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:not(.selected) .monaco-editor .lines-content .selectionHighlight {
opacity: 0.33;
}
.monaco-workbench .notebookOverlay .notebook-content-widgets {
position: absolute;
top: 0;
left: 0;
width: 100%;
}
.monaco-workbench .notebookOverlay .output {
position: absolute;
height: 0px;
user-select: text;
-webkit-user-select: text;
-ms-user-select: text;
transform: translate3d(0px, 0px, 0px);
cursor: auto;
box-sizing: border-box;
z-index: 27; /* Over drag handle */
}
.monaco-workbench .notebookOverlay .output p {
white-space: initial;
overflow-x: auto;
margin: 0px;
}
.monaco-workbench .notebookOverlay .output > div.foreground {
width: 100%;
min-height: 24px;
box-sizing: border-box;
}
.monaco-workbench .notebookOverlay .output > div.foreground.output-inner-container {
width: 100%;
padding: 4px 8px;
box-sizing: border-box;
}
.monaco-workbench .notebookOverlay .output > div.foreground .output-stream,
.monaco-workbench .notebookOverlay .output > div.foreground .output-plaintext {
font-family: var(--monaco-monospace-font);
white-space: pre-wrap;
word-wrap: break-word;
}
.monaco-workbench .notebookOverlay .cell-drag-image .output .multi-mimetype-output {
display: none;
}
.monaco-workbench .notebookOverlay .output .multi-mimetype-output {
position: absolute;
top: 4px;
left: -30px;
width: 16px;
height: 16px;
cursor: pointer;
padding: 6px;
}
.monaco-workbench .notebookOverlay .output pre {
margin: 4px 0;
}
.monaco-workbench .notebookOverlay .output .error_message {
color: red;
}
.monaco-workbench .notebookOverlay .output .error > div {
white-space: normal;
}
.monaco-workbench .notebookOverlay .output .error pre.traceback {
margin: 8px 0;
}
.monaco-workbench .notebookOverlay .output .error .traceback > span {
display: block;
}
.monaco-workbench .notebookOverlay .output .display img {
max-width: 100%;
}
.monaco-workbench .notebookOverlay .output-show-more-container {
position: absolute;
}
.monaco-workbench .notebookOverlay .output-show-more-container p {
padding: 8px 8px 0 8px;
margin: 0px;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .menu {
position: absolute;
left: 0;
top: 28px;
visibility: hidden;
width: 16px;
margin: auto;
padding-left: 4px;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .menu.mouseover,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover .menu,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-output-hover .menu {
visibility: visible;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-output-hover {
outline: none !important;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused {
outline: none !important;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-collapsed-part {
position: relative;
box-sizing: border-box;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-collapsed-part .codicon {
position: absolute;
padding: 2px 6px;
left: -30px;
bottom: 0;
cursor: pointer;
z-index: 29; /* Over drag handle and bottom cell toolbar */
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.collapsed .notebook-folding-indicator,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.collapsed .cell-title-toolbar {
display: none;
}
/* top and bottom borders on cells */
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-top:before,
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-bottom:before,
.monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row.focused .cell-inner-container:before,
.monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row.focused .cell-inner-container:after {
content: "";
position: absolute;
width: 100%;
height: 1px;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-left:before,
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-right:before {
content: "";
position: absolute;
width: 1px;
height: 100%;
z-index: 1;
}
/* top border */
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-top:before {
border-top: 1px solid transparent;
}
/* left border */
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-left:before {
border-left: 1px solid transparent;
}
/* bottom border */
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-bottom:before {
border-bottom: 1px solid transparent;
}
/* right border */
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-right:before {
border-right: 1px solid transparent;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-top:before {
top: 0;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-left:before {
left: 0;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-bottom:before {
bottom: 0px;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-right:before {
right: 0;
}
.monaco-workbench.hc-black .notebookOverlay .monaco-list-row .cell-editor-focus .cell-editor-part:before {
outline-style: dashed;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .menu.mouseover,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .menu:hover {
cursor: pointer;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-title-toolbar {
visibility: hidden;
display: inline-flex;
position: absolute;
height: 26px;
top: -12px;
/* this lines up the bottom toolbar border with the current line when on line 01 */
z-index: 30;
}
.monaco-workbench .notebookOverlay.cell-title-toolbar-right > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-title-toolbar {
right: 44px;
}
.monaco-workbench .notebookOverlay.cell-title-toolbar-left > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-title-toolbar {
left: 76px;
}
.monaco-workbench .notebookOverlay.cell-title-toolbar-hidden > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-title-toolbar {
display: none;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-title-toolbar .action-item {
width: 24px;
height: 24px;
display: flex;
align-items: center;
margin: 1px 2px;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-title-toolbar .action-item .action-label {
display: flex;
align-items: center;
margin: auto;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-title-toolbar .action-item .monaco-dropdown {
width: 100%;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-title-toolbar .action-item .monaco-dropdown .dropdown-label {
display: flex;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container {
height: 22px;
font-size: 12px;
display: flex;
position: relative;
}
.monaco-workbench .notebookOverlay.cell-statusbar-hidden .cell-statusbar-container {
display: none;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-status-left {
display: flex;
flex-grow: 1;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-status-left,
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-status-right {
padding-right: 12px;
display: flex;
z-index: 26;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-status-right .cell-contributed-items {
justify-content: flex-end;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-contributed-items {
display: flex;
flex-wrap: wrap;
overflow: hidden;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-status-item {
display: flex;
align-items: center;
white-space: pre;
height: 21px; /* Editor outline is -1px in, don't overlap */
padding: 0px 6px;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-status-item.cell-status-item-has-command {
cursor: pointer;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-language-picker {
cursor: pointer;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-duration {
margin-right: 8px;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-duration,
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-status-message {
display: flex;
align-items: center;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-status-message {
margin-right: 6px;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-status {
height: 100%;
display: flex;
align-items: center;
margin-left: 18px;
width: 18px;
margin-right: 2px;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-status-left > div:first-child {
margin-left: 18px;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .codicon {
font-size: 14px;
}
.monaco-workbench .notebookOverlay .cell-status-placeholder {
position: absolute;
left: 18px;
display: flex;
align-items: center;
bottom: 0px;
top: 0px;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .run-button-container {
position: relative;
flex-shrink: 0;
z-index: 27;
/* Above the drag handle */
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .run-button-container .monaco-toolbar {
visibility: hidden;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .run-button-container .monaco-toolbar .codicon {
margin: 0 4px 0 0;
padding: 6px;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .run-button-container .monaco-toolbar .actions-container {
justify-content: center;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover .runnable .run-button-container .monaco-toolbar,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused .runnable .run-button-container .monaco-toolbar,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-output-hover .runnable .run-button-container .monaco-toolbar {
visibility: visible;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .execution-count-label {
position: absolute;
font-size: 10px;
font-family: var(--monaco-monospace-font);
white-space: pre;
box-sizing: border-box;
opacity: .6;
/* Sizing hacks */
left: 26px;
width: 35px;
bottom: 0px;
text-align: center;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .output-collapsed .execution-count-label {
bottom: 24px;
}
.monaco-workbench .notebookOverlay .cell .cell-editor-part {
position: relative;
}
.monaco-workbench .notebookOverlay .cell .monaco-progress-container {
top: -3px;
position: absolute;
left: 0;
z-index: 5;
height: 2px;
}
.monaco-workbench .notebookOverlay .cell .monaco-progress-container .progress-bit {
height: 2px;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list:focus-within > .monaco-scrollable-element > .monaco-list-rows:not(:hover) > .monaco-list-row.focused .cell-has-toolbar-actions .cell-title-toolbar,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover .cell-has-toolbar-actions .cell-title-toolbar,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-has-toolbar-actions.cell-output-hover .cell-title-toolbar,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-has-toolbar-actions:hover .cell-title-toolbar {
visibility: visible;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list:not(.element-focused):focus:before {
outline: none !important;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator {
position: absolute;
top: 0px;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-side {
/** Overidden for code cells */
top: 0px;
bottom: 0px;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-top,
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-bottom {
width: 100%;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-right {
right: 0px;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-drag-handle {
position: absolute;
top: 0px;
z-index: 26; /* Above the bottom toolbar */
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-drag-handle:hover,
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.markdown-cell-row .cell-inner-container:hover {
cursor: grab;
}
.monaco-workbench .notebookOverlay.notebook-editor-editable > .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar.visible {
z-index: 25;
cursor: default;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator .codicon:hover {
cursor: pointer;
}
.monaco-workbench .notebookOverlay .monaco-list-row .cell-editor-part:before {
z-index: 20;
content: "";
right: 0px;
left: 0px;
top: 0px;
bottom: 0px;
outline-offset: -1px;
display: block;
position: absolute;
pointer-events: none;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-insertion-indicator-top {
top: -15px;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .cell-list-insertion-indicator {
position: absolute;
height: 2px;
left: 0px;
right: 0px;
opacity: 0;
z-index: 10;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list .monaco-list-row .cell-dragging {
opacity: 0.5 !important;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container.emptyNotebook {
opacity: 1 !important;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container {
position: absolute;
display: flex;
align-items: center;
justify-content: center;
z-index: 28; /* over the focus outline on the editor, below the title toolbar */
width: 100%;
opacity: 0;
transition: opacity 0.2s ease-in-out;
padding: 0;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image .cell-bottom-toolbar-container {
display: none;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container:focus-within,
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container:hover,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover .cell-bottom-toolbar-container,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list:focus-within > .monaco-scrollable-element > .monaco-list-rows:not(:hover) > .monaco-list-row.focused .cell-bottom-toolbar-container,
.monaco-workbench .notebookOverlay.notebook-editor-editable > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container:focus-within {
opacity: 1;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container .monaco-toolbar,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container .monaco-toolbar {
margin: 0px 8px;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container .monaco-toolbar .action-item,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container .monaco-toolbar .action-item {
display: flex;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container .monaco-toolbar .action-item.active,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container .monaco-toolbar .action-item.active {
transform: none;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container .monaco-toolbar .action-label,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container .monaco-toolbar .action-label {
font-size: 12px;
margin: 0px;
display: inline-flex;
padding: 0px 4px;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container .monaco-toolbar .action-label .codicon,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container .monaco-toolbar .action-label .codicon {
margin-right: 3px;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container .monaco-action-bar,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container .monaco-action-bar {
display: flex;
align-items: center;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container .action-item:first-child,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container .action-item:first-child {
margin-right: 16px;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container span.codicon,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container span.codicon {
text-align: center;
font-size: 14px;
color: inherit;
}
/* markdown */
.monaco-workbench .notebookOverlay .cell.markdown img {
max-width: 100%;
max-height: 100%;
}
.monaco-workbench .notebookOverlay .cell.markdown a {
text-decoration: none;
}
.monaco-workbench .notebookOverlay .cell.markdown a:hover {
text-decoration: underline;
}
.monaco-workbench .notebookOverlay .cell.markdown a:focus,
.monaco-workbench .notebookOverlay .cell.markdown input:focus,
.monaco-workbench .notebookOverlay .cell.markdown select:focus,
.monaco-workbench .notebookOverlay .cell.markdown textarea:focus {
outline: 1px solid -webkit-focus-ring-color;
outline-offset: -1px;
}
.monaco-workbench .notebookOverlay .cell.markdown hr {
border: 0;
height: 2px;
border-bottom: 2px solid;
}
.monaco-workbench .notebookOverlay .cell.markdown h1 {
padding-bottom: 0.3em;
line-height: 1.2;
border-bottom-width: 1px;
border-bottom-style: solid;
border-color: rgba(255, 255, 255, 0.18);
}
.monaco-workbench.vs .monaco-workbench .notebookOverlay .cell.markdown h1 {
border-color: rgba(0, 0, 0, 0.18);
}
.monaco-workbench .notebookOverlay .cell.markdown h1,
.monaco-workbench .notebookOverlay .cell.markdown h2,
.monaco-workbench .notebookOverlay .cell.markdown h3 {
font-weight: normal;
}
.monaco-workbench .notebookOverlay .cell.markdown div {
width: 100%;
}
/* Adjust margin of first item in markdown cell */
.monaco-workbench .notebookOverlay .cell.markdown div *:first-child {
margin-top: 0px;
}
/* h1 tags don't need top margin */
.monaco-workbench .notebookOverlay .cell.markdown div h1:first-child {
margin-top: 0;
}
/* Removes bottom margin when only one item exists in markdown cell */
.monaco-workbench .notebookOverlay .cell.markdown div *:only-child,
.monaco-workbench .notebookOverlay .cell.markdown div *:last-child {
margin-bottom: 0;
padding-bottom: 0;
}
/* makes all markdown cells consistent */
.monaco-workbench .notebookOverlay .cell.markdown div {
min-height: 24px;
}
.monaco-workbench .notebookOverlay .cell.markdown table {
border-collapse: collapse;
border-spacing: 0;
}
.monaco-workbench .notebookOverlay .cell.markdown table th,
.monaco-workbench .notebookOverlay .cell.markdown table td {
border: 1px solid;
}
.monaco-workbench .notebookOverlay .cell.markdown table > thead > tr > th {
text-align: left;
border-bottom: 1px solid;
}
.monaco-workbench .notebookOverlay .cell.markdown table > thead > tr > th,
.monaco-workbench .notebookOverlay .cell.markdown table > thead > tr > td,
.monaco-workbench .notebookOverlay .cell.markdown table > tbody > tr > th,
.monaco-workbench .notebookOverlay .cell.markdown table > tbody > tr > td {
padding: 5px 10px;
}
.monaco-workbench .notebookOverlay .cell.markdown table > tbody > tr + tr > td {
border-top: 1px solid;
}
.monaco-workbench .notebookOverlay .cell.markdown blockquote {
margin: 0 7px 0 5px;
padding: 0 16px 0 10px;
border-left-width: 5px;
border-left-style: solid;
}
.monaco-workbench .notebookOverlay .cell.markdown code,
.monaco-workbench .notebookOverlay .cell.markdown .code {
font-family: var(--monaco-monospace-font);
font-size: 1em;
line-height: 1.357em;
}
.monaco-workbench .notebookOverlay .cell.markdown .code {
white-space: pre-wrap;
}
.monaco-workbench .notebookOverlay .cell.markdown .latex-block {
display: block;
}
.monaco-workbench .notebookOverlay .cell.markdown .latex {
vertical-align: middle;
display: inline-block;
}
.monaco-workbench .notebookOverlay .cell.markdown .latex img,
.monaco-workbench .notebookOverlay .cell.markdown .latex-block img {
filter: brightness(0) invert(0)
}
.monaco-workbench.vs-dark .notebookOverlay .cell.markdown .latex img,
.monaco-workbench.vs-dark .notebookOverlay .cell.markdown .latex-block img {
filter: brightness(0) invert(1)
}
.monaco-workbench .notebookOverlay > .cell-list-container .notebook-folding-indicator {
height: 20px;
width: 20px;
position: absolute;
top: 6px;
left: 8px;
display: flex;
justify-content: center;
align-items: center;
z-index: 26;
}
.monaco-workbench .notebookOverlay > .cell-list-container .notebook-folding-indicator .codicon {
visibility: visible;
height: 16px;
padding: 4px;
}
/** Theming */
/* .monaco-workbench .notebookOverlay .cell.markdown pre {
background-color: rgba(220, 220, 220, 0.4);
}
.monaco-workbench.vs-dark .monaco-workbench .notebookOverlay .cell.markdown pre {
background-color: rgba(10, 10, 10, 0.4);
}
.monaco-workbench.hc-black .monaco-workbench .notebookOverlay .cell.markdown pre {
background-color: rgb(0, 0, 0);
}
.monaco-workbench.hc-black .monaco-workbench .notebookOverlay .cell.markdown h1 {
border-color: rgb(0, 0, 0);
}
.monaco-workbench .notebookOverlay .cell.markdown table > thead > tr > th {
border-color: rgba(0, 0, 0, 0.18);
}
.monaco-workbench.vs-dark .monaco-workbench .notebookOverlay .cell.markdown table > thead > tr > th {
border-color: rgba(255, 255, 255, 0.18);
}
.monaco-workbench .notebookOverlay .cell.markdown h1,
.monaco-workbench .notebookOverlay .cell.markdown hr,
.monaco-workbench .notebookOverlay .cell.markdown table > tbody > tr > td {
border-color: rgba(0, 0, 0, 0.18);
}
.monaco-workbench.vs-dark .monaco-workbench .notebookOverlay .cell.markdown h1,
.monaco-workbench.vs-dark .monaco-workbench .notebookOverlay .cell.markdown hr,
.monaco-workbench.vs-dark .monaco-workbench .notebookOverlay .cell.markdown table > tbody > tr > td {
border-color: rgba(255, 255, 255, 0.18);
} */
.monaco-action-bar .action-item.verticalSeparator {
width: 1px !important;
height: 16px !important;
margin: 5px 4px !important;
cursor: none;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-decoration {
top: -6px;
position: absolute;
display: flex;
}
.output-show-more {
padding: 8px 0;
}
.cell-contributed-items.cell-contributed-items-left {
margin-left: 4px;
}
.monaco-workbench .notebookOverlay .output-plaintext::-webkit-scrollbar {
width: 10px; /* width of the entire scrollbar */
height: 10px;
}
.monaco-workbench .notebookOverlay .output-plaintext::-webkit-scrollbar-thumb {
height: 10px;
width: 10px;
}
.monaco-workbench .notebookOverlay .output .output-plaintext {
margin: 4px 0;
overflow-x: auto;
}
| src/vs/workbench/contrib/notebook/browser/media/notebook.css | 1 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.00017764736548997462,
0.00017023230611812323,
0.00016378032159991562,
0.00017068347369786352,
0.0000028668785034824396
] |
{
"id": 9,
"code_window": [
"\t\t\t\t\tcellId,\n",
"\t\t\t\t});\n",
"\t\t\t});\n",
"\n",
"\t\t\tpreviewContainerNode.setAttribute('draggable', 'true');\n",
"\n",
"\t\t\tpreviewContainerNode.addEventListener('dragstart', e => {\n",
"\t\t\t\tif (!e.dataTransfer) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tpreviewContainerNode.addEventListener('mouseenter', () => {\n",
"\t\t\t\tvscode.postMessage({\n",
"\t\t\t\t\t__vscode_notebook_message: true,\n",
"\t\t\t\t\ttype: 'mouseEnterMarkdownPreview',\n",
"\t\t\t\t\tcellId,\n",
"\t\t\t\t});\n",
"\t\t\t});\n",
"\t\t\tpreviewContainerNode.addEventListener('mouseleave', () => {\n",
"\t\t\t\tvscode.postMessage({\n",
"\t\t\t\t\t__vscode_notebook_message: true,\n",
"\t\t\t\t\ttype: 'mouseLeaveMarkdownPreview',\n",
"\t\t\t\t\tcellId,\n",
"\t\t\t\t});\n",
"\t\t\t});\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts",
"type": "add",
"edit_start_line_idx": 719
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { ITextModel, FindMatch } from 'vs/editor/common/model';
import { editorMatchesToTextSearchResults, addContextToEditorMatches } from 'vs/workbench/services/search/common/searchHelpers';
import { Range } from 'vs/editor/common/core/range';
import { ITextQuery, QueryType, ITextSearchContext } from 'vs/workbench/services/search/common/search';
suite('SearchHelpers', () => {
suite('editorMatchesToTextSearchResults', () => {
const mockTextModel: ITextModel = <ITextModel>{
getLineContent(lineNumber: number): string {
return '' + lineNumber;
}
};
test('simple', () => {
const results = editorMatchesToTextSearchResults([new FindMatch(new Range(6, 1, 6, 2), null)], mockTextModel);
assert.equal(results.length, 1);
assert.equal(results[0].preview.text, '6\n');
assert.deepEqual(results[0].preview.matches, [new Range(0, 0, 0, 1)]);
assert.deepEqual(results[0].ranges, [new Range(5, 0, 5, 1)]);
});
test('multiple', () => {
const results = editorMatchesToTextSearchResults(
[
new FindMatch(new Range(6, 1, 6, 2), null),
new FindMatch(new Range(6, 4, 8, 2), null),
new FindMatch(new Range(9, 1, 10, 3), null),
],
mockTextModel);
assert.equal(results.length, 2);
assert.deepEqual(results[0].preview.matches, [
new Range(0, 0, 0, 1),
new Range(0, 3, 2, 1),
]);
assert.deepEqual(results[0].ranges, [
new Range(5, 0, 5, 1),
new Range(5, 3, 7, 1),
]);
assert.equal(results[0].preview.text, '6\n7\n8\n');
assert.deepEqual(results[1].preview.matches, [
new Range(0, 0, 1, 2),
]);
assert.deepEqual(results[1].ranges, [
new Range(8, 0, 9, 2),
]);
assert.equal(results[1].preview.text, '9\n10\n');
});
});
suite('addContextToEditorMatches', () => {
const MOCK_LINE_COUNT = 100;
const mockTextModel: ITextModel = <ITextModel>{
getLineContent(lineNumber: number): string {
if (lineNumber < 1 || lineNumber > MOCK_LINE_COUNT) {
throw new Error(`invalid line count: ${lineNumber}`);
}
return '' + lineNumber;
},
getLineCount(): number {
return MOCK_LINE_COUNT;
}
};
function getQuery(beforeContext?: number, afterContext?: number): ITextQuery {
return {
folderQueries: [],
type: QueryType.Text,
contentPattern: { pattern: 'test' },
beforeContext,
afterContext
};
}
test('no context', () => {
const matches = [{
preview: {
text: 'foo',
matches: new Range(0, 0, 0, 10)
},
ranges: new Range(0, 0, 0, 10)
}];
assert.deepEqual(addContextToEditorMatches(matches, mockTextModel, getQuery()), matches);
});
test('simple', () => {
const matches = [{
preview: {
text: 'foo',
matches: new Range(0, 0, 0, 10)
},
ranges: new Range(1, 0, 1, 10)
}];
assert.deepEqual(addContextToEditorMatches(matches, mockTextModel, getQuery(1, 2)), [
<ITextSearchContext>{
text: '1',
lineNumber: 0
},
...matches,
<ITextSearchContext>{
text: '3',
lineNumber: 2
},
<ITextSearchContext>{
text: '4',
lineNumber: 3
},
]);
});
test('multiple matches next to each other', () => {
const matches = [
{
preview: {
text: 'foo',
matches: new Range(0, 0, 0, 10)
},
ranges: new Range(1, 0, 1, 10)
},
{
preview: {
text: 'bar',
matches: new Range(0, 0, 0, 10)
},
ranges: new Range(2, 0, 2, 10)
}];
assert.deepEqual(addContextToEditorMatches(matches, mockTextModel, getQuery(1, 2)), [
<ITextSearchContext>{
text: '1',
lineNumber: 0
},
...matches,
<ITextSearchContext>{
text: '4',
lineNumber: 3
},
<ITextSearchContext>{
text: '5',
lineNumber: 4
},
]);
});
test('boundaries', () => {
const matches = [
{
preview: {
text: 'foo',
matches: new Range(0, 0, 0, 10)
},
ranges: new Range(0, 0, 0, 10)
},
{
preview: {
text: 'bar',
matches: new Range(0, 0, 0, 10)
},
ranges: new Range(MOCK_LINE_COUNT - 1, 0, MOCK_LINE_COUNT - 1, 10)
}];
assert.deepEqual(addContextToEditorMatches(matches, mockTextModel, getQuery(1, 2)), [
matches[0],
<ITextSearchContext>{
text: '2',
lineNumber: 1
},
<ITextSearchContext>{
text: '3',
lineNumber: 2
},
<ITextSearchContext>{
text: '' + (MOCK_LINE_COUNT - 1),
lineNumber: MOCK_LINE_COUNT - 2
},
matches[1]
]);
});
});
}); | src/vs/workbench/services/search/test/common/searchHelpers.test.ts | 0 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.00017883772670757025,
0.0001720782311167568,
0.0001635489024920389,
0.00017367058899253607,
0.000003901934178429656
] |
{
"id": 9,
"code_window": [
"\t\t\t\t\tcellId,\n",
"\t\t\t\t});\n",
"\t\t\t});\n",
"\n",
"\t\t\tpreviewContainerNode.setAttribute('draggable', 'true');\n",
"\n",
"\t\t\tpreviewContainerNode.addEventListener('dragstart', e => {\n",
"\t\t\t\tif (!e.dataTransfer) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tpreviewContainerNode.addEventListener('mouseenter', () => {\n",
"\t\t\t\tvscode.postMessage({\n",
"\t\t\t\t\t__vscode_notebook_message: true,\n",
"\t\t\t\t\ttype: 'mouseEnterMarkdownPreview',\n",
"\t\t\t\t\tcellId,\n",
"\t\t\t\t});\n",
"\t\t\t});\n",
"\t\t\tpreviewContainerNode.addEventListener('mouseleave', () => {\n",
"\t\t\t\tvscode.postMessage({\n",
"\t\t\t\t\t__vscode_notebook_message: true,\n",
"\t\t\t\t\ttype: 'mouseLeaveMarkdownPreview',\n",
"\t\t\t\t\tcellId,\n",
"\t\t\t\t});\n",
"\t\t\t});\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts",
"type": "add",
"edit_start_line_idx": 719
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter } from 'vs/base/common/event';
import { INativeHostService } from 'vs/platform/native/electron-sandbox/native';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { Disposable } from 'vs/base/common/lifecycle';
import { IHostColorSchemeService } from 'vs/workbench/services/themes/common/hostColorSchemeService';
export class NativeHostColorSchemeService extends Disposable implements IHostColorSchemeService {
declare readonly _serviceBrand: undefined;
constructor(
@INativeHostService private readonly nativeHostService: INativeHostService,
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService
) {
super();
this.registerListeners();
}
private registerListeners(): void {
// Color Scheme
this._register(this.nativeHostService.onDidChangeColorScheme(({ highContrast, dark }) => {
this.dark = dark;
this.highContrast = highContrast;
this._onDidChangeColorScheme.fire();
}));
}
private readonly _onDidChangeColorScheme = this._register(new Emitter<void>());
readonly onDidChangeColorScheme = this._onDidChangeColorScheme.event;
public dark: boolean = this.environmentService.configuration.colorScheme.dark;
public highContrast: boolean = this.environmentService.configuration.colorScheme.highContrast;
}
registerSingleton(IHostColorSchemeService, NativeHostColorSchemeService, true);
| src/vs/workbench/services/themes/electron-sandbox/nativeHostColorSchemeService.ts | 0 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.00017455815395805985,
0.0001729582727421075,
0.00016940767818596214,
0.0001735151745378971,
0.0000018617852219904307
] |
{
"id": 9,
"code_window": [
"\t\t\t\t\tcellId,\n",
"\t\t\t\t});\n",
"\t\t\t});\n",
"\n",
"\t\t\tpreviewContainerNode.setAttribute('draggable', 'true');\n",
"\n",
"\t\t\tpreviewContainerNode.addEventListener('dragstart', e => {\n",
"\t\t\t\tif (!e.dataTransfer) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tpreviewContainerNode.addEventListener('mouseenter', () => {\n",
"\t\t\t\tvscode.postMessage({\n",
"\t\t\t\t\t__vscode_notebook_message: true,\n",
"\t\t\t\t\ttype: 'mouseEnterMarkdownPreview',\n",
"\t\t\t\t\tcellId,\n",
"\t\t\t\t});\n",
"\t\t\t});\n",
"\t\t\tpreviewContainerNode.addEventListener('mouseleave', () => {\n",
"\t\t\t\tvscode.postMessage({\n",
"\t\t\t\t\t__vscode_notebook_message: true,\n",
"\t\t\t\t\ttype: 'mouseLeaveMarkdownPreview',\n",
"\t\t\t\t\tcellId,\n",
"\t\t\t\t});\n",
"\t\t\t});\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/webviewPreloads.ts",
"type": "add",
"edit_start_line_idx": 719
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Color, RGBA } from 'vs/base/common/color';
import { localize } from 'vs/nls';
import { editorErrorForeground, editorForeground, editorHintForeground, editorInfoForeground, editorWarningForeground, inputActiveOptionBackground, inputActiveOptionBorder, inputActiveOptionForeground, registerColor } from 'vs/platform/theme/common/colorRegistry';
import { registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { TestMessageSeverity, TestRunState } from 'vs/workbench/api/common/extHostTypes';
import { ACTIVITY_BAR_BADGE_BACKGROUND } from 'vs/workbench/common/theme';
export const testingColorIconFailed = registerColor('testing.iconFailed', {
dark: '#f14c4c',
light: '#f14c4c',
hc: '#000000'
}, localize('testing.iconFailed', "Color for the 'failed' icon in the test explorer."));
export const testingColorIconErrored = registerColor('testing.iconErrored', {
dark: '#f14c4c',
light: '#f14c4c',
hc: '#000000'
}, localize('testing.iconErrored', "Color for the 'Errored' icon in the test explorer."));
export const testingColorIconPassed = registerColor('testing.iconPassed', {
dark: '#73c991',
light: '#73c991',
hc: '#000000'
}, localize('testing.iconPassed', "Color for the 'passed' icon in the test explorer."));
export const testingColorRunAction = registerColor('testing.runAction', {
dark: testingColorIconPassed,
light: testingColorIconPassed,
hc: testingColorIconPassed
}, localize('testing.runAction', "Color for 'run' icons in the editor."));
export const testingColorIconQueued = registerColor('testing.iconQueued', {
dark: '#cca700',
light: '#cca700',
hc: '#000000'
}, localize('testing.iconQueued', "Color for the 'Queued' icon in the test explorer."));
export const testingColorIconUnset = registerColor('testing.iconUnset', {
dark: '#848484',
light: '#848484',
hc: '#848484'
}, localize('testing.iconUnset', "Color for the 'Unset' icon in the test explorer."));
export const testingColorIconSkipped = registerColor('testing.iconSkipped', {
dark: '#848484',
light: '#848484',
hc: '#848484'
}, localize('testing.iconSkipped', "Color for the 'Skipped' icon in the test explorer."));
export const testingPeekBorder = registerColor('testing.peekBorder', {
dark: editorErrorForeground,
light: editorErrorForeground,
hc: editorErrorForeground,
}, localize('testing.peekBorder', 'Color of the peek view borders and arrow.'));
export const testMessageSeverityColors: {
[K in TestMessageSeverity]: {
decorationForeground: string,
marginBackground: string,
};
} = {
[TestMessageSeverity.Error]: {
decorationForeground: registerColor(
'testing.message.error.decorationForeground',
{ dark: editorErrorForeground, light: editorErrorForeground, hc: editorForeground },
localize('testing.message.error.decorationForeground', 'Text color of test error messages shown inline in the editor.')
),
marginBackground: registerColor(
'testing.message.error.lineBackground',
{ dark: new Color(new RGBA(255, 0, 0, 0.2)), light: new Color(new RGBA(255, 0, 0, 0.2)), hc: null },
localize('testing.message.error.marginBackground', 'Margin color beside error messages shown inline in the editor.')
),
},
[TestMessageSeverity.Warning]: {
decorationForeground: registerColor(
'testing.message.warning.decorationForeground',
{ dark: editorWarningForeground, light: editorWarningForeground, hc: editorForeground },
localize('testing.message.warning.decorationForeground', 'Text color of test warning messages shown inline in the editor.')
),
marginBackground: registerColor(
'testing.message.warning.lineBackground',
{ dark: new Color(new RGBA(255, 208, 0, 0.2)), light: new Color(new RGBA(255, 208, 0, 0.2)), hc: null },
localize('testing.message.warning.marginBackground', 'Margin color beside warning messages shown inline in the editor.')
),
},
[TestMessageSeverity.Information]: {
decorationForeground: registerColor(
'testing.message.info.decorationForeground',
{ dark: editorInfoForeground, light: editorInfoForeground, hc: editorForeground },
localize('testing.message.info.decorationForeground', 'Text color of test info messages shown inline in the editor.')
),
marginBackground: registerColor(
'testing.message.info.lineBackground',
{ dark: new Color(new RGBA(0, 127, 255, 0.2)), light: new Color(new RGBA(0, 127, 255, 0.2)), hc: null },
localize('testing.message.info.marginBackground', 'Margin color beside info messages shown inline in the editor.')
),
},
[TestMessageSeverity.Hint]: {
decorationForeground: registerColor(
'testing.message.hint.decorationForeground',
{ dark: editorHintForeground, light: editorHintForeground, hc: editorForeground },
localize('testing.message.hint.decorationForeground', 'Text color of test hint messages shown inline in the editor.')
),
marginBackground: registerColor(
'testing.message.hint.lineBackground',
{ dark: null, light: null, hc: editorForeground },
localize('testing.message.hint.marginBackground', 'Margin color beside hint messages shown inline in the editor.')
),
},
};
export const testStatesToIconColors: { [K in TestRunState]?: string } = {
[TestRunState.Errored]: testingColorIconErrored,
[TestRunState.Failed]: testingColorIconFailed,
[TestRunState.Passed]: testingColorIconPassed,
[TestRunState.Queued]: testingColorIconQueued,
[TestRunState.Unset]: testingColorIconUnset,
[TestRunState.Skipped]: testingColorIconUnset,
};
registerThemingParticipant((theme, collector) => {
//#region test states
for (const [state, { marginBackground }] of Object.entries(testMessageSeverityColors)) {
collector.addRule(`.monaco-editor .testing-inline-message-severity-${state} {
background: ${theme.getColor(marginBackground)};
}`);
}
//#endregion test states
//#region active buttons
const inputActiveOptionBorderColor = theme.getColor(inputActiveOptionBorder);
if (inputActiveOptionBorderColor) {
collector.addRule(`.testing-filter-button.checked { border-color: ${inputActiveOptionBorderColor}; }`);
}
const inputActiveOptionForegroundColor = theme.getColor(inputActiveOptionForeground);
if (inputActiveOptionForegroundColor) {
collector.addRule(`.testing-filter-button.checked { color: ${inputActiveOptionForegroundColor}; }`);
}
const inputActiveOptionBackgroundColor = theme.getColor(inputActiveOptionBackground);
if (inputActiveOptionBackgroundColor) {
collector.addRule(`.testing-filter-button.checked { background-color: ${inputActiveOptionBackgroundColor}; }`);
}
const badgeColor = theme.getColor(ACTIVITY_BAR_BADGE_BACKGROUND);
collector.addRule(`.monaco-workbench .part > .title > .title-actions .action-label.codicon-testing-autorun::after { background-color: ${badgeColor}; }`);
//#endregion
});
| src/vs/workbench/contrib/testing/browser/theme.ts | 0 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.00017751580162439495,
0.00017300821491517127,
0.00016805976338218898,
0.00017418140487279743,
0.0000026637001155904727
] |
{
"id": 10,
"code_window": [
"\tpublic set outputIsHovered(v: boolean) {\n",
"\t\tthis._hoveringOutput = v;\n",
"\t}\n",
"\n",
"\tconstructor(\n",
"\t\treadonly viewType: string,\n",
"\t\treadonly model: NotebookCellTextModel,\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate _hoveringCell = false;\n",
"\tpublic get cellIsHovered(): boolean {\n",
"\t\treturn this._hoveringCell;\n",
"\t}\n",
"\n",
"\tpublic set cellIsHovered(v: boolean) {\n",
"\t\tthis._hoveringCell = v;\n",
"\t\tthis._onDidChangeState.fire({ cellIsHoveredChanged: true });\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/markdownCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 71
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-workbench .notebookOverlay.notebook-editor {
box-sizing: border-box;
line-height: 22px;
user-select: initial;
-webkit-user-select: initial;
position: relative;
}
.monaco-workbench .cell.markdown {
user-select: text;
-webkit-user-select: text;
-ms-user-select: text;
white-space: initial;
}
.monaco-workbench .cell.markdown p.emptyMarkdownPlaceholder {
font-style: italic;
opacity: 0.6;
}
.monaco-workbench .notebookOverlay .simple-fr-find-part-wrapper.visible {
z-index: 100;
}
.monaco-workbench .notebookOverlay .cell-list-container .overflowingContentWidgets > div {
z-index: 600 !important;
/* @rebornix: larger than the editor title bar */
}
.monaco-workbench .notebookOverlay .cell-list-container .monaco-list-rows {
min-height: 100%;
overflow: visible !important;
}
.monaco-workbench .notebookOverlay .cell-list-container {
position: relative;
}
.monaco-workbench .notebookOverlay.global-drag-active .webview {
pointer-events: none;
}
.monaco-workbench .notebookOverlay .cell-list-container .webview-cover {
position: absolute;
top: 0;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row {
cursor: default;
overflow: visible !important;
width: 100%;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .notebook-gutter > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row {
cursor: default;
overflow: visible !important;
width: 100%;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image {
position: absolute;
top: -500px;
z-index: 1000;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image .execution-count-label {
display: none;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image .cell-editor-container > div {
padding: 12px 16px;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image .cell-drag-handle {
display: none;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image.code-cell-row .cell-focus-indicator-side {
height: 44px !important;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image.code-cell-row .cell-focus-indicator-bottom {
top: 50px !important;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image.markdown-cell-row .cell-focus-indicator {
bottom: 8px;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image.code-cell-row {
padding: 6px 0px;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image .output {
display: none !important;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image .cell-title-toolbar {
display: none;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image .cell-statusbar-container {
display: none;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image .cell-editor-part {
width: 100%;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image .cell-editor-container > div > div {
/* Rendered code content - show a single unwrapped line */
height: 20px;
overflow: hidden;
white-space: pre-wrap;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image.markdown-cell-row .cell.markdown {
white-space: nowrap;
overflow: hidden;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell {
display: flex;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:not(.selected) .monaco-editor .lines-content .selected-text,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:not(.selected) .monaco-editor .lines-content .selectionHighlight {
opacity: 0.33;
}
.monaco-workbench .notebookOverlay .notebook-content-widgets {
position: absolute;
top: 0;
left: 0;
width: 100%;
}
.monaco-workbench .notebookOverlay .output {
position: absolute;
height: 0px;
user-select: text;
-webkit-user-select: text;
-ms-user-select: text;
transform: translate3d(0px, 0px, 0px);
cursor: auto;
box-sizing: border-box;
z-index: 27; /* Over drag handle */
}
.monaco-workbench .notebookOverlay .output p {
white-space: initial;
overflow-x: auto;
margin: 0px;
}
.monaco-workbench .notebookOverlay .output > div.foreground {
width: 100%;
min-height: 24px;
box-sizing: border-box;
}
.monaco-workbench .notebookOverlay .output > div.foreground.output-inner-container {
width: 100%;
padding: 4px 8px;
box-sizing: border-box;
}
.monaco-workbench .notebookOverlay .output > div.foreground .output-stream,
.monaco-workbench .notebookOverlay .output > div.foreground .output-plaintext {
font-family: var(--monaco-monospace-font);
white-space: pre-wrap;
word-wrap: break-word;
}
.monaco-workbench .notebookOverlay .cell-drag-image .output .multi-mimetype-output {
display: none;
}
.monaco-workbench .notebookOverlay .output .multi-mimetype-output {
position: absolute;
top: 4px;
left: -30px;
width: 16px;
height: 16px;
cursor: pointer;
padding: 6px;
}
.monaco-workbench .notebookOverlay .output pre {
margin: 4px 0;
}
.monaco-workbench .notebookOverlay .output .error_message {
color: red;
}
.monaco-workbench .notebookOverlay .output .error > div {
white-space: normal;
}
.monaco-workbench .notebookOverlay .output .error pre.traceback {
margin: 8px 0;
}
.monaco-workbench .notebookOverlay .output .error .traceback > span {
display: block;
}
.monaco-workbench .notebookOverlay .output .display img {
max-width: 100%;
}
.monaco-workbench .notebookOverlay .output-show-more-container {
position: absolute;
}
.monaco-workbench .notebookOverlay .output-show-more-container p {
padding: 8px 8px 0 8px;
margin: 0px;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .menu {
position: absolute;
left: 0;
top: 28px;
visibility: hidden;
width: 16px;
margin: auto;
padding-left: 4px;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .menu.mouseover,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover .menu,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-output-hover .menu {
visibility: visible;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-output-hover {
outline: none !important;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused {
outline: none !important;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-collapsed-part {
position: relative;
box-sizing: border-box;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-collapsed-part .codicon {
position: absolute;
padding: 2px 6px;
left: -30px;
bottom: 0;
cursor: pointer;
z-index: 29; /* Over drag handle and bottom cell toolbar */
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.collapsed .notebook-folding-indicator,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.collapsed .cell-title-toolbar {
display: none;
}
/* top and bottom borders on cells */
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-top:before,
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-bottom:before,
.monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row.focused .cell-inner-container:before,
.monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row.focused .cell-inner-container:after {
content: "";
position: absolute;
width: 100%;
height: 1px;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-left:before,
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-right:before {
content: "";
position: absolute;
width: 1px;
height: 100%;
z-index: 1;
}
/* top border */
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-top:before {
border-top: 1px solid transparent;
}
/* left border */
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-left:before {
border-left: 1px solid transparent;
}
/* bottom border */
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-bottom:before {
border-bottom: 1px solid transparent;
}
/* right border */
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-right:before {
border-right: 1px solid transparent;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-top:before {
top: 0;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-left:before {
left: 0;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-bottom:before {
bottom: 0px;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-right:before {
right: 0;
}
.monaco-workbench.hc-black .notebookOverlay .monaco-list-row .cell-editor-focus .cell-editor-part:before {
outline-style: dashed;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .menu.mouseover,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .menu:hover {
cursor: pointer;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-title-toolbar {
visibility: hidden;
display: inline-flex;
position: absolute;
height: 26px;
top: -12px;
/* this lines up the bottom toolbar border with the current line when on line 01 */
z-index: 30;
}
.monaco-workbench .notebookOverlay.cell-title-toolbar-right > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-title-toolbar {
right: 44px;
}
.monaco-workbench .notebookOverlay.cell-title-toolbar-left > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-title-toolbar {
left: 76px;
}
.monaco-workbench .notebookOverlay.cell-title-toolbar-hidden > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-title-toolbar {
display: none;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-title-toolbar .action-item {
width: 24px;
height: 24px;
display: flex;
align-items: center;
margin: 1px 2px;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-title-toolbar .action-item .action-label {
display: flex;
align-items: center;
margin: auto;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-title-toolbar .action-item .monaco-dropdown {
width: 100%;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-title-toolbar .action-item .monaco-dropdown .dropdown-label {
display: flex;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container {
height: 22px;
font-size: 12px;
display: flex;
position: relative;
}
.monaco-workbench .notebookOverlay.cell-statusbar-hidden .cell-statusbar-container {
display: none;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-status-left {
display: flex;
flex-grow: 1;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-status-left,
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-status-right {
padding-right: 12px;
display: flex;
z-index: 26;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-status-right .cell-contributed-items {
justify-content: flex-end;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-contributed-items {
display: flex;
flex-wrap: wrap;
overflow: hidden;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-status-item {
display: flex;
align-items: center;
white-space: pre;
height: 21px; /* Editor outline is -1px in, don't overlap */
padding: 0px 6px;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-status-item.cell-status-item-has-command {
cursor: pointer;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-language-picker {
cursor: pointer;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-duration {
margin-right: 8px;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-duration,
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-status-message {
display: flex;
align-items: center;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-status-message {
margin-right: 6px;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-status {
height: 100%;
display: flex;
align-items: center;
margin-left: 18px;
width: 18px;
margin-right: 2px;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-status-left > div:first-child {
margin-left: 18px;
}
.monaco-workbench .notebookOverlay .cell-statusbar-container .codicon {
font-size: 14px;
}
.monaco-workbench .notebookOverlay .cell-status-placeholder {
position: absolute;
left: 18px;
display: flex;
align-items: center;
bottom: 0px;
top: 0px;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .run-button-container {
position: relative;
flex-shrink: 0;
z-index: 27;
/* Above the drag handle */
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .run-button-container .monaco-toolbar {
visibility: hidden;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .run-button-container .monaco-toolbar .codicon {
margin: 0 4px 0 0;
padding: 6px;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .run-button-container .monaco-toolbar .actions-container {
justify-content: center;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover .runnable .run-button-container .monaco-toolbar,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused .runnable .run-button-container .monaco-toolbar,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-output-hover .runnable .run-button-container .monaco-toolbar {
visibility: visible;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .execution-count-label {
position: absolute;
font-size: 10px;
font-family: var(--monaco-monospace-font);
white-space: pre;
box-sizing: border-box;
opacity: .6;
/* Sizing hacks */
left: 26px;
width: 35px;
bottom: 0px;
text-align: center;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .output-collapsed .execution-count-label {
bottom: 24px;
}
.monaco-workbench .notebookOverlay .cell .cell-editor-part {
position: relative;
}
.monaco-workbench .notebookOverlay .cell .monaco-progress-container {
top: -3px;
position: absolute;
left: 0;
z-index: 5;
height: 2px;
}
.monaco-workbench .notebookOverlay .cell .monaco-progress-container .progress-bit {
height: 2px;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list:focus-within > .monaco-scrollable-element > .monaco-list-rows:not(:hover) > .monaco-list-row.focused .cell-has-toolbar-actions .cell-title-toolbar,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover .cell-has-toolbar-actions .cell-title-toolbar,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-has-toolbar-actions.cell-output-hover .cell-title-toolbar,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-has-toolbar-actions:hover .cell-title-toolbar {
visibility: visible;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list:not(.element-focused):focus:before {
outline: none !important;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator {
position: absolute;
top: 0px;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-side {
/** Overidden for code cells */
top: 0px;
bottom: 0px;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-top,
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-bottom {
width: 100%;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-right {
right: 0px;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-drag-handle {
position: absolute;
top: 0px;
z-index: 26; /* Above the bottom toolbar */
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-drag-handle:hover,
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.markdown-cell-row .cell-inner-container:hover {
cursor: grab;
}
.monaco-workbench .notebookOverlay.notebook-editor-editable > .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar.visible {
z-index: 25;
cursor: default;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator .codicon:hover {
cursor: pointer;
}
.monaco-workbench .notebookOverlay .monaco-list-row .cell-editor-part:before {
z-index: 20;
content: "";
right: 0px;
left: 0px;
top: 0px;
bottom: 0px;
outline-offset: -1px;
display: block;
position: absolute;
pointer-events: none;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-insertion-indicator-top {
top: -15px;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .cell-list-insertion-indicator {
position: absolute;
height: 2px;
left: 0px;
right: 0px;
opacity: 0;
z-index: 10;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list .monaco-list-row .cell-dragging {
opacity: 0.5 !important;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container.emptyNotebook {
opacity: 1 !important;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container {
position: absolute;
display: flex;
align-items: center;
justify-content: center;
z-index: 28; /* over the focus outline on the editor, below the title toolbar */
width: 100%;
opacity: 0;
transition: opacity 0.2s ease-in-out;
padding: 0;
}
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.cell-drag-image .cell-bottom-toolbar-container {
display: none;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container:focus-within,
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container:hover,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover .cell-bottom-toolbar-container,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list:focus-within > .monaco-scrollable-element > .monaco-list-rows:not(:hover) > .monaco-list-row.focused .cell-bottom-toolbar-container,
.monaco-workbench .notebookOverlay.notebook-editor-editable > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container:focus-within {
opacity: 1;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container .monaco-toolbar,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container .monaco-toolbar {
margin: 0px 8px;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container .monaco-toolbar .action-item,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container .monaco-toolbar .action-item {
display: flex;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container .monaco-toolbar .action-item.active,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container .monaco-toolbar .action-item.active {
transform: none;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container .monaco-toolbar .action-label,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container .monaco-toolbar .action-label {
font-size: 12px;
margin: 0px;
display: inline-flex;
padding: 0px 4px;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container .monaco-toolbar .action-label .codicon,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container .monaco-toolbar .action-label .codicon {
margin-right: 3px;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container .monaco-action-bar,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container .monaco-action-bar {
display: flex;
align-items: center;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container .action-item:first-child,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container .action-item:first-child {
margin-right: 16px;
}
.monaco-workbench .notebookOverlay .cell-list-top-cell-toolbar-container span.codicon,
.monaco-workbench .notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row .cell-bottom-toolbar-container span.codicon {
text-align: center;
font-size: 14px;
color: inherit;
}
/* markdown */
.monaco-workbench .notebookOverlay .cell.markdown img {
max-width: 100%;
max-height: 100%;
}
.monaco-workbench .notebookOverlay .cell.markdown a {
text-decoration: none;
}
.monaco-workbench .notebookOverlay .cell.markdown a:hover {
text-decoration: underline;
}
.monaco-workbench .notebookOverlay .cell.markdown a:focus,
.monaco-workbench .notebookOverlay .cell.markdown input:focus,
.monaco-workbench .notebookOverlay .cell.markdown select:focus,
.monaco-workbench .notebookOverlay .cell.markdown textarea:focus {
outline: 1px solid -webkit-focus-ring-color;
outline-offset: -1px;
}
.monaco-workbench .notebookOverlay .cell.markdown hr {
border: 0;
height: 2px;
border-bottom: 2px solid;
}
.monaco-workbench .notebookOverlay .cell.markdown h1 {
padding-bottom: 0.3em;
line-height: 1.2;
border-bottom-width: 1px;
border-bottom-style: solid;
border-color: rgba(255, 255, 255, 0.18);
}
.monaco-workbench.vs .monaco-workbench .notebookOverlay .cell.markdown h1 {
border-color: rgba(0, 0, 0, 0.18);
}
.monaco-workbench .notebookOverlay .cell.markdown h1,
.monaco-workbench .notebookOverlay .cell.markdown h2,
.monaco-workbench .notebookOverlay .cell.markdown h3 {
font-weight: normal;
}
.monaco-workbench .notebookOverlay .cell.markdown div {
width: 100%;
}
/* Adjust margin of first item in markdown cell */
.monaco-workbench .notebookOverlay .cell.markdown div *:first-child {
margin-top: 0px;
}
/* h1 tags don't need top margin */
.monaco-workbench .notebookOverlay .cell.markdown div h1:first-child {
margin-top: 0;
}
/* Removes bottom margin when only one item exists in markdown cell */
.monaco-workbench .notebookOverlay .cell.markdown div *:only-child,
.monaco-workbench .notebookOverlay .cell.markdown div *:last-child {
margin-bottom: 0;
padding-bottom: 0;
}
/* makes all markdown cells consistent */
.monaco-workbench .notebookOverlay .cell.markdown div {
min-height: 24px;
}
.monaco-workbench .notebookOverlay .cell.markdown table {
border-collapse: collapse;
border-spacing: 0;
}
.monaco-workbench .notebookOverlay .cell.markdown table th,
.monaco-workbench .notebookOverlay .cell.markdown table td {
border: 1px solid;
}
.monaco-workbench .notebookOverlay .cell.markdown table > thead > tr > th {
text-align: left;
border-bottom: 1px solid;
}
.monaco-workbench .notebookOverlay .cell.markdown table > thead > tr > th,
.monaco-workbench .notebookOverlay .cell.markdown table > thead > tr > td,
.monaco-workbench .notebookOverlay .cell.markdown table > tbody > tr > th,
.monaco-workbench .notebookOverlay .cell.markdown table > tbody > tr > td {
padding: 5px 10px;
}
.monaco-workbench .notebookOverlay .cell.markdown table > tbody > tr + tr > td {
border-top: 1px solid;
}
.monaco-workbench .notebookOverlay .cell.markdown blockquote {
margin: 0 7px 0 5px;
padding: 0 16px 0 10px;
border-left-width: 5px;
border-left-style: solid;
}
.monaco-workbench .notebookOverlay .cell.markdown code,
.monaco-workbench .notebookOverlay .cell.markdown .code {
font-family: var(--monaco-monospace-font);
font-size: 1em;
line-height: 1.357em;
}
.monaco-workbench .notebookOverlay .cell.markdown .code {
white-space: pre-wrap;
}
.monaco-workbench .notebookOverlay .cell.markdown .latex-block {
display: block;
}
.monaco-workbench .notebookOverlay .cell.markdown .latex {
vertical-align: middle;
display: inline-block;
}
.monaco-workbench .notebookOverlay .cell.markdown .latex img,
.monaco-workbench .notebookOverlay .cell.markdown .latex-block img {
filter: brightness(0) invert(0)
}
.monaco-workbench.vs-dark .notebookOverlay .cell.markdown .latex img,
.monaco-workbench.vs-dark .notebookOverlay .cell.markdown .latex-block img {
filter: brightness(0) invert(1)
}
.monaco-workbench .notebookOverlay > .cell-list-container .notebook-folding-indicator {
height: 20px;
width: 20px;
position: absolute;
top: 6px;
left: 8px;
display: flex;
justify-content: center;
align-items: center;
z-index: 26;
}
.monaco-workbench .notebookOverlay > .cell-list-container .notebook-folding-indicator .codicon {
visibility: visible;
height: 16px;
padding: 4px;
}
/** Theming */
/* .monaco-workbench .notebookOverlay .cell.markdown pre {
background-color: rgba(220, 220, 220, 0.4);
}
.monaco-workbench.vs-dark .monaco-workbench .notebookOverlay .cell.markdown pre {
background-color: rgba(10, 10, 10, 0.4);
}
.monaco-workbench.hc-black .monaco-workbench .notebookOverlay .cell.markdown pre {
background-color: rgb(0, 0, 0);
}
.monaco-workbench.hc-black .monaco-workbench .notebookOverlay .cell.markdown h1 {
border-color: rgb(0, 0, 0);
}
.monaco-workbench .notebookOverlay .cell.markdown table > thead > tr > th {
border-color: rgba(0, 0, 0, 0.18);
}
.monaco-workbench.vs-dark .monaco-workbench .notebookOverlay .cell.markdown table > thead > tr > th {
border-color: rgba(255, 255, 255, 0.18);
}
.monaco-workbench .notebookOverlay .cell.markdown h1,
.monaco-workbench .notebookOverlay .cell.markdown hr,
.monaco-workbench .notebookOverlay .cell.markdown table > tbody > tr > td {
border-color: rgba(0, 0, 0, 0.18);
}
.monaco-workbench.vs-dark .monaco-workbench .notebookOverlay .cell.markdown h1,
.monaco-workbench.vs-dark .monaco-workbench .notebookOverlay .cell.markdown hr,
.monaco-workbench.vs-dark .monaco-workbench .notebookOverlay .cell.markdown table > tbody > tr > td {
border-color: rgba(255, 255, 255, 0.18);
} */
.monaco-action-bar .action-item.verticalSeparator {
width: 1px !important;
height: 16px !important;
margin: 5px 4px !important;
cursor: none;
}
.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row .cell-decoration {
top: -6px;
position: absolute;
display: flex;
}
.output-show-more {
padding: 8px 0;
}
.cell-contributed-items.cell-contributed-items-left {
margin-left: 4px;
}
.monaco-workbench .notebookOverlay .output-plaintext::-webkit-scrollbar {
width: 10px; /* width of the entire scrollbar */
height: 10px;
}
.monaco-workbench .notebookOverlay .output-plaintext::-webkit-scrollbar-thumb {
height: 10px;
width: 10px;
}
.monaco-workbench .notebookOverlay .output .output-plaintext {
margin: 4px 0;
overflow-x: auto;
}
| src/vs/workbench/contrib/notebook/browser/media/notebook.css | 1 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.0003081294125877321,
0.00016881932970136404,
0.00016346095071639866,
0.0001666794705670327,
0.000015021214494481683
] |
{
"id": 10,
"code_window": [
"\tpublic set outputIsHovered(v: boolean) {\n",
"\t\tthis._hoveringOutput = v;\n",
"\t}\n",
"\n",
"\tconstructor(\n",
"\t\treadonly viewType: string,\n",
"\t\treadonly model: NotebookCellTextModel,\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate _hoveringCell = false;\n",
"\tpublic get cellIsHovered(): boolean {\n",
"\t\treturn this._hoveringCell;\n",
"\t}\n",
"\n",
"\tpublic set cellIsHovered(v: boolean) {\n",
"\t\tthis._hoveringCell = v;\n",
"\t\tthis._onDidChangeState.fire({ cellIsHoveredChanged: true });\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/markdownCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 71
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'mocha';
import * as assert from 'assert';
import * as embeddedSupport from '../modes/embeddedSupport';
import { getLanguageService } from 'vscode-html-languageservice';
import { TextDocument } from '../modes/languageModes';
suite('HTML Embedded Support', () => {
const htmlLanguageService = getLanguageService();
function assertLanguageId(value: string, expectedLanguageId: string | undefined): void {
const offset = value.indexOf('|');
value = value.substr(0, offset) + value.substr(offset + 1);
const document = TextDocument.create('test://test/test.html', 'html', 0, value);
const position = document.positionAt(offset);
const docRegions = embeddedSupport.getDocumentRegions(htmlLanguageService, document);
const languageId = docRegions.getLanguageAtPosition(position);
assert.equal(languageId, expectedLanguageId);
}
function assertEmbeddedLanguageContent(value: string, languageId: string, expectedContent: string): void {
const document = TextDocument.create('test://test/test.html', 'html', 0, value);
const docRegions = embeddedSupport.getDocumentRegions(htmlLanguageService, document);
const content = docRegions.getEmbeddedDocument(languageId);
assert.equal(content.getText(), expectedContent);
}
test('Styles', function (): any {
assertLanguageId('|<html><style>foo { }</style></html>', 'html');
assertLanguageId('<html|><style>foo { }</style></html>', 'html');
assertLanguageId('<html><st|yle>foo { }</style></html>', 'html');
assertLanguageId('<html><style>|foo { }</style></html>', 'css');
assertLanguageId('<html><style>foo| { }</style></html>', 'css');
assertLanguageId('<html><style>foo { }|</style></html>', 'css');
assertLanguageId('<html><style>foo { }</sty|le></html>', 'html');
});
test('Styles - Incomplete HTML', function (): any {
assertLanguageId('|<html><style>foo { }', 'html');
assertLanguageId('<html><style>fo|o { }', 'css');
assertLanguageId('<html><style>foo { }|', 'css');
});
test('Style in attribute', function (): any {
assertLanguageId('<div id="xy" |style="color: red"/>', 'html');
assertLanguageId('<div id="xy" styl|e="color: red"/>', 'html');
assertLanguageId('<div id="xy" style=|"color: red"/>', 'html');
assertLanguageId('<div id="xy" style="|color: red"/>', 'css');
assertLanguageId('<div id="xy" style="color|: red"/>', 'css');
assertLanguageId('<div id="xy" style="color: red|"/>', 'css');
assertLanguageId('<div id="xy" style="color: red"|/>', 'html');
assertLanguageId('<div id="xy" style=\'color: r|ed\'/>', 'css');
assertLanguageId('<div id="xy" style|=color:red/>', 'html');
assertLanguageId('<div id="xy" style=|color:red/>', 'css');
assertLanguageId('<div id="xy" style=color:r|ed/>', 'css');
assertLanguageId('<div id="xy" style=color:red|/>', 'css');
assertLanguageId('<div id="xy" style=color:red/|>', 'html');
});
test('Style content', function (): any {
assertEmbeddedLanguageContent('<html><style>foo { }</style></html>', 'css', ' foo { } ');
assertEmbeddedLanguageContent('<html><script>var i = 0;</script></html>', 'css', ' ');
assertEmbeddedLanguageContent('<html><style>foo { }</style>Hello<style>foo { }</style></html>', 'css', ' foo { } foo { } ');
assertEmbeddedLanguageContent('<html>\n <style>\n foo { } \n </style>\n</html>\n', 'css', '\n \n foo { } \n \n\n');
assertEmbeddedLanguageContent('<div style="color: red"></div>', 'css', ' __{color: red} ');
assertEmbeddedLanguageContent('<div style=color:red></div>', 'css', ' __{color:red} ');
});
test('Scripts', function (): any {
assertLanguageId('|<html><script>var i = 0;</script></html>', 'html');
assertLanguageId('<html|><script>var i = 0;</script></html>', 'html');
assertLanguageId('<html><scr|ipt>var i = 0;</script></html>', 'html');
assertLanguageId('<html><script>|var i = 0;</script></html>', 'javascript');
assertLanguageId('<html><script>var| i = 0;</script></html>', 'javascript');
assertLanguageId('<html><script>var i = 0;|</script></html>', 'javascript');
assertLanguageId('<html><script>var i = 0;</scr|ipt></html>', 'html');
assertLanguageId('<script type="text/javascript">var| i = 0;</script>', 'javascript');
assertLanguageId('<script type="text/ecmascript">var| i = 0;</script>', 'javascript');
assertLanguageId('<script type="application/javascript">var| i = 0;</script>', 'javascript');
assertLanguageId('<script type="application/ecmascript">var| i = 0;</script>', 'javascript');
assertLanguageId('<script type="application/typescript">var| i = 0;</script>', undefined);
assertLanguageId('<script type=\'text/javascript\'>var| i = 0;</script>', 'javascript');
});
test('Scripts in attribute', function (): any {
assertLanguageId('<div |onKeyUp="foo()" onkeydown=\'bar()\'/>', 'html');
assertLanguageId('<div onKeyUp=|"foo()" onkeydown=\'bar()\'/>', 'html');
assertLanguageId('<div onKeyUp="|foo()" onkeydown=\'bar()\'/>', 'javascript');
assertLanguageId('<div onKeyUp="foo(|)" onkeydown=\'bar()\'/>', 'javascript');
assertLanguageId('<div onKeyUp="foo()|" onkeydown=\'bar()\'/>', 'javascript');
assertLanguageId('<div onKeyUp="foo()"| onkeydown=\'bar()\'/>', 'html');
assertLanguageId('<div onKeyUp="foo()" onkeydown=|\'bar()\'/>', 'html');
assertLanguageId('<div onKeyUp="foo()" onkeydown=\'|bar()\'/>', 'javascript');
assertLanguageId('<div onKeyUp="foo()" onkeydown=\'bar()|\'/>', 'javascript');
assertLanguageId('<div onKeyUp="foo()" onkeydown=\'bar()\'|/>', 'html');
assertLanguageId('<DIV ONKEYUP|=foo()</DIV>', 'html');
assertLanguageId('<DIV ONKEYUP=|foo()</DIV>', 'javascript');
assertLanguageId('<DIV ONKEYUP=f|oo()</DIV>', 'javascript');
assertLanguageId('<DIV ONKEYUP=foo(|)</DIV>', 'javascript');
assertLanguageId('<DIV ONKEYUP=foo()|</DIV>', 'javascript');
assertLanguageId('<DIV ONKEYUP=foo()<|/DIV>', 'html');
assertLanguageId('<label data-content="|Checkbox"/>', 'html');
assertLanguageId('<label on="|Checkbox"/>', 'html');
});
test('Script content', function (): any {
assertEmbeddedLanguageContent('<html><script>var i = 0;</script></html>', 'javascript', ' var i = 0; ');
assertEmbeddedLanguageContent('<script type="text/javascript">var i = 0;</script>', 'javascript', ' var i = 0; ');
assertEmbeddedLanguageContent('<div onKeyUp="foo()" onkeydown="bar()"/>', 'javascript', ' foo(); bar(); ');
});
});
| extensions/html-language-features/server/src/test/embedded.test.ts | 0 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.00017380528151988983,
0.000170844592503272,
0.00016766729822847992,
0.00017123960424214602,
0.000001787663904906367
] |
{
"id": 10,
"code_window": [
"\tpublic set outputIsHovered(v: boolean) {\n",
"\t\tthis._hoveringOutput = v;\n",
"\t}\n",
"\n",
"\tconstructor(\n",
"\t\treadonly viewType: string,\n",
"\t\treadonly model: NotebookCellTextModel,\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate _hoveringCell = false;\n",
"\tpublic get cellIsHovered(): boolean {\n",
"\t\treturn this._hoveringCell;\n",
"\t}\n",
"\n",
"\tpublic set cellIsHovered(v: boolean) {\n",
"\t\tthis._hoveringCell = v;\n",
"\t\tthis._onDidChangeState.fire({ cellIsHoveredChanged: true });\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/markdownCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 71
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
//@ts-check
'use strict';
const withBrowserDefaults = require('../../shared.webpack.config').browser;
const path = require('path');
module.exports = withBrowserDefaults({
context: __dirname,
entry: {
extension: './src/browser/jsonServerMain.ts',
},
output: {
filename: 'jsonServerMain.js',
path: path.join(__dirname, 'dist', 'browser'),
libraryTarget: 'var'
}
});
| extensions/json-language-features/server/extension-browser.webpack.config.js | 0 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.000173625405295752,
0.000173045220435597,
0.00017227628268301487,
0.00017323397332802415,
5.667178584189969e-7
] |
{
"id": 10,
"code_window": [
"\tpublic set outputIsHovered(v: boolean) {\n",
"\t\tthis._hoveringOutput = v;\n",
"\t}\n",
"\n",
"\tconstructor(\n",
"\t\treadonly viewType: string,\n",
"\t\treadonly model: NotebookCellTextModel,\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tprivate _hoveringCell = false;\n",
"\tpublic get cellIsHovered(): boolean {\n",
"\t\treturn this._hoveringCell;\n",
"\t}\n",
"\n",
"\tpublic set cellIsHovered(v: boolean) {\n",
"\t\tthis._hoveringCell = v;\n",
"\t\tthis._onDidChangeState.fire({ cellIsHoveredChanged: true });\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/viewModel/markdownCellViewModel.ts",
"type": "add",
"edit_start_line_idx": 71
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as DOM from 'vs/base/browser/dom';
import * as aria from 'vs/base/browser/ui/aria/aria';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
import { Button } from 'vs/base/browser/ui/button/button';
import { ITreeElement } from 'vs/base/browser/ui/tree/tree';
import { Action } from 'vs/base/common/actions';
import { Delayer, IntervalTimer, ThrottledDelayer, timeout } from 'vs/base/common/async';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import * as collections from 'vs/base/common/collections';
import { fromNow } from 'vs/base/common/date';
import { getErrorMessage, isPromiseCanceledError } from 'vs/base/common/errors';
import { Emitter } from 'vs/base/common/event';
import { Iterable } from 'vs/base/common/iterator';
import { KeyCode } from 'vs/base/common/keyCodes';
import { Disposable } from 'vs/base/common/lifecycle';
import * as platform from 'vs/base/common/platform';
import { isArray, withNullAsUndefined, withUndefinedAsNull } from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import 'vs/css!./media/settingsEditor2';
import { localize } from 'vs/nls';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { ConfigurationTarget, IConfigurationOverrides, IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IEditorModel } from 'vs/platform/editor/common/editor';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ILogService } from 'vs/platform/log/common/log';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { badgeBackground, badgeForeground, contrastBorder, editorForeground } from 'vs/platform/theme/common/colorRegistry';
import { attachButtonStyler, attachStylerCallback } from 'vs/platform/theme/common/styler';
import { IThemeService, ThemeIcon } from 'vs/platform/theme/common/themeService';
import { IUserDataAutoSyncEnablementService, IUserDataSyncService, SyncStatus } from 'vs/platform/userDataSync/common/userDataSync';
import { EditorPane } from 'vs/workbench/browser/parts/editor/editorPane';
import { IEditorMemento, IEditorOpenContext, IEditorPane } from 'vs/workbench/common/editor';
import { attachSuggestEnabledInputBoxStyler, SuggestEnabledInput } from 'vs/workbench/contrib/codeEditor/browser/suggestEnabledInput/suggestEnabledInput';
import { SettingsTarget, SettingsTargetsWidget } from 'vs/workbench/contrib/preferences/browser/preferencesWidgets';
import { commonlyUsedData, tocData } from 'vs/workbench/contrib/preferences/browser/settingsLayout';
import { AbstractSettingRenderer, ISettingLinkClickEvent, ISettingOverrideClickEvent, resolveExtensionsSettings, resolveSettingsTree, SettingsTree, SettingTreeRenderers } from 'vs/workbench/contrib/preferences/browser/settingsTree';
import { ISettingsEditorViewState, parseQuery, SearchResultIdx, SearchResultModel, SettingsTreeElement, SettingsTreeGroupChild, SettingsTreeGroupElement, SettingsTreeModel, SettingsTreeSettingElement } from 'vs/workbench/contrib/preferences/browser/settingsTreeModels';
import { settingsTextInputBorder } from 'vs/workbench/contrib/preferences/browser/settingsWidgets';
import { createTOCIterator, TOCTree, TOCTreeModel } from 'vs/workbench/contrib/preferences/browser/tocTree';
import { CONTEXT_SETTINGS_EDITOR, CONTEXT_SETTINGS_ROW_FOCUS, CONTEXT_SETTINGS_SEARCH_FOCUS, CONTEXT_TOC_ROW_FOCUS, EXTENSION_SETTING_TAG, FEATURE_SETTING_TAG, ID_SETTING_TAG, IPreferencesSearchService, ISearchProvider, MODIFIED_SETTING_TAG, SETTINGS_EDITOR_COMMAND_CLEAR_SEARCH_RESULTS } from 'vs/workbench/contrib/preferences/common/preferences';
import { IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IPreferencesService, ISearchResult, ISettingsEditorModel, ISettingsEditorOptions, SettingsEditorOptions, SettingValueType } from 'vs/workbench/services/preferences/common/preferences';
import { SettingsEditor2Input } from 'vs/workbench/services/preferences/browser/preferencesEditorInput';
import { Settings2EditorModel } from 'vs/workbench/services/preferences/common/preferencesModels';
import { IUserDataSyncWorkbenchService } from 'vs/workbench/services/userDataSync/common/userDataSync';
import { preferencesClearInputIcon } from 'vs/workbench/contrib/preferences/browser/preferencesIcons';
export const enum SettingsFocusContext {
Search,
TableOfContents,
SettingTree,
SettingControl
}
export function createGroupIterator(group: SettingsTreeGroupElement): Iterable<ITreeElement<SettingsTreeGroupChild>> {
return Iterable.map(group.children, g => {
return {
element: g,
children: g instanceof SettingsTreeGroupElement ?
createGroupIterator(g) :
undefined
};
});
}
const $ = DOM.$;
interface IFocusEventFromScroll extends KeyboardEvent {
fromScroll: true;
}
const searchBoxLabel = localize('SearchSettings.AriaLabel', "Search settings");
const SETTINGS_AUTOSAVE_NOTIFIED_KEY = 'hasNotifiedOfSettingsAutosave';
const SETTINGS_EDITOR_STATE_KEY = 'settingsEditorState';
export class SettingsEditor2 extends EditorPane {
static readonly ID: string = 'workbench.editor.settings2';
private static NUM_INSTANCES: number = 0;
private static SETTING_UPDATE_FAST_DEBOUNCE: number = 200;
private static SETTING_UPDATE_SLOW_DEBOUNCE: number = 1000;
private static CONFIG_SCHEMA_UPDATE_DELAYER = 500;
private static readonly SUGGESTIONS: string[] = [
`@${MODIFIED_SETTING_TAG}`, '@tag:usesOnlineServices', '@tag:sync', `@${ID_SETTING_TAG}`, `@${EXTENSION_SETTING_TAG}`, `@${FEATURE_SETTING_TAG}scm`, `@${FEATURE_SETTING_TAG}explorer`, `@${FEATURE_SETTING_TAG}search`, `@${FEATURE_SETTING_TAG}debug`, `@${FEATURE_SETTING_TAG}extensions`, `@${FEATURE_SETTING_TAG}terminal`, `@${FEATURE_SETTING_TAG}task`, `@${FEATURE_SETTING_TAG}problems`, `@${FEATURE_SETTING_TAG}output`, `@${FEATURE_SETTING_TAG}comments`, `@${FEATURE_SETTING_TAG}remote`, `@${FEATURE_SETTING_TAG}timeline`
];
private static shouldSettingUpdateFast(type: SettingValueType | SettingValueType[]): boolean {
if (isArray(type)) {
// nullable integer/number or complex
return false;
}
return type === SettingValueType.Enum ||
type === SettingValueType.ArrayOfString ||
type === SettingValueType.Complex ||
type === SettingValueType.Boolean ||
type === SettingValueType.Exclude;
}
// (!) Lots of props that are set once on the first render
private defaultSettingsEditorModel!: Settings2EditorModel;
private rootElement!: HTMLElement;
private headerContainer!: HTMLElement;
private searchWidget!: SuggestEnabledInput;
private countElement!: HTMLElement;
private controlsElement!: HTMLElement;
private settingsTargetsWidget!: SettingsTargetsWidget;
private settingsTreeContainer!: HTMLElement;
private settingsTree!: SettingsTree;
private settingRenderers!: SettingTreeRenderers;
private tocTreeModel!: TOCTreeModel;
private settingsTreeModel!: SettingsTreeModel;
private noResultsMessage!: HTMLElement;
private clearFilterLinkContainer!: HTMLElement;
private tocTreeContainer!: HTMLElement;
private tocTree!: TOCTree;
private delayedFilterLogging: Delayer<void>;
private localSearchDelayer: Delayer<void>;
private remoteSearchThrottle: ThrottledDelayer<void>;
private searchInProgress: CancellationTokenSource | null = null;
private updatedConfigSchemaDelayer: Delayer<void>;
private settingFastUpdateDelayer: Delayer<void>;
private settingSlowUpdateDelayer: Delayer<void>;
private pendingSettingUpdate: { key: string, value: any } | null = null;
private readonly viewState: ISettingsEditorViewState;
private _searchResultModel: SearchResultModel | null = null;
private searchResultLabel: string | null = null;
private lastSyncedLabel: string | null = null;
private tocRowFocused: IContextKey<boolean>;
private settingRowFocused: IContextKey<boolean>;
private inSettingsEditorContextKey: IContextKey<boolean>;
private searchFocusContextKey: IContextKey<boolean>;
private scheduledRefreshes: Map<string, DOM.IFocusTracker>;
private _currentFocusContext: SettingsFocusContext = SettingsFocusContext.Search;
/** Don't spam warnings */
private hasWarnedMissingSettings = false;
private editorMemento: IEditorMemento<ISettingsEditor2State>;
private tocFocusedElement: SettingsTreeGroupElement | null = null;
private treeFocusedElement: SettingsTreeElement | null = null;
private settingsTreeScrollTop = 0;
private dimension!: DOM.Dimension;
constructor(
@ITelemetryService telemetryService: ITelemetryService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IThemeService themeService: IThemeService,
@IPreferencesService private readonly preferencesService: IPreferencesService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IPreferencesSearchService private readonly preferencesSearchService: IPreferencesSearchService,
@ILogService private readonly logService: ILogService,
@IContextKeyService contextKeyService: IContextKeyService,
@IStorageService private readonly storageService: IStorageService,
@INotificationService private readonly notificationService: INotificationService,
@IEditorGroupsService protected editorGroupService: IEditorGroupsService,
@IUserDataSyncWorkbenchService private readonly userDataSyncWorkbenchService: IUserDataSyncWorkbenchService,
@IUserDataAutoSyncEnablementService private readonly userDataAutoSyncEnablementService: IUserDataAutoSyncEnablementService
) {
super(SettingsEditor2.ID, telemetryService, themeService, storageService);
this.delayedFilterLogging = new Delayer<void>(1000);
this.localSearchDelayer = new Delayer(300);
this.remoteSearchThrottle = new ThrottledDelayer(200);
this.viewState = { settingsTarget: ConfigurationTarget.USER_LOCAL };
this.settingFastUpdateDelayer = new Delayer<void>(SettingsEditor2.SETTING_UPDATE_FAST_DEBOUNCE);
this.settingSlowUpdateDelayer = new Delayer<void>(SettingsEditor2.SETTING_UPDATE_SLOW_DEBOUNCE);
this.updatedConfigSchemaDelayer = new Delayer<void>(SettingsEditor2.CONFIG_SCHEMA_UPDATE_DELAYER);
this.inSettingsEditorContextKey = CONTEXT_SETTINGS_EDITOR.bindTo(contextKeyService);
this.searchFocusContextKey = CONTEXT_SETTINGS_SEARCH_FOCUS.bindTo(contextKeyService);
this.tocRowFocused = CONTEXT_TOC_ROW_FOCUS.bindTo(contextKeyService);
this.settingRowFocused = CONTEXT_SETTINGS_ROW_FOCUS.bindTo(contextKeyService);
this.scheduledRefreshes = new Map<string, DOM.IFocusTracker>();
this.editorMemento = this.getEditorMemento<ISettingsEditor2State>(editorGroupService, SETTINGS_EDITOR_STATE_KEY);
this._register(configurationService.onDidChangeConfiguration(e => {
if (e.source !== ConfigurationTarget.DEFAULT) {
this.onConfigUpdate(e.affectedKeys);
}
}));
}
get minimumWidth(): number { return 375; }
get maximumWidth(): number { return Number.POSITIVE_INFINITY; }
// these setters need to exist because this extends from EditorPane
set minimumWidth(value: number) { /*noop*/ }
set maximumWidth(value: number) { /*noop*/ }
private get currentSettingsModel() {
return this.searchResultModel || this.settingsTreeModel;
}
private get searchResultModel(): SearchResultModel | null {
return this._searchResultModel;
}
private set searchResultModel(value: SearchResultModel | null) {
this._searchResultModel = value;
this.rootElement.classList.toggle('search-mode', !!this._searchResultModel);
}
private get focusedSettingDOMElement(): HTMLElement | undefined {
const focused = this.settingsTree.getFocus()[0];
if (!(focused instanceof SettingsTreeSettingElement)) {
return;
}
return this.settingRenderers.getDOMElementsForSettingKey(this.settingsTree.getHTMLElement(), focused.setting.key)[0];
}
get currentFocusContext() {
return this._currentFocusContext;
}
createEditor(parent: HTMLElement): void {
parent.setAttribute('tabindex', '-1');
this.rootElement = DOM.append(parent, $('.settings-editor', { tabindex: '-1' }));
this.createHeader(this.rootElement);
this.createBody(this.rootElement);
this.addCtrlAInterceptor(this.rootElement);
this.updateStyles();
}
setInput(input: SettingsEditor2Input, options: SettingsEditorOptions | undefined, context: IEditorOpenContext, token: CancellationToken): Promise<void> {
this.inSettingsEditorContextKey.set(true);
return super.setInput(input, options, context, token)
.then(() => timeout(0)) // Force setInput to be async
.then(() => {
// Don't block setInput on render (which can trigger an async search)
this.render(token).then(() => {
options = options || SettingsEditorOptions.create({});
if (!this.viewState.settingsTarget) {
if (!options.target) {
options.target = ConfigurationTarget.USER_LOCAL;
}
}
this._setOptions(options);
this._register(input.onDispose(() => {
this.searchWidget.setValue('');
}));
// Init TOC selection
this.updateTreeScrollSync();
});
});
}
private restoreCachedState(): ISettingsEditor2State | null {
const cachedState = this.group && this.input && this.editorMemento.loadEditorState(this.group, this.input);
if (cachedState && typeof cachedState.target === 'object') {
cachedState.target = URI.revive(cachedState.target);
}
if (cachedState) {
const settingsTarget = cachedState.target;
this.settingsTargetsWidget.settingsTarget = settingsTarget;
this.viewState.settingsTarget = settingsTarget;
this.searchWidget.setValue(cachedState.searchQuery);
}
if (this.input) {
this.editorMemento.clearEditorState(this.input, this.group);
}
return withUndefinedAsNull(cachedState);
}
setOptions(options: SettingsEditorOptions | undefined): void {
super.setOptions(options);
if (options) {
this._setOptions(options);
}
}
private _setOptions(options: SettingsEditorOptions): void {
if (options.focusSearch) {
this.focusSearch();
}
if (options.query) {
this.searchWidget.setValue(options.query);
}
const target: SettingsTarget = options.folderUri || <SettingsTarget>options.target;
if (target) {
this.settingsTargetsWidget.settingsTarget = target;
this.viewState.settingsTarget = target;
}
}
clearInput(): void {
this.inSettingsEditorContextKey.set(false);
super.clearInput();
}
layout(dimension: DOM.Dimension): void {
this.dimension = dimension;
if (!this.isVisible()) {
return;
}
this.layoutTrees(dimension);
const innerWidth = Math.min(1000, dimension.width) - 24 * 2; // 24px padding on left and right;
// minus padding inside inputbox, countElement width, controls width, extra padding before countElement
const monacoWidth = innerWidth - 10 - this.countElement.clientWidth - this.controlsElement.clientWidth - 12;
this.searchWidget.layout(new DOM.Dimension(monacoWidth, 20));
this.rootElement.classList.toggle('mid-width', dimension.width < 1000 && dimension.width >= 600);
this.rootElement.classList.toggle('narrow-width', dimension.width < 600);
}
focus(): void {
if (this._currentFocusContext === SettingsFocusContext.Search) {
this.focusSearch();
} else if (this._currentFocusContext === SettingsFocusContext.SettingControl) {
const element = this.focusedSettingDOMElement;
if (element) {
const control = element.querySelector(AbstractSettingRenderer.CONTROL_SELECTOR);
if (control) {
(<HTMLElement>control).focus();
return;
}
}
} else if (this._currentFocusContext === SettingsFocusContext.SettingTree) {
this.settingsTree.domFocus();
} else if (this._currentFocusContext === SettingsFocusContext.TableOfContents) {
this.tocTree.domFocus();
}
}
protected setEditorVisible(visible: boolean, group: IEditorGroup | undefined): void {
super.setEditorVisible(visible, group);
if (!visible) {
// Wait for editor to be removed from DOM #106303
setTimeout(() => {
this.searchWidget.onHide();
}, 0);
}
}
focusSettings(focusSettingInput = false): void {
const focused = this.settingsTree.getFocus();
if (!focused.length) {
this.settingsTree.focusFirst();
}
this.settingsTree.domFocus();
if (focusSettingInput) {
const controlInFocusedRow = this.settingsTree.getHTMLElement().querySelector(`.focused ${AbstractSettingRenderer.CONTROL_SELECTOR}`);
if (controlInFocusedRow) {
(<HTMLElement>controlInFocusedRow).focus();
}
}
}
focusTOC(): void {
this.tocTree.domFocus();
}
showContextMenu(): void {
const focused = this.settingsTree.getFocus()[0];
const rowElement = this.focusedSettingDOMElement;
if (rowElement && focused instanceof SettingsTreeSettingElement) {
this.settingRenderers.showContextMenu(focused, rowElement);
}
}
focusSearch(filter?: string, selectAll = true): void {
if (filter && this.searchWidget) {
this.searchWidget.setValue(filter);
}
this.searchWidget.focus(selectAll);
}
clearSearchResults(): void {
this.searchWidget.setValue('');
this.focusSearch();
}
clearSearchFilters(): void {
let query = this.searchWidget.getValue();
SettingsEditor2.SUGGESTIONS.forEach(suggestion => {
query = query.replace(suggestion, '');
});
this.searchWidget.setValue(query.trim());
}
private updateInputAriaLabel() {
let label = searchBoxLabel;
if (this.searchResultLabel) {
label += `. ${this.searchResultLabel}`;
}
if (this.lastSyncedLabel) {
label += `. ${this.lastSyncedLabel}`;
}
this.searchWidget.updateAriaLabel(label);
}
private createHeader(parent: HTMLElement): void {
this.headerContainer = DOM.append(parent, $('.settings-header'));
const searchContainer = DOM.append(this.headerContainer, $('.search-container'));
const clearInputAction = new Action(SETTINGS_EDITOR_COMMAND_CLEAR_SEARCH_RESULTS, localize('clearInput', "Clear Settings Search Input"), ThemeIcon.asClassName(preferencesClearInputIcon), false, () => { this.clearSearchResults(); return Promise.resolve(null); });
this.searchWidget = this._register(this.instantiationService.createInstance(SuggestEnabledInput, `${SettingsEditor2.ID}.searchbox`, searchContainer, {
triggerCharacters: ['@'],
provideResults: (query: string) => {
return SettingsEditor2.SUGGESTIONS.filter(tag => query.indexOf(tag) === -1).map(tag => tag.endsWith(':') ? tag : tag + ' ');
}
}, searchBoxLabel, 'settingseditor:searchinput' + SettingsEditor2.NUM_INSTANCES++, {
placeholderText: searchBoxLabel,
focusContextKey: this.searchFocusContextKey,
// TODO: Aria-live
}));
this._register(this.searchWidget.onFocus(() => {
this._currentFocusContext = SettingsFocusContext.Search;
}));
this._register(attachSuggestEnabledInputBoxStyler(this.searchWidget, this.themeService, {
inputBorder: settingsTextInputBorder
}));
this.countElement = DOM.append(searchContainer, DOM.$('.settings-count-widget.monaco-count-badge.long'));
this._register(attachStylerCallback(this.themeService, { badgeBackground, contrastBorder, badgeForeground }, colors => {
const background = colors.badgeBackground ? colors.badgeBackground.toString() : '';
const border = colors.contrastBorder ? colors.contrastBorder.toString() : '';
const foreground = colors.badgeForeground ? colors.badgeForeground.toString() : '';
this.countElement.style.backgroundColor = background;
this.countElement.style.color = foreground;
this.countElement.style.borderWidth = border ? '1px' : '';
this.countElement.style.borderStyle = border ? 'solid' : '';
this.countElement.style.borderColor = border;
}));
this._register(this.searchWidget.onInputDidChange(() => {
const searchVal = this.searchWidget.getValue();
clearInputAction.enabled = !!searchVal;
this.onSearchInputChanged();
}));
const headerControlsContainer = DOM.append(this.headerContainer, $('.settings-header-controls'));
const targetWidgetContainer = DOM.append(headerControlsContainer, $('.settings-target-container'));
this.settingsTargetsWidget = this._register(this.instantiationService.createInstance(SettingsTargetsWidget, targetWidgetContainer, { enableRemoteSettings: true }));
this.settingsTargetsWidget.settingsTarget = ConfigurationTarget.USER_LOCAL;
this.settingsTargetsWidget.onDidTargetChange(target => this.onDidSettingsTargetChange(target));
this._register(DOM.addDisposableListener(targetWidgetContainer, DOM.EventType.KEY_DOWN, e => {
const event = new StandardKeyboardEvent(e);
if (event.keyCode === KeyCode.DownArrow) {
this.focusSettings();
}
}));
if (this.userDataSyncWorkbenchService.enabled && this.userDataAutoSyncEnablementService.canToggleEnablement()) {
const syncControls = this._register(this.instantiationService.createInstance(SyncControls, headerControlsContainer));
this._register(syncControls.onDidChangeLastSyncedLabel(lastSyncedLabel => {
this.lastSyncedLabel = lastSyncedLabel;
this.updateInputAriaLabel();
}));
}
this.controlsElement = DOM.append(searchContainer, DOM.$('.settings-clear-widget'));
const actionBar = this._register(new ActionBar(this.controlsElement, {
animated: false,
actionViewItemProvider: (_action) => { return undefined; }
}));
actionBar.push([clearInputAction], { label: false, icon: true });
}
private onDidSettingsTargetChange(target: SettingsTarget): void {
this.viewState.settingsTarget = target;
// TODO Instead of rebuilding the whole model, refresh and uncache the inspected setting value
this.onConfigUpdate(undefined, true);
}
private onDidClickSetting(evt: ISettingLinkClickEvent, recursed?: boolean): void {
const elements = this.currentSettingsModel.getElementsByName(evt.targetKey);
if (elements && elements[0]) {
let sourceTop = 0.5;
try {
const _sourceTop = this.settingsTree.getRelativeTop(evt.source);
if (_sourceTop !== null) {
sourceTop = _sourceTop;
}
} catch {
// e.g. clicked a searched element, now the search has been cleared
}
this.settingsTree.reveal(elements[0], sourceTop);
// We need to shift focus from the setting that contains the link to the setting that's
// linked. Clicking on the link sets focus on the setting that contains the link,
// which is why we need the setTimeout
setTimeout(() => this.settingsTree.setFocus([elements[0]]), 50);
const domElements = this.settingRenderers.getDOMElementsForSettingKey(this.settingsTree.getHTMLElement(), evt.targetKey);
if (domElements && domElements[0]) {
const control = domElements[0].querySelector(AbstractSettingRenderer.CONTROL_SELECTOR);
if (control) {
(<HTMLElement>control).focus();
}
}
} else if (!recursed) {
const p = this.triggerSearch('');
p.then(() => {
this.searchWidget.setValue('');
this.onDidClickSetting(evt, true);
});
}
}
switchToSettingsFile(): Promise<IEditorPane | undefined> {
const query = parseQuery(this.searchWidget.getValue()).query;
return this.openSettingsFile({ query });
}
private async openSettingsFile(options?: ISettingsEditorOptions): Promise<IEditorPane | undefined> {
const currentSettingsTarget = this.settingsTargetsWidget.settingsTarget;
if (currentSettingsTarget === ConfigurationTarget.USER_LOCAL) {
return this.preferencesService.openGlobalSettings(true, options);
} else if (currentSettingsTarget === ConfigurationTarget.USER_REMOTE) {
return this.preferencesService.openRemoteSettings();
} else if (currentSettingsTarget === ConfigurationTarget.WORKSPACE) {
return this.preferencesService.openWorkspaceSettings(true, options);
} else if (URI.isUri(currentSettingsTarget)) {
return this.preferencesService.openFolderSettings(currentSettingsTarget, true, options);
}
return undefined;
}
private createBody(parent: HTMLElement): void {
const bodyContainer = DOM.append(parent, $('.settings-body'));
this.noResultsMessage = DOM.append(bodyContainer, $('.no-results-message'));
this.noResultsMessage.innerText = localize('noResults', "No Settings Found");
this.clearFilterLinkContainer = $('span.clear-search-filters');
this.clearFilterLinkContainer.textContent = ' - ';
const clearFilterLink = DOM.append(this.clearFilterLinkContainer, $('a.pointer.prominent', { tabindex: 0 }, localize('clearSearchFilters', 'Clear Filters')));
this._register(DOM.addDisposableListener(clearFilterLink, DOM.EventType.CLICK, (e: MouseEvent) => {
DOM.EventHelper.stop(e, false);
this.clearSearchFilters();
}));
DOM.append(this.noResultsMessage, this.clearFilterLinkContainer);
this._register(attachStylerCallback(this.themeService, { editorForeground }, colors => {
this.noResultsMessage.style.color = colors.editorForeground ? colors.editorForeground.toString() : '';
}));
this.createTOC(bodyContainer);
this.createSettingsTree(bodyContainer);
}
private addCtrlAInterceptor(container: HTMLElement): void {
this._register(DOM.addStandardDisposableListener(container, DOM.EventType.KEY_DOWN, (e: StandardKeyboardEvent) => {
if (
e.keyCode === KeyCode.KEY_A &&
(platform.isMacintosh ? e.metaKey : e.ctrlKey) &&
e.target.tagName !== 'TEXTAREA' &&
e.target.tagName !== 'INPUT'
) {
// Avoid browser ctrl+a
e.browserEvent.stopPropagation();
e.browserEvent.preventDefault();
}
}));
}
private createTOC(parent: HTMLElement): void {
this.tocTreeModel = this.instantiationService.createInstance(TOCTreeModel, this.viewState);
this.tocTreeContainer = DOM.append(parent, $('.settings-toc-container'));
this.tocTree = this._register(this.instantiationService.createInstance(TOCTree,
DOM.append(this.tocTreeContainer, $('.settings-toc-wrapper', {
'role': 'navigation',
'aria-label': localize('settings', "Settings"),
})),
this.viewState));
this._register(this.tocTree.onDidFocus(() => {
this._currentFocusContext = SettingsFocusContext.TableOfContents;
}));
this._register(this.tocTree.onDidChangeFocus(e => {
const element: SettingsTreeGroupElement | null = e.elements[0];
if (this.tocFocusedElement === element) {
return;
}
this.tocFocusedElement = element;
this.tocTree.setSelection(element ? [element] : []);
if (this.searchResultModel) {
if (this.viewState.filterToCategory !== element) {
this.viewState.filterToCategory = withNullAsUndefined(element);
this.renderTree();
this.settingsTree.scrollTop = 0;
}
} else if (element && (!e.browserEvent || !(<IFocusEventFromScroll>e.browserEvent).fromScroll)) {
this.settingsTree.reveal(element, 0);
this.settingsTree.setFocus([element]);
}
}));
this._register(this.tocTree.onDidFocus(() => {
this.tocRowFocused.set(true);
}));
this._register(this.tocTree.onDidBlur(() => {
this.tocRowFocused.set(false);
}));
}
private createSettingsTree(parent: HTMLElement): void {
this.settingsTreeContainer = DOM.append(parent, $('.settings-tree-container'));
this.settingRenderers = this.instantiationService.createInstance(SettingTreeRenderers);
this._register(this.settingRenderers.onDidChangeSetting(e => this.onDidChangeSetting(e.key, e.value, e.type)));
this._register(this.settingRenderers.onDidOpenSettings(settingKey => {
this.openSettingsFile({ revealSetting: { key: settingKey, edit: true } });
}));
this._register(this.settingRenderers.onDidClickSettingLink(settingName => this.onDidClickSetting(settingName)));
this._register(this.settingRenderers.onDidFocusSetting(element => {
this.settingsTree.setFocus([element]);
this._currentFocusContext = SettingsFocusContext.SettingControl;
this.settingRowFocused.set(false);
}));
this._register(this.settingRenderers.onDidClickOverrideElement((element: ISettingOverrideClickEvent) => {
if (element.scope.toLowerCase() === 'workspace') {
this.settingsTargetsWidget.updateTarget(ConfigurationTarget.WORKSPACE);
} else if (element.scope.toLowerCase() === 'user') {
this.settingsTargetsWidget.updateTarget(ConfigurationTarget.USER_LOCAL);
} else if (element.scope.toLowerCase() === 'remote') {
this.settingsTargetsWidget.updateTarget(ConfigurationTarget.USER_REMOTE);
}
this.searchWidget.setValue(element.targetKey);
}));
this.settingsTree = this._register(this.instantiationService.createInstance(SettingsTree,
this.settingsTreeContainer,
this.viewState,
this.settingRenderers.allRenderers));
this._register(this.settingsTree.onDidScroll(() => {
if (this.settingsTree.scrollTop === this.settingsTreeScrollTop) {
return;
}
this.settingsTreeScrollTop = this.settingsTree.scrollTop;
// setTimeout because calling setChildren on the settingsTree can trigger onDidScroll, so it fires when
// setChildren has called on the settings tree but not the toc tree yet, so their rendered elements are out of sync
setTimeout(() => {
this.updateTreeScrollSync();
}, 0);
}));
this._register(this.settingsTree.onDidFocus(() => {
if (document.activeElement?.classList.contains('monaco-list')) {
this._currentFocusContext = SettingsFocusContext.SettingTree;
this.settingRowFocused.set(true);
}
}));
this._register(this.settingsTree.onDidBlur(() => {
this.settingRowFocused.set(false);
}));
// There is no different select state in the settings tree
this._register(this.settingsTree.onDidChangeFocus(e => {
const element = e.elements[0];
if (this.treeFocusedElement === element) {
return;
}
if (this.treeFocusedElement) {
this.treeFocusedElement.tabbable = false;
}
this.treeFocusedElement = element;
if (this.treeFocusedElement) {
this.treeFocusedElement.tabbable = true;
}
this.settingsTree.setSelection(element ? [element] : []);
}));
}
private notifyNoSaveNeeded() {
if (!this.storageService.getBoolean(SETTINGS_AUTOSAVE_NOTIFIED_KEY, StorageScope.GLOBAL, false)) {
this.storageService.store(SETTINGS_AUTOSAVE_NOTIFIED_KEY, true, StorageScope.GLOBAL, StorageTarget.USER);
this.notificationService.info(localize('settingsNoSaveNeeded', "Changes to settings are saved automatically."));
}
}
private onDidChangeSetting(key: string, value: any, type: SettingValueType | SettingValueType[]): void {
this.notifyNoSaveNeeded();
if (this.pendingSettingUpdate && this.pendingSettingUpdate.key !== key) {
this.updateChangedSetting(key, value);
}
this.pendingSettingUpdate = { key, value };
if (SettingsEditor2.shouldSettingUpdateFast(type)) {
this.settingFastUpdateDelayer.trigger(() => this.updateChangedSetting(key, value));
} else {
this.settingSlowUpdateDelayer.trigger(() => this.updateChangedSetting(key, value));
}
}
private updateTreeScrollSync(): void {
this.settingRenderers.cancelSuggesters();
if (this.searchResultModel) {
return;
}
if (!this.tocTreeModel) {
return;
}
const elementToSync = this.settingsTree.firstVisibleElement;
const element = elementToSync instanceof SettingsTreeSettingElement ? elementToSync.parent :
elementToSync instanceof SettingsTreeGroupElement ? elementToSync :
null;
// It's possible for this to be called when the TOC and settings tree are out of sync - e.g. when the settings tree has deferred a refresh because
// it is focused. So, bail if element doesn't exist in the TOC.
let nodeExists = true;
try { this.tocTree.getNode(element); } catch (e) { nodeExists = false; }
if (!nodeExists) {
return;
}
if (element && this.tocTree.getSelection()[0] !== element) {
const ancestors = this.getAncestors(element);
ancestors.forEach(e => this.tocTree.expand(<SettingsTreeGroupElement>e));
this.tocTree.reveal(element);
const elementTop = this.tocTree.getRelativeTop(element);
if (typeof elementTop !== 'number') {
return;
}
this.tocTree.collapseAll();
ancestors.forEach(e => this.tocTree.expand(<SettingsTreeGroupElement>e));
if (elementTop < 0 || elementTop > 1) {
this.tocTree.reveal(element);
} else {
this.tocTree.reveal(element, elementTop);
}
this.tocTree.expand(element);
this.tocTree.setSelection([element]);
const fakeKeyboardEvent = new KeyboardEvent('keydown');
(<IFocusEventFromScroll>fakeKeyboardEvent).fromScroll = true;
this.tocTree.setFocus([element], fakeKeyboardEvent);
}
}
private getAncestors(element: SettingsTreeElement): SettingsTreeElement[] {
const ancestors: any[] = [];
while (element.parent) {
if (element.parent.id !== 'root') {
ancestors.push(element.parent);
}
element = element.parent;
}
return ancestors.reverse();
}
private updateChangedSetting(key: string, value: any): Promise<void> {
// ConfigurationService displays the error if this fails.
// Force a render afterwards because onDidConfigurationUpdate doesn't fire if the update doesn't result in an effective setting value change
const settingsTarget = this.settingsTargetsWidget.settingsTarget;
const resource = URI.isUri(settingsTarget) ? settingsTarget : undefined;
const configurationTarget = <ConfigurationTarget>(resource ? ConfigurationTarget.WORKSPACE_FOLDER : settingsTarget);
const overrides: IConfigurationOverrides = { resource };
const isManualReset = value === undefined;
// If the user is changing the value back to the default, do a 'reset' instead
const inspected = this.configurationService.inspect(key, overrides);
if (inspected.defaultValue === value) {
value = undefined;
}
return this.configurationService.updateValue(key, value, overrides, configurationTarget)
.then(() => {
this.renderTree(key, isManualReset);
const reportModifiedProps = {
key,
query: this.searchWidget.getValue(),
searchResults: this.searchResultModel && this.searchResultModel.getUniqueResults(),
rawResults: this.searchResultModel && this.searchResultModel.getRawResults(),
showConfiguredOnly: !!this.viewState.tagFilters && this.viewState.tagFilters.has(MODIFIED_SETTING_TAG),
isReset: typeof value === 'undefined',
settingsTarget: this.settingsTargetsWidget.settingsTarget as SettingsTarget
};
return this.reportModifiedSetting(reportModifiedProps);
});
}
private reportModifiedSetting(props: { key: string, query: string, searchResults: ISearchResult[] | null, rawResults: ISearchResult[] | null, showConfiguredOnly: boolean, isReset: boolean, settingsTarget: SettingsTarget }): void {
this.pendingSettingUpdate = null;
let groupId: string | undefined = undefined;
let nlpIndex: number | undefined = undefined;
let displayIndex: number | undefined = undefined;
if (props.searchResults) {
const remoteResult = props.searchResults[SearchResultIdx.Remote];
const localResult = props.searchResults[SearchResultIdx.Local];
const localIndex = localResult!.filterMatches.findIndex(m => m.setting.key === props.key);
groupId = localIndex >= 0 ?
'local' :
'remote';
displayIndex = localIndex >= 0 ?
localIndex :
remoteResult && (remoteResult.filterMatches.findIndex(m => m.setting.key === props.key) + localResult.filterMatches.length);
if (this.searchResultModel) {
const rawResults = this.searchResultModel.getRawResults();
if (rawResults[SearchResultIdx.Remote]) {
const _nlpIndex = rawResults[SearchResultIdx.Remote].filterMatches.findIndex(m => m.setting.key === props.key);
nlpIndex = _nlpIndex >= 0 ? _nlpIndex : undefined;
}
}
}
const reportedTarget = props.settingsTarget === ConfigurationTarget.USER_LOCAL ? 'user' :
props.settingsTarget === ConfigurationTarget.USER_REMOTE ? 'user_remote' :
props.settingsTarget === ConfigurationTarget.WORKSPACE ? 'workspace' :
'folder';
const data = {
key: props.key,
query: props.query,
groupId,
nlpIndex,
displayIndex,
showConfiguredOnly: props.showConfiguredOnly,
isReset: props.isReset,
target: reportedTarget
};
/* __GDPR__
"settingsEditor.settingModified" : {
"key" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"query" : { "classification": "CustomerContent", "purpose": "FeatureInsight" },
"groupId" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"nlpIndex" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"displayIndex" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"showConfiguredOnly" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"isReset" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"target" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetryService.publicLog('settingsEditor.settingModified', data);
}
private render(token: CancellationToken): Promise<any> {
if (this.input) {
return this.input.resolve()
.then((model: IEditorModel | null) => {
if (token.isCancellationRequested || !(model instanceof Settings2EditorModel)) {
return undefined;
}
this._register(model.onDidChangeGroups(() => {
this.updatedConfigSchemaDelayer.trigger(() => {
this.onConfigUpdate(undefined, undefined, true);
});
}));
this.defaultSettingsEditorModel = model;
return this.onConfigUpdate(undefined, true);
});
}
return Promise.resolve(null);
}
private onSearchModeToggled(): void {
this.rootElement.classList.remove('no-toc-search');
if (this.configurationService.getValue('workbench.settings.settingsSearchTocBehavior') === 'hide') {
this.rootElement.classList.toggle('no-toc-search', !!this.searchResultModel);
}
}
private scheduleRefresh(element: HTMLElement, key = ''): void {
if (key && this.scheduledRefreshes.has(key)) {
return;
}
if (!key) {
this.scheduledRefreshes.forEach(r => r.dispose());
this.scheduledRefreshes.clear();
}
const scheduledRefreshTracker = DOM.trackFocus(element);
this.scheduledRefreshes.set(key, scheduledRefreshTracker);
scheduledRefreshTracker.onDidBlur(() => {
scheduledRefreshTracker.dispose();
this.scheduledRefreshes.delete(key);
this.onConfigUpdate([key]);
});
}
private async onConfigUpdate(keys?: string[], forceRefresh = false, schemaChange = false): Promise<void> {
if (keys && this.settingsTreeModel) {
return this.updateElementsByKey(keys);
}
const groups = this.defaultSettingsEditorModel.settingsGroups.slice(1); // Without commonlyUsed
const dividedGroups = collections.groupBy(groups, g => g.extensionInfo ? 'extension' : 'core');
const settingsResult = resolveSettingsTree(tocData, dividedGroups.core, this.logService);
const resolvedSettingsRoot = settingsResult.tree;
// Warn for settings not included in layout
if (settingsResult.leftoverSettings.size && !this.hasWarnedMissingSettings) {
const settingKeyList: string[] = [];
settingsResult.leftoverSettings.forEach(s => {
settingKeyList.push(s.key);
});
this.logService.warn(`SettingsEditor2: Settings not included in settingsLayout.ts: ${settingKeyList.join(', ')}`);
this.hasWarnedMissingSettings = true;
}
const commonlyUsed = resolveSettingsTree(commonlyUsedData, dividedGroups.core, this.logService);
resolvedSettingsRoot.children!.unshift(commonlyUsed.tree);
resolvedSettingsRoot.children!.push(resolveExtensionsSettings(dividedGroups.extension || []));
if (this.searchResultModel) {
this.searchResultModel.updateChildren();
}
if (this.settingsTreeModel) {
this.settingsTreeModel.update(resolvedSettingsRoot);
if (schemaChange && !!this.searchResultModel) {
// If an extension's settings were just loaded and a search is active, retrigger the search so it shows up
return await this.onSearchInputChanged();
}
this.refreshTOCTree();
this.renderTree(undefined, forceRefresh);
} else {
this.settingsTreeModel = this.instantiationService.createInstance(SettingsTreeModel, this.viewState);
this.settingsTreeModel.update(resolvedSettingsRoot);
this.tocTreeModel.settingsTreeRoot = this.settingsTreeModel.root as SettingsTreeGroupElement;
const cachedState = this.restoreCachedState();
if (cachedState && cachedState.searchQuery) {
await this.onSearchInputChanged();
} else {
this.refreshTOCTree();
this.refreshTree();
this.tocTree.collapseAll();
}
}
}
private updateElementsByKey(keys: string[]): void {
if (keys.length) {
if (this.searchResultModel) {
keys.forEach(key => this.searchResultModel!.updateElementsByName(key));
}
if (this.settingsTreeModel) {
keys.forEach(key => this.settingsTreeModel.updateElementsByName(key));
}
keys.forEach(key => this.renderTree(key));
} else {
return this.renderTree();
}
}
private getActiveControlInSettingsTree(): HTMLElement | null {
return (document.activeElement && DOM.isAncestor(document.activeElement, this.settingsTree.getHTMLElement())) ?
<HTMLElement>document.activeElement :
null;
}
private renderTree(key?: string, force = false): void {
if (!force && key && this.scheduledRefreshes.has(key)) {
this.updateModifiedLabelForKey(key);
return;
}
// If the context view is focused, delay rendering settings
if (this.contextViewFocused()) {
const element = document.querySelector('.context-view');
if (element) {
this.scheduleRefresh(element as HTMLElement, key);
}
return;
}
// If a setting control is currently focused, schedule a refresh for later
const activeElement = this.getActiveControlInSettingsTree();
const focusedSetting = activeElement && this.settingRenderers.getSettingDOMElementForDOMElement(activeElement);
if (focusedSetting && !force) {
// If a single setting is being refreshed, it's ok to refresh now if that is not the focused setting
if (key) {
const focusedKey = focusedSetting.getAttribute(AbstractSettingRenderer.SETTING_KEY_ATTR);
if (focusedKey === key &&
// update `list`s live, as they have a separate "submit edit" step built in before this
(focusedSetting.parentElement && !focusedSetting.parentElement.classList.contains('setting-item-list'))
) {
this.updateModifiedLabelForKey(key);
this.scheduleRefresh(focusedSetting, key);
return;
}
} else {
this.scheduleRefresh(focusedSetting);
return;
}
}
this.renderResultCountMessages();
if (key) {
const elements = this.currentSettingsModel.getElementsByName(key);
if (elements && elements.length) {
// TODO https://github.com/microsoft/vscode/issues/57360
this.refreshTree();
} else {
// Refresh requested for a key that we don't know about
return;
}
} else {
this.refreshTree();
}
return;
}
private contextViewFocused(): boolean {
return !!DOM.findParentWithClass(<HTMLElement>document.activeElement, 'context-view');
}
private refreshTree(): void {
if (this.isVisible()) {
this.settingsTree.setChildren(null, createGroupIterator(this.currentSettingsModel.root));
}
}
private refreshTOCTree(): void {
if (this.isVisible()) {
this.tocTreeModel.update();
this.tocTree.setChildren(null, createTOCIterator(this.tocTreeModel, this.tocTree));
}
}
private updateModifiedLabelForKey(key: string): void {
const dataElements = this.currentSettingsModel.getElementsByName(key);
const isModified = dataElements && dataElements[0] && dataElements[0].isConfigured; // all elements are either configured or not
const elements = this.settingRenderers.getDOMElementsForSettingKey(this.settingsTree.getHTMLElement(), key);
if (elements && elements[0]) {
elements[0].classList.toggle('is-configured', !!isModified);
}
}
private async onSearchInputChanged(): Promise<void> {
const query = this.searchWidget.getValue().trim();
this.delayedFilterLogging.cancel();
await this.triggerSearch(query.replace(/โบ/g, ' '));
if (query && this.searchResultModel) {
this.delayedFilterLogging.trigger(() => this.reportFilteringUsed(query, this.searchResultModel!.getUniqueResults()));
}
}
private parseSettingFromJSON(query: string): string | null {
const match = query.match(/"([a-zA-Z.]+)": /);
return match && match[1];
}
private triggerSearch(query: string): Promise<void> {
this.viewState.tagFilters = new Set<string>();
this.viewState.extensionFilters = new Set<string>();
this.viewState.featureFilters = new Set<string>();
this.viewState.idFilters = new Set<string>();
if (query) {
const parsedQuery = parseQuery(query);
query = parsedQuery.query;
parsedQuery.tags.forEach(tag => this.viewState.tagFilters!.add(tag));
parsedQuery.extensionFilters.forEach(extensionId => this.viewState.extensionFilters!.add(extensionId));
parsedQuery.featureFilters!.forEach(feature => this.viewState.featureFilters!.add(feature));
parsedQuery.idFilters!.forEach(id => this.viewState.idFilters!.add(id));
}
if (query && query !== '@') {
query = this.parseSettingFromJSON(query) || query;
return this.triggerFilterPreferences(query);
} else {
if (this.viewState.tagFilters.size || this.viewState.extensionFilters.size || this.viewState.featureFilters.size || this.viewState.idFilters.size) {
this.searchResultModel = this.createFilterModel();
} else {
this.searchResultModel = null;
}
this.localSearchDelayer.cancel();
this.remoteSearchThrottle.cancel();
if (this.searchInProgress) {
this.searchInProgress.cancel();
this.searchInProgress.dispose();
this.searchInProgress = null;
}
this.tocTree.setFocus([]);
this.viewState.filterToCategory = undefined;
this.tocTreeModel.currentSearchModel = this.searchResultModel;
this.onSearchModeToggled();
if (this.searchResultModel) {
// Added a filter model
this.tocTree.setSelection([]);
this.tocTree.expandAll();
this.refreshTOCTree();
this.renderResultCountMessages();
this.refreshTree();
} else {
// Leaving search mode
this.tocTree.collapseAll();
this.refreshTOCTree();
this.renderResultCountMessages();
this.refreshTree();
}
}
return Promise.resolve();
}
/**
* Return a fake SearchResultModel which can hold a flat list of all settings, to be filtered (@modified etc)
*/
private createFilterModel(): SearchResultModel {
const filterModel = this.instantiationService.createInstance(SearchResultModel, this.viewState);
const fullResult: ISearchResult = {
filterMatches: []
};
for (const g of this.defaultSettingsEditorModel.settingsGroups.slice(1)) {
for (const sect of g.sections) {
for (const setting of sect.settings) {
fullResult.filterMatches.push({ setting, matches: [], score: 0 });
}
}
}
filterModel.setResult(0, fullResult);
return filterModel;
}
private reportFilteringUsed(query: string, results: ISearchResult[]): void {
const nlpResult = results[SearchResultIdx.Remote];
const nlpMetadata = nlpResult && nlpResult.metadata;
const durations = {
nlpResult: nlpMetadata && nlpMetadata.duration
};
// Count unique results
const counts: { nlpResult?: number, filterResult?: number } = {};
const filterResult = results[SearchResultIdx.Local];
if (filterResult) {
counts['filterResult'] = filterResult.filterMatches.length;
}
if (nlpResult) {
counts['nlpResult'] = nlpResult.filterMatches.length;
}
const requestCount = nlpMetadata && nlpMetadata.requestCount;
const data = {
query,
durations,
counts,
requestCount
};
/* __GDPR__
"settingsEditor.filter" : {
"query": { "classification": "CustomerContent", "purpose": "FeatureInsight" },
"durations.nlpResult" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"counts.nlpResult" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"counts.filterResult" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"requestCount" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
}
*/
this.telemetryService.publicLog('settingsEditor.filter', data);
}
private triggerFilterPreferences(query: string): Promise<void> {
if (this.searchInProgress) {
this.searchInProgress.cancel();
this.searchInProgress = null;
}
// Trigger the local search. If it didn't find an exact match, trigger the remote search.
const searchInProgress = this.searchInProgress = new CancellationTokenSource();
return this.localSearchDelayer.trigger(() => {
if (searchInProgress && !searchInProgress.token.isCancellationRequested) {
return this.localFilterPreferences(query).then(result => {
if (result && !result.exactMatch) {
this.remoteSearchThrottle.trigger(() => {
return searchInProgress && !searchInProgress.token.isCancellationRequested ?
this.remoteSearchPreferences(query, this.searchInProgress!.token) :
Promise.resolve();
});
}
});
} else {
return Promise.resolve();
}
});
}
private localFilterPreferences(query: string, token?: CancellationToken): Promise<ISearchResult | null> {
const localSearchProvider = this.preferencesSearchService.getLocalSearchProvider(query);
return this.filterOrSearchPreferences(query, SearchResultIdx.Local, localSearchProvider, token);
}
private remoteSearchPreferences(query: string, token?: CancellationToken): Promise<void> {
const remoteSearchProvider = this.preferencesSearchService.getRemoteSearchProvider(query);
const newExtSearchProvider = this.preferencesSearchService.getRemoteSearchProvider(query, true);
return Promise.all([
this.filterOrSearchPreferences(query, SearchResultIdx.Remote, remoteSearchProvider, token),
this.filterOrSearchPreferences(query, SearchResultIdx.NewExtensions, newExtSearchProvider, token)
]).then(() => { });
}
private filterOrSearchPreferences(query: string, type: SearchResultIdx, searchProvider?: ISearchProvider, token?: CancellationToken): Promise<ISearchResult | null> {
return this._filterOrSearchPreferencesModel(query, this.defaultSettingsEditorModel, searchProvider, token).then(result => {
if (token && token.isCancellationRequested) {
// Handle cancellation like this because cancellation is lost inside the search provider due to async/await
return null;
}
if (!this.searchResultModel) {
this.searchResultModel = this.instantiationService.createInstance(SearchResultModel, this.viewState);
this.searchResultModel.setResult(type, result);
this.tocTreeModel.currentSearchModel = this.searchResultModel;
this.onSearchModeToggled();
} else {
this.searchResultModel.setResult(type, result);
this.tocTreeModel.update();
}
if (type === SearchResultIdx.Local) {
this.tocTree.setFocus([]);
this.viewState.filterToCategory = undefined;
this.tocTree.expandAll();
}
this.refreshTOCTree();
this.renderTree(undefined, true);
return result;
});
}
private renderResultCountMessages() {
if (!this.currentSettingsModel) {
return;
}
this.clearFilterLinkContainer.style.display = this.viewState.tagFilters && this.viewState.tagFilters.size > 0
? 'initial'
: 'none';
if (!this.searchResultModel) {
if (this.countElement.style.display !== 'none') {
this.searchResultLabel = null;
this.countElement.style.display = 'none';
this.layout(this.dimension);
}
this.rootElement.classList.remove('no-results');
return;
}
if (this.tocTreeModel && this.tocTreeModel.settingsTreeRoot) {
const count = this.tocTreeModel.settingsTreeRoot.count;
let resultString: string;
switch (count) {
case 0: resultString = localize('noResults', "No Settings Found"); break;
case 1: resultString = localize('oneResult', "1 Setting Found"); break;
default: resultString = localize('moreThanOneResult', "{0} Settings Found", count);
}
this.searchResultLabel = resultString;
this.updateInputAriaLabel();
this.countElement.innerText = resultString;
aria.status(resultString);
if (this.countElement.style.display !== 'block') {
this.countElement.style.display = 'block';
this.layout(this.dimension);
}
this.rootElement.classList.toggle('no-results', count === 0);
}
}
private _filterOrSearchPreferencesModel(filter: string, model: ISettingsEditorModel, provider?: ISearchProvider, token?: CancellationToken): Promise<ISearchResult | null> {
const searchP = provider ? provider.searchModel(model, token) : Promise.resolve(null);
return searchP
.then<ISearchResult, ISearchResult | null>(undefined, err => {
if (isPromiseCanceledError(err)) {
return Promise.reject(err);
} else {
/* __GDPR__
"settingsEditor.searchError" : {
"message": { "classification": "CallstackOrException", "purpose": "FeatureInsight" }
}
*/
const message = getErrorMessage(err).trim();
if (message && message !== 'Error') {
// "Error" = any generic network error
this.telemetryService.publicLogError('settingsEditor.searchError', { message });
this.logService.info('Setting search error: ' + message);
}
return null;
}
});
}
private layoutTrees(dimension: DOM.Dimension): void {
const listHeight = dimension.height - (72 + 11 /* header height + editor padding */);
const settingsTreeHeight = listHeight - 14;
this.settingsTreeContainer.style.height = `${settingsTreeHeight}px`;
this.settingsTree.layout(settingsTreeHeight, dimension.width);
const tocTreeHeight = settingsTreeHeight - 1;
this.tocTreeContainer.style.height = `${tocTreeHeight}px`;
this.tocTree.layout(tocTreeHeight);
}
protected saveState(): void {
if (this.isVisible()) {
const searchQuery = this.searchWidget.getValue().trim();
const target = this.settingsTargetsWidget.settingsTarget as SettingsTarget;
if (this.group && this.input) {
this.editorMemento.saveEditorState(this.group, this.input, { searchQuery, target });
}
}
super.saveState();
}
}
class SyncControls extends Disposable {
private readonly lastSyncedLabel!: HTMLElement;
private readonly turnOnSyncButton!: Button;
private readonly _onDidChangeLastSyncedLabel = this._register(new Emitter<string>());
public readonly onDidChangeLastSyncedLabel = this._onDidChangeLastSyncedLabel.event;
constructor(
container: HTMLElement,
@ICommandService private readonly commandService: ICommandService,
@IUserDataSyncService private readonly userDataSyncService: IUserDataSyncService,
@IUserDataAutoSyncEnablementService private readonly userDataAutoSyncEnablementService: IUserDataAutoSyncEnablementService,
@IThemeService themeService: IThemeService,
) {
super();
const headerRightControlsContainer = DOM.append(container, $('.settings-right-controls'));
const turnOnSyncButtonContainer = DOM.append(headerRightControlsContainer, $('.turn-on-sync'));
this.turnOnSyncButton = this._register(new Button(turnOnSyncButtonContainer, { title: true }));
this._register(attachButtonStyler(this.turnOnSyncButton, themeService));
this.lastSyncedLabel = DOM.append(headerRightControlsContainer, $('.last-synced-label'));
DOM.hide(this.lastSyncedLabel);
this.turnOnSyncButton.enabled = true;
this.turnOnSyncButton.label = localize('turnOnSyncButton', "Turn on Settings Sync");
DOM.hide(this.turnOnSyncButton.element);
this._register(this.turnOnSyncButton.onDidClick(async () => {
await this.commandService.executeCommand('workbench.userDataSync.actions.turnOn');
}));
this.updateLastSyncedTime();
this._register(this.userDataSyncService.onDidChangeLastSyncTime(() => {
this.updateLastSyncedTime();
}));
const updateLastSyncedTimer = this._register(new IntervalTimer());
updateLastSyncedTimer.cancelAndSet(() => this.updateLastSyncedTime(), 60 * 1000);
this.update();
this._register(this.userDataSyncService.onDidChangeStatus(() => {
this.update();
}));
this._register(this.userDataAutoSyncEnablementService.onDidChangeEnablement(() => {
this.update();
}));
}
private updateLastSyncedTime(): void {
const last = this.userDataSyncService.lastSyncTime;
let label: string;
if (typeof last === 'number') {
const d = fromNow(last, true);
label = localize('lastSyncedLabel', "Last synced: {0}", d);
} else {
label = '';
}
this.lastSyncedLabel.textContent = label;
this._onDidChangeLastSyncedLabel.fire(label);
}
private update(): void {
if (this.userDataSyncService.status === SyncStatus.Uninitialized) {
return;
}
if (this.userDataAutoSyncEnablementService.isEnabled() || this.userDataSyncService.status !== SyncStatus.Idle) {
DOM.show(this.lastSyncedLabel);
DOM.hide(this.turnOnSyncButton.element);
} else {
DOM.hide(this.lastSyncedLabel);
DOM.show(this.turnOnSyncButton.element);
}
}
}
interface ISettingsEditor2State {
searchQuery: string;
target: SettingsTarget;
}
| src/vs/workbench/contrib/preferences/browser/settingsEditor2.ts | 0 | https://github.com/microsoft/vscode/commit/a2a3bf27e9ecb46851f18c321c1af1e6272bdbe1 | [
0.00027108093490824103,
0.00017214783292729408,
0.00016461685299873352,
0.0001689986966084689,
0.000014564752746082377
] |
{
"id": 0,
"code_window": [
"const convertedMass = convert(25).from('mcg').to('t');\n",
"const convertedMassBack = convert(convertedMass).from('t').to('mcg');\n",
"\n",
"const unit = convert(66).getUnit<'mcg'>('mcg');\n"
],
"labels": [
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"// Using `convert` without a value.\n",
"const measures = convert().measures();\n",
"const allUnits = convert().possibilities();\n",
"const massUnits = convert().possibilities('mass');\n",
"const distanceUnits = convert().from('m').possibilities();\n",
"const kgDescription = convert().describe('kg');\n",
"\n",
"const kgAbbr: string = kgDescription.abbr;\n",
"const kgMeasure: string = kgDescription.measure;\n",
"const kgSystem: string = kgDescription.system;\n",
"const kgSingular: string = kgDescription.singular;\n",
"const kgPlural: string = kgDescription.plural;"
],
"file_path": "types/convert-units/convert-units-tests.ts",
"type": "add",
"edit_start_line_idx": 6
} | // Type definitions for convert-units 2.3
// Project: https://github.com/ben-ng/convert-units#readme
// Definitions by: vladkampov <https://github.com/vladkampov>
// ben-ng <https://github.com/ben-ng>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.7
type uDistance = "mm" | "cm" | "m" | "km" | "in" | "ft-us" | "ft" | "mi"; // Distance
type uArea = "mm2" | "cm2" | "m2" | "ha" | "km2" | "in2" | "ft2" | "ac" | "mi2"; // Area
type uMass = "mcg" | "mg" | "g" | "kg" | "oz" | "lb" | "mt" | "t"; // Mass
type uVolume = "mm3" | "cm3" | "ml" | "l" | "kl" | "m3" | "km3" | "tsp" | "Tbs" | "in3" | "fl-oz" | "cup" | "pnt" | "qt" | "gal" | "ft3" | "yd3"; // Volume
type uVolumeFlowRate =
| "mm3/s"
| "cm3/s"
| "ml/s"
| "cl/s"
| "dl/s"
| "l/s"
| "l/min"
| "l/h"
| "kl/s"
| "kl/min"
| "kl/h"
| "m3/s"
| "m3/min"
| "m3/h"
| "km3/s"
| "tsp/s"
| "Tbs/s"
| "in3/s"
| "in3/min"
| "in3/h"
| "fl-oz/s"
| "fl-oz/min"
| "fl-oz/h"
| "cup/s"
| "pnt/s"
| "pnt/min"
| "pnt/h"
| "qt/s"
| "gal/s"
| "gal/min"
| "gal/h"
| "ft3/s"
| "ft3/min"
| "ft3/h"
| "yd3/s"
| "yd3/min"
| "yd3/h"; // Volume Flow Rate
type uTemperature = "C" | "F" | "K" | "R"; // Temperature
type uTime = "ns" | "mu" | "ms" | "s" | "min" | "h" | "d" | "week" | "month" | "year"; // Time
type uFrequency = "Hz" | "mHz" | "kHz" | "MHz" | "GHz" | "THz" | "rpm" | "deg/s" | "rad/s"; // Frequency
type uSpeed = "m/s" | "km/h" | "m/h" | "knot" | "ft/s"; // Speed
type uPace = "s/m" | "min/km" | "s/ft" | "min/km"; // Pace
type uPressure = "Pa" | "hPa" | "kPa" | "MPa" | "bar" | "torr" | "psi" | "ksi"; // Pressure
type uDitgital = "b" | "Kb" | "Mb" | "Gb" | "Tb" | "B" | "KB" | "MB" | "GB" | "TB"; // Digital
type uIlluminance = "lx" | "ft-cd"; // Illumunance
type uPartsPer = "ppm" | "ppb" | "ppt" | "ppq"; // Parts-Per
type uVoltage = "V" | "mV" | "kV"; // Voltage
type uCurrent = "A" | "mA" | "kA"; // Current
type uPower = "W" | "mW" | "kM" | "MW" | "GW";
type uApparentPower = "VA" | "mVA" | "kVA" | "MVA" | "GVA"; // Apparent Power
type uReactivePower = "VAR" | "mVAR" | "kVAR" | "MVAR" | "GVAR"; // Reactive Power
type uEnergy = "Wh" | "mWh" | "kWh" | "MWh" | "GWh" | "J" | "kJ"; // Energy
type uReactiveEnergy = "VARh" | "mVARh" | "kVARh" | "MVARh" | "GVARH"; // Reactive Energy
type uAngle = "deg" | "rad" | "grad" | "arcmin" | "arcsec"; // Angle
type unit = uDistance
| uArea
| uMass
| uVolume
| uVolumeFlowRate
| uTemperature
| uTime
| uFrequency
| uSpeed
| uPace
| uPressure
| uDitgital
| uIlluminance
| uPartsPer
| uVoltage
| uCurrent
| uPower
| uApparentPower
| uReactivePower
| uEnergy
| uReactiveEnergy
| uAngle;
type measure = "distance"
| "area"
| "mass"
| "volume"
| "volumeFlowRate"
| "temperature"
| "time"
| "frequency"
| "speed"
| "pace"
| "pressure"
| "ditgital"
| "illuminance"
| "partsPer"
| "voltage"
| "current"
| "power"
| "apparentPower"
| "reactivePower"
| "energy"
| "reactiveEnergy"
| "angle";
type system = "metric"
| "imperial"
| "bits"
| "bytes";
declare class Convert {
constructor(numerator: number, denominator: number);
from(from: unit): this;
to(to: unit): number;
toBest(options?: { exclude?: unit[], cutOffNumber?: number }): { val: number, unit: string, singular: string, plural: string };
getUnit<T extends unit>(abbr: T): { abbr: T, measure: measure, system: system, unit: { name: { singular: string, plural: string }, to_anchor: number } };
describe<T extends unit>(abbr: T): { abbr: T, measure: measure, system: system, singular: string, plural: string };
list(measure?: measure): unit[];
private throwUnsupportedUnitError(what: string): void;
possibilities(measure?: measure): unit[];
measures(): measure[];
}
declare function convert(value: number): Convert;
export = convert;
| types/convert-units/index.d.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/29ece6dcb30cd4f2b704eb221a124a20aa70a8af | [
0.009423501789569855,
0.0016398541629314423,
0.00016120236250571907,
0.0001769589725881815,
0.0031631330493837595
] |
{
"id": 0,
"code_window": [
"const convertedMass = convert(25).from('mcg').to('t');\n",
"const convertedMassBack = convert(convertedMass).from('t').to('mcg');\n",
"\n",
"const unit = convert(66).getUnit<'mcg'>('mcg');\n"
],
"labels": [
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"// Using `convert` without a value.\n",
"const measures = convert().measures();\n",
"const allUnits = convert().possibilities();\n",
"const massUnits = convert().possibilities('mass');\n",
"const distanceUnits = convert().from('m').possibilities();\n",
"const kgDescription = convert().describe('kg');\n",
"\n",
"const kgAbbr: string = kgDescription.abbr;\n",
"const kgMeasure: string = kgDescription.measure;\n",
"const kgSystem: string = kgDescription.system;\n",
"const kgSingular: string = kgDescription.singular;\n",
"const kgPlural: string = kgDescription.plural;"
],
"file_path": "types/convert-units/convert-units-tests.ts",
"type": "add",
"edit_start_line_idx": 6
} | {
"extends": "dtslint/dt.json"
}
| types/joi-password-complexity/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/29ece6dcb30cd4f2b704eb221a124a20aa70a8af | [
0.00017337674216832966,
0.00017337674216832966,
0.00017337674216832966,
0.00017337674216832966,
0
] |
{
"id": 0,
"code_window": [
"const convertedMass = convert(25).from('mcg').to('t');\n",
"const convertedMassBack = convert(convertedMass).from('t').to('mcg');\n",
"\n",
"const unit = convert(66).getUnit<'mcg'>('mcg');\n"
],
"labels": [
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"// Using `convert` without a value.\n",
"const measures = convert().measures();\n",
"const allUnits = convert().possibilities();\n",
"const massUnits = convert().possibilities('mass');\n",
"const distanceUnits = convert().from('m').possibilities();\n",
"const kgDescription = convert().describe('kg');\n",
"\n",
"const kgAbbr: string = kgDescription.abbr;\n",
"const kgMeasure: string = kgDescription.measure;\n",
"const kgSystem: string = kgDescription.system;\n",
"const kgSingular: string = kgDescription.singular;\n",
"const kgPlural: string = kgDescription.plural;"
],
"file_path": "types/convert-units/convert-units-tests.ts",
"type": "add",
"edit_start_line_idx": 6
} | {
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"verror-tests.ts"
]
} | types/verror/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/29ece6dcb30cd4f2b704eb221a124a20aa70a8af | [
0.00017415996990166605,
0.00017258063599001616,
0.0001705363392829895,
0.00017304561333730817,
0.0000015154370203163126
] |
{
"id": 0,
"code_window": [
"const convertedMass = convert(25).from('mcg').to('t');\n",
"const convertedMassBack = convert(convertedMass).from('t').to('mcg');\n",
"\n",
"const unit = convert(66).getUnit<'mcg'>('mcg');\n"
],
"labels": [
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"// Using `convert` without a value.\n",
"const measures = convert().measures();\n",
"const allUnits = convert().possibilities();\n",
"const massUnits = convert().possibilities('mass');\n",
"const distanceUnits = convert().from('m').possibilities();\n",
"const kgDescription = convert().describe('kg');\n",
"\n",
"const kgAbbr: string = kgDescription.abbr;\n",
"const kgMeasure: string = kgDescription.measure;\n",
"const kgSystem: string = kgDescription.system;\n",
"const kgSingular: string = kgDescription.singular;\n",
"const kgPlural: string = kgDescription.plural;"
],
"file_path": "types/convert-units/convert-units-tests.ts",
"type": "add",
"edit_start_line_idx": 6
} | // Type definitions for sanctuary 0.14
// Project: https://github.com/sanctuary-js/sanctuary#readme
// Definitions by: David Chambers <https://github.com/davidchambers>
// Juan J. Jimenez-Anca <https://github.com/cortopy>
// Ken Aguilar <https://github.com/piq9117>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare var S: Sanctuary.Environment;
export = S;
export as namespace S;
type Nullable<A> = A | null;
type Pair<A, B> = [A, B];
type Thunk<A> = () => A;
type Fn<A, B> = (a: A) => B;
type Fn2<A, B, C> = (a: A) => (b: B) => C;
type Fn3<A, B, C, D> = (a: A) => (b: B) => (c: C) => D;
type Fn4<A, B, C, D, E> = (a: A) => (b: B) => (c: C) => (d: D) => E;
type Fn5<A, B, C, D, E, F> = (a: A) => (b: B) => (c: C) => (d: D) => (e: E) => F;
type Fn2_<A, B, C> = (a: A, b: B) => C;
type Fn3_<A, B, C, D> = (a: A, b: B, c: C) => D;
type Fn4_<A, B, C, D, E> = (a: A, b: B, c: C, d: D) => E;
type Fn5_<A, B, C, D, E, F> = (a: A, b: B, c: C, d: D, e: E) => F;
type Predicate<A> = (a: A) => boolean;
interface StrMap<A> { [k: string]: A; }
interface Maybe<A> {
constructor: {
'@@type': 'sanctuary/Maybe';
};
}
interface Either<A, B> {
constructor: {
'@@type': 'sanctuary/Either';
};
}
type ValidNumber = number;
type FiniteNumber = number;
type NonZeroFiniteNumber = number;
type Integer = number;
type NonNegativeInteger = number;
interface TypeRep {}
interface Setoid<A> {}
interface Ord<A> extends Setoid<A> {}
interface Semigroupoid<A, B> {}
interface Category<A> extends Semigroupoid<A, A> {}
interface Semigroup<A> {}
interface Monoid<A> extends Semigroup<A> {}
interface Functor<A> {}
interface Bifunctor<A, C> extends Functor<C> {}
interface Profunctor<B, C> extends Functor<C> {}
interface Apply<A> extends Functor<A> {}
interface Applicative<A> extends Apply<A> {}
interface Chain<A> extends Apply<A> {}
interface ChainRec<A> extends Chain<A> {}
interface Monad<A> extends Applicative<A>, Chain<A> {}
interface Alt<A> extends Functor<A> {}
interface Plus<A> extends Alt<A> {}
interface Alternative<A> extends Applicative<A>, Plus<A> {}
interface Foldable<A> {}
interface Traversable<A> extends Functor<A>, Foldable<A> {}
interface Extend<A> extends Functor<A> {}
interface Comonad<A> extends Extend<A> {}
interface Contravariant<A> {}
interface ListToMaybeList {
(xs: string): Maybe<string>;
<A>(xs: ReadonlyArray<A>): Maybe<A[]>;
}
interface MatchObj {
match: string;
groups: ReadonlyArray<Maybe<string>>;
}
declare namespace Sanctuary {
interface Static {
Maybe: TypeRep;
Nothing: Maybe<any>;
Just<A>(x: A): Maybe<A>;
Either: TypeRep;
Left<A>(x: A): Either<A, any>;
Right<A>(x: A): Either<any, A>;
// Classify
type(x: any): {
namespace: Maybe<string>
name: string
version: NonNegativeInteger
};
is(typeRep: TypeRep): (x: any) => boolean;
// Showable
toString(x: any): string;
// Fantasy Land
equals<A>(x: Setoid<A>): (y: Setoid<A>) => boolean;
lt <A>(x: Ord<A>): (y: Ord<A>) => boolean;
lte<A>(x: Ord<A>): (y: Ord<A>) => boolean;
gt <A>(x: Ord<A>): (y: Ord<A>) => boolean;
gte<A>(x: Ord<A>): (y: Ord<A>) => boolean;
min<A>(x: Ord<A>): (y: Ord<A>) => A;
max<A>(x: Ord<A>): (y: Ord<A>) => A;
id<A>(p: TypeRep): Fn<A, A> | Category<any>;
concat<A>(x: Semigroup<A>): (y: Semigroup<A>) => Semigroup<A>;
concat<A>(x: ReadonlyArray<A>): (y: ReadonlyArray<A>) => A[];
concat<A>(x: StrMap<A>): (y: StrMap<A>) => StrMap<A>;
concat(x: string): (y: string) => string;
empty(p: TypeRep): Monoid<any>;
map<A, B>(p: Fn<A, B>): {
<C>(q: Fn<C, A>): Fn<C, B>;
(q: ReadonlyArray<A>): B[];
(q: StrMap<A>): StrMap<B>;
(q: Functor<A>): Functor<B>;
};
bimap<A, B>(p: Fn<A, B>): <C, D>(q: Fn<C, D>) => (r: Bifunctor<A, C>) => Bifunctor<B, D>;
promap<A, B>(p: Fn<A, B>): <C, D>(q: Fn<C, D>) => {
(r: Fn<B, C>): Fn<A, D>;
(r: Profunctor<B, C>): Profunctor<A, D>;
};
alt<A>(x: Alt<A>): (y: Alt<A>) => Alt<A>;
zero(p: TypeRep): Plus<any>;
reduce<A, B>(p: Fn2<B, A, B>): (q: B) => (r: ReadonlyArray<A> | StrMap<A> | Maybe<A> | Either<any, A> | Foldable<A>) => B;
traverse(typeRep: TypeRep): <A, B>(f: Fn<A, Applicative<B>>) => (traversable: Traversable<A>) => Applicative<Traversable<B>>;
sequence(typeRep: TypeRep): <A>(traversable: Traversable<Applicative<A>>) => Applicative<Traversable<A>>;
ap<A, B>(p: Apply<Fn<A, B>>): (q: Apply<A>) => Apply<B>;
lift2<A, B, C>(f: Fn2<A, B, C>): {
<X>(x: Fn<X, A>): (y: Fn<X, B>) => Fn<X, C>;
(x: Apply<A>): (y: Apply<B>) => Apply<C>;
};
lift3<A, B, C, D>(f: Fn3<A, B, C, D>): {
<X>(x: Fn<X, A>): (y: Fn<X, B>) => (z: Fn<X, C>) => Fn<X, D>;
(x: Apply<A>): (y: Apply<B>) => (z: Apply<C>) => Apply<D>;
};
apFirst <A>(x: Apply<A>): (y: Apply<any>) => Apply<A>;
apSecond(x: Apply<any>): <B>(y: Apply<B>) => Apply<B>;
of<A>(typeRep: TypeRep): (x: A) => Fn<any, A>;
of<A>(typeRep: TypeRep): (x: A) => Applicative<A>;
chain<A, B, X>(f: Fn2<A, X, B>): (chain_: Fn<X, A>) => Fn<X, B>;
chain<A, B>(f: Fn <A, Chain<B>>): (chain_: Chain<A>) => Chain<B>;
join<A, B>(chain_: Fn2<B, B, A>): Fn<B, A>;
join<A>(chain_: ReadonlyArray<ReadonlyArray<A>>): A[];
join<A>(chain_: Maybe<Maybe<A>>): Maybe<A>;
join<A>(chain_: Chain<Chain<A>>): Chain<A>;
chainRec(typeRep: TypeRep): {
<A, B, X>(f: Fn2<A, X, Either<A, B>>): (x: A) => Fn<X, B>;
<A, B> (f: Fn <A, ChainRec<Either<A, B>>>): (x: A) => ChainRec<B>;
};
extend<A, B>(f: Fn<Extend<A>, B>): (extend_: Extend<A>) => Extend<B>;
extract<A>(comonad: Comonad<A>): A;
contramap<A, B>(f: Fn<B, A>): {
<X>(contravariant: Fn<A, X>): Fn<B, X>;
(contravariant: Contravariant<A>): Contravariant<B>;
};
filter <A>(pred: Predicate<A>): {
(m: ReadonlyArray<A>): A[];
(m: Foldable<A>): Foldable<A>;
};
filterM<A>(pred: Predicate<A>): {
(m: ReadonlyArray<A>): A[];
(m: Foldable<A>): Foldable<A>;
};
takeWhile<A>(pred: Predicate<A>): (foldable: Foldable<A>) => Foldable<A>;
dropWhile<A>(pred: Predicate<A>): (foldable: Foldable<A>) => Foldable<A>;
// Combinator
I<A>(x: A): A;
K<A>(x: A): (y: any) => A;
T<A>(x: A): <B>(f: Fn<A, B>) => B;
// Function
curry2<A, B, C>(f: Fn2_<A, B, C>): Fn2<A, B, C>;
curry3<A, B, C, D>(f: Fn3_<A, B, C, D>): Fn3<A, B, C, D>;
curry4<A, B, C, D, E>(f: Fn4_<A, B, C, D, E>): Fn4<A, B, C, D, E>;
curry5<A, B, C, D, E, F>(f: Fn5_<A, B, C, D, E, F>): Fn5<A, B, C, D, E, F>;
flip<A, B, C>(f: Fn2<A, B, C>): Fn2<B, A, C>;
// Composition
compose<B, C>(f: Fn<B, C>): <A>(g: Fn<A, B>) => Fn<A, C>;
compose<B, C>(x: Semigroupoid<B, C>): <A>(y: Semigroupoid<A, B>) => Semigroupoid<A, C>;
pipe<A, B>(fs: [Fn<A, B>]): (x: A) => B;
pipe<A, B, C>(fs: [Fn<A, B>, Fn<B, C>]): (x: A) => C;
pipe<A, B, C, D>(fs: [Fn<A, B>, Fn<B, C>, Fn<C, D>]): (x: A) => D;
pipe<A, B, C, D, E>(fs: [Fn<A, B>, Fn<B, C>, Fn<C, D>, Fn<D, E>]): (x: A) => E;
pipe<A, B, C, D, E, F>(fs: [Fn<A, B>, Fn<B, C>, Fn<C, D>, Fn<D, E>, Fn<E, F>]): (x: A) => F;
pipe(fs: ReadonlyArray<Fn<any, any>>): (x: any) => any;
on<A, B, C>(p: Fn2<B, B, C>): (q: Fn<A, B>) => (r: A) => Fn<A, C>;
// TODO: Maybe
isNothing(p: Maybe<any>): boolean;
isJust(p: Maybe<any>): boolean;
fromMaybe<A>(p: A): (q: Maybe<A>) => A;
fromMaybe_<A>(p: Thunk<A>): (q: Maybe<A>) => A;
maybeToNullable<A>(p: Maybe<A>): Nullable<A>;
toMaybe<A>(p: A | null | undefined): Maybe<A>;
maybe<B>(p: B): <A>(q: Fn<A, B>) => (r: Maybe<A>) => B;
maybe_<B>(p: Thunk<B>): <A>(q: Fn<A, B>) => (r: Maybe<A>) => B;
justs<A>(p: ReadonlyArray<Maybe<A>>): A[];
mapMaybe<A>(p: Fn<A, Maybe<any>>): (q: A[]) => A[];
encase<A, B>(p: Fn<A, B>): Fn<A, Maybe<B>>;
encase2<A, B, C>(p: Fn2<A, B, C>): Fn2<A, B, Maybe<C>>;
encase3<A, B, C, D>(p: Fn3<A, B, C, D>): Fn3<A, B, C, Maybe<D>>;
maybeToEither<A>(p: A): <B>(q: Maybe<B>) => Either<A, B>;
// TODO: Either
isLeft(p: Either<any, any>): boolean;
isRight(p: Either<any, any>): boolean;
fromEither<B>(p: B): (q: Either<any, B>) => B;
toEither<A>(p: A): <B>(q: B | null | undefined) => Either<A, B>;
either<A, C>(p: Fn<A, C>): <B>(q: Fn<B, C>) => (r: Either<A, B>) => C;
lefts<A>(p: ReadonlyArray<Either<A, any>>): A[];
rights<B>(p: ReadonlyArray<Either<any, B>>): B[];
tagBy<A>(p: Predicate<A>): (q: A) => Either<A, A>;
encaseEither<L>(p: Fn<Error, L>): <A, R>(q: Fn<A, R>) => Fn<A, Either<L, R>>;
encaseEither2<L>(p: Fn<Error, L>): <A, B, R>(q: Fn2<A, B, R>) => Fn2<A, B, Either<L, R>>;
encaseEither3<L>(p: Fn<Error, L>): <A, B, C, R>(q: Fn3<A, B, C, R>) => Fn3<A, B, C, Either<L, R>>;
eitherToMaybe<B>(p: Either<any, B>): Maybe<B>;
// Logic
and(p: boolean): (q: boolean) => boolean;
or(p: boolean): (q: boolean) => boolean;
not(p: boolean): boolean;
complement<A>(p: Predicate<A>): Predicate<A>;
ifElse<A, B>(p: Predicate<A>): (q: Fn<A, B>) => (r: Fn<A, B>) => Fn<A, B>;
when<A>(p: Predicate<A>): (q: Fn<A, A>) => Fn<A, A>;
unless<A>(p: Predicate<A>): (q: Fn<A, A>) => Fn<A, A>;
allPass<A>(p: ReadonlyArray<Predicate<A>>): Predicate<A>;
anyPass<A>(p: ReadonlyArray<Predicate<A>>): Predicate<A>;
// List
slice(p: Integer): (q: Integer) => ListToMaybeList;
at(p: Integer): {
(q: string): Maybe<string>;
<A>(q: ReadonlyArray<A>): Maybe<A>;
};
head(xs: string): Maybe<string>;
head<A>(xs: ReadonlyArray<A>): Maybe<A>;
last(xs: string): Maybe<string>;
last<A>(xs: ReadonlyArray<A>): Maybe<A>;
tail(xs: string): Maybe<string>;
tail<A>(xs: ReadonlyArray<A>): Maybe<A[]>;
init(xs: string): Maybe<string>;
init<A>(xs: ReadonlyArray<A>): Maybe<A[]>;
take(n: Integer): ListToMaybeList;
takeLast(n: Integer): ListToMaybeList;
drop(n: Integer): ListToMaybeList;
dropLast(n: Integer): ListToMaybeList;
// Array
// TODO: Fantasyland overloads, non-curried versions
append<A>(x: A): {
(xs: ReadonlyArray<A>): A[];
(xs: Applicative<A>): Applicative<A>;
};
prepend<A>(x: A): {
(xs: ReadonlyArray<A>): A[];
(xs: Applicative<A>): Applicative<A>;
};
joinWith(p: string): (q: ReadonlyArray<string>) => string;
elem<A>(p: A): (q: Foldable<A> | StrMap<A> | ReadonlyArray<A>) => boolean;
find<A>(p: Predicate<A>): (q: ReadonlyArray<A> | StrMap<A> | Foldable<A>) => Maybe<A>;
pluck(key: string): (xs: Functor<any>) => Functor<any>;
unfoldr<A, B>(f: Fn<B, Maybe<Pair<A, B>>>): (x: B) => A[];
range(from: Integer): (to: Integer) => Integer[];
groupBy<A>(f: Fn2<A, A, boolean>): (xs: ReadonlyArray<A>) => A[][];
reverse<A>(foldable: ReadonlyArray<A>): A[];
reverse<A>(foldable: Foldable<A>): Foldable<A>;
sort<A>(foldable: ReadonlyArray<A>): A[];
sort<A>(foldable: Foldable<A>): Foldable<A>;
sortBy<A>(f: Fn<A, Ord<any>>): {
(foldable: ReadonlyArray<A>): A[];
(foldable: Foldable<A>): Foldable<A>;
};
// Object
prop(p: string): (q: any) => any;
props(p: ReadonlyArray<string>): (q: any) => any;
get(p: Predicate<any>): (q: string) => (r: any) => Maybe<any>;
gets(p: Predicate<any>): (q: ReadonlyArray<string>) => (r: any) => Maybe<any>;
// StrMap
keys(p: StrMap<any>): string[];
values<A>(p: StrMap<A>): A[];
pairs<A>(p: StrMap<A>): Array<Pair<string, A>>;
// Number
negate(n: ValidNumber): ValidNumber;
add(p: FiniteNumber): (q: FiniteNumber) => FiniteNumber;
sum(p: Foldable<FiniteNumber> | ReadonlyArray<FiniteNumber>): FiniteNumber;
sub(p: FiniteNumber): (q: FiniteNumber) => FiniteNumber;
mult(x: FiniteNumber): (q: FiniteNumber) => FiniteNumber;
product(p: Foldable<FiniteNumber> | ReadonlyArray<FiniteNumber>): FiniteNumber;
div(p: NonZeroFiniteNumber): (q: FiniteNumber) => FiniteNumber;
pow(p: FiniteNumber): (q: FiniteNumber) => FiniteNumber;
mean(p: Foldable<FiniteNumber> | ReadonlyArray<FiniteNumber>): Maybe<FiniteNumber>;
// Integer
even(n: Integer): boolean;
odd(n: Integer): boolean;
// Parse
parseDate(s: string): Maybe<Date>;
parseFloat(s: string): Maybe<number>;
parseInt(p: Integer): (q: string) => Maybe<Integer>;
parseJson(p: Predicate<any>): (q: string) => Maybe<any>;
// RegExp
regex(p: string): (q: string) => RegExp;
regexEscape(s: string): string;
test(pattern: RegExp): Predicate<string>;
match(pattern: RegExp): (q: string) => Array<Maybe<MatchObj>>;
matchAll(pattern: RegExp): (q: string) => MatchObj[];
// String
toUpper(s: string): string;
toLower(s: string): string;
trim(s: string): string;
stripPrefix(prefix: string): (q: string) => Maybe<string>;
stripSuffix(suffix: string): (q: string) => Maybe<string>;
words(s: string): string[];
unwords(xs: ReadonlyArray<string>): string;
lines(s: string): string[];
unlines(xs: ReadonlyArray<string>): string;
splitOn(separator: string): (q: string) => string[];
splitOnRegex(pattern: RegExp): (q: string) => string[];
}
interface Environment extends Static {
env: ReadonlyArray<any>;
create(opts: {checkTypes: boolean, env: ReadonlyArray<any>}): Static;
}
}
| types/sanctuary/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/29ece6dcb30cd4f2b704eb221a124a20aa70a8af | [
0.00017837484483607113,
0.00017316291632596403,
0.00016299170965794474,
0.0001741518353810534,
0.000003671210833999794
] |
{
"id": 1,
"code_window": [
"// Type definitions for convert-units 2.3\n",
"// Project: https://github.com/ben-ng/convert-units#readme\n",
"// Definitions by: vladkampov <https://github.com/vladkampov>\n",
"// ben-ng <https://github.com/ben-ng>\n",
"// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n",
"// TypeScript Version: 2.7\n",
"\n",
"type uDistance = \"mm\" | \"cm\" | \"m\" | \"km\" | \"in\" | \"ft-us\" | \"ft\" | \"mi\"; // Distance\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// Toby Bell <https://github.com/tobybell>\n"
],
"file_path": "types/convert-units/index.d.ts",
"type": "add",
"edit_start_line_idx": 4
} | import convert = require('convert-units');
const convertedMass = convert(25).from('mcg').to('t');
const convertedMassBack = convert(convertedMass).from('t').to('mcg');
const unit = convert(66).getUnit<'mcg'>('mcg');
| types/convert-units/convert-units-tests.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/29ece6dcb30cd4f2b704eb221a124a20aa70a8af | [
0.00019036739831790328,
0.00019036739831790328,
0.00019036739831790328,
0.00019036739831790328,
0
] |
{
"id": 1,
"code_window": [
"// Type definitions for convert-units 2.3\n",
"// Project: https://github.com/ben-ng/convert-units#readme\n",
"// Definitions by: vladkampov <https://github.com/vladkampov>\n",
"// ben-ng <https://github.com/ben-ng>\n",
"// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n",
"// TypeScript Version: 2.7\n",
"\n",
"type uDistance = \"mm\" | \"cm\" | \"m\" | \"km\" | \"in\" | \"ft-us\" | \"ft\" | \"mi\"; // Distance\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// Toby Bell <https://github.com/tobybell>\n"
],
"file_path": "types/convert-units/index.d.ts",
"type": "add",
"edit_start_line_idx": 4
} | // Type definitions for is-typedarray 1.0
// Project: https://github.com/hughsk/is-typedarray
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
/// <reference types="node" />
export = isTypedArray;
declare function isTypedArray(candidate: any): candidate is isTypedArray.TypedArray;
declare namespace isTypedArray {
function strict(candidate: any): candidate is TypedArray;
function loose(candidate: any): candidate is TypedArray;
type TypedArray =
| Int8Array
| Int16Array
| Int32Array
| Uint8Array
| Uint8ClampedArray
| Uint16Array
| Uint32Array
| Float32Array
| Float64Array
| Buffer;
}
| types/is-typedarray/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/29ece6dcb30cd4f2b704eb221a124a20aa70a8af | [
0.00020790408598259091,
0.00018136650032829493,
0.0001635535736568272,
0.00017264182679355145,
0.00001912819607241545
] |
{
"id": 1,
"code_window": [
"// Type definitions for convert-units 2.3\n",
"// Project: https://github.com/ben-ng/convert-units#readme\n",
"// Definitions by: vladkampov <https://github.com/vladkampov>\n",
"// ben-ng <https://github.com/ben-ng>\n",
"// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n",
"// TypeScript Version: 2.7\n",
"\n",
"type uDistance = \"mm\" | \"cm\" | \"m\" | \"km\" | \"in\" | \"ft-us\" | \"ft\" | \"mi\"; // Distance\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// Toby Bell <https://github.com/tobybell>\n"
],
"file_path": "types/convert-units/index.d.ts",
"type": "add",
"edit_start_line_idx": 4
} | declare class BusyContext {
addBusyState(options: {
description: {
toString: () => string;
[propName: string]: any;
} | (() => string) | string;
}): (() => void);
applicationBootstrapComplete(): undefined;
clear(): undefined;
dump(message?: string): undefined;
getBusyStates(): Array<{
id: string;
description: string;
}>;
isReady(): boolean;
toString(): string;
whenReady(timeout?: number): Promise<(boolean | Error)>;
}
declare namespace Context {
interface BusyContext {
addBusyState(options: {
description: {
toString: () => string;
[propName: string]: any;
} | (() => string) | string;
}): (() => void);
applicationBootstrapComplete(): undefined;
clear(): undefined;
dump(message?: string): undefined;
getBusyStates(): Array<{
id: string;
description: string;
}>;
isReady(): boolean;
toString(): string;
whenReady(timeout?: number): Promise<(boolean | Error)>;
}
}
declare class Context {
static getContext(node: Element): Context;
static getPageContext(): Context;
static setBusyContextDefaultTimeout(timeout: number): any;
getBusyContext(): BusyContext;
}
export = Context;
| types/oracle__oraclejet/ojcontext/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/29ece6dcb30cd4f2b704eb221a124a20aa70a8af | [
0.00017255361308343709,
0.00016822200268507004,
0.00016259649419225752,
0.00016863198834471405,
0.000003193205202478566
] |
{
"id": 1,
"code_window": [
"// Type definitions for convert-units 2.3\n",
"// Project: https://github.com/ben-ng/convert-units#readme\n",
"// Definitions by: vladkampov <https://github.com/vladkampov>\n",
"// ben-ng <https://github.com/ben-ng>\n",
"// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n",
"// TypeScript Version: 2.7\n",
"\n",
"type uDistance = \"mm\" | \"cm\" | \"m\" | \"km\" | \"in\" | \"ft-us\" | \"ft\" | \"mi\"; // Distance\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// Toby Bell <https://github.com/tobybell>\n"
],
"file_path": "types/convert-units/index.d.ts",
"type": "add",
"edit_start_line_idx": 4
} | { "extends": "dtslint/dt.json" }
| types/typpy/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/29ece6dcb30cd4f2b704eb221a124a20aa70a8af | [
0.00017094952636398375,
0.00017094952636398375,
0.00017094952636398375,
0.00017094952636398375,
0
] |
{
"id": 2,
"code_window": [
" measures(): measure[];\n",
"}\n",
"\n",
"declare function convert(value: number): Convert;\n",
"\n",
"export = convert;"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"declare function convert(value?: number): Convert;\n"
],
"file_path": "types/convert-units/index.d.ts",
"type": "replace",
"edit_start_line_idx": 131
} | // Type definitions for convert-units 2.3
// Project: https://github.com/ben-ng/convert-units#readme
// Definitions by: vladkampov <https://github.com/vladkampov>
// ben-ng <https://github.com/ben-ng>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.7
type uDistance = "mm" | "cm" | "m" | "km" | "in" | "ft-us" | "ft" | "mi"; // Distance
type uArea = "mm2" | "cm2" | "m2" | "ha" | "km2" | "in2" | "ft2" | "ac" | "mi2"; // Area
type uMass = "mcg" | "mg" | "g" | "kg" | "oz" | "lb" | "mt" | "t"; // Mass
type uVolume = "mm3" | "cm3" | "ml" | "l" | "kl" | "m3" | "km3" | "tsp" | "Tbs" | "in3" | "fl-oz" | "cup" | "pnt" | "qt" | "gal" | "ft3" | "yd3"; // Volume
type uVolumeFlowRate =
| "mm3/s"
| "cm3/s"
| "ml/s"
| "cl/s"
| "dl/s"
| "l/s"
| "l/min"
| "l/h"
| "kl/s"
| "kl/min"
| "kl/h"
| "m3/s"
| "m3/min"
| "m3/h"
| "km3/s"
| "tsp/s"
| "Tbs/s"
| "in3/s"
| "in3/min"
| "in3/h"
| "fl-oz/s"
| "fl-oz/min"
| "fl-oz/h"
| "cup/s"
| "pnt/s"
| "pnt/min"
| "pnt/h"
| "qt/s"
| "gal/s"
| "gal/min"
| "gal/h"
| "ft3/s"
| "ft3/min"
| "ft3/h"
| "yd3/s"
| "yd3/min"
| "yd3/h"; // Volume Flow Rate
type uTemperature = "C" | "F" | "K" | "R"; // Temperature
type uTime = "ns" | "mu" | "ms" | "s" | "min" | "h" | "d" | "week" | "month" | "year"; // Time
type uFrequency = "Hz" | "mHz" | "kHz" | "MHz" | "GHz" | "THz" | "rpm" | "deg/s" | "rad/s"; // Frequency
type uSpeed = "m/s" | "km/h" | "m/h" | "knot" | "ft/s"; // Speed
type uPace = "s/m" | "min/km" | "s/ft" | "min/km"; // Pace
type uPressure = "Pa" | "hPa" | "kPa" | "MPa" | "bar" | "torr" | "psi" | "ksi"; // Pressure
type uDitgital = "b" | "Kb" | "Mb" | "Gb" | "Tb" | "B" | "KB" | "MB" | "GB" | "TB"; // Digital
type uIlluminance = "lx" | "ft-cd"; // Illumunance
type uPartsPer = "ppm" | "ppb" | "ppt" | "ppq"; // Parts-Per
type uVoltage = "V" | "mV" | "kV"; // Voltage
type uCurrent = "A" | "mA" | "kA"; // Current
type uPower = "W" | "mW" | "kM" | "MW" | "GW";
type uApparentPower = "VA" | "mVA" | "kVA" | "MVA" | "GVA"; // Apparent Power
type uReactivePower = "VAR" | "mVAR" | "kVAR" | "MVAR" | "GVAR"; // Reactive Power
type uEnergy = "Wh" | "mWh" | "kWh" | "MWh" | "GWh" | "J" | "kJ"; // Energy
type uReactiveEnergy = "VARh" | "mVARh" | "kVARh" | "MVARh" | "GVARH"; // Reactive Energy
type uAngle = "deg" | "rad" | "grad" | "arcmin" | "arcsec"; // Angle
type unit = uDistance
| uArea
| uMass
| uVolume
| uVolumeFlowRate
| uTemperature
| uTime
| uFrequency
| uSpeed
| uPace
| uPressure
| uDitgital
| uIlluminance
| uPartsPer
| uVoltage
| uCurrent
| uPower
| uApparentPower
| uReactivePower
| uEnergy
| uReactiveEnergy
| uAngle;
type measure = "distance"
| "area"
| "mass"
| "volume"
| "volumeFlowRate"
| "temperature"
| "time"
| "frequency"
| "speed"
| "pace"
| "pressure"
| "ditgital"
| "illuminance"
| "partsPer"
| "voltage"
| "current"
| "power"
| "apparentPower"
| "reactivePower"
| "energy"
| "reactiveEnergy"
| "angle";
type system = "metric"
| "imperial"
| "bits"
| "bytes";
declare class Convert {
constructor(numerator: number, denominator: number);
from(from: unit): this;
to(to: unit): number;
toBest(options?: { exclude?: unit[], cutOffNumber?: number }): { val: number, unit: string, singular: string, plural: string };
getUnit<T extends unit>(abbr: T): { abbr: T, measure: measure, system: system, unit: { name: { singular: string, plural: string }, to_anchor: number } };
describe<T extends unit>(abbr: T): { abbr: T, measure: measure, system: system, singular: string, plural: string };
list(measure?: measure): unit[];
private throwUnsupportedUnitError(what: string): void;
possibilities(measure?: measure): unit[];
measures(): measure[];
}
declare function convert(value: number): Convert;
export = convert;
| types/convert-units/index.d.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/29ece6dcb30cd4f2b704eb221a124a20aa70a8af | [
0.9969977140426636,
0.07185690850019455,
0.00016473604773636907,
0.00017119105905294418,
0.2565895915031433
] |
{
"id": 2,
"code_window": [
" measures(): measure[];\n",
"}\n",
"\n",
"declare function convert(value: number): Convert;\n",
"\n",
"export = convert;"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"declare function convert(value?: number): Convert;\n"
],
"file_path": "types/convert-units/index.d.ts",
"type": "replace",
"edit_start_line_idx": 131
} | // Type definitions for leaflet-geosearch 2.7
// Project: https://github.com/smeijer/leaflet-geosearch#readme
// Definitions by: Dmytro Borysovskyi <https://github.com/dimabory>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
import { MarkerOptions, Control } from 'leaflet';
type BoundsTuple = [[number, number], [number, number]];
type PointTuple = [number, number];
interface LatLngLiteral {
lat: number;
lng: number;
}
interface SearchResult<Raw> {
x: string;
y: string;
label: string;
bounds: BoundsTuple;
raw: Raw;
}
interface SearchQuery {
query: string;
}
export class BaseProvider<ProviderOptions = {}, Raw = {}> {
constructor(options?: ProviderOptions);
search(options: SearchQuery): Promise<Array<SearchResult<Raw>>>;
}
/**
* OpenStreetMap
*/
interface OpenStreetMapProviderResultRaw {
boundingbox: [string, string, string, string];
class: string;
display_name: string;
icon: string;
importance: number;
lat: string;
licence: string;
lon: string;
osm_id: number;
osm_type: string;
place_id: number;
type: string;
}
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
type OpenStreetMapProviderReverseResult = Omit<SearchResult<OpenStreetMapProviderResultRaw>, 'raw'> & {
raw: {
address: {
house_number: string;
road: string;
town: string;
city: string;
county: string;
state_district: string;
state: string;
postcode: string;
country: string;
country_code: string;
};
};
};
interface OpenStreetMapProviderOptionsOutputFormat {
json_callback?: string;
}
interface OpenStreetMapProviderOptionsOutputDetails {
addressdetails?: 0 | 1;
extratags?: 0 | 1;
namedetails?: 0 | 1;
}
interface OpenStreetMapProviderOptionsResultLanguage {
'accept-language'?: string;
}
interface OpenStreetMapProviderOptionsResultLimitation {
countrycodes?: string;
exclude_place_ids?: string;
limit?: number;
viewbox?: string;
bounded?: 0 | 1;
zoom?: number;
}
interface OpenStreetMapProviderOptionsPolygonOutput {
polygon_geojson?: number;
polygon_kml?: number;
polygon_svg?: number;
polygon_text?: number;
polygon_threshold?: string;
}
interface OpenStreetMapProviderOptionsOther {
email?: string;
dedupe?: 0 | 1;
debug?: 0 | 1;
}
type OpenStreetMapProviderOptions = OpenStreetMapProviderOptionsOutputFormat &
OpenStreetMapProviderOptionsOutputDetails &
OpenStreetMapProviderOptionsResultLanguage &
OpenStreetMapProviderOptionsResultLimitation &
OpenStreetMapProviderOptionsPolygonOutput &
OpenStreetMapProviderOptionsOther;
interface OpenStreetMapProviderReverseSearch {
data: { raw: { osm_id?: number; osm_type?: 'node' | 'way' | 'relation' } };
}
export class OpenStreetMapProvider extends BaseProvider<
OpenStreetMapProviderOptions,
OpenStreetMapProviderResultRaw | OpenStreetMapProviderReverseResult
> {
/** https://nominatim.org/release-docs/develop/api/Search/ */
search(options: SearchQuery): Promise<Array<SearchResult<OpenStreetMapProviderResultRaw>>>;
/** https://nominatim.org/release-docs/develop/api/Reverse/ */
search(options: OpenStreetMapProviderReverseSearch): Promise<OpenStreetMapProviderReverseResult[]>;
}
/**
* Bing Maps
*/
interface BingProviderCultureOptions {
culture?: string;
c?: string;
}
interface BingProviderUserContextOptions {
userMapView?: string;
umv?: string;
userLocation?: string;
ul?: string;
userIp?: string;
userRegion?: string;
ur?: string;
}
export type BingProviderOptions = {
key: string;
adminDistrict?: string;
includeNeighborhood?: -1 | 0 | 1;
inclnb?: -1 | 0 | 1;
include?: string;
incl?: string;
maxResults?: number;
} & BingProviderCultureOptions &
BingProviderUserContextOptions;
export interface BingProviderResultPoint {
type: string;
coordinates: PointTuple;
}
export interface BingProviderResultRaw {
__type: string;
bbox: [number, number, number, number];
name: string;
point: BingProviderResultPoint;
address: {
adminDistrict: string;
adminDistrict2: string;
countryRegion: string;
formattedAddress: string;
locality: string;
neighborhood: string;
landmark: string;
};
confidence: string;
entityType: string;
geocodePoints: Array<BingProviderResultPoint & { calculationMethod: string; usageTypes: string[] }>;
matchCodes: string[];
}
/** https://docs.microsoft.com/en-us/bingmaps/rest-services/locations/find-a-location-by-query */
export class BingProvider<Options = BingProviderOptions> extends BaseProvider<Options, BingProviderResultRaw> {
constructor(options: Options);
}
/** ArcGIS Online Geocoding Service */
export class EsriProvider extends BaseProvider<BingProviderOptions> {}
/**
* Google Maps Service
*/
export interface GoogleProviderOptions {
key: string;
language?: string;
bounds?: string;
region?: string;
}
interface GoogleProviderResultAddressComponent {
long_name: string;
short_name: string;
types: string[];
}
export interface GoogleProviderResultRaw {
address_components: GoogleProviderResultAddressComponent[];
formatted_address: string;
geometry: {
location: LatLngLiteral;
location_type: string;
viewport: {
northeast: LatLngLiteral;
southwest: LatLngLiteral;
};
};
place_id: string;
types: string[];
}
/** https://developers.google.com/maps/documentation/geocoding/intro#geocoding */
export class GoogleProvider<Options = GoogleProviderOptions> extends BaseProvider<Options, GoogleProviderResultRaw> {
constructor(options: Options);
}
/**
* GeoSearchControl
*/
interface GeoSearchControlOptions {
provider: BaseProvider;
/** @default 'topleft' */
position?: string;
/** @default 'button' */
style?: 'button' | 'bar';
/** @default true */
showMarker?: boolean;
/** @default false */
showPopup?: boolean;
/** @default ({ result }) => `${result.label}` */
popupFormat?({ query, result }: { query: string; result: SearchResult<object> }): string;
/**
* @default {
* icon: new L.Icon.Default(),
* draggable: false,
* }
*/
marker?: MarkerOptions;
/** @default false */
maxMarkers?: number;
/** @default false */
retainZoomLevel?: boolean;
/** @default true */
animateZoom?: boolean;
/** @default 'Enter address' */
searchLabel?: string;
/** @default 'Sorry; that address could not be found.' */
notFoundMessage?: string;
/** @default 3000 */
messageHideDelay?: number;
/** @default 18 */
zoomLevel?: number;
/**
* @default {
* container: 'leaflet-bar leaflet-control leaflet-control-geosearch';
* button: 'leaflet-bar-part leaflet-bar-part-single';
* resetButton: 'reset';
* msgbox: 'leaflet-bar message';
* form: '';
* input: '';
* }
*/
classNames?: {
container?: string;
button?: string;
resetButton?: string;
msgbox?: string;
form?: string;
input?: string;
};
/** @default true */
autoComplete?: boolean;
/** @default 250 */
autoCompleteDelay?: number;
/** @default false */
autoClose?: boolean;
/** @default false */
keepResult?: boolean;
}
export class GeoSearchControl extends Control {
constructor(options: GeoSearchControlOptions);
}
export {};
| types/leaflet-geosearch/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/29ece6dcb30cd4f2b704eb221a124a20aa70a8af | [
0.0003137396415695548,
0.00018743718101177365,
0.00016609294107183814,
0.00017155156820081174,
0.00003427776391617954
] |
{
"id": 2,
"code_window": [
" measures(): measure[];\n",
"}\n",
"\n",
"declare function convert(value: number): Convert;\n",
"\n",
"export = convert;"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"declare function convert(value?: number): Convert;\n"
],
"file_path": "types/convert-units/index.d.ts",
"type": "replace",
"edit_start_line_idx": 131
} | import feathers, { Application } from '@feathersjs/feathers';
import feathersPrimus from '@feathersjs/primus';
const app: Application = feathers().configure(feathersPrimus({}));
| types/feathersjs__primus/feathersjs__primus-tests.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/29ece6dcb30cd4f2b704eb221a124a20aa70a8af | [
0.00017157284310087562,
0.00017157284310087562,
0.00017157284310087562,
0.00017157284310087562,
0
] |
{
"id": 2,
"code_window": [
" measures(): measure[];\n",
"}\n",
"\n",
"declare function convert(value: number): Convert;\n",
"\n",
"export = convert;"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"declare function convert(value?: number): Convert;\n"
],
"file_path": "types/convert-units/index.d.ts",
"type": "replace",
"edit_start_line_idx": 131
} | // Type definitions for postcss-custom-properties 9.1
// Project: https://github.com/postcss/postcss-custom-properties#readme
// Definitions by: Piotr Bลaลผejewicz <https://github.com/peterblazejewicz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import { Plugin, Result, LazyResult } from 'postcss';
declare namespace postcssCustomProperties {
/**
* Sources where Custom Properties can be imported from or export to,
* which might be CSS, JS, and JSON files, functions, and directly passed objects
*/
type ImportSources =
| string
| (() => CustomPropertiesObject)
| CustomPropertiesObject
| (() => CustomPropertiesObject)
| Promise<CustomPropertiesObject>;
/**
* Sources where Custom Properties can be imported from or export to,
* which might be CSS, JS, and JSON files, functions, and directly passed objects
*/
type ExportSources =
| string
| CustomPropertiesObject
| ((customProperties: CustomPropertiesObject) => any)
| Promise<CustomPropertiesObject>;
interface CustomPropertiesObject {
customProperties?: {
[name: string]: string;
};
['custom-properties']?: {
[name: string]: string;
};
}
interface Options {
/**
* The preserve option determines whether Custom Properties
* and properties using custom properties should be preserved in their original form.
* By default, both of these are preserved
* @see {@link https://github.com/postcss/postcss-custom-properties#preserve}
*/
preserve?: boolean;
/**
* The importFrom option specifies sources where Custom Properties can be imported from,
* which might be CSS, JS, and JSON files, functions, and directly passed objects.
* Multiple sources can be passed into this option, and they will be parsed in the order they are received.
* JavaScript files, JSON files, functions, and objects will need to namespace Custom Properties using the customProperties or custom-properties key.
* @see {@link https://github.com/postcss/postcss-custom-properties#importfrom}
*/
importFrom?: ImportSources | ImportSources[];
/**
* The exportTo option specifies destinations where Custom Properties can be exported to,
* which might be CSS, JS, and JSON files, functions, and directly passed objects.
* Multiple destinations can be passed into this option, and they will be parsed in the order they are received.
* JavaScript files, JSON files, and objects will need to namespace Custom Properties using the customProperties or custom-properties key.
* @see {@link https://github.com/postcss/postcss-custom-properties#exportto}
*/
exportTo?: ExportSources | ExportSources[];
}
type CustomPropertiesPlugin = Plugin<Options> & {
process: (
css:
| string
| {
toString(): string;
}
| Result,
opts?: any,
pluginOptions?: Options,
) => LazyResult;
};
}
declare const postcssCustomProperties: postcssCustomProperties.CustomPropertiesPlugin;
export = postcssCustomProperties;
| types/postcss-custom-properties/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/29ece6dcb30cd4f2b704eb221a124a20aa70a8af | [
0.0005400563823059201,
0.00021541470778174698,
0.0001645951997488737,
0.00017425381520297378,
0.00011509838077472523
] |
{
"id": 0,
"code_window": [
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n",
"// Applies to all tests in this file\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "docs/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | ---
id: setup-teardown
title: Setup and Teardown
---
Often while writing tests you have some setup work that needs to happen before tests run, and you have some finishing work that needs to happen after tests run. Jest provides helper functions to handle this.
## Repeating Setup
If you have some work you need to do repeatedly for many tests, you can use `beforeEach` and `afterEach` hooks.
For example, let's say that several tests interact with a database of cities. You have a method `initializeCityDatabase()` that must be called before each of these tests, and a method `clearCityDatabase()` that must be called after each of these tests. You can do this with:
```js
beforeEach(() => {
initializeCityDatabase();
});
afterEach(() => {
clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
```
`beforeEach` and `afterEach` can handle asynchronous code in the same ways that [tests can handle asynchronous code](TestingAsyncCode.md) - they can either take a `done` parameter or return a promise. For example, if `initializeCityDatabase()` returned a promise that resolved when the database was initialized, we would want to return that promise:
```js
beforeEach(() => {
return initializeCityDatabase();
});
```
## One-Time Setup
In some cases, you only need to do setup once, at the beginning of a file. This can be especially bothersome when the setup is asynchronous, so you can't do it inline. Jest provides `beforeAll` and `afterAll` hooks to handle this situation.
For example, if both `initializeCityDatabase()` and `clearCityDatabase()` returned promises, and the city database could be reused between tests, we could change our test code to:
```js
beforeAll(() => {
return initializeCityDatabase();
});
afterAll(() => {
return clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
```
## Scoping
By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.
For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:
```js
// Applies to all tests in this file
beforeEach(() => {
return initializeCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
describe('matching cities to foods', () => {
// Applies only to tests in this describe block
beforeEach(() => {
return initializeFoodDatabase();
});
test('Vienna <3 veal', () => {
expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true);
});
test('San Juan <3 plantains', () => {
expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true);
});
});
```
Note that the top-level `beforeEach` is executed before the `beforeEach` inside the `describe` block. It may help to illustrate the order of execution of all hooks.
```js
beforeAll(() => console.log('1 - beforeAll'));
afterAll(() => console.log('1 - afterAll'));
beforeEach(() => console.log('1 - beforeEach'));
afterEach(() => console.log('1 - afterEach'));
test('', () => console.log('1 - test'));
describe('Scoped / Nested block', () => {
beforeAll(() => console.log('2 - beforeAll'));
afterAll(() => console.log('2 - afterAll'));
beforeEach(() => console.log('2 - beforeEach'));
afterEach(() => console.log('2 - afterEach'));
test('', () => console.log('2 - test'));
});
// 1 - beforeAll
// 1 - beforeEach
// 1 - test
// 1 - afterEach
// 2 - beforeAll
// 1 - beforeEach
// 2 - beforeEach
// 2 - test
// 2 - afterEach
// 1 - afterEach
// 2 - afterAll
// 1 - afterAll
```
## Order of Execution
Jest executes all describe handlers in a test file _before_ it executes any of the actual tests. This is another reason to do setup and teardown inside `before*` and `after*` handlers rather than inside the `describe` blocks. Once the `describe` blocks are complete, by default Jest runs all the tests serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on.
Consider the following illustrative test file and output:
```js
describe('describe outer', () => {
console.log('describe outer-a');
describe('describe inner 1', () => {
console.log('describe inner 1');
test('test 1', () => console.log('test 1'));
});
console.log('describe outer-b');
test('test 2', () => console.log('test 2'));
describe('describe inner 2', () => {
console.log('describe inner 2');
test('test 3', () => console.log('test 3'));
});
console.log('describe outer-c');
});
// describe outer-a
// describe inner 1
// describe outer-b
// describe inner 2
// describe outer-c
// test 1
// test 2
// test 3
```
Just like the `describe` and `test` blocks Jest calls the `before*` and `after*` hooks in the order of declaration. Note that the `after*` hooks of the enclosing scope are called first. For example, here is how you can set up and tear down resources which depend on each other:
```js
beforeEach(() => console.log('connection setup'));
beforeEach(() => console.log('database setup'));
afterEach(() => console.log('database teardown'));
afterEach(() => console.log('connection teardown'));
test('test 1', () => console.log('test 1'));
describe('extra', () => {
beforeEach(() => console.log('extra database setup'));
afterEach(() => console.log('extra database teardown'));
test('test 2', () => console.log('test 2'));
});
// connection setup
// database setup
// test 1
// database teardown
// connection teardown
// connection setup
// database setup
// extra database setup
// test 2
// extra database teardown
// database teardown
// connection teardown
```
:::note
If you are using `jasmine2` test runner, take into account that it calls the `after*` hooks in the reverse order of declaration. To have identical output, the above example should be altered like this:
```diff
beforeEach(() => console.log('connection setup'));
+ afterEach(() => console.log('connection teardown'));
beforeEach(() => console.log('database setup'));
+ afterEach(() => console.log('database teardown'));
- afterEach(() => console.log('database teardown'));
- afterEach(() => console.log('connection teardown'));
// ...
```
:::
## General Advice
If a test is failing, one of the first things to check should be whether the test is failing when it's the only test that runs. To run only one test with Jest, temporarily change that `test` command to a `test.only`:
```js
test.only('this will be the only test that runs', () => {
expect(true).toBe(false);
});
test('this test will not run', () => {
expect('A').toBe('A');
});
```
If you have a test that often fails when it's run as part of a larger suite, but doesn't fail when you run it alone, it's a good bet that something from a different test is interfering with this one. You can often fix this by clearing some shared state with `beforeEach`. If you're not sure whether some shared state is being modified, you can also try a `beforeEach` that logs data.
| website/versioned_docs/version-28.x/SetupAndTeardown.md | 1 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.9886638522148132,
0.04256672039628029,
0.00016381061868742108,
0.00024221223429776728,
0.19728511571884155
] |
{
"id": 0,
"code_window": [
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n",
"// Applies to all tests in this file\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "docs/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | {
"extension": "json"
}
| e2e/resolve/test2.json | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00017066841246560216,
0.00017066841246560216,
0.00017066841246560216,
0.00017066841246560216,
0
] |
{
"id": 0,
"code_window": [
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n",
"// Applies to all tests in this file\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "docs/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import * as React from 'react';
import {plugins} from '../';
import setPrettyPrint from './setPrettyPrint';
const {ReactElement} = plugins;
setPrettyPrint([ReactElement]);
describe('ReactElement Plugin', () => {
let forwardRefComponent: {
(_props: unknown, _ref: unknown): React.ReactElement | null;
displayName?: string;
};
let forwardRefExample: ReturnType<typeof React.forwardRef>;
beforeEach(() => {
forwardRefComponent = (_props, _ref) => null;
forwardRefExample = React.forwardRef(forwardRefComponent);
forwardRefExample.displayName = undefined;
});
test('serializes forwardRef without displayName', () => {
forwardRefExample = React.forwardRef((_props, _ref) => null);
expect(React.createElement(forwardRefExample)).toPrettyPrintTo(
'<ForwardRef />',
);
});
test('serializes forwardRef with displayName', () => {
forwardRefExample.displayName = 'Display';
expect(React.createElement(forwardRefExample)).toPrettyPrintTo(
'<Display />',
);
});
test('serializes forwardRef component with displayName', () => {
forwardRefComponent.displayName = 'Display';
expect(React.createElement(forwardRefExample)).toPrettyPrintTo(
'<ForwardRef(Display) />',
);
});
});
| packages/pretty-format/src/__tests__/ReactElement.test.ts | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00017807848053053021,
0.0001716933911666274,
0.0001640278787817806,
0.00017152432701550424,
0.00000503631144965766
] |
{
"id": 0,
"code_window": [
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n",
"// Applies to all tests in this file\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "docs/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
test('basic test', () => {
expect(true).toBeTruthy();
});
| e2e/worker-restarting/__tests__/test1.js | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00017072456830646843,
0.00016927852993831038,
0.00016783250612206757,
0.00016927852993831038,
0.0000014460310922004282
] |
{
"id": 1,
"code_window": [
"});\n",
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n",
"// Applies to all tests in this file\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-25.x/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | ---
id: setup-teardown
title: Setup and Teardown
---
Often while writing tests you have some setup work that needs to happen before tests run, and you have some finishing work that needs to happen after tests run. Jest provides helper functions to handle this.
## Repeating Setup
If you have some work you need to do repeatedly for many tests, you can use `beforeEach` and `afterEach` hooks.
For example, let's say that several tests interact with a database of cities. You have a method `initializeCityDatabase()` that must be called before each of these tests, and a method `clearCityDatabase()` that must be called after each of these tests. You can do this with:
```js
beforeEach(() => {
initializeCityDatabase();
});
afterEach(() => {
clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
```
`beforeEach` and `afterEach` can handle asynchronous code in the same ways that [tests can handle asynchronous code](TestingAsyncCode.md) - they can either take a `done` parameter or return a promise. For example, if `initializeCityDatabase()` returned a promise that resolved when the database was initialized, we would want to return that promise:
```js
beforeEach(() => {
return initializeCityDatabase();
});
```
## One-Time Setup
In some cases, you only need to do setup once, at the beginning of a file. This can be especially bothersome when the setup is asynchronous, so you can't do it inline. Jest provides `beforeAll` and `afterAll` hooks to handle this situation.
For example, if both `initializeCityDatabase()` and `clearCityDatabase()` returned promises, and the city database could be reused between tests, we could change our test code to:
```js
beforeAll(() => {
return initializeCityDatabase();
});
afterAll(() => {
return clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
```
## Scoping
By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.
For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:
```js
// Applies to all tests in this file
beforeEach(() => {
return initializeCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
describe('matching cities to foods', () => {
// Applies only to tests in this describe block
beforeEach(() => {
return initializeFoodDatabase();
});
test('Vienna <3 veal', () => {
expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true);
});
test('San Juan <3 plantains', () => {
expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true);
});
});
```
Note that the top-level `beforeEach` is executed before the `beforeEach` inside the `describe` block. It may help to illustrate the order of execution of all hooks.
```js
beforeAll(() => console.log('1 - beforeAll'));
afterAll(() => console.log('1 - afterAll'));
beforeEach(() => console.log('1 - beforeEach'));
afterEach(() => console.log('1 - afterEach'));
test('', () => console.log('1 - test'));
describe('Scoped / Nested block', () => {
beforeAll(() => console.log('2 - beforeAll'));
afterAll(() => console.log('2 - afterAll'));
beforeEach(() => console.log('2 - beforeEach'));
afterEach(() => console.log('2 - afterEach'));
test('', () => console.log('2 - test'));
});
// 1 - beforeAll
// 1 - beforeEach
// 1 - test
// 1 - afterEach
// 2 - beforeAll
// 1 - beforeEach
// 2 - beforeEach
// 2 - test
// 2 - afterEach
// 1 - afterEach
// 2 - afterAll
// 1 - afterAll
```
## Order of Execution
Jest executes all describe handlers in a test file _before_ it executes any of the actual tests. This is another reason to do setup and teardown inside `before*` and `after*` handlers rather than inside the `describe` blocks. Once the `describe` blocks are complete, by default Jest runs all the tests serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on.
Consider the following illustrative test file and output:
```js
describe('describe outer', () => {
console.log('describe outer-a');
describe('describe inner 1', () => {
console.log('describe inner 1');
test('test 1', () => console.log('test 1'));
});
console.log('describe outer-b');
test('test 2', () => console.log('test 2'));
describe('describe inner 2', () => {
console.log('describe inner 2');
test('test 3', () => console.log('test 3'));
});
console.log('describe outer-c');
});
// describe outer-a
// describe inner 1
// describe outer-b
// describe inner 2
// describe outer-c
// test 1
// test 2
// test 3
```
Just like the `describe` and `test` blocks Jest calls the `before*` and `after*` hooks in the order of declaration. Note that the `after*` hooks of the enclosing scope are called first. For example, here is how you can set up and tear down resources which depend on each other:
```js
beforeEach(() => console.log('connection setup'));
beforeEach(() => console.log('database setup'));
afterEach(() => console.log('database teardown'));
afterEach(() => console.log('connection teardown'));
test('test 1', () => console.log('test 1'));
describe('extra', () => {
beforeEach(() => console.log('extra database setup'));
afterEach(() => console.log('extra database teardown'));
test('test 2', () => console.log('test 2'));
});
// connection setup
// database setup
// test 1
// database teardown
// connection teardown
// connection setup
// database setup
// extra database setup
// test 2
// extra database teardown
// database teardown
// connection teardown
```
:::note
If you are using `jasmine2` test runner, take into account that it calls the `after*` hooks in the reverse order of declaration. To have identical output, the above example should be altered like this:
```diff
beforeEach(() => console.log('connection setup'));
+ afterEach(() => console.log('connection teardown'));
beforeEach(() => console.log('database setup'));
+ afterEach(() => console.log('database teardown'));
- afterEach(() => console.log('database teardown'));
- afterEach(() => console.log('connection teardown'));
// ...
```
:::
## General Advice
If a test is failing, one of the first things to check should be whether the test is failing when it's the only test that runs. To run only one test with Jest, temporarily change that `test` command to a `test.only`:
```js
test.only('this will be the only test that runs', () => {
expect(true).toBe(false);
});
test('this test will not run', () => {
expect('A').toBe('A');
});
```
If you have a test that often fails when it's run as part of a larger suite, but doesn't fail when you run it alone, it's a good bet that something from a different test is interfering with this one. You can often fix this by clearing some shared state with `beforeEach`. If you're not sure whether some shared state is being modified, you can also try a `beforeEach` that logs data.
| website/versioned_docs/version-27.x/SetupAndTeardown.md | 1 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.9907298684120178,
0.042288970202207565,
0.00016081961803138256,
0.00019656072254292667,
0.19776910543441772
] |
{
"id": 1,
"code_window": [
"});\n",
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n",
"// Applies to all tests in this file\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-25.x/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | ---
id: dynamodb
title: Using with DynamoDB
---
With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can work smoothly with [DynamoDB](https://aws.amazon.com/dynamodb/).
## Use jest-dynamodb Preset
[Jest DynamoDB](https://github.com/shelfio/jest-dynamodb) provides all required configuration to run your tests using DynamoDB.
1. First, install `@shelf/jest-dynamodb`
```bash npm2yarn
npm install --save-dev @shelf/jest-dynamodb
```
2. Specify preset in your Jest configuration:
```json
{
"preset": "@shelf/jest-dynamodb"
}
```
3. Create `jest-dynamodb-config.js` and define DynamoDB tables
See [Create Table API](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#createTable-property)
```js
module.exports = {
tables: [
{
TableName: `files`,
KeySchema: [{AttributeName: 'id', KeyType: 'HASH'}],
AttributeDefinitions: [{AttributeName: 'id', AttributeType: 'S'}],
ProvisionedThroughput: {ReadCapacityUnits: 1, WriteCapacityUnits: 1},
},
// etc
],
};
```
4. Configure DynamoDB client
```js
const {DocumentClient} = require('aws-sdk/clients/dynamodb');
const isTest = process.env.JEST_WORKER_ID;
const config = {
convertEmptyValues: true,
...(isTest && {
endpoint: 'localhost:8000',
sslEnabled: false,
region: 'local-env',
}),
};
const ddb = new DocumentClient(config);
```
5. Write tests
```js
it('should insert item into table', async () => {
await ddb
.put({TableName: 'files', Item: {id: '1', hello: 'world'}})
.promise();
const {Item} = await ddb.get({TableName: 'files', Key: {id: '1'}}).promise();
expect(Item).toEqual({
id: '1',
hello: 'world',
});
});
```
There's no need to load any dependencies.
See [documentation](https://github.com/shelfio/jest-dynamodb) for details.
| website/versioned_docs/version-29.1/DynamoDB.md | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00017189118079841137,
0.0001670426718192175,
0.00016235931252595037,
0.00016674958169460297,
0.0000028949052648385987
] |
{
"id": 1,
"code_window": [
"});\n",
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n",
"// Applies to all tests in this file\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-25.x/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import type {CompareKeys, Config, Printer, Refs} from './types';
const getKeysOfEnumerableProperties = (
object: Record<string, unknown>,
compareKeys: CompareKeys,
) => {
const rawKeys = Object.keys(object);
const keys: Array<string | symbol> =
compareKeys !== null ? rawKeys.sort(compareKeys) : rawKeys;
if (Object.getOwnPropertySymbols) {
Object.getOwnPropertySymbols(object).forEach(symbol => {
if (Object.getOwnPropertyDescriptor(object, symbol)!.enumerable) {
keys.push(symbol);
}
});
}
return keys as Array<string>;
};
/**
* Return entries (for example, of a map)
* with spacing, indentation, and comma
* without surrounding punctuation (for example, braces)
*/
export function printIteratorEntries(
iterator: Iterator<[unknown, unknown]>,
config: Config,
indentation: string,
depth: number,
refs: Refs,
printer: Printer,
// Too bad, so sad that separator for ECMAScript Map has been ' => '
// What a distracting diff if you change a data structure to/from
// ECMAScript Object or Immutable.Map/OrderedMap which use the default.
separator = ': ',
): string {
let result = '';
let width = 0;
let current = iterator.next();
if (!current.done) {
result += config.spacingOuter;
const indentationNext = indentation + config.indent;
while (!current.done) {
result += indentationNext;
if (width++ === config.maxWidth) {
result += 'โฆ';
break;
}
const name = printer(
current.value[0],
config,
indentationNext,
depth,
refs,
);
const value = printer(
current.value[1],
config,
indentationNext,
depth,
refs,
);
result += name + separator + value;
current = iterator.next();
if (!current.done) {
result += `,${config.spacingInner}`;
} else if (!config.min) {
result += ',';
}
}
result += config.spacingOuter + indentation;
}
return result;
}
/**
* Return values (for example, of a set)
* with spacing, indentation, and comma
* without surrounding punctuation (braces or brackets)
*/
export function printIteratorValues(
iterator: Iterator<unknown>,
config: Config,
indentation: string,
depth: number,
refs: Refs,
printer: Printer,
): string {
let result = '';
let width = 0;
let current = iterator.next();
if (!current.done) {
result += config.spacingOuter;
const indentationNext = indentation + config.indent;
while (!current.done) {
result += indentationNext;
if (width++ === config.maxWidth) {
result += 'โฆ';
break;
}
result += printer(current.value, config, indentationNext, depth, refs);
current = iterator.next();
if (!current.done) {
result += `,${config.spacingInner}`;
} else if (!config.min) {
result += ',';
}
}
result += config.spacingOuter + indentation;
}
return result;
}
/**
* Return items (for example, of an array)
* with spacing, indentation, and comma
* without surrounding punctuation (for example, brackets)
**/
export function printListItems(
list: ArrayLike<unknown>,
config: Config,
indentation: string,
depth: number,
refs: Refs,
printer: Printer,
): string {
let result = '';
if (list.length) {
result += config.spacingOuter;
const indentationNext = indentation + config.indent;
for (let i = 0; i < list.length; i++) {
result += indentationNext;
if (i === config.maxWidth) {
result += 'โฆ';
break;
}
if (i in list) {
result += printer(list[i], config, indentationNext, depth, refs);
}
if (i < list.length - 1) {
result += `,${config.spacingInner}`;
} else if (!config.min) {
result += ',';
}
}
result += config.spacingOuter + indentation;
}
return result;
}
/**
* Return properties of an object
* with spacing, indentation, and comma
* without surrounding punctuation (for example, braces)
*/
export function printObjectProperties(
val: Record<string, unknown>,
config: Config,
indentation: string,
depth: number,
refs: Refs,
printer: Printer,
): string {
let result = '';
const keys = getKeysOfEnumerableProperties(val, config.compareKeys);
if (keys.length) {
result += config.spacingOuter;
const indentationNext = indentation + config.indent;
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const name = printer(key, config, indentationNext, depth, refs);
const value = printer(val[key], config, indentationNext, depth, refs);
result += `${indentationNext + name}: ${value}`;
if (i < keys.length - 1) {
result += `,${config.spacingInner}`;
} else if (!config.min) {
result += ',';
}
}
result += config.spacingOuter + indentation;
}
return result;
}
| packages/pretty-format/src/collections.ts | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00017565896268934011,
0.0001715713442536071,
0.000161275384016335,
0.00017271016258746386,
0.0000036320602703199256
] |
{
"id": 1,
"code_window": [
"});\n",
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n",
"// Applies to all tests in this file\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-25.x/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
jest.mock('graceful-fs').mock('../generateEmptyCoverage');
const globalConfig = {collectCoverage: true};
const config = {};
const context = {};
const workerOptions = {config, context, globalConfig, path: 'banana.js'};
let fs;
let generateEmptyCoverage;
let worker;
beforeEach(() => {
jest.resetModules();
fs = require('graceful-fs');
generateEmptyCoverage = require('../generateEmptyCoverage').default;
worker = require('../CoverageWorker').worker;
});
test('resolves to the result of generateEmptyCoverage upon success', async () => {
expect.assertions(2);
const validJS = 'function(){}';
fs.readFileSync.mockImplementation(() => validJS);
generateEmptyCoverage.mockImplementation(() => 42);
const result = await worker(workerOptions);
expect(generateEmptyCoverage).toHaveBeenCalledWith(
validJS,
'banana.js',
globalConfig,
config,
undefined,
undefined,
);
expect(result).toBe(42);
});
test('throws errors on invalid JavaScript', async () => {
expect.assertions(1);
generateEmptyCoverage.mockImplementation(() => {
throw new Error('SyntaxError');
});
// We intentionally expect the worker to fail!
try {
await worker(workerOptions);
} catch (error) {
expect(error).toBeInstanceOf(Error);
}
});
| packages/jest-reporters/src/__tests__/CoverageWorker.test.js | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00017358169134240597,
0.0001714862883090973,
0.00016646426229272038,
0.00017238128930330276,
0.000002190899294873816
] |
{
"id": 2,
"code_window": [
"});\n",
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-26.x/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | ---
id: setup-teardown
title: Setup and Teardown
---
Often while writing tests you have some setup work that needs to happen before tests run, and you have some finishing work that needs to happen after tests run. Jest provides helper functions to handle this.
## Repeating Setup
If you have some work you need to do repeatedly for many tests, you can use `beforeEach` and `afterEach` hooks.
For example, let's say that several tests interact with a database of cities. You have a method `initializeCityDatabase()` that must be called before each of these tests, and a method `clearCityDatabase()` that must be called after each of these tests. You can do this with:
```js
beforeEach(() => {
initializeCityDatabase();
});
afterEach(() => {
clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
```
`beforeEach` and `afterEach` can handle asynchronous code in the same ways that [tests can handle asynchronous code](TestingAsyncCode.md) - they can either take a `done` parameter or return a promise. For example, if `initializeCityDatabase()` returned a promise that resolved when the database was initialized, we would want to return that promise:
```js
beforeEach(() => {
return initializeCityDatabase();
});
```
## One-Time Setup
In some cases, you only need to do setup once, at the beginning of a file. This can be especially bothersome when the setup is asynchronous, so you can't do it inline. Jest provides `beforeAll` and `afterAll` hooks to handle this situation.
For example, if both `initializeCityDatabase()` and `clearCityDatabase()` returned promises, and the city database could be reused between tests, we could change our test code to:
```js
beforeAll(() => {
return initializeCityDatabase();
});
afterAll(() => {
return clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
```
## Scoping
By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.
For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:
```js
// Applies to all tests in this file
beforeEach(() => {
return initializeCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
describe('matching cities to foods', () => {
// Applies only to tests in this describe block
beforeEach(() => {
return initializeFoodDatabase();
});
test('Vienna <3 veal', () => {
expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true);
});
test('San Juan <3 plantains', () => {
expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true);
});
});
```
Note that the top-level `beforeEach` is executed before the `beforeEach` inside the `describe` block. It may help to illustrate the order of execution of all hooks.
```js
beforeAll(() => console.log('1 - beforeAll'));
afterAll(() => console.log('1 - afterAll'));
beforeEach(() => console.log('1 - beforeEach'));
afterEach(() => console.log('1 - afterEach'));
test('', () => console.log('1 - test'));
describe('Scoped / Nested block', () => {
beforeAll(() => console.log('2 - beforeAll'));
afterAll(() => console.log('2 - afterAll'));
beforeEach(() => console.log('2 - beforeEach'));
afterEach(() => console.log('2 - afterEach'));
test('', () => console.log('2 - test'));
});
// 1 - beforeAll
// 1 - beforeEach
// 1 - test
// 1 - afterEach
// 2 - beforeAll
// 1 - beforeEach
// 2 - beforeEach
// 2 - test
// 2 - afterEach
// 1 - afterEach
// 2 - afterAll
// 1 - afterAll
```
## Order of Execution
Jest executes all describe handlers in a test file _before_ it executes any of the actual tests. This is another reason to do setup and teardown inside `before*` and `after*` handlers rather than inside the `describe` blocks. Once the `describe` blocks are complete, by default Jest runs all the tests serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on.
Consider the following illustrative test file and output:
```js
describe('describe outer', () => {
console.log('describe outer-a');
describe('describe inner 1', () => {
console.log('describe inner 1');
test('test 1', () => console.log('test 1'));
});
console.log('describe outer-b');
test('test 2', () => console.log('test 2'));
describe('describe inner 2', () => {
console.log('describe inner 2');
test('test 3', () => console.log('test 3'));
});
console.log('describe outer-c');
});
// describe outer-a
// describe inner 1
// describe outer-b
// describe inner 2
// describe outer-c
// test 1
// test 2
// test 3
```
Just like the `describe` and `test` blocks Jest calls the `before*` and `after*` hooks in the order of declaration. Note that the `after*` hooks of the enclosing scope are called first. For example, here is how you can set up and tear down resources which depend on each other:
```js
beforeEach(() => console.log('connection setup'));
beforeEach(() => console.log('database setup'));
afterEach(() => console.log('database teardown'));
afterEach(() => console.log('connection teardown'));
test('test 1', () => console.log('test 1'));
describe('extra', () => {
beforeEach(() => console.log('extra database setup'));
afterEach(() => console.log('extra database teardown'));
test('test 2', () => console.log('test 2'));
});
// connection setup
// database setup
// test 1
// database teardown
// connection teardown
// connection setup
// database setup
// extra database setup
// test 2
// extra database teardown
// database teardown
// connection teardown
```
:::note
If you are using `jasmine2` test runner, take into account that it calls the `after*` hooks in the reverse order of declaration. To have identical output, the above example should be altered like this:
```diff
beforeEach(() => console.log('connection setup'));
+ afterEach(() => console.log('connection teardown'));
beforeEach(() => console.log('database setup'));
+ afterEach(() => console.log('database teardown'));
- afterEach(() => console.log('database teardown'));
- afterEach(() => console.log('connection teardown'));
// ...
```
:::
## General Advice
If a test is failing, one of the first things to check should be whether the test is failing when it's the only test that runs. To run only one test with Jest, temporarily change that `test` command to a `test.only`:
```js
test.only('this will be the only test that runs', () => {
expect(true).toBe(false);
});
test('this test will not run', () => {
expect('A').toBe('A');
});
```
If you have a test that often fails when it's run as part of a larger suite, but doesn't fail when you run it alone, it's a good bet that something from a different test is interfering with this one. You can often fix this by clearing some shared state with `beforeEach`. If you're not sure whether some shared state is being modified, you can also try a `beforeEach` that logs data.
| docs/SetupAndTeardown.md | 1 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.9937711358070374,
0.0421430878341198,
0.00016400660388171673,
0.00021688049309886992,
0.19843044877052307
] |
{
"id": 2,
"code_window": [
"});\n",
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-26.x/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
let createRuntime;
describe('Runtime', () => {
beforeEach(() => {
createRuntime = require('createRuntime');
});
describe('wrapCodeInModuleWrapper', () => {
it('generates the correct args for the module wrapper', async () => {
const runtime = await createRuntime(__filename);
expect(
runtime.wrapCodeInModuleWrapper('module.exports = "Hello!"'),
).toMatchSnapshot();
});
it('injects "extra globals"', async () => {
const runtime = await createRuntime(__filename, {
sandboxInjectedGlobals: ['Math'],
});
expect(
runtime.wrapCodeInModuleWrapper('module.exports = "Hello!"'),
).toMatchSnapshot();
});
});
});
| packages/jest-runtime/src/__tests__/runtime_wrap.js | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.0001742483291309327,
0.00016872055130079389,
0.00016243240679614246,
0.0001691007346380502,
0.000004195046130917035
] |
{
"id": 2,
"code_window": [
"});\n",
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-26.x/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | name: 'Close stale issues and PRs'
on:
schedule:
- cron: '*/10 * * * *'
permissions:
issues: write # to close stale issues (actions/stale)
pull-requests: write # to close stale PRs (actions/stale)
jobs:
stale:
name: 'Close month old issues and PRs'
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v7
with:
start-date: '2022-01-01T00:00:00Z'
stale-issue-message: 'This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 30 days.'
stale-pr-message: 'This PR is stale because it has been open 90 days with no activity. Remove stale label or comment or this will be closed in 30 days.'
close-issue-message: 'This issue was closed because it has been stalled for 30 days with no activity. Please open a new issue if the issue is still relevant, linking to this one.'
close-pr-message: 'This PR was closed because it has been stalled for 30 days with no activity. Please open a new PR if the issue is still relevant, linking to this one.'
days-before-issue-stale: 30
days-before-pr-stale: 90
days-before-issue-close: 30
days-before-pr-close: 30
exempt-all-milestones: true
exempt-issue-labels: Pinned
exempt-draft-pr: true
operations-per-run: 1750
stale-legacy:
name: 'Close year old issues and PRs'
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v7
with:
stale-issue-message: 'This issue is stale because it has been open for 1 year with no activity. Remove stale label or comment or this will be closed in 30 days.'
stale-pr-message: 'This PR is stale because it has been open 1 year with no activity. Remove stale label or comment or this will be closed in 30 days.'
close-issue-message: 'This issue was closed because it has been stalled for 30 days with no activity. Please open a new issue if the issue is still relevant, linking to this one.'
close-pr-message: 'This PR was closed because it has been stalled for 30 days with no activity. Please open a new PR if the issue is still relevant, linking to this one.'
days-before-issue-stale: 365
days-before-pr-stale: 365
days-before-issue-close: 30
days-before-pr-close: 30
exempt-all-milestones: true
exempt-issue-labels: Pinned
operations-per-run: 1750
| .github/workflows/close-stale.yml | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00017576753452885896,
0.0001743383181747049,
0.00017272893455810845,
0.00017463690892327577,
0.0000013270262115838705
] |
{
"id": 2,
"code_window": [
"});\n",
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-26.x/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
'use strict';
const path = require('path');
const moduleDirectories = ['module_dir'];
let createRuntime;
let rootDir;
describe('Runtime', () => {
beforeEach(() => {
rootDir = path.resolve(path.dirname(__filename), 'test_root');
createRuntime = require('createRuntime');
});
it('uses configured moduleDirectories', async () => {
const runtime = await createRuntime(__filename, {
moduleDirectories,
});
const exports = runtime.requireModule(
runtime.__mockRootPath,
'module_dir_module',
);
expect(exports).toBeDefined();
});
it('resolves packages', async () => {
const runtime = await createRuntime(__filename, {
moduleDirectories,
});
const exports = runtime.requireModule(runtime.__mockRootPath, 'my-module');
expect(exports.isNodeModule).toBe(true);
});
it('finds closest module from moduleDirectories', async () => {
const runtime = await createRuntime(__filename, {moduleDirectories});
const exports = runtime.requireModule(
path.join(rootDir, 'subdir2', 'my_module.js'),
'module_dir_module',
);
expect(exports.modulePath).toBe('subdir2/module_dir/module_dir_module.js');
});
it('only checks the configured directories', async () => {
const runtime = await createRuntime(__filename, {
moduleDirectories,
});
expect(() => {
runtime.requireModule(runtime.__mockRootPath, 'not-a-haste-package');
}).toThrow(
new Error("Cannot find module 'not-a-haste-package' from 'root.js'"),
);
});
});
| packages/jest-runtime/src/__tests__/runtime_module_directories.test.js | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00017694916459731758,
0.00017089115863200277,
0.00016722788859624416,
0.00016915201558731496,
0.0000032946286410151515
] |
{
"id": 3,
"code_window": [
"});\n",
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-27.x/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | ---
id: setup-teardown
title: Setup and Teardown
---
Often while writing tests you have some setup work that needs to happen before tests run, and you have some finishing work that needs to happen after tests run. Jest provides helper functions to handle this.
## Repeating Setup
If you have some work you need to do repeatedly for many tests, you can use `beforeEach` and `afterEach` hooks.
For example, let's say that several tests interact with a database of cities. You have a method `initializeCityDatabase()` that must be called before each of these tests, and a method `clearCityDatabase()` that must be called after each of these tests. You can do this with:
```js
beforeEach(() => {
initializeCityDatabase();
});
afterEach(() => {
clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
```
`beforeEach` and `afterEach` can handle asynchronous code in the same ways that [tests can handle asynchronous code](TestingAsyncCode.md) - they can either take a `done` parameter or return a promise. For example, if `initializeCityDatabase()` returned a promise that resolved when the database was initialized, we would want to return that promise:
```js
beforeEach(() => {
return initializeCityDatabase();
});
```
## One-Time Setup
In some cases, you only need to do setup once, at the beginning of a file. This can be especially bothersome when the setup is asynchronous, so you can't do it inline. Jest provides `beforeAll` and `afterAll` hooks to handle this situation.
For example, if both `initializeCityDatabase()` and `clearCityDatabase()` returned promises, and the city database could be reused between tests, we could change our test code to:
```js
beforeAll(() => {
return initializeCityDatabase();
});
afterAll(() => {
return clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
```
## Scoping
By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.
For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:
```js
// Applies to all tests in this file
beforeEach(() => {
return initializeCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
describe('matching cities to foods', () => {
// Applies only to tests in this describe block
beforeEach(() => {
return initializeFoodDatabase();
});
test('Vienna <3 veal', () => {
expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true);
});
test('San Juan <3 plantains', () => {
expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true);
});
});
```
Note that the top-level `beforeEach` is executed before the `beforeEach` inside the `describe` block. It may help to illustrate the order of execution of all hooks.
```js
beforeAll(() => console.log('1 - beforeAll'));
afterAll(() => console.log('1 - afterAll'));
beforeEach(() => console.log('1 - beforeEach'));
afterEach(() => console.log('1 - afterEach'));
test('', () => console.log('1 - test'));
describe('Scoped / Nested block', () => {
beforeAll(() => console.log('2 - beforeAll'));
afterAll(() => console.log('2 - afterAll'));
beforeEach(() => console.log('2 - beforeEach'));
afterEach(() => console.log('2 - afterEach'));
test('', () => console.log('2 - test'));
});
// 1 - beforeAll
// 1 - beforeEach
// 1 - test
// 1 - afterEach
// 2 - beforeAll
// 1 - beforeEach
// 2 - beforeEach
// 2 - test
// 2 - afterEach
// 1 - afterEach
// 2 - afterAll
// 1 - afterAll
```
## Order of Execution
Jest executes all describe handlers in a test file _before_ it executes any of the actual tests. This is another reason to do setup and teardown inside `before*` and `after*` handlers rather than inside the `describe` blocks. Once the `describe` blocks are complete, by default Jest runs all the tests serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on.
Consider the following illustrative test file and output:
```js
describe('describe outer', () => {
console.log('describe outer-a');
describe('describe inner 1', () => {
console.log('describe inner 1');
test('test 1', () => console.log('test 1'));
});
console.log('describe outer-b');
test('test 2', () => console.log('test 2'));
describe('describe inner 2', () => {
console.log('describe inner 2');
test('test 3', () => console.log('test 3'));
});
console.log('describe outer-c');
});
// describe outer-a
// describe inner 1
// describe outer-b
// describe inner 2
// describe outer-c
// test 1
// test 2
// test 3
```
Just like the `describe` and `test` blocks Jest calls the `before*` and `after*` hooks in the order of declaration. Note that the `after*` hooks of the enclosing scope are called first. For example, here is how you can set up and tear down resources which depend on each other:
```js
beforeEach(() => console.log('connection setup'));
beforeEach(() => console.log('database setup'));
afterEach(() => console.log('database teardown'));
afterEach(() => console.log('connection teardown'));
test('test 1', () => console.log('test 1'));
describe('extra', () => {
beforeEach(() => console.log('extra database setup'));
afterEach(() => console.log('extra database teardown'));
test('test 2', () => console.log('test 2'));
});
// connection setup
// database setup
// test 1
// database teardown
// connection teardown
// connection setup
// database setup
// extra database setup
// test 2
// extra database teardown
// database teardown
// connection teardown
```
:::note
If you are using `jasmine2` test runner, take into account that it calls the `after*` hooks in the reverse order of declaration. To have identical output, the above example should be altered like this:
```diff
beforeEach(() => console.log('connection setup'));
+ afterEach(() => console.log('connection teardown'));
beforeEach(() => console.log('database setup'));
+ afterEach(() => console.log('database teardown'));
- afterEach(() => console.log('database teardown'));
- afterEach(() => console.log('connection teardown'));
// ...
```
:::
## General Advice
If a test is failing, one of the first things to check should be whether the test is failing when it's the only test that runs. To run only one test with Jest, temporarily change that `test` command to a `test.only`:
```js
test.only('this will be the only test that runs', () => {
expect(true).toBe(false);
});
test('this test will not run', () => {
expect('A').toBe('A');
});
```
If you have a test that often fails when it's run as part of a larger suite, but doesn't fail when you run it alone, it's a good bet that something from a different test is interfering with this one. You can often fix this by clearing some shared state with `beforeEach`. If you're not sure whether some shared state is being modified, you can also try a `beforeEach` that logs data.
| website/versioned_docs/version-28.x/SetupAndTeardown.md | 1 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.9937711358070374,
0.0421430878341198,
0.00016400660388171673,
0.00021688049309886992,
0.19843044877052307
] |
{
"id": 3,
"code_window": [
"});\n",
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-27.x/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type {Config} from '@jest/types';
import {readInitialOptions} from '../';
describe(readInitialOptions, () => {
test('should be able to use serialized jest config', async () => {
const inputConfig = {jestConfig: 'serialized'};
const {config, configPath} = await readInitialOptions(
JSON.stringify(inputConfig),
);
expect(config).toEqual({...inputConfig, rootDir: process.cwd()});
expect(configPath).toBeNull();
});
test('should allow deserialized options', async () => {
const inputConfig = {jestConfig: 'deserialized'};
const {config, configPath} = await readInitialOptions(undefined, {
packageRootOrConfig: inputConfig as Config.InitialOptions,
parentConfigDirname: process.cwd(),
});
expect(config).toEqual({...inputConfig, rootDir: process.cwd()});
expect(configPath).toBeNull();
});
// Note: actual file reading is tested in e2e test
});
| packages/jest-config/src/__tests__/readInitialOptions.test.ts | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00017387556727044284,
0.00017032050527632236,
0.00016647999291308224,
0.0001704632304608822,
0.000003133373411401408
] |
{
"id": 3,
"code_window": [
"});\n",
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-27.x/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
function awaitable() {
return Promise.resolve();
}
module.exports.syncMethod = () => 42;
module.exports.asyncMethod = async () => {
await awaitable();
return 42;
};
| e2e/native-async-mock/Native.js | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00017357541946694255,
0.0001719136198516935,
0.0001702518347883597,
0.0001719136198516935,
0.0000016617922256045858
] |
{
"id": 3,
"code_window": [
"});\n",
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-27.x/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`printDiffOrStringify asymmetricMatcher array 1`] = `
<g>- Expected - 1</>
<r>+ Received + 1</>
<d> Array [</>
<d> 1,</>
<d> Any<Number>,</>
<g>- 3,</>
<r>+ 2,</>
<d> ]</>
`;
exports[`printDiffOrStringify asymmetricMatcher circular array 1`] = `
<g>- Expected - 1</>
<r>+ Received + 1</>
<d> Array [</>
<d> 1,</>
<d> Any<Number>,</>
<g>- 3,</>
<r>+ 2,</>
<d> [Circular],</>
<d> ]</>
`;
exports[`printDiffOrStringify asymmetricMatcher circular map 1`] = `
<g>- Expected - 2</>
<r>+ Received + 2</>
<d> Map {</>
<d> "a" => 1,</>
<d> "b" => Any<Number>,</>
<g>- "c" => 3,</>
<r>+ "c" => 2,</>
<d> "circular" => Map {</>
<d> "a" => 1,</>
<d> "b" => Any<Number>,</>
<g>- "c" => 3,</>
<r>+ "c" => 2,</>
<d> "circular" => [Circular],</>
<d> },</>
<d> }</>
`;
exports[`printDiffOrStringify asymmetricMatcher circular object 1`] = `
<g>- Expected - 1</>
<r>+ Received + 1</>
<d> Object {</>
<d> "a": [Circular],</>
<d> "b": Any<Number>,</>
<g>- "c": 3,</>
<r>+ "c": 2,</>
<d> }</>
`;
exports[`printDiffOrStringify asymmetricMatcher custom asymmetricMatcher 1`] = `
<g>- Expected - 1</>
<r>+ Received + 1</>
<d> Object {</>
<d> "a": equal5<>,</>
<g>- "b": false,</>
<r>+ "b": true,</>
<d> }</>
`;
exports[`printDiffOrStringify asymmetricMatcher jest asymmetricMatcher 1`] = `
<g>- Expected - 1</>
<r>+ Received + 1</>
<d> Object {</>
<d> "a": Any<Number>,</>
<d> "b": Anything,</>
<d> "c": ArrayContaining [</>
<d> 1,</>
<d> 3,</>
<d> ],</>
<d> "d": StringContaining "jest",</>
<d> "e": StringMatching /^jest/,</>
<d> "f": ObjectContaining {</>
<d> "a": Any<Date>,</>
<d> },</>
<g>- "g": true,</>
<r>+ "g": false,</>
<d> Symbol(h): Any<String>,</>
<d> }</>
`;
exports[`printDiffOrStringify asymmetricMatcher map 1`] = `
<g>- Expected - 1</>
<r>+ Received + 1</>
<d> Map {</>
<d> "a" => 1,</>
<d> "b" => Any<Number>,</>
<g>- "c" => 3,</>
<r>+ "c" => 2,</>
<d> }</>
`;
exports[`printDiffOrStringify asymmetricMatcher minimal test 1`] = `
<g>- Expected - 1</>
<r>+ Received + 1</>
<d> Object {</>
<d> "a": Any<Number>,</>
<g>- "b": 2,</>
<r>+ "b": 1,</>
<d> }</>
`;
exports[`printDiffOrStringify asymmetricMatcher nested object 1`] = `
<g>- Expected - 1</>
<r>+ Received + 1</>
<d> Object {</>
<d> "a": Any<Number>,</>
<d> "b": Object {</>
<d> "a": 1,</>
<d> "b": Any<Number>,</>
<d> },</>
<g>- "c": 2,</>
<r>+ "c": 1,</>
<d> }</>
`;
exports[`printDiffOrStringify asymmetricMatcher object in array 1`] = `
<g>- Expected - 1</>
<r>+ Received + 1</>
<d> Array [</>
<d> 1,</>
<d> Object {</>
<d> "a": 1,</>
<d> "b": Any<Number>,</>
<d> },</>
<g>- 3,</>
<r>+ 2,</>
<d> ]</>
`;
exports[`printDiffOrStringify asymmetricMatcher transitive circular 1`] = `
<g>- Expected - 1</>
<r>+ Received + 1</>
<d> Object {</>
<g>- "a": 3,</>
<r>+ "a": 2,</>
<d> "nested": Object {</>
<d> "b": Any<Number>,</>
<d> "parent": [Circular],</>
<d> },</>
<d> }</>
`;
exports[`printDiffOrStringify expected and received are multi line with trailing spaces 1`] = `
<g>- Expected - 3</>
<r>+ Received + 3</>
<g>- <i>delete</i><Y> </></>
<r>+ <i>insert</i><Y> </></>
<g>- common <i>expect</i>ed common</>
<r>+ common <i>receiv</i>ed common</>
<g>- <i>prev</i><Y> </></>
<r>+ <i>next</i><Y> </></>
`;
exports[`printDiffOrStringify expected and received are single line with multiple changes 1`] = `
Expected: <g>"<i>delete</i> common <i>expect</i>ed common <i>prev</i>"</>
Received: <r>"<i>insert</i> common <i>receiv</i>ed common <i>next</i>"</>
`;
exports[`printDiffOrStringify expected is empty and received is single line 1`] = `
Expected: <g>""</>
Received: <r>"single line"</>
`;
exports[`printDiffOrStringify expected is multi line and received is empty 1`] = `
Expected: <g>"multi</>
<g>line"</>
Received: <r>""</>
`;
exports[`printDiffOrStringify has no common after clean up chaff multiline 1`] = `
<g>- Expected - 2</>
<r>+ Received + 2</>
<g>- delete</>
<g>- two</>
<r>+ insert</>
<r>+ 2</>
`;
exports[`printDiffOrStringify has no common after clean up chaff one-line 1`] = `
Expected: <g>"delete"</>
Received: <r>"insert"</>
`;
exports[`printDiffOrStringify object contain readonly symbol key object 1`] = `
<g>- Expected - 1</>
<r>+ Received + 1</>
<d> Object {</>
<g>- "b": 2,</>
<r>+ "b": 1,</>
<d> Symbol(key): Object {</>
<d> "a": 1,</>
<d> },</>
<d> }</>
`;
| packages/jest-matcher-utils/src/__tests__/__snapshots__/printDiffOrStringify.test.ts.snap | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.0001751630479702726,
0.00017097190720960498,
0.00016560949734412134,
0.0001710847718641162,
0.000002323609805898741
] |
{
"id": 4,
"code_window": [
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-28.x/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | ---
id: setup-teardown
title: Setup and Teardown
---
Often while writing tests you have some setup work that needs to happen before tests run, and you have some finishing work that needs to happen after tests run. Jest provides helper functions to handle this.
## Repeating Setup
If you have some work you need to do repeatedly for many tests, you can use `beforeEach` and `afterEach` hooks.
For example, let's say that several tests interact with a database of cities. You have a method `initializeCityDatabase()` that must be called before each of these tests, and a method `clearCityDatabase()` that must be called after each of these tests. You can do this with:
```js
beforeEach(() => {
initializeCityDatabase();
});
afterEach(() => {
clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
```
`beforeEach` and `afterEach` can handle asynchronous code in the same ways that [tests can handle asynchronous code](TestingAsyncCode.md) - they can either take a `done` parameter or return a promise. For example, if `initializeCityDatabase()` returned a promise that resolved when the database was initialized, we would want to return that promise:
```js
beforeEach(() => {
return initializeCityDatabase();
});
```
## One-Time Setup
In some cases, you only need to do setup once, at the beginning of a file. This can be especially bothersome when the setup is asynchronous, so you can't do it inline. Jest provides `beforeAll` and `afterAll` hooks to handle this situation.
For example, if both `initializeCityDatabase()` and `clearCityDatabase()` returned promises, and the city database could be reused between tests, we could change our test code to:
```js
beforeAll(() => {
return initializeCityDatabase();
});
afterAll(() => {
return clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
```
## Scoping
By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.
For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:
```js
// Applies to all tests in this file
beforeEach(() => {
return initializeCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
describe('matching cities to foods', () => {
// Applies only to tests in this describe block
beforeEach(() => {
return initializeFoodDatabase();
});
test('Vienna <3 veal', () => {
expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true);
});
test('San Juan <3 plantains', () => {
expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true);
});
});
```
Note that the top-level `beforeEach` is executed before the `beforeEach` inside the `describe` block. It may help to illustrate the order of execution of all hooks.
```js
beforeAll(() => console.log('1 - beforeAll'));
afterAll(() => console.log('1 - afterAll'));
beforeEach(() => console.log('1 - beforeEach'));
afterEach(() => console.log('1 - afterEach'));
test('', () => console.log('1 - test'));
describe('Scoped / Nested block', () => {
beforeAll(() => console.log('2 - beforeAll'));
afterAll(() => console.log('2 - afterAll'));
beforeEach(() => console.log('2 - beforeEach'));
afterEach(() => console.log('2 - afterEach'));
test('', () => console.log('2 - test'));
});
// 1 - beforeAll
// 1 - beforeEach
// 1 - test
// 1 - afterEach
// 2 - beforeAll
// 1 - beforeEach
// 2 - beforeEach
// 2 - test
// 2 - afterEach
// 1 - afterEach
// 2 - afterAll
// 1 - afterAll
```
## Order of Execution
Jest executes all describe handlers in a test file _before_ it executes any of the actual tests. This is another reason to do setup and teardown inside `before*` and `after*` handlers rather than inside the `describe` blocks. Once the `describe` blocks are complete, by default Jest runs all the tests serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on.
Consider the following illustrative test file and output:
```js
describe('describe outer', () => {
console.log('describe outer-a');
describe('describe inner 1', () => {
console.log('describe inner 1');
test('test 1', () => console.log('test 1'));
});
console.log('describe outer-b');
test('test 2', () => console.log('test 2'));
describe('describe inner 2', () => {
console.log('describe inner 2');
test('test 3', () => console.log('test 3'));
});
console.log('describe outer-c');
});
// describe outer-a
// describe inner 1
// describe outer-b
// describe inner 2
// describe outer-c
// test 1
// test 2
// test 3
```
Just like the `describe` and `test` blocks Jest calls the `before*` and `after*` hooks in the order of declaration. Note that the `after*` hooks of the enclosing scope are called first. For example, here is how you can set up and tear down resources which depend on each other:
```js
beforeEach(() => console.log('connection setup'));
beforeEach(() => console.log('database setup'));
afterEach(() => console.log('database teardown'));
afterEach(() => console.log('connection teardown'));
test('test 1', () => console.log('test 1'));
describe('extra', () => {
beforeEach(() => console.log('extra database setup'));
afterEach(() => console.log('extra database teardown'));
test('test 2', () => console.log('test 2'));
});
// connection setup
// database setup
// test 1
// database teardown
// connection teardown
// connection setup
// database setup
// extra database setup
// test 2
// extra database teardown
// database teardown
// connection teardown
```
:::note
If you are using `jasmine2` test runner, take into account that it calls the `after*` hooks in the reverse order of declaration. To have identical output, the above example should be altered like this:
```diff
beforeEach(() => console.log('connection setup'));
+ afterEach(() => console.log('connection teardown'));
beforeEach(() => console.log('database setup'));
+ afterEach(() => console.log('database teardown'));
- afterEach(() => console.log('database teardown'));
- afterEach(() => console.log('connection teardown'));
// ...
```
:::
## General Advice
If a test is failing, one of the first things to check should be whether the test is failing when it's the only test that runs. To run only one test with Jest, temporarily change that `test` command to a `test.only`:
```js
test.only('this will be the only test that runs', () => {
expect(true).toBe(false);
});
test('this test will not run', () => {
expect('A').toBe('A');
});
```
If you have a test that often fails when it's run as part of a larger suite, but doesn't fail when you run it alone, it's a good bet that something from a different test is interfering with this one. You can often fix this by clearing some shared state with `beforeEach`. If you're not sure whether some shared state is being modified, you can also try a `beforeEach` that logs data.
| website/versioned_docs/version-29.2/SetupAndTeardown.md | 1 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.9941399097442627,
0.04188000038266182,
0.0001637886161915958,
0.00022093400184530765,
0.1985606998205185
] |
{
"id": 4,
"code_window": [
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-28.x/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | {
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "build"
},
"include": ["./src/**/*"],
"exclude": ["./**/__tests__/**/*"],
"references": [
{"path": "../jest-get-type"},
{"path": "../jest-types"},
{"path": "../pretty-format"}
]
}
| packages/jest-validate/tsconfig.json | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00017234249389730394,
0.00017198303248733282,
0.0001716235710773617,
0.00017198303248733282,
3.5946140997111797e-7
] |
{
"id": 4,
"code_window": [
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-28.x/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | {
"version": "0.0.0"
}
| e2e/pnp/lib/package.json | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.0001707465562503785,
0.0001707465562503785,
0.0001707465562503785,
0.0001707465562503785,
0
] |
{
"id": 4,
"code_window": [
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-28.x/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type {Circus} from '@jest/types';
import {
injectGlobalErrorHandlers,
restoreGlobalErrorHandlers,
} from './globalErrorHandlers';
import {LOG_ERRORS_BEFORE_RETRY, TEST_TIMEOUT_SYMBOL} from './types';
import {
addErrorToEachTestUnderDescribe,
describeBlockHasTests,
getTestDuration,
invariant,
makeDescribe,
makeTest,
} from './utils';
const eventHandler: Circus.EventHandler = (event, state) => {
switch (event.name) {
case 'include_test_location_in_result': {
state.includeTestLocationInResult = true;
break;
}
case 'hook_start': {
event.hook.seenDone = false;
break;
}
case 'start_describe_definition': {
const {blockName, mode} = event;
const {currentDescribeBlock, currentlyRunningTest} = state;
if (currentlyRunningTest) {
currentlyRunningTest.errors.push(
new Error(
`Cannot nest a describe inside a test. Describe block "${blockName}" cannot run because it is nested within "${currentlyRunningTest.name}".`,
),
);
break;
}
const describeBlock = makeDescribe(blockName, currentDescribeBlock, mode);
currentDescribeBlock.children.push(describeBlock);
state.currentDescribeBlock = describeBlock;
break;
}
case 'finish_describe_definition': {
const {currentDescribeBlock} = state;
invariant(currentDescribeBlock, 'currentDescribeBlock must be there');
if (!describeBlockHasTests(currentDescribeBlock)) {
currentDescribeBlock.hooks.forEach(hook => {
hook.asyncError.message = `Invalid: ${hook.type}() may not be used in a describe block containing no tests.`;
state.unhandledErrors.push(hook.asyncError);
});
}
// pass mode of currentDescribeBlock to tests
// but do not when there is already a single test with "only" mode
const shouldPassMode = !(
currentDescribeBlock.mode === 'only' &&
currentDescribeBlock.children.some(
child => child.type === 'test' && child.mode === 'only',
)
);
if (shouldPassMode) {
currentDescribeBlock.children.forEach(child => {
if (child.type === 'test' && !child.mode) {
child.mode = currentDescribeBlock.mode;
}
});
}
if (
!state.hasFocusedTests &&
currentDescribeBlock.mode !== 'skip' &&
currentDescribeBlock.children.some(
child => child.type === 'test' && child.mode === 'only',
)
) {
state.hasFocusedTests = true;
}
if (currentDescribeBlock.parent) {
state.currentDescribeBlock = currentDescribeBlock.parent;
}
break;
}
case 'add_hook': {
const {currentDescribeBlock, currentlyRunningTest, hasStarted} = state;
const {asyncError, fn, hookType: type, timeout} = event;
if (currentlyRunningTest) {
currentlyRunningTest.errors.push(
new Error(
`Hooks cannot be defined inside tests. Hook of type "${type}" is nested within "${currentlyRunningTest.name}".`,
),
);
break;
} else if (hasStarted) {
state.unhandledErrors.push(
new Error(
'Cannot add a hook after tests have started running. Hooks must be defined synchronously.',
),
);
break;
}
const parent = currentDescribeBlock;
currentDescribeBlock.hooks.push({
asyncError,
fn,
parent,
seenDone: false,
timeout,
type,
});
break;
}
case 'add_test': {
const {currentDescribeBlock, currentlyRunningTest, hasStarted} = state;
const {
asyncError,
fn,
mode,
testName: name,
timeout,
concurrent,
failing,
} = event;
if (currentlyRunningTest) {
currentlyRunningTest.errors.push(
new Error(
`Tests cannot be nested. Test "${name}" cannot run because it is nested within "${currentlyRunningTest.name}".`,
),
);
break;
} else if (hasStarted) {
state.unhandledErrors.push(
new Error(
'Cannot add a test after tests have started running. Tests must be defined synchronously.',
),
);
break;
}
const test = makeTest(
fn,
mode,
concurrent,
name,
currentDescribeBlock,
timeout,
asyncError,
failing,
);
if (currentDescribeBlock.mode !== 'skip' && test.mode === 'only') {
state.hasFocusedTests = true;
}
currentDescribeBlock.children.push(test);
currentDescribeBlock.tests.push(test);
break;
}
case 'hook_failure': {
const {test, describeBlock, error, hook} = event;
const {asyncError, type} = hook;
if (type === 'beforeAll') {
invariant(describeBlock, 'always present for `*All` hooks');
addErrorToEachTestUnderDescribe(describeBlock, error, asyncError);
} else if (type === 'afterAll') {
// Attaching `afterAll` errors to each test makes execution flow
// too complicated, so we'll consider them to be global.
state.unhandledErrors.push([error, asyncError]);
} else {
invariant(test, 'always present for `*Each` hooks');
test.errors.push([error, asyncError]);
}
break;
}
case 'test_skip': {
event.test.status = 'skip';
break;
}
case 'test_todo': {
event.test.status = 'todo';
break;
}
case 'test_done': {
event.test.duration = getTestDuration(event.test);
event.test.status = 'done';
state.currentlyRunningTest = null;
break;
}
case 'test_start': {
state.currentlyRunningTest = event.test;
event.test.startedAt = Date.now();
event.test.invocations += 1;
break;
}
case 'test_fn_start': {
event.test.seenDone = false;
break;
}
case 'test_fn_failure': {
const {
error,
test: {asyncError},
} = event;
event.test.errors.push([error, asyncError]);
break;
}
case 'test_retry': {
const logErrorsBeforeRetry: boolean =
// eslint-disable-next-line no-restricted-globals
global[LOG_ERRORS_BEFORE_RETRY] || false;
if (logErrorsBeforeRetry) {
event.test.retryReasons.push(...event.test.errors);
}
event.test.errors = [];
break;
}
case 'run_start': {
state.hasStarted = true;
/* eslint-disable no-restricted-globals */
global[TEST_TIMEOUT_SYMBOL] &&
(state.testTimeout = global[TEST_TIMEOUT_SYMBOL]);
/* eslint-enable */
break;
}
case 'run_finish': {
break;
}
case 'setup': {
// Uncaught exception handlers should be defined on the parent process
// object. If defined on the VM's process object they just no op and let
// the parent process crash. It might make sense to return a `dispatch`
// function to the parent process and register handlers there instead, but
// i'm not sure if this is works. For now i just replicated whatever
// jasmine was doing -- dabramov
state.parentProcess = event.parentProcess;
invariant(state.parentProcess);
state.originalGlobalErrorHandlers = injectGlobalErrorHandlers(
state.parentProcess,
);
if (event.testNamePattern) {
state.testNamePattern = new RegExp(event.testNamePattern, 'i');
}
break;
}
case 'teardown': {
invariant(state.originalGlobalErrorHandlers);
invariant(state.parentProcess);
restoreGlobalErrorHandlers(
state.parentProcess,
state.originalGlobalErrorHandlers,
);
break;
}
case 'error': {
// It's very likely for long-running async tests to throw errors. In this
// case we want to catch them and fail the current test. At the same time
// there's a possibility that one test sets a long timeout, that will
// eventually throw after this test finishes but during some other test
// execution, which will result in one test's error failing another test.
// In any way, it should be possible to track where the error was thrown
// from.
state.currentlyRunningTest
? state.currentlyRunningTest.errors.push(event.error)
: state.unhandledErrors.push(event.error);
break;
}
}
};
export default eventHandler;
| packages/jest-circus/src/eventHandler.ts | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.0004585648130159825,
0.00021814178035128862,
0.00016564203542657197,
0.00017295141879003495,
0.00008261355833383277
] |
{
"id": 5,
"code_window": [
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n",
"// Applies to all tests in this file\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-29.0/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | ---
id: setup-teardown
title: Setup and Teardown
---
Often while writing tests you have some setup work that needs to happen before tests run, and you have some finishing work that needs to happen after tests run. Jest provides helper functions to handle this.
## Repeating Setup
If you have some work you need to do repeatedly for many tests, you can use `beforeEach` and `afterEach` hooks.
For example, let's say that several tests interact with a database of cities. You have a method `initializeCityDatabase()` that must be called before each of these tests, and a method `clearCityDatabase()` that must be called after each of these tests. You can do this with:
```js
beforeEach(() => {
initializeCityDatabase();
});
afterEach(() => {
clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
```
`beforeEach` and `afterEach` can handle asynchronous code in the same ways that [tests can handle asynchronous code](TestingAsyncCode.md) - they can either take a `done` parameter or return a promise. For example, if `initializeCityDatabase()` returned a promise that resolved when the database was initialized, we would want to return that promise:
```js
beforeEach(() => {
return initializeCityDatabase();
});
```
## One-Time Setup
In some cases, you only need to do setup once, at the beginning of a file. This can be especially bothersome when the setup is asynchronous, so you can't do it inline. Jest provides `beforeAll` and `afterAll` hooks to handle this situation.
For example, if both `initializeCityDatabase()` and `clearCityDatabase()` returned promises, and the city database could be reused between tests, we could change our test code to:
```js
beforeAll(() => {
return initializeCityDatabase();
});
afterAll(() => {
return clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
```
## Scoping
By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.
For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:
```js
// Applies to all tests in this file
beforeEach(() => {
return initializeCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
describe('matching cities to foods', () => {
// Applies only to tests in this describe block
beforeEach(() => {
return initializeFoodDatabase();
});
test('Vienna <3 veal', () => {
expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true);
});
test('San Juan <3 plantains', () => {
expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true);
});
});
```
Note that the top-level `beforeEach` is executed before the `beforeEach` inside the `describe` block. It may help to illustrate the order of execution of all hooks.
```js
beforeAll(() => console.log('1 - beforeAll'));
afterAll(() => console.log('1 - afterAll'));
beforeEach(() => console.log('1 - beforeEach'));
afterEach(() => console.log('1 - afterEach'));
test('', () => console.log('1 - test'));
describe('Scoped / Nested block', () => {
beforeAll(() => console.log('2 - beforeAll'));
afterAll(() => console.log('2 - afterAll'));
beforeEach(() => console.log('2 - beforeEach'));
afterEach(() => console.log('2 - afterEach'));
test('', () => console.log('2 - test'));
});
// 1 - beforeAll
// 1 - beforeEach
// 1 - test
// 1 - afterEach
// 2 - beforeAll
// 1 - beforeEach
// 2 - beforeEach
// 2 - test
// 2 - afterEach
// 1 - afterEach
// 2 - afterAll
// 1 - afterAll
```
## Order of Execution
Jest executes all describe handlers in a test file _before_ it executes any of the actual tests. This is another reason to do setup and teardown inside `before*` and `after*` handlers rather than inside the `describe` blocks. Once the `describe` blocks are complete, by default Jest runs all the tests serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on.
Consider the following illustrative test file and output:
```js
describe('describe outer', () => {
console.log('describe outer-a');
describe('describe inner 1', () => {
console.log('describe inner 1');
test('test 1', () => console.log('test 1'));
});
console.log('describe outer-b');
test('test 2', () => console.log('test 2'));
describe('describe inner 2', () => {
console.log('describe inner 2');
test('test 3', () => console.log('test 3'));
});
console.log('describe outer-c');
});
// describe outer-a
// describe inner 1
// describe outer-b
// describe inner 2
// describe outer-c
// test 1
// test 2
// test 3
```
Just like the `describe` and `test` blocks Jest calls the `before*` and `after*` hooks in the order of declaration. Note that the `after*` hooks of the enclosing scope are called first. For example, here is how you can set up and tear down resources which depend on each other:
```js
beforeEach(() => console.log('connection setup'));
beforeEach(() => console.log('database setup'));
afterEach(() => console.log('database teardown'));
afterEach(() => console.log('connection teardown'));
test('test 1', () => console.log('test 1'));
describe('extra', () => {
beforeEach(() => console.log('extra database setup'));
afterEach(() => console.log('extra database teardown'));
test('test 2', () => console.log('test 2'));
});
// connection setup
// database setup
// test 1
// database teardown
// connection teardown
// connection setup
// database setup
// extra database setup
// test 2
// extra database teardown
// database teardown
// connection teardown
```
:::note
If you are using `jasmine2` test runner, take into account that it calls the `after*` hooks in the reverse order of declaration. To have identical output, the above example should be altered like this:
```diff
beforeEach(() => console.log('connection setup'));
+ afterEach(() => console.log('connection teardown'));
beforeEach(() => console.log('database setup'));
+ afterEach(() => console.log('database teardown'));
- afterEach(() => console.log('database teardown'));
- afterEach(() => console.log('connection teardown'));
// ...
```
:::
## General Advice
If a test is failing, one of the first things to check should be whether the test is failing when it's the only test that runs. To run only one test with Jest, temporarily change that `test` command to a `test.only`:
```js
test.only('this will be the only test that runs', () => {
expect(true).toBe(false);
});
test('this test will not run', () => {
expect('A').toBe('A');
});
```
If you have a test that often fails when it's run as part of a larger suite, but doesn't fail when you run it alone, it's a good bet that something from a different test is interfering with this one. You can often fix this by clearing some shared state with `beforeEach`. If you're not sure whether some shared state is being modified, you can also try a `beforeEach` that logs data.
| website/versioned_docs/version-29.0/SetupAndTeardown.md | 1 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.991320788860321,
0.0420149601995945,
0.00016461354971397668,
0.00020852462330367416,
0.19794614613056183
] |
{
"id": 5,
"code_window": [
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n",
"// Applies to all tests in this file\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-29.0/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class MyWatchPlugin {
// Add hooks to Jest lifecycle events
apply(jestHooks) {}
// Get the prompt information for interactive plugins
getUsageInfo(globalConfig) {
console.log('getUsageInfo');
}
// Executed when the key from `getUsageInfo` is input
run(globalConfig, updateConfigAndRun) {}
}
module.exports = MyWatchPlugin;
| e2e/watch-plugins/cjs/my-watch-plugin.cjs | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00017275511345360428,
0.00016884738579392433,
0.0001641658745938912,
0.00016962119843810797,
0.000003548974973455188
] |
{
"id": 5,
"code_window": [
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n",
"// Applies to all tests in this file\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-29.0/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | **/__mocks__/**
**/__tests__/**
__typetests__
src
tsconfig.json
tsconfig.tsbuildinfo
api-extractor.json
| packages/jest-core/.npmignore | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00017043588741216809,
0.00017043588741216809,
0.00017043588741216809,
0.00017043588741216809,
0
] |
{
"id": 5,
"code_window": [
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n",
"// Applies to all tests in this file\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-29.0/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | # Jest
๐ Delightful JavaScript Testing
- **๐ฉ๐ปโ๐ป Developer Ready**: Complete and ready to set-up JavaScript testing solution. Works out of the box for any React project.
- **๐๐ฝ Instant Feedback**: Failed tests run first. Fast interactive mode can switch between running all tests or only test files related to changed files.
- **๐ธ Snapshot Testing**: Jest can [capture snapshots](https://jestjs.io/docs/snapshot-testing) of React trees or other serializable values to simplify UI testing.
Read More: https://jestjs.io/
| packages/jest-cli/README.md | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00017122409190051258,
0.00016855017747730017,
0.00016587626305408776,
0.00016855017747730017,
0.000002673914423212409
] |
{
"id": 6,
"code_window": [
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n",
"// Applies to all tests in this file\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-29.1/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | ---
id: setup-teardown
title: Setup and Teardown
---
Often while writing tests you have some setup work that needs to happen before tests run, and you have some finishing work that needs to happen after tests run. Jest provides helper functions to handle this.
## Repeating Setup For Many Tests
If you have some work you need to do repeatedly for many tests, you can use `beforeEach` and `afterEach`.
For example, let's say that several tests interact with a database of cities. You have a method `initializeCityDatabase()` that must be called before each of these tests, and a method `clearCityDatabase()` that must be called after each of these tests. You can do this with:
```js
beforeEach(() => {
initializeCityDatabase();
});
afterEach(() => {
clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
```
`beforeEach` and `afterEach` can handle asynchronous code in the same ways that [tests can handle asynchronous code](TestingAsyncCode.md) - they can either take a `done` parameter or return a promise. For example, if `initializeCityDatabase()` returned a promise that resolved when the database was initialized, we would want to return that promise:
```js
beforeEach(() => {
return initializeCityDatabase();
});
```
## One-Time Setup
In some cases, you only need to do setup once, at the beginning of a file. This can be especially bothersome when the setup is asynchronous, so you can't do it inline. Jest provides `beforeAll` and `afterAll` to handle this situation.
For example, if both `initializeCityDatabase` and `clearCityDatabase` returned promises, and the city database could be reused between tests, we could change our test code to:
```js
beforeAll(() => {
return initializeCityDatabase();
});
afterAll(() => {
return clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
```
## Scoping
By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.
For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:
```js
// Applies to all tests in this file
beforeEach(() => {
return initializeCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
describe('matching cities to foods', () => {
// Applies only to tests in this describe block
beforeEach(() => {
return initializeFoodDatabase();
});
test('Vienna <3 veal', () => {
expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true);
});
test('San Juan <3 plantains', () => {
expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true);
});
});
```
Note that the top-level `beforeEach` is executed before the `beforeEach` inside the `describe` block. It may help to illustrate the order of execution of all hooks.
```js
beforeAll(() => console.log('1 - beforeAll'));
afterAll(() => console.log('1 - afterAll'));
beforeEach(() => console.log('1 - beforeEach'));
afterEach(() => console.log('1 - afterEach'));
test('', () => console.log('1 - test'));
describe('Scoped / Nested block', () => {
beforeAll(() => console.log('2 - beforeAll'));
afterAll(() => console.log('2 - afterAll'));
beforeEach(() => console.log('2 - beforeEach'));
afterEach(() => console.log('2 - afterEach'));
test('', () => console.log('2 - test'));
});
// 1 - beforeAll
// 1 - beforeEach
// 1 - test
// 1 - afterEach
// 2 - beforeAll
// 1 - beforeEach
// 2 - beforeEach
// 2 - test
// 2 - afterEach
// 1 - afterEach
// 2 - afterAll
// 1 - afterAll
```
## Order of execution of describe and test blocks
Jest executes all describe handlers in a test file _before_ it executes any of the actual tests. This is another reason to do setup and teardown inside `before*` and `after*` handlers rather than inside the describe blocks. Once the describe blocks are complete, by default Jest runs all the tests serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on.
Consider the following illustrative test file and output:
```js
describe('outer', () => {
console.log('describe outer-a');
describe('describe inner 1', () => {
console.log('describe inner 1');
test('test 1', () => {
console.log('test for describe inner 1');
expect(true).toBe(true);
});
});
console.log('describe outer-b');
test('test 1', () => {
console.log('test for describe outer');
expect(true).toBe(true);
});
describe('describe inner 2', () => {
console.log('describe inner 2');
test('test for describe inner 2', () => {
console.log('test for describe inner 2');
expect(false).toBe(false);
});
});
console.log('describe outer-c');
});
// describe outer-a
// describe inner 1
// describe outer-b
// describe inner 2
// describe outer-c
// test for describe inner 1
// test for describe outer
// test for describe inner 2
```
## General Advice
If a test is failing, one of the first things to check should be whether the test is failing when it's the only test that runs. To run only one test with Jest, temporarily change that `test` command to a `test.only`:
```js
test.only('this will be the only test that runs', () => {
expect(true).toBe(false);
});
test('this test will not run', () => {
expect('A').toBe('A');
});
```
If you have a test that often fails when it's run as part of a larger suite, but doesn't fail when you run it alone, it's a good bet that something from a different test is interfering with this one. You can often fix this by clearing some shared state with `beforeEach`. If you're not sure whether some shared state is being modified, you can also try a `beforeEach` that logs data.
| website/versioned_docs/version-26.x/SetupAndTeardown.md | 1 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.991320788860321,
0.0501774325966835,
0.0001686156028881669,
0.00029855885077267885,
0.21591448783874512
] |
{
"id": 6,
"code_window": [
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n",
"// Applies to all tests in this file\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-29.1/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | ---
id: tutorial-react
title: Testing React Apps
---
At Facebook, we use Jest to test [React](https://reactjs.org/) applications.
## Setup
### Setup with Create React App
If you are new to React, we recommend using [Create React App](https://create-react-app.dev/). It is ready to use and [ships with Jest](https://create-react-app.dev/docs/running-tests/#docsNav)! You will only need to add `react-test-renderer` for rendering snapshots.
Run
```bash
yarn add --dev react-test-renderer
```
### Setup without Create React App
If you have an existing application you'll need to install a few packages to make everything work well together. We are using the `babel-jest` package and the `react` babel preset to transform our code inside of the test environment. Also see [using babel](GettingStarted.md#using-babel).
Run
```bash
yarn add --dev jest babel-jest @babel/preset-env @babel/preset-react react-test-renderer
```
Your `package.json` should look something like this (where `<current-version>` is the actual latest version number for the package). Please add the scripts and jest configuration entries:
```json
"dependencies": {
"react": "<current-version>",
"react-dom": "<current-version>"
},
"devDependencies": {
"@babel/preset-env": "<current-version>",
"@babel/preset-react": "<current-version>",
"babel-jest": "<current-version>",
"jest": "<current-version>",
"react-test-renderer": "<current-version>"
},
"scripts": {
"test": "jest"
}
```
```js title="babel.config.js"
module.exports = {
presets: ['@babel/preset-env', '@babel/preset-react'],
};
```
**And you're good to go!**
### Snapshot Testing
Let's create a [snapshot test](SnapshotTesting.md) for a Link component that renders hyperlinks:
```tsx title="Link.js"
import React, {useState} from 'react';
const STATUS = {
HOVERED: 'hovered',
NORMAL: 'normal',
};
const Link = ({page, children}) => {
const [status, setStatus] = useState(STATUS.NORMAL);
const onMouseEnter = () => {
setStatus(STATUS.HOVERED);
};
const onMouseLeave = () => {
setStatus(STATUS.NORMAL);
};
return (
<a
className={status}
href={page || '#'}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
>
{children}
</a>
);
};
export default Link;
```
:::note
Examples are using Function components, but Class components can be tested in the same way. See [React: Function and Class Components](https://reactjs.org/docs/components-and-props.html#function-and-class-components). **Reminders** that with Class components, we expect Jest to be used to test props and not methods directly.
:::
Now let's use React's test renderer and Jest's snapshot feature to interact with the component and capture the rendered output and create a snapshot file:
```tsx title="Link.test.js"
import React from 'react';
import renderer from 'react-test-renderer';
import Link from '../Link';
test('Link changes the class when hovered', () => {
const component = renderer.create(
<Link page="http://www.facebook.com">Facebook</Link>,
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
// manually trigger the callback
tree.props.onMouseEnter();
// re-rendering
tree = component.toJSON();
expect(tree).toMatchSnapshot();
// manually trigger the callback
tree.props.onMouseLeave();
// re-rendering
tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
```
When you run `yarn test` or `jest`, this will produce an output file like this:
```javascript title="__tests__/__snapshots__/Link.test.js.snap"
exports[`Link changes the class when hovered 1`] = `
<a
className="normal"
href="http://www.facebook.com"
onMouseEnter={[Function]}
onMouseLeave={[Function]}>
Facebook
</a>
`;
exports[`Link changes the class when hovered 2`] = `
<a
className="hovered"
href="http://www.facebook.com"
onMouseEnter={[Function]}
onMouseLeave={[Function]}>
Facebook
</a>
`;
exports[`Link changes the class when hovered 3`] = `
<a
className="normal"
href="http://www.facebook.com"
onMouseEnter={[Function]}
onMouseLeave={[Function]}>
Facebook
</a>
`;
```
The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot.
The code for this example is available at [examples/snapshot](https://github.com/facebook/jest/tree/main/examples/snapshot).
#### Snapshot Testing with Mocks, Enzyme and React 16
There's a caveat around snapshot testing when using Enzyme and React 16+. If you mock out a module using the following style:
```js
jest.mock('../SomeDirectory/SomeComponent', () => 'SomeComponent');
```
Then you will see warnings in the console:
```bash
Warning: <SomeComponent /> is using uppercase HTML. Always use lowercase HTML tags in React.
# Or:
Warning: The tag <SomeComponent> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.
```
React 16 triggers these warnings due to how it checks element types, and the mocked module fails these checks. Your options are:
1. Render as text. This way you won't see the props passed to the mock component in the snapshot, but it's straightforward:
```js
jest.mock('./SomeComponent', () => () => 'SomeComponent');
```
2. Render as a custom element. DOM "custom elements" aren't checked for anything and shouldn't fire warnings. They are lowercase and have a dash in the name.
```tsx
jest.mock('./Widget', () => () => <mock-widget />);
```
3. Use `react-test-renderer`. The test renderer doesn't care about element types and will happily accept e.g. `SomeComponent`. You could check snapshots using the test renderer, and check component behavior separately using Enzyme.
4. Disable warnings all together (should be done in your jest setup file):
```js
jest.mock('fbjs/lib/warning', () => require('fbjs/lib/emptyFunction'));
```
This shouldn't normally be your option of choice as useful warnings could be lost. However, in some cases, for example when testing react-native's components we are rendering react-native tags into the DOM and many warnings are irrelevant. Another option is to swizzle the console.warn and suppress specific warnings.
### DOM Testing
If you'd like to assert, and manipulate your rendered components you can use [react-testing-library](https://github.com/kentcdodds/react-testing-library), [Enzyme](https://enzymejs.github.io/enzyme/), or React's [TestUtils](https://reactjs.org/docs/test-utils.html). The following two examples use react-testing-library and Enzyme.
#### react-testing-library
You have to run `yarn add --dev @testing-library/react` to use react-testing-library.
Let's implement a checkbox which swaps between two labels:
```tsx title="CheckboxWithLabel.js"
import React, {useState} from 'react';
const CheckboxWithLabel = ({labelOn, labelOff}) => {
const [isChecked, setIsChecked] = useState(false);
const onChange = () => {
setIsChecked(!isChecked);
};
return (
<label>
<input type="checkbox" checked={isChecked} onChange={onChange} />
{isChecked ? labelOn : labelOff}
</label>
);
};
export default CheckboxWithLabel;
```
```tsx title="__tests__/CheckboxWithLabel-test.js"
import React from 'react';
import {cleanup, fireEvent, render} from '@testing-library/react';
import CheckboxWithLabel from '../CheckboxWithLabel';
// Note: running cleanup afterEach is done automatically for you in @testing-library/[email protected] or higher
// unmount and cleanup DOM after the test is finished.
afterEach(cleanup);
it('CheckboxWithLabel changes the text after click', () => {
const {queryByLabelText, getByLabelText} = render(
<CheckboxWithLabel labelOn="On" labelOff="Off" />,
);
expect(queryByLabelText(/off/i)).toBeTruthy();
fireEvent.click(getByLabelText(/off/i));
expect(queryByLabelText(/on/i)).toBeTruthy();
});
```
The code for this example is available at [examples/react-testing-library](https://github.com/facebook/jest/tree/main/examples/react-testing-library).
#### Enzyme
You have to run `yarn add --dev enzyme` to use Enzyme. If you are using a React version below 15.5.0, you will also need to install `react-addons-test-utils`.
Let's rewrite the test from above using Enzyme instead of react-testing-library. We use Enzyme's [shallow renderer](https://enzymejs.github.io/enzyme/docs/api/shallow.html) in this example.
```tsx title="__tests__/CheckboxWithLabel-test.js"
import React from 'react';
import {shallow} from 'enzyme';
import CheckboxWithLabel from '../CheckboxWithLabel';
test('CheckboxWithLabel changes the text after click', () => {
// Render a checkbox with label in the document
const checkbox = shallow(<CheckboxWithLabel labelOn="On" labelOff="Off" />);
expect(checkbox.text()).toBe('Off');
checkbox.find('input').simulate('change');
expect(checkbox.text()).toBe('On');
});
```
The code for this example is available at [examples/enzyme](https://github.com/facebook/jest/tree/main/examples/enzyme).
### Custom transformers
If you need more advanced functionality, you can also build your own transformer. Instead of using `babel-jest`, here is an example of using `@babel/core`:
```javascript title="custom-transformer.js"
'use strict';
const {transform} = require('@babel/core');
const jestPreset = require('babel-preset-jest');
module.exports = {
process(src, filename) {
const result = transform(src, {
filename,
presets: [jestPreset],
});
return result || src;
},
};
```
Don't forget to install the `@babel/core` and `babel-preset-jest` packages for this example to work.
To make this work with Jest you need to update your Jest configuration with this: `"transform": {"\\.js$": "path/to/custom-transformer.js"}`.
If you'd like to build a transformer with babel support, you can also use `babel-jest` to compose one and pass in your custom configuration options:
```javascript
const babelJest = require('babel-jest');
module.exports = babelJest.createTransformer({
presets: ['my-custom-preset'],
});
```
| website/versioned_docs/version-26.x/TutorialReact.md | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.0001787081710062921,
0.00016815451090224087,
0.00016134782345034182,
0.00016697806131560355,
0.000004295943199394969
] |
{
"id": 6,
"code_window": [
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n",
"// Applies to all tests in this file\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-29.1/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import * as path from 'path';
import {mergeProcessCovs} from '@bcoe/v8-coverage';
import type {EncodedSourceMap} from '@jridgewell/trace-mapping';
import chalk = require('chalk');
import glob = require('glob');
import * as fs from 'graceful-fs';
import istanbulCoverage = require('istanbul-lib-coverage');
import istanbulReport = require('istanbul-lib-report');
import libSourceMaps = require('istanbul-lib-source-maps');
import istanbulReports = require('istanbul-reports');
import v8toIstanbul = require('v8-to-istanbul');
import type {
AggregatedResult,
RuntimeTransformResult,
Test,
TestContext,
TestResult,
V8CoverageResult,
} from '@jest/test-result';
import type {Config} from '@jest/types';
import {clearLine, isInteractive} from 'jest-util';
import {JestWorkerFarm, Worker} from 'jest-worker';
import BaseReporter from './BaseReporter';
import getWatermarks from './getWatermarks';
import type {ReporterContext} from './types';
type CoverageWorker = typeof import('./CoverageWorker');
const FAIL_COLOR = chalk.bold.red;
const RUNNING_TEST_COLOR = chalk.bold.dim;
export default class CoverageReporter extends BaseReporter {
private readonly _context: ReporterContext;
private readonly _coverageMap: istanbulCoverage.CoverageMap;
private readonly _globalConfig: Config.GlobalConfig;
private readonly _sourceMapStore: libSourceMaps.MapStore;
private readonly _v8CoverageResults: Array<V8CoverageResult>;
static readonly filename = __filename;
constructor(globalConfig: Config.GlobalConfig, context: ReporterContext) {
super();
this._context = context;
this._coverageMap = istanbulCoverage.createCoverageMap({});
this._globalConfig = globalConfig;
this._sourceMapStore = libSourceMaps.createSourceMapStore();
this._v8CoverageResults = [];
}
override onTestResult(_test: Test, testResult: TestResult): void {
if (testResult.v8Coverage) {
this._v8CoverageResults.push(testResult.v8Coverage);
return;
}
if (testResult.coverage) {
this._coverageMap.merge(testResult.coverage);
}
}
override async onRunComplete(
testContexts: Set<TestContext>,
aggregatedResults: AggregatedResult,
): Promise<void> {
await this._addUntestedFiles(testContexts);
const {map, reportContext} = await this._getCoverageResult();
try {
const coverageReporters = this._globalConfig.coverageReporters || [];
if (!this._globalConfig.useStderr && coverageReporters.length < 1) {
coverageReporters.push('text-summary');
}
coverageReporters.forEach(reporter => {
let additionalOptions = {};
if (Array.isArray(reporter)) {
[reporter, additionalOptions] = reporter;
}
istanbulReports
.create(reporter, {
maxCols: process.stdout.columns || Infinity,
...additionalOptions,
})
.execute(reportContext);
});
aggregatedResults.coverageMap = map;
} catch (e: any) {
console.error(
chalk.red(`
Failed to write coverage reports:
ERROR: ${e.toString()}
STACK: ${e.stack}
`),
);
}
this._checkThreshold(map);
}
private async _addUntestedFiles(
testContexts: Set<TestContext>,
): Promise<void> {
const files: Array<{config: Config.ProjectConfig; path: string}> = [];
testContexts.forEach(context => {
const config = context.config;
if (
this._globalConfig.collectCoverageFrom &&
this._globalConfig.collectCoverageFrom.length
) {
context.hasteFS
.matchFilesWithGlob(
this._globalConfig.collectCoverageFrom,
config.rootDir,
)
.forEach(filePath =>
files.push({
config,
path: filePath,
}),
);
}
});
if (!files.length) {
return;
}
if (isInteractive) {
process.stderr.write(
RUNNING_TEST_COLOR('Running coverage on untested files...'),
);
}
let worker:
| JestWorkerFarm<CoverageWorker>
| typeof import('./CoverageWorker');
if (this._globalConfig.maxWorkers <= 1) {
worker = require('./CoverageWorker');
} else {
worker = new Worker(require.resolve('./CoverageWorker'), {
exposedMethods: ['worker'],
forkOptions: {serialization: 'json'},
maxRetries: 2,
numWorkers: this._globalConfig.maxWorkers,
}) as JestWorkerFarm<CoverageWorker>;
}
const instrumentation = files.map(async fileObj => {
const filename = fileObj.path;
const config = fileObj.config;
const hasCoverageData = this._v8CoverageResults.some(v8Res =>
v8Res.some(innerRes => innerRes.result.url === filename),
);
if (
!hasCoverageData &&
!this._coverageMap.data[filename] &&
'worker' in worker
) {
try {
const result = await worker.worker({
config,
context: {
changedFiles:
this._context.changedFiles &&
Array.from(this._context.changedFiles),
sourcesRelatedToTestsInChangedFiles:
this._context.sourcesRelatedToTestsInChangedFiles &&
Array.from(this._context.sourcesRelatedToTestsInChangedFiles),
},
globalConfig: this._globalConfig,
path: filename,
});
if (result) {
if (result.kind === 'V8Coverage') {
this._v8CoverageResults.push([
{codeTransformResult: undefined, result: result.result},
]);
} else {
this._coverageMap.addFileCoverage(result.coverage);
}
}
} catch (error: any) {
console.error(
chalk.red(
[
`Failed to collect coverage from ${filename}`,
`ERROR: ${error.message}`,
`STACK: ${error.stack}`,
].join('\n'),
),
);
}
}
});
try {
await Promise.all(instrumentation);
} catch {
// Do nothing; errors were reported earlier to the console.
}
if (isInteractive) {
clearLine(process.stderr);
}
if (worker && 'end' in worker && typeof worker.end === 'function') {
await worker.end();
}
}
private _checkThreshold(map: istanbulCoverage.CoverageMap) {
const {coverageThreshold} = this._globalConfig;
if (coverageThreshold) {
function check(
name: string,
thresholds: Config.CoverageThresholdValue,
actuals: istanbulCoverage.CoverageSummaryData,
) {
return (
['statements', 'branches', 'lines', 'functions'] as Array<
keyof istanbulCoverage.CoverageSummaryData
>
).reduce<Array<string>>((errors, key) => {
const actual = actuals[key].pct;
const actualUncovered = actuals[key].total - actuals[key].covered;
const threshold = thresholds[key];
if (threshold !== undefined) {
if (threshold < 0) {
if (threshold * -1 < actualUncovered) {
errors.push(
`Jest: Uncovered count for ${key} (${actualUncovered}) ` +
`exceeds ${name} threshold (${-1 * threshold})`,
);
}
} else if (actual < threshold) {
errors.push(
`Jest: "${name}" coverage threshold for ${key} (${threshold}%) not met: ${actual}%`,
);
}
}
return errors;
}, []);
}
const THRESHOLD_GROUP_TYPES = {
GLOB: 'glob',
GLOBAL: 'global',
PATH: 'path',
};
const coveredFiles = map.files();
const thresholdGroups = Object.keys(coverageThreshold);
const groupTypeByThresholdGroup: {[index: string]: string} = {};
const filesByGlob: {[index: string]: Array<string>} = {};
const coveredFilesSortedIntoThresholdGroup = coveredFiles.reduce<
Array<[string, string | undefined]>
>((files, file) => {
const pathOrGlobMatches = thresholdGroups.reduce<
Array<[string, string]>
>((agg, thresholdGroup) => {
// Preserve trailing slash, but not required if root dir
// See https://github.com/facebook/jest/issues/12703
const resolvedThresholdGroup = path.resolve(thresholdGroup);
const suffix =
(thresholdGroup.endsWith(path.sep) ||
(process.platform === 'win32' && thresholdGroup.endsWith('/'))) &&
!resolvedThresholdGroup.endsWith(path.sep)
? path.sep
: '';
const absoluteThresholdGroup = `${resolvedThresholdGroup}${suffix}`;
// The threshold group might be a path:
if (file.indexOf(absoluteThresholdGroup) === 0) {
groupTypeByThresholdGroup[thresholdGroup] =
THRESHOLD_GROUP_TYPES.PATH;
return agg.concat([[file, thresholdGroup]]);
}
// If the threshold group is not a path it might be a glob:
// Note: glob.sync is slow. By memoizing the files matching each glob
// (rather than recalculating it for each covered file) we save a tonne
// of execution time.
if (filesByGlob[absoluteThresholdGroup] === undefined) {
filesByGlob[absoluteThresholdGroup] = glob
.sync(absoluteThresholdGroup)
.map(filePath => path.resolve(filePath));
}
if (filesByGlob[absoluteThresholdGroup].indexOf(file) > -1) {
groupTypeByThresholdGroup[thresholdGroup] =
THRESHOLD_GROUP_TYPES.GLOB;
return agg.concat([[file, thresholdGroup]]);
}
return agg;
}, []);
if (pathOrGlobMatches.length > 0) {
return files.concat(pathOrGlobMatches);
}
// Neither a glob or a path? Toss it in global if there's a global threshold:
if (thresholdGroups.indexOf(THRESHOLD_GROUP_TYPES.GLOBAL) > -1) {
groupTypeByThresholdGroup[THRESHOLD_GROUP_TYPES.GLOBAL] =
THRESHOLD_GROUP_TYPES.GLOBAL;
return files.concat([[file, THRESHOLD_GROUP_TYPES.GLOBAL]]);
}
// A covered file that doesn't have a threshold:
return files.concat([[file, undefined]]);
}, []);
const getFilesInThresholdGroup = (thresholdGroup: string) =>
coveredFilesSortedIntoThresholdGroup
.filter(fileAndGroup => fileAndGroup[1] === thresholdGroup)
.map(fileAndGroup => fileAndGroup[0]);
function combineCoverage(filePaths: Array<string>) {
return filePaths
.map(filePath => map.fileCoverageFor(filePath))
.reduce(
(
combinedCoverage:
| istanbulCoverage.CoverageSummary
| null
| undefined,
nextFileCoverage: istanbulCoverage.FileCoverage,
) => {
if (combinedCoverage === undefined || combinedCoverage === null) {
return nextFileCoverage.toSummary();
}
return combinedCoverage.merge(nextFileCoverage.toSummary());
},
undefined,
);
}
let errors: Array<string> = [];
thresholdGroups.forEach(thresholdGroup => {
switch (groupTypeByThresholdGroup[thresholdGroup]) {
case THRESHOLD_GROUP_TYPES.GLOBAL: {
const coverage = combineCoverage(
getFilesInThresholdGroup(THRESHOLD_GROUP_TYPES.GLOBAL),
);
if (coverage) {
errors = errors.concat(
check(
thresholdGroup,
coverageThreshold[thresholdGroup],
coverage,
),
);
}
break;
}
case THRESHOLD_GROUP_TYPES.PATH: {
const coverage = combineCoverage(
getFilesInThresholdGroup(thresholdGroup),
);
if (coverage) {
errors = errors.concat(
check(
thresholdGroup,
coverageThreshold[thresholdGroup],
coverage,
),
);
}
break;
}
case THRESHOLD_GROUP_TYPES.GLOB:
getFilesInThresholdGroup(thresholdGroup).forEach(
fileMatchingGlob => {
errors = errors.concat(
check(
fileMatchingGlob,
coverageThreshold[thresholdGroup],
map.fileCoverageFor(fileMatchingGlob).toSummary(),
),
);
},
);
break;
default:
// If the file specified by path is not found, error is returned.
if (thresholdGroup !== THRESHOLD_GROUP_TYPES.GLOBAL) {
errors = errors.concat(
`Jest: Coverage data for ${thresholdGroup} was not found.`,
);
}
// Sometimes all files in the coverage data are matched by
// PATH and GLOB threshold groups in which case, don't error when
// the global threshold group doesn't match any files.
}
});
errors = errors.filter(
err => err !== undefined && err !== null && err.length > 0,
);
if (errors.length > 0) {
this.log(`${FAIL_COLOR(errors.join('\n'))}`);
this._setError(new Error(errors.join('\n')));
}
}
}
private async _getCoverageResult(): Promise<{
map: istanbulCoverage.CoverageMap;
reportContext: istanbulReport.Context;
}> {
if (this._globalConfig.coverageProvider === 'v8') {
const mergedCoverages = mergeProcessCovs(
this._v8CoverageResults.map(cov => ({result: cov.map(r => r.result)})),
);
const fileTransforms = new Map<string, RuntimeTransformResult>();
this._v8CoverageResults.forEach(res =>
res.forEach(r => {
if (r.codeTransformResult && !fileTransforms.has(r.result.url)) {
fileTransforms.set(r.result.url, r.codeTransformResult);
}
}),
);
const transformedCoverage = await Promise.all(
mergedCoverages.result.map(async res => {
const fileTransform = fileTransforms.get(res.url);
let sourcemapContent: EncodedSourceMap | undefined = undefined;
if (
fileTransform?.sourceMapPath &&
fs.existsSync(fileTransform.sourceMapPath)
) {
sourcemapContent = JSON.parse(
fs.readFileSync(fileTransform.sourceMapPath, 'utf8'),
);
}
const converter = v8toIstanbul(
res.url,
fileTransform?.wrapperLength ?? 0,
fileTransform && sourcemapContent
? {
originalSource: fileTransform.originalCode,
source: fileTransform.code,
sourceMap: {
sourcemap: {file: res.url, ...sourcemapContent},
},
}
: {source: fs.readFileSync(res.url, 'utf8')},
);
await converter.load();
converter.applyCoverage(res.functions);
const istanbulData = converter.toIstanbul();
return istanbulData;
}),
);
const map = istanbulCoverage.createCoverageMap({});
transformedCoverage.forEach(res => map.merge(res));
const reportContext = istanbulReport.createContext({
coverageMap: map,
dir: this._globalConfig.coverageDirectory,
watermarks: getWatermarks(this._globalConfig),
});
return {map, reportContext};
}
const map = await this._sourceMapStore.transformCoverage(this._coverageMap);
const reportContext = istanbulReport.createContext({
coverageMap: map,
dir: this._globalConfig.coverageDirectory,
sourceFinder: this._sourceMapStore.sourceFinder,
watermarks: getWatermarks(this._globalConfig),
});
return {map, reportContext};
}
}
| packages/jest-reporters/src/CoverageReporter.ts | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00018778828962240368,
0.00017275969730690122,
0.00016363157192245126,
0.00017286519869230688,
0.000004361301762401126
] |
{
"id": 6,
"code_window": [
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n",
"// Applies to all tests in this file\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-29.1/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const {getTruthy} = require('../index');
test('test', () => {
expect(getTruthy()).toBeTruthy();
beforeEach(() => {
// nothing to see here
});
});
| e2e/nested-test-definitions/__tests__/nestedHookInTest.js | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00017611277871765196,
0.00017068872693926096,
0.00016526466060895473,
0.00017068872693926096,
0.000005424059054348618
] |
{
"id": 7,
"code_window": [
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-29.2/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | ---
id: setup-teardown
title: Setup and Teardown
---
Often while writing tests you have some setup work that needs to happen before tests run, and you have some finishing work that needs to happen after tests run. Jest provides helper functions to handle this.
## Repeating Setup
If you have some work you need to do repeatedly for many tests, you can use `beforeEach` and `afterEach` hooks.
For example, let's say that several tests interact with a database of cities. You have a method `initializeCityDatabase()` that must be called before each of these tests, and a method `clearCityDatabase()` that must be called after each of these tests. You can do this with:
```js
beforeEach(() => {
initializeCityDatabase();
});
afterEach(() => {
clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
```
`beforeEach` and `afterEach` can handle asynchronous code in the same ways that [tests can handle asynchronous code](TestingAsyncCode.md) - they can either take a `done` parameter or return a promise. For example, if `initializeCityDatabase()` returned a promise that resolved when the database was initialized, we would want to return that promise:
```js
beforeEach(() => {
return initializeCityDatabase();
});
```
## One-Time Setup
In some cases, you only need to do setup once, at the beginning of a file. This can be especially bothersome when the setup is asynchronous, so you can't do it inline. Jest provides `beforeAll` and `afterAll` hooks to handle this situation.
For example, if both `initializeCityDatabase()` and `clearCityDatabase()` returned promises, and the city database could be reused between tests, we could change our test code to:
```js
beforeAll(() => {
return initializeCityDatabase();
});
afterAll(() => {
return clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
```
## Scoping
By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.
For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:
```js
// Applies to all tests in this file
beforeEach(() => {
return initializeCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
describe('matching cities to foods', () => {
// Applies only to tests in this describe block
beforeEach(() => {
return initializeFoodDatabase();
});
test('Vienna <3 veal', () => {
expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true);
});
test('San Juan <3 plantains', () => {
expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true);
});
});
```
Note that the top-level `beforeEach` is executed before the `beforeEach` inside the `describe` block. It may help to illustrate the order of execution of all hooks.
```js
beforeAll(() => console.log('1 - beforeAll'));
afterAll(() => console.log('1 - afterAll'));
beforeEach(() => console.log('1 - beforeEach'));
afterEach(() => console.log('1 - afterEach'));
test('', () => console.log('1 - test'));
describe('Scoped / Nested block', () => {
beforeAll(() => console.log('2 - beforeAll'));
afterAll(() => console.log('2 - afterAll'));
beforeEach(() => console.log('2 - beforeEach'));
afterEach(() => console.log('2 - afterEach'));
test('', () => console.log('2 - test'));
});
// 1 - beforeAll
// 1 - beforeEach
// 1 - test
// 1 - afterEach
// 2 - beforeAll
// 1 - beforeEach
// 2 - beforeEach
// 2 - test
// 2 - afterEach
// 1 - afterEach
// 2 - afterAll
// 1 - afterAll
```
## Order of Execution
Jest executes all describe handlers in a test file _before_ it executes any of the actual tests. This is another reason to do setup and teardown inside `before*` and `after*` handlers rather than inside the `describe` blocks. Once the `describe` blocks are complete, by default Jest runs all the tests serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on.
Consider the following illustrative test file and output:
```js
describe('describe outer', () => {
console.log('describe outer-a');
describe('describe inner 1', () => {
console.log('describe inner 1');
test('test 1', () => console.log('test 1'));
});
console.log('describe outer-b');
test('test 2', () => console.log('test 2'));
describe('describe inner 2', () => {
console.log('describe inner 2');
test('test 3', () => console.log('test 3'));
});
console.log('describe outer-c');
});
// describe outer-a
// describe inner 1
// describe outer-b
// describe inner 2
// describe outer-c
// test 1
// test 2
// test 3
```
Just like the `describe` and `test` blocks Jest calls the `before*` and `after*` hooks in the order of declaration. Note that the `after*` hooks of the enclosing scope are called first. For example, here is how you can set up and tear down resources which depend on each other:
```js
beforeEach(() => console.log('connection setup'));
beforeEach(() => console.log('database setup'));
afterEach(() => console.log('database teardown'));
afterEach(() => console.log('connection teardown'));
test('test 1', () => console.log('test 1'));
describe('extra', () => {
beforeEach(() => console.log('extra database setup'));
afterEach(() => console.log('extra database teardown'));
test('test 2', () => console.log('test 2'));
});
// connection setup
// database setup
// test 1
// database teardown
// connection teardown
// connection setup
// database setup
// extra database setup
// test 2
// extra database teardown
// database teardown
// connection teardown
```
:::note
If you are using `jasmine2` test runner, take into account that it calls the `after*` hooks in the reverse order of declaration. To have identical output, the above example should be altered like this:
```diff
beforeEach(() => console.log('connection setup'));
+ afterEach(() => console.log('connection teardown'));
beforeEach(() => console.log('database setup'));
+ afterEach(() => console.log('database teardown'));
- afterEach(() => console.log('database teardown'));
- afterEach(() => console.log('connection teardown'));
// ...
```
:::
## General Advice
If a test is failing, one of the first things to check should be whether the test is failing when it's the only test that runs. To run only one test with Jest, temporarily change that `test` command to a `test.only`:
```js
test.only('this will be the only test that runs', () => {
expect(true).toBe(false);
});
test('this test will not run', () => {
expect('A').toBe('A');
});
```
If you have a test that often fails when it's run as part of a larger suite, but doesn't fail when you run it alone, it's a good bet that something from a different test is interfering with this one. You can often fix this by clearing some shared state with `beforeEach`. If you're not sure whether some shared state is being modified, you can also try a `beforeEach` that logs data.
| website/versioned_docs/version-28.x/SetupAndTeardown.md | 1 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.9928128123283386,
0.042388830333948135,
0.00016455691365990788,
0.00020304587087593973,
0.19818533957004547
] |
{
"id": 7,
"code_window": [
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-29.2/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | {
"jest": {
"testEnvironment": "node",
"setupFiles": [
"<rootDir>/setup.js"
]
}
}
| e2e/override-globals/package.json | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00016909540863707662,
0.00016909540863707662,
0.00016909540863707662,
0.00016909540863707662,
0
] |
{
"id": 7,
"code_window": [
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-29.2/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | packages/jest-runtime/src/__tests__/test_root/NativeModule.node | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00016798669821582735,
0.00016798669821582735,
0.00016798669821582735,
0.00016798669821582735,
0
] |
|
{
"id": 7,
"code_window": [
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-29.2/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function invalidTeardownWithNamedExport(jestConfig): void {
console.log(jestConfig.testPathPattern);
}
export {invalidTeardownWithNamedExport};
| e2e/global-teardown/invalidTeardownWithNamedExport.js | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00017663714243099093,
0.00017373458831571043,
0.00017083204875234514,
0.00017373458831571043,
0.000002902546839322895
] |
{
"id": 8,
"code_window": [
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n",
"// Applies to all tests in this file\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-29.3/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | ---
id: setup-teardown
title: Setup and Teardown
---
Often while writing tests you have some setup work that needs to happen before tests run, and you have some finishing work that needs to happen after tests run. Jest provides helper functions to handle this.
## Repeating Setup
If you have some work you need to do repeatedly for many tests, you can use `beforeEach` and `afterEach` hooks.
For example, let's say that several tests interact with a database of cities. You have a method `initializeCityDatabase()` that must be called before each of these tests, and a method `clearCityDatabase()` that must be called after each of these tests. You can do this with:
```js
beforeEach(() => {
initializeCityDatabase();
});
afterEach(() => {
clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
```
`beforeEach` and `afterEach` can handle asynchronous code in the same ways that [tests can handle asynchronous code](TestingAsyncCode.md) - they can either take a `done` parameter or return a promise. For example, if `initializeCityDatabase()` returned a promise that resolved when the database was initialized, we would want to return that promise:
```js
beforeEach(() => {
return initializeCityDatabase();
});
```
## One-Time Setup
In some cases, you only need to do setup once, at the beginning of a file. This can be especially bothersome when the setup is asynchronous, so you can't do it inline. Jest provides `beforeAll` and `afterAll` hooks to handle this situation.
For example, if both `initializeCityDatabase()` and `clearCityDatabase()` returned promises, and the city database could be reused between tests, we could change our test code to:
```js
beforeAll(() => {
return initializeCityDatabase();
});
afterAll(() => {
return clearCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
```
## Scoping
By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.
For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:
```js
// Applies to all tests in this file
beforeEach(() => {
return initializeCityDatabase();
});
test('city database has Vienna', () => {
expect(isCity('Vienna')).toBeTruthy();
});
test('city database has San Juan', () => {
expect(isCity('San Juan')).toBeTruthy();
});
describe('matching cities to foods', () => {
// Applies only to tests in this describe block
beforeEach(() => {
return initializeFoodDatabase();
});
test('Vienna <3 veal', () => {
expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true);
});
test('San Juan <3 plantains', () => {
expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true);
});
});
```
Note that the top-level `beforeEach` is executed before the `beforeEach` inside the `describe` block. It may help to illustrate the order of execution of all hooks.
```js
beforeAll(() => console.log('1 - beforeAll'));
afterAll(() => console.log('1 - afterAll'));
beforeEach(() => console.log('1 - beforeEach'));
afterEach(() => console.log('1 - afterEach'));
test('', () => console.log('1 - test'));
describe('Scoped / Nested block', () => {
beforeAll(() => console.log('2 - beforeAll'));
afterAll(() => console.log('2 - afterAll'));
beforeEach(() => console.log('2 - beforeEach'));
afterEach(() => console.log('2 - afterEach'));
test('', () => console.log('2 - test'));
});
// 1 - beforeAll
// 1 - beforeEach
// 1 - test
// 1 - afterEach
// 2 - beforeAll
// 1 - beforeEach
// 2 - beforeEach
// 2 - test
// 2 - afterEach
// 1 - afterEach
// 2 - afterAll
// 1 - afterAll
```
## Order of Execution
Jest executes all describe handlers in a test file _before_ it executes any of the actual tests. This is another reason to do setup and teardown inside `before*` and `after*` handlers rather than inside the `describe` blocks. Once the `describe` blocks are complete, by default Jest runs all the tests serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on.
Consider the following illustrative test file and output:
```js
describe('describe outer', () => {
console.log('describe outer-a');
describe('describe inner 1', () => {
console.log('describe inner 1');
test('test 1', () => console.log('test 1'));
});
console.log('describe outer-b');
test('test 2', () => console.log('test 2'));
describe('describe inner 2', () => {
console.log('describe inner 2');
test('test 3', () => console.log('test 3'));
});
console.log('describe outer-c');
});
// describe outer-a
// describe inner 1
// describe outer-b
// describe inner 2
// describe outer-c
// test 1
// test 2
// test 3
```
Just like the `describe` and `test` blocks Jest calls the `before*` and `after*` hooks in the order of declaration. Note that the `after*` hooks of the enclosing scope are called first. For example, here is how you can set up and tear down resources which depend on each other:
```js
beforeEach(() => console.log('connection setup'));
beforeEach(() => console.log('database setup'));
afterEach(() => console.log('database teardown'));
afterEach(() => console.log('connection teardown'));
test('test 1', () => console.log('test 1'));
describe('extra', () => {
beforeEach(() => console.log('extra database setup'));
afterEach(() => console.log('extra database teardown'));
test('test 2', () => console.log('test 2'));
});
// connection setup
// database setup
// test 1
// database teardown
// connection teardown
// connection setup
// database setup
// extra database setup
// test 2
// extra database teardown
// database teardown
// connection teardown
```
:::note
If you are using `jasmine2` test runner, take into account that it calls the `after*` hooks in the reverse order of declaration. To have identical output, the above example should be altered like this:
```diff
beforeEach(() => console.log('connection setup'));
+ afterEach(() => console.log('connection teardown'));
beforeEach(() => console.log('database setup'));
+ afterEach(() => console.log('database teardown'));
- afterEach(() => console.log('database teardown'));
- afterEach(() => console.log('connection teardown'));
// ...
```
:::
## General Advice
If a test is failing, one of the first things to check should be whether the test is failing when it's the only test that runs. To run only one test with Jest, temporarily change that `test` command to a `test.only`:
```js
test.only('this will be the only test that runs', () => {
expect(true).toBe(false);
});
test('this test will not run', () => {
expect('A').toBe('A');
});
```
If you have a test that often fails when it's run as part of a larger suite, but doesn't fail when you run it alone, it's a good bet that something from a different test is interfering with this one. You can often fix this by clearing some shared state with `beforeEach`. If you're not sure whether some shared state is being modified, you can also try a `beforeEach` that logs data.
| website/versioned_docs/version-29.2/SetupAndTeardown.md | 1 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.9886638522148132,
0.04256672039628029,
0.00016381061868742108,
0.00024221223429776728,
0.19728511571884155
] |
{
"id": 8,
"code_window": [
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n",
"// Applies to all tests in this file\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-29.3/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | **/__mocks__/**
**/__tests__/**
__typetests__
src
tsconfig.json
tsconfig.tsbuildinfo
api-extractor.json
| packages/jest-cli/.npmignore | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00016829516971483827,
0.00016829516971483827,
0.00016829516971483827,
0.00016829516971483827,
0
] |
{
"id": 8,
"code_window": [
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n",
"// Applies to all tests in this file\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-29.3/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
it('passes', () => {
expect(10).toBe(10);
});
it('fails', () => {
expect(10).toBe(101);
});
it.skip('skips', () => {
expect(10).toBe(101);
});
it.todo('todo');
| e2e/test-todo/__tests__/statuses.test.js | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.00017593000666238368,
0.00017259088053833693,
0.00016783250612206757,
0.00017401008517481387,
0.000003454756779319723
] |
{
"id": 8,
"code_window": [
"```\n",
"\n",
"## Scoping\n",
"\n",
"By default, the `beforeAll` and `afterAll` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `beforeAll` and `afterAll` blocks only apply to the tests within that `describe` block.\n",
"\n",
"For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests:\n",
"\n",
"```js\n",
"// Applies to all tests in this file\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block.\n"
],
"file_path": "website/versioned_docs/version-29.3/SetupAndTeardown.md",
"type": "replace",
"edit_start_line_idx": 65
} | {
"jest": {
"testEnvironment": "node"
}
}
| e2e/auto-clear-mocks/without-auto-clear/package.json | 0 | https://github.com/jestjs/jest/commit/6a2bb4e26cb22c7af952a945a8236c1128d3fbe8 | [
0.0001705400791252032,
0.0001705400791252032,
0.0001705400791252032,
0.0001705400791252032,
0
] |
{
"id": 0,
"code_window": [
" * Use of this source code is governed by an MIT-style license that can be\n",
" * found in the LICENSE file at https://angular.io/license\n",
" */\n",
"\n",
"import chalk from 'chalk';\n",
"import {Arguments, Argv} from 'yargs';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "dev-infra/pr/merge/cli.ts",
"type": "replace",
"edit_start_line_idx": 8
} | /**
* @license
* Copyright Google LLC 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 chalk from 'chalk';
import {getRepoBaseDir} from '../../utils/config';
import {promptConfirm} from '../../utils/console';
import {loadAndValidateConfig, MergeConfigWithRemote} from './config';
import {GithubApiRequestError} from './git';
import {MergeResult, MergeStatus, PullRequestMergeTask} from './task';
/** URL to the Github page where personal access tokens can be generated. */
export const GITHUB_TOKEN_GENERATE_URL = `https://github.com/settings/tokens`;
/**
* Merges a given pull request based on labels configured in the given merge configuration.
* Pull requests can be merged with different strategies such as the Github API merge
* strategy, or the local autosquash strategy. Either strategy has benefits and downsides.
* More information on these strategies can be found in their dedicated strategy classes.
*
* See {@link GithubApiMergeStrategy} and {@link AutosquashMergeStrategy}
*
* @param prNumber Number of the pull request that should be merged.
* @param githubToken Github token used for merging (i.e. fetching and pushing)
* @param projectRoot Path to the local Git project that is used for merging.
* @param config Configuration for merging pull requests.
*/
export async function mergePullRequest(
prNumber: number, githubToken: string, projectRoot: string = getRepoBaseDir(),
config?: MergeConfigWithRemote) {
// If no explicit configuration has been specified, we load and validate
// the configuration from the shared dev-infra configuration.
if (config === undefined) {
const {config: _config, errors} = loadAndValidateConfig();
if (errors) {
console.error(chalk.red('Invalid configuration:'));
errors.forEach(desc => console.error(chalk.yellow(` - ${desc}`)));
process.exit(1);
}
config = _config!;
}
const api = new PullRequestMergeTask(projectRoot, config, githubToken);
// Perform the merge. Force mode can be activated through a command line flag.
// Alternatively, if the merge fails with non-fatal failures, the script
// will prompt whether it should rerun in force mode.
if (!await performMerge(false)) {
process.exit(1);
}
/** Performs the merge and returns whether it was successful or not. */
async function performMerge(ignoreFatalErrors: boolean): Promise<boolean> {
try {
const result = await api.merge(prNumber, ignoreFatalErrors);
return await handleMergeResult(result, ignoreFatalErrors);
} catch (e) {
// Catch errors to the Github API for invalid requests. We want to
// exit the script with a better explanation of the error.
if (e instanceof GithubApiRequestError && e.status === 401) {
console.error(chalk.red('Github API request failed. ' + e.message));
console.error(chalk.yellow('Please ensure that your provided token is valid.'));
console.error(chalk.yellow(`You can generate a token here: ${GITHUB_TOKEN_GENERATE_URL}`));
process.exit(1);
}
throw e;
}
}
/**
* Prompts whether the specified pull request should be forcibly merged. If so, merges
* the specified pull request forcibly (ignoring non-critical failures).
* @returns Whether the specified pull request has been forcibly merged.
*/
async function promptAndPerformForceMerge(): Promise<boolean> {
if (await promptConfirm('Do you want to forcibly proceed with merging?')) {
// Perform the merge in force mode. This means that non-fatal failures
// are ignored and the merge continues.
return performMerge(true);
}
return false;
}
/**
* Handles the merge result by printing console messages, exiting the process
* based on the result, or by restarting the merge if force mode has been enabled.
* @returns Whether the merge was successful or not.
*/
async function handleMergeResult(result: MergeResult, disableForceMergePrompt = false) {
const {failure, status} = result;
const canForciblyMerge = failure && failure.nonFatal;
switch (status) {
case MergeStatus.SUCCESS:
console.info(chalk.green(`Successfully merged the pull request: ${prNumber}`));
return true;
case MergeStatus.DIRTY_WORKING_DIR:
console.error(chalk.red(
`Local working repository not clean. Please make sure there are ` +
`no uncommitted changes.`));
return false;
case MergeStatus.UNKNOWN_GIT_ERROR:
console.error(chalk.red(
'An unknown Git error has been thrown. Please check the output ' +
'above for details.'));
return false;
case MergeStatus.FAILED:
console.error(chalk.yellow(`Could not merge the specified pull request.`));
console.error(chalk.red(failure!.message));
if (canForciblyMerge && !disableForceMergePrompt) {
console.info();
console.info(chalk.yellow('The pull request above failed due to non-critical errors.'));
console.info(chalk.yellow(`This error can be forcibly ignored if desired.`));
return await promptAndPerformForceMerge();
}
return false;
default:
throw Error(`Unexpected merge result: ${status}`);
}
}
}
| dev-infra/pr/merge/index.ts | 1 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.0006464727339334786,
0.00027815077919512987,
0.00016674019570928067,
0.00017611462681088597,
0.00016081510693766177
] |
{
"id": 0,
"code_window": [
" * Use of this source code is governed by an MIT-style license that can be\n",
" * found in the LICENSE file at https://angular.io/license\n",
" */\n",
"\n",
"import chalk from 'chalk';\n",
"import {Arguments, Argv} from 'yargs';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "dev-infra/pr/merge/cli.ts",
"type": "replace",
"edit_start_line_idx": 8
} | /**
* @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
*/
// rxjs/operators
(function(factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
} else if (typeof define === 'function' && define.amd) {
define('rxjs/operators', ['exports', 'rxjs'], factory);
}
})(function(exports, rxjs) {
'use strict';
Object.keys(rxjs.operators).forEach(function(key) { exports[key] = rxjs.operators[key]; });
Object.defineProperty(exports, '__esModule', {value: true});
});
// rxjs/testing
(function(factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
} else if (typeof define === 'function' && define.amd) {
define('rxjs/testing', ['exports', 'rxjs'], factory);
}
})(function(exports, rxjs) {
'use strict';
Object.keys(rxjs.testing).forEach(function(key) { exports[key] = rxjs.testing[key]; });
Object.defineProperty(exports, '__esModule', {value: true});
});
| integration/bazel/src/rxjs_shims.js | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.0001758867292664945,
0.00017250972450710833,
0.0001648155302973464,
0.0001746683265082538,
0.000004488995728024747
] |
{
"id": 0,
"code_window": [
" * Use of this source code is governed by an MIT-style license that can be\n",
" * found in the LICENSE file at https://angular.io/license\n",
" */\n",
"\n",
"import chalk from 'chalk';\n",
"import {Arguments, Argv} from 'yargs';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "dev-infra/pr/merge/cli.ts",
"type": "replace",
"edit_start_line_idx": 8
} | import { browser, by, element } from 'protractor';
export class AppPage {
navigateTo() {
return browser.get(browser.baseUrl) as Promise<any>;
}
getTitleText() {
return element(by.css('app-root .content span')).getText() as Promise<string>;
}
}
| integration/cli-hello-world/e2e/src/app.po.ts | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.00018091435777023435,
0.0001792640978237614,
0.00017761383787728846,
0.0001792640978237614,
0.0000016502599464729428
] |
{
"id": 0,
"code_window": [
" * Use of this source code is governed by an MIT-style license that can be\n",
" * found in the LICENSE file at https://angular.io/license\n",
" */\n",
"\n",
"import chalk from 'chalk';\n",
"import {Arguments, Argv} from 'yargs';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "dev-infra/pr/merge/cli.ts",
"type": "replace",
"edit_start_line_idx": 8
} | // #docregion
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent { }
| aio/content/examples/lifecycle-hooks/src/app/app.component.ts | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.00016709911869838834,
0.00016709911869838834,
0.00016709911869838834,
0.00016709911869838834,
0
] |
{
"id": 1,
"code_window": [
"import {Arguments, Argv} from 'yargs';\n",
"import {GITHUB_TOKEN_GENERATE_URL, mergePullRequest} from './index';\n",
"\n",
"/** Builds the options for the merge command. */\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"import {error, red, yellow} from '../../utils/console';\n",
"\n"
],
"file_path": "dev-infra/pr/merge/cli.ts",
"type": "add",
"edit_start_line_idx": 10
} | /**
* @license
* Copyright Google LLC 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 chalk from 'chalk';
import {getRepoBaseDir} from '../../utils/config';
import {promptConfirm} from '../../utils/console';
import {loadAndValidateConfig, MergeConfigWithRemote} from './config';
import {GithubApiRequestError} from './git';
import {MergeResult, MergeStatus, PullRequestMergeTask} from './task';
/** URL to the Github page where personal access tokens can be generated. */
export const GITHUB_TOKEN_GENERATE_URL = `https://github.com/settings/tokens`;
/**
* Merges a given pull request based on labels configured in the given merge configuration.
* Pull requests can be merged with different strategies such as the Github API merge
* strategy, or the local autosquash strategy. Either strategy has benefits and downsides.
* More information on these strategies can be found in their dedicated strategy classes.
*
* See {@link GithubApiMergeStrategy} and {@link AutosquashMergeStrategy}
*
* @param prNumber Number of the pull request that should be merged.
* @param githubToken Github token used for merging (i.e. fetching and pushing)
* @param projectRoot Path to the local Git project that is used for merging.
* @param config Configuration for merging pull requests.
*/
export async function mergePullRequest(
prNumber: number, githubToken: string, projectRoot: string = getRepoBaseDir(),
config?: MergeConfigWithRemote) {
// If no explicit configuration has been specified, we load and validate
// the configuration from the shared dev-infra configuration.
if (config === undefined) {
const {config: _config, errors} = loadAndValidateConfig();
if (errors) {
console.error(chalk.red('Invalid configuration:'));
errors.forEach(desc => console.error(chalk.yellow(` - ${desc}`)));
process.exit(1);
}
config = _config!;
}
const api = new PullRequestMergeTask(projectRoot, config, githubToken);
// Perform the merge. Force mode can be activated through a command line flag.
// Alternatively, if the merge fails with non-fatal failures, the script
// will prompt whether it should rerun in force mode.
if (!await performMerge(false)) {
process.exit(1);
}
/** Performs the merge and returns whether it was successful or not. */
async function performMerge(ignoreFatalErrors: boolean): Promise<boolean> {
try {
const result = await api.merge(prNumber, ignoreFatalErrors);
return await handleMergeResult(result, ignoreFatalErrors);
} catch (e) {
// Catch errors to the Github API for invalid requests. We want to
// exit the script with a better explanation of the error.
if (e instanceof GithubApiRequestError && e.status === 401) {
console.error(chalk.red('Github API request failed. ' + e.message));
console.error(chalk.yellow('Please ensure that your provided token is valid.'));
console.error(chalk.yellow(`You can generate a token here: ${GITHUB_TOKEN_GENERATE_URL}`));
process.exit(1);
}
throw e;
}
}
/**
* Prompts whether the specified pull request should be forcibly merged. If so, merges
* the specified pull request forcibly (ignoring non-critical failures).
* @returns Whether the specified pull request has been forcibly merged.
*/
async function promptAndPerformForceMerge(): Promise<boolean> {
if (await promptConfirm('Do you want to forcibly proceed with merging?')) {
// Perform the merge in force mode. This means that non-fatal failures
// are ignored and the merge continues.
return performMerge(true);
}
return false;
}
/**
* Handles the merge result by printing console messages, exiting the process
* based on the result, or by restarting the merge if force mode has been enabled.
* @returns Whether the merge was successful or not.
*/
async function handleMergeResult(result: MergeResult, disableForceMergePrompt = false) {
const {failure, status} = result;
const canForciblyMerge = failure && failure.nonFatal;
switch (status) {
case MergeStatus.SUCCESS:
console.info(chalk.green(`Successfully merged the pull request: ${prNumber}`));
return true;
case MergeStatus.DIRTY_WORKING_DIR:
console.error(chalk.red(
`Local working repository not clean. Please make sure there are ` +
`no uncommitted changes.`));
return false;
case MergeStatus.UNKNOWN_GIT_ERROR:
console.error(chalk.red(
'An unknown Git error has been thrown. Please check the output ' +
'above for details.'));
return false;
case MergeStatus.FAILED:
console.error(chalk.yellow(`Could not merge the specified pull request.`));
console.error(chalk.red(failure!.message));
if (canForciblyMerge && !disableForceMergePrompt) {
console.info();
console.info(chalk.yellow('The pull request above failed due to non-critical errors.'));
console.info(chalk.yellow(`This error can be forcibly ignored if desired.`));
return await promptAndPerformForceMerge();
}
return false;
default:
throw Error(`Unexpected merge result: ${status}`);
}
}
}
| dev-infra/pr/merge/index.ts | 1 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.004478598944842815,
0.0006700421217828989,
0.00016604701522737741,
0.00017346141976304352,
0.0011789791751652956
] |
{
"id": 1,
"code_window": [
"import {Arguments, Argv} from 'yargs';\n",
"import {GITHUB_TOKEN_GENERATE_URL, mergePullRequest} from './index';\n",
"\n",
"/** Builds the options for the merge command. */\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"import {error, red, yellow} from '../../utils/console';\n",
"\n"
],
"file_path": "dev-infra/pr/merge/cli.ts",
"type": "add",
"edit_start_line_idx": 10
} | /**
* @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 {ษตParsedTranslation} from '@angular/localize';
import {NodePath, PluginObj} from '@babel/core';
import {CallExpression} from '@babel/types';
import {Diagnostics} from '../../diagnostics';
import {buildCodeFrameError, buildLocalizeReplacement, isBabelParseError, isLocalize, translate, TranslatePluginOptions, unwrapMessagePartsFromLocalizeCall, unwrapSubstitutionsFromLocalizeCall} from '../../source_file_utils';
export function makeEs5TranslatePlugin(
diagnostics: Diagnostics, translations: Record<string, ษตParsedTranslation>,
{missingTranslation = 'error', localizeName = '$localize'}: TranslatePluginOptions = {}):
PluginObj {
return {
visitor: {
CallExpression(callPath: NodePath<CallExpression>) {
try {
const calleePath = callPath.get('callee');
if (isLocalize(calleePath, localizeName)) {
const messageParts = unwrapMessagePartsFromLocalizeCall(callPath);
const expressions = unwrapSubstitutionsFromLocalizeCall(callPath.node);
const translated =
translate(diagnostics, translations, messageParts, expressions, missingTranslation);
callPath.replaceWith(buildLocalizeReplacement(translated[0], translated[1]));
}
} catch (e) {
if (isBabelParseError(e)) {
diagnostics.error(buildCodeFrameError(callPath, e));
}
}
}
}
};
}
| packages/localize/src/tools/src/translate/source_files/es5_translate_plugin.ts | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.00017530072364024818,
0.000171186140505597,
0.00016779779980424792,
0.00016987223352771252,
0.000003117629830740043
] |
{
"id": 1,
"code_window": [
"import {Arguments, Argv} from 'yargs';\n",
"import {GITHUB_TOKEN_GENERATE_URL, mergePullRequest} from './index';\n",
"\n",
"/** Builds the options for the merge command. */\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"import {error, red, yellow} from '../../utils/console';\n",
"\n"
],
"file_path": "dev-infra/pr/merge/cli.ts",
"type": "add",
"edit_start_line_idx": 10
} | /**
* @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
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
const u = undefined;
function plural(n) {
if (n === 0) return 0;
if (n === 1) return 1;
if (n === 2) return 2;
if (n % 100 === Math.floor(n % 100) && n % 100 >= 3 && n % 100 <= 10) return 3;
if (n % 100 === Math.floor(n % 100) && n % 100 >= 11 && n % 100 <= 99) return 4;
return 5;
}
global.ng.common.locales['ar-sa'] = [
'ar-SA',
[['ุต', 'ู
'], u, u],
[['ุต', 'ู
'], u, ['ุตุจุงุญูุง', 'ู
ุณุงุกู']],
[
['ุญ', 'ู', 'ุซ', 'ุฑ', 'ุฎ', 'ุฌ', 'ุณ'],
[
'ุงูุฃุญุฏ', 'ุงูุงุซููู', 'ุงูุซูุงุซุงุก', 'ุงูุฃุฑุจุนุงุก', 'ุงูุฎู
ูุณ',
'ุงูุฌู
ุนุฉ', 'ุงูุณุจุช'
],
u,
['ุฃุญุฏ', 'ุฅุซููู', 'ุซูุงุซุงุก', 'ุฃุฑุจุนุงุก', 'ุฎู
ูุณ', 'ุฌู
ุนุฉ', 'ุณุจุช']
],
u,
[
['ู', 'ู', 'ู
', 'ุฃ', 'ู', 'ู', 'ู', 'ุบ', 'ุณ', 'ู', 'ุจ', 'ุฏ'],
[
'ููุงูุฑ', 'ูุจุฑุงูุฑ', 'ู
ุงุฑุณ', 'ุฃุจุฑูู', 'ู
ุงูู', 'ููููู',
'ููููู', 'ุฃุบุณุทุณ', 'ุณุจุชู
ุจุฑ', 'ุฃูุชูุจุฑ', 'ูููู
ุจุฑ', 'ุฏูุณู
ุจุฑ'
],
u
],
u,
[['ู.ู
', 'ู
'], u, ['ูุจู ุงูู
ููุงุฏ', 'ู
ููุงุฏู']],
0,
[5, 6],
['d\u200f/M\u200f/y', 'dd\u200f/MM\u200f/y', 'd MMMM y', 'EEEEุ d MMMM y'],
['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'],
['{1} {0}', u, u, u],
['.', ',', ';', 'ูช', '\u200e+', '\u200e-', 'E', 'ร', 'โฐ', 'โ', 'ููุณย ุฑูู
ูุง', ':'],
['#,##0.###', '#,##0%', 'ยคย #,##0.00', '#E0'],
'SAR',
'ุฑ.ุณ.\u200f',
'ุฑูุงู ุณุนูุฏู',
{
'AED': ['ุฏ.ุฅ.\u200f'],
'ARS': [u, 'AR$'],
'AUD': ['AU$'],
'BBD': [u, 'BB$'],
'BHD': ['ุฏ.ุจ.\u200f'],
'BMD': [u, 'BM$'],
'BND': [u, 'BN$'],
'BSD': [u, 'BS$'],
'BZD': [u, 'BZ$'],
'CAD': ['CA$'],
'CLP': [u, 'CL$'],
'CNY': ['CNยฅ'],
'COP': [u, 'CO$'],
'CUP': [u, 'CU$'],
'DOP': [u, 'DO$'],
'DZD': ['ุฏ.ุฌ.\u200f'],
'EGP': ['ุฌ.ู
.\u200f', 'Eยฃ'],
'FJD': [u, 'FJ$'],
'GBP': ['UKยฃ'],
'GYD': [u, 'GY$'],
'HKD': ['HK$'],
'IQD': ['ุฏ.ุน.\u200f'],
'IRR': ['ุฑ.ุฅ.'],
'JMD': [u, 'JM$'],
'JOD': ['ุฏ.ุฃ.\u200f'],
'JPY': ['JPยฅ'],
'KWD': ['ุฏ.ู.\u200f'],
'KYD': [u, 'KY$'],
'LBP': ['ู.ู.\u200f', 'Lยฃ'],
'LRD': [u, '$LR'],
'LYD': ['ุฏ.ู.\u200f'],
'MAD': ['ุฏ.ู
.\u200f'],
'MRU': ['ุฃ.ู
.'],
'MXN': ['MX$'],
'NZD': ['NZ$'],
'OMR': ['ุฑ.ุน.\u200f'],
'QAR': ['ุฑ.ู.\u200f'],
'SAR': ['ุฑ.ุณ.\u200f'],
'SBD': [u, 'SB$'],
'SDD': ['ุฏ.ุณ.\u200f'],
'SDG': ['ุฌ.ุณ.'],
'SRD': [u, 'SR$'],
'SYP': ['ู.ุณ.\u200f', 'ยฃ'],
'THB': ['เธฟ'],
'TND': ['ุฏ.ุช.\u200f'],
'TTD': [u, 'TT$'],
'TWD': ['NT$'],
'USD': ['US$'],
'UYU': [u, 'UY$'],
'XXX': ['***'],
'YER': ['ุฑ.ู.\u200f']
},
'rtl',
plural,
[
[
[
'ูุฌุฑูุง', 'ุตุจุงุญูุง', 'ุธูุฑูุง', 'ุจุนุฏ ุงูุธูุฑ', 'ู
ุณุงุกู',
'ู
ูุชุตู ุงูููู', 'ูููุงู'
],
[
'ูุฌุฑูุง', 'ุต', 'ุธูุฑูุง', 'ุจุนุฏ ุงูุธูุฑ', 'ู
ุณุงุกู',
'ู
ูุชุตู ุงูููู', 'ู'
],
[
'ูุฌุฑูุง', 'ุตุจุงุญูุง', 'ุธูุฑูุง', 'ุจุนุฏ ุงูุธูุฑ', 'ู
ุณุงุกู',
'ู
ูุชุตู ุงูููู', 'ูููุงู'
]
],
[
[
'ูุฌุฑูุง', 'ุตุจุงุญูุง', 'ุธูุฑูุง', 'ุจุนุฏ ุงูุธูุฑ', 'ู
ุณุงุกู',
'ู
ูุชุตู ุงูููู', 'ูููุงู'
],
[
'ูุฌุฑูุง', 'ุต', 'ุธูุฑูุง', 'ุจุนุฏ ุงูุธูุฑ', 'ู
ุณุงุกู',
'ู
ูุชุตู ุงูููู', 'ูููุงู'
],
[
'ูุฌุฑูุง', 'ุตุจุงุญูุง', 'ุธูุฑูุง', 'ุจุนุฏ ุงูุธูุฑ', 'ู
ุณุงุกู',
'ู
ูุชุตู ุงูููู', 'ูููุงู'
]
],
[
['03:00', '06:00'], ['06:00', '12:00'], ['12:00', '13:00'], ['13:00', '18:00'],
['18:00', '24:00'], ['00:00', '01:00'], ['01:00', '03:00']
]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
| packages/common/locales/global/ar-SA.js | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.00018481274310033768,
0.00017076919903047383,
0.00016437843441963196,
0.00016912168939597905,
0.000004752144377562217
] |
{
"id": 1,
"code_window": [
"import {Arguments, Argv} from 'yargs';\n",
"import {GITHUB_TOKEN_GENERATE_URL, mergePullRequest} from './index';\n",
"\n",
"/** Builds the options for the merge command. */\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"import {error, red, yellow} from '../../utils/console';\n",
"\n"
],
"file_path": "dev-infra/pr/merge/cli.ts",
"type": "add",
"edit_start_line_idx": 10
} | // #docregion item-class
export interface Item {
id: number;
name: string;
}
// #enddocregion item-class
| aio/content/examples/property-binding/src/app/item.ts | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.0001723776658764109,
0.0001723776658764109,
0.0001723776658764109,
0.0001723776658764109,
0
] |
{
"id": 2,
"code_window": [
"export async function handleMergeCommand(args: Arguments) {\n",
" const githubToken = args.githubToken || process.env.GITHUB_TOKEN || process.env.TOKEN;\n",
" if (!githubToken) {\n",
" console.error(\n",
" chalk.red('No Github token set. Please set the `GITHUB_TOKEN` environment variable.'));\n",
" console.error(chalk.red('Alternatively, pass the `--github-token` command line flag.'));\n",
" console.error(chalk.yellow(`You can generate a token here: ${GITHUB_TOKEN_GENERATE_URL}`));\n",
" process.exit(1);\n",
" }\n",
"\n",
" await mergePullRequest(args.prNumber, githubToken);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" error(red('No Github token set. Please set the `GITHUB_TOKEN` environment variable.'));\n",
" error(red('Alternatively, pass the `--github-token` command line flag.'));\n",
" error(yellow(`You can generate a token here: ${GITHUB_TOKEN_GENERATE_URL}`));\n"
],
"file_path": "dev-infra/pr/merge/cli.ts",
"type": "replace",
"edit_start_line_idx": 24
} | /**
* @license
* Copyright Google LLC 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 chalk from 'chalk';
import {getRepoBaseDir} from '../../utils/config';
import {promptConfirm} from '../../utils/console';
import {loadAndValidateConfig, MergeConfigWithRemote} from './config';
import {GithubApiRequestError} from './git';
import {MergeResult, MergeStatus, PullRequestMergeTask} from './task';
/** URL to the Github page where personal access tokens can be generated. */
export const GITHUB_TOKEN_GENERATE_URL = `https://github.com/settings/tokens`;
/**
* Merges a given pull request based on labels configured in the given merge configuration.
* Pull requests can be merged with different strategies such as the Github API merge
* strategy, or the local autosquash strategy. Either strategy has benefits and downsides.
* More information on these strategies can be found in their dedicated strategy classes.
*
* See {@link GithubApiMergeStrategy} and {@link AutosquashMergeStrategy}
*
* @param prNumber Number of the pull request that should be merged.
* @param githubToken Github token used for merging (i.e. fetching and pushing)
* @param projectRoot Path to the local Git project that is used for merging.
* @param config Configuration for merging pull requests.
*/
export async function mergePullRequest(
prNumber: number, githubToken: string, projectRoot: string = getRepoBaseDir(),
config?: MergeConfigWithRemote) {
// If no explicit configuration has been specified, we load and validate
// the configuration from the shared dev-infra configuration.
if (config === undefined) {
const {config: _config, errors} = loadAndValidateConfig();
if (errors) {
console.error(chalk.red('Invalid configuration:'));
errors.forEach(desc => console.error(chalk.yellow(` - ${desc}`)));
process.exit(1);
}
config = _config!;
}
const api = new PullRequestMergeTask(projectRoot, config, githubToken);
// Perform the merge. Force mode can be activated through a command line flag.
// Alternatively, if the merge fails with non-fatal failures, the script
// will prompt whether it should rerun in force mode.
if (!await performMerge(false)) {
process.exit(1);
}
/** Performs the merge and returns whether it was successful or not. */
async function performMerge(ignoreFatalErrors: boolean): Promise<boolean> {
try {
const result = await api.merge(prNumber, ignoreFatalErrors);
return await handleMergeResult(result, ignoreFatalErrors);
} catch (e) {
// Catch errors to the Github API for invalid requests. We want to
// exit the script with a better explanation of the error.
if (e instanceof GithubApiRequestError && e.status === 401) {
console.error(chalk.red('Github API request failed. ' + e.message));
console.error(chalk.yellow('Please ensure that your provided token is valid.'));
console.error(chalk.yellow(`You can generate a token here: ${GITHUB_TOKEN_GENERATE_URL}`));
process.exit(1);
}
throw e;
}
}
/**
* Prompts whether the specified pull request should be forcibly merged. If so, merges
* the specified pull request forcibly (ignoring non-critical failures).
* @returns Whether the specified pull request has been forcibly merged.
*/
async function promptAndPerformForceMerge(): Promise<boolean> {
if (await promptConfirm('Do you want to forcibly proceed with merging?')) {
// Perform the merge in force mode. This means that non-fatal failures
// are ignored and the merge continues.
return performMerge(true);
}
return false;
}
/**
* Handles the merge result by printing console messages, exiting the process
* based on the result, or by restarting the merge if force mode has been enabled.
* @returns Whether the merge was successful or not.
*/
async function handleMergeResult(result: MergeResult, disableForceMergePrompt = false) {
const {failure, status} = result;
const canForciblyMerge = failure && failure.nonFatal;
switch (status) {
case MergeStatus.SUCCESS:
console.info(chalk.green(`Successfully merged the pull request: ${prNumber}`));
return true;
case MergeStatus.DIRTY_WORKING_DIR:
console.error(chalk.red(
`Local working repository not clean. Please make sure there are ` +
`no uncommitted changes.`));
return false;
case MergeStatus.UNKNOWN_GIT_ERROR:
console.error(chalk.red(
'An unknown Git error has been thrown. Please check the output ' +
'above for details.'));
return false;
case MergeStatus.FAILED:
console.error(chalk.yellow(`Could not merge the specified pull request.`));
console.error(chalk.red(failure!.message));
if (canForciblyMerge && !disableForceMergePrompt) {
console.info();
console.info(chalk.yellow('The pull request above failed due to non-critical errors.'));
console.info(chalk.yellow(`This error can be forcibly ignored if desired.`));
return await promptAndPerformForceMerge();
}
return false;
default:
throw Error(`Unexpected merge result: ${status}`);
}
}
}
| dev-infra/pr/merge/index.ts | 1 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.9585310816764832,
0.083729587495327,
0.0001670049678068608,
0.0005096294335089624,
0.25460100173950195
] |
{
"id": 2,
"code_window": [
"export async function handleMergeCommand(args: Arguments) {\n",
" const githubToken = args.githubToken || process.env.GITHUB_TOKEN || process.env.TOKEN;\n",
" if (!githubToken) {\n",
" console.error(\n",
" chalk.red('No Github token set. Please set the `GITHUB_TOKEN` environment variable.'));\n",
" console.error(chalk.red('Alternatively, pass the `--github-token` command line flag.'));\n",
" console.error(chalk.yellow(`You can generate a token here: ${GITHUB_TOKEN_GENERATE_URL}`));\n",
" process.exit(1);\n",
" }\n",
"\n",
" await mergePullRequest(args.prNumber, githubToken);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" error(red('No Github token set. Please set the `GITHUB_TOKEN` environment variable.'));\n",
" error(red('Alternatively, pass the `--github-token` command line flag.'));\n",
" error(yellow(`You can generate a token here: ${GITHUB_TOKEN_GENERATE_URL}`));\n"
],
"file_path": "dev-infra/pr/merge/cli.ts",
"type": "replace",
"edit_start_line_idx": 24
} | /**
* @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 {NgModule, Type} from '@angular/core';
import {CheckboxControlValueAccessor} from './directives/checkbox_value_accessor';
import {DefaultValueAccessor} from './directives/default_value_accessor';
import {NgControlStatus, NgControlStatusGroup} from './directives/ng_control_status';
import {NgForm} from './directives/ng_form';
import {NgModel} from './directives/ng_model';
import {NgModelGroup} from './directives/ng_model_group';
import {NgNoValidate} from './directives/ng_no_validate_directive';
import {NumberValueAccessor} from './directives/number_value_accessor';
import {RadioControlValueAccessor} from './directives/radio_control_value_accessor';
import {RangeValueAccessor} from './directives/range_value_accessor';
import {FormControlDirective} from './directives/reactive_directives/form_control_directive';
import {FormControlName} from './directives/reactive_directives/form_control_name';
import {FormGroupDirective} from './directives/reactive_directives/form_group_directive';
import {FormArrayName, FormGroupName} from './directives/reactive_directives/form_group_name';
import {NgSelectOption, SelectControlValueAccessor} from './directives/select_control_value_accessor';
import {NgSelectMultipleOption, SelectMultipleControlValueAccessor} from './directives/select_multiple_control_value_accessor';
import {CheckboxRequiredValidator, EmailValidator, MaxLengthValidator, MinLengthValidator, PatternValidator, RequiredValidator} from './directives/validators';
export {CheckboxControlValueAccessor} from './directives/checkbox_value_accessor';
export {ControlValueAccessor} from './directives/control_value_accessor';
export {DefaultValueAccessor} from './directives/default_value_accessor';
export {NgControl} from './directives/ng_control';
export {NgControlStatus, NgControlStatusGroup} from './directives/ng_control_status';
export {NgForm} from './directives/ng_form';
export {NgModel} from './directives/ng_model';
export {NgModelGroup} from './directives/ng_model_group';
export {NumberValueAccessor} from './directives/number_value_accessor';
export {RadioControlValueAccessor} from './directives/radio_control_value_accessor';
export {RangeValueAccessor} from './directives/range_value_accessor';
export {FormControlDirective, NG_MODEL_WITH_FORM_CONTROL_WARNING} from './directives/reactive_directives/form_control_directive';
export {FormControlName} from './directives/reactive_directives/form_control_name';
export {FormGroupDirective} from './directives/reactive_directives/form_group_directive';
export {FormArrayName, FormGroupName} from './directives/reactive_directives/form_group_name';
export {NgSelectOption, SelectControlValueAccessor} from './directives/select_control_value_accessor';
export {NgSelectMultipleOption, SelectMultipleControlValueAccessor} from './directives/select_multiple_control_value_accessor';
export const SHARED_FORM_DIRECTIVES: Type<any>[] = [
NgNoValidate,
NgSelectOption,
NgSelectMultipleOption,
DefaultValueAccessor,
NumberValueAccessor,
RangeValueAccessor,
CheckboxControlValueAccessor,
SelectControlValueAccessor,
SelectMultipleControlValueAccessor,
RadioControlValueAccessor,
NgControlStatus,
NgControlStatusGroup,
RequiredValidator,
MinLengthValidator,
MaxLengthValidator,
PatternValidator,
CheckboxRequiredValidator,
EmailValidator,
];
export const TEMPLATE_DRIVEN_DIRECTIVES: Type<any>[] = [NgModel, NgModelGroup, NgForm];
export const REACTIVE_DRIVEN_DIRECTIVES: Type<any>[] =
[FormControlDirective, FormGroupDirective, FormControlName, FormGroupName, FormArrayName];
/**
* Internal module used for sharing directives between FormsModule and ReactiveFormsModule
*/
@NgModule({
declarations: SHARED_FORM_DIRECTIVES,
exports: SHARED_FORM_DIRECTIVES,
})
export class ษตInternalFormsSharedModule {
}
export {ษตInternalFormsSharedModule as InternalFormsSharedModule};
| packages/forms/src/directives.ts | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.00017992727225646377,
0.00017362055950798094,
0.00016895760199986398,
0.00017322208441328257,
0.0000031325305371865397
] |
{
"id": 2,
"code_window": [
"export async function handleMergeCommand(args: Arguments) {\n",
" const githubToken = args.githubToken || process.env.GITHUB_TOKEN || process.env.TOKEN;\n",
" if (!githubToken) {\n",
" console.error(\n",
" chalk.red('No Github token set. Please set the `GITHUB_TOKEN` environment variable.'));\n",
" console.error(chalk.red('Alternatively, pass the `--github-token` command line flag.'));\n",
" console.error(chalk.yellow(`You can generate a token here: ${GITHUB_TOKEN_GENERATE_URL}`));\n",
" process.exit(1);\n",
" }\n",
"\n",
" await mergePullRequest(args.prNumber, githubToken);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" error(red('No Github token set. Please set the `GITHUB_TOKEN` environment variable.'));\n",
" error(red('Alternatively, pass the `--github-token` command line flag.'));\n",
" error(yellow(`You can generate a token here: ${GITHUB_TOKEN_GENERATE_URL}`));\n"
],
"file_path": "dev-infra/pr/merge/cli.ts",
"type": "replace",
"edit_start_line_idx": 24
} | /**
* @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
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
const u = undefined;
function plural(n) {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0) return 1;
return 5;
}
global.ng.common.locales['en-cm'] = [
'en-CM',
[['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'],
'XAF',
'FCFA',
'Central African CFA Franc',
{'JPY': ['JPยฅ', 'ยฅ'], 'USD': ['US$', '$']},
'ltr',
plural,
[
[
['mi', 'n', 'in the morning', 'in the afternoon', 'in the evening', 'at night'],
['midnight', 'noon', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], u
],
[['midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'], u, u],
[
'00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'],
['21:00', '06:00']
]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
| packages/common/locales/global/en-CM.js | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.00017469984595663846,
0.00017227949865628034,
0.000168646321981214,
0.0001733851822791621,
0.0000019900633105862653
] |
{
"id": 2,
"code_window": [
"export async function handleMergeCommand(args: Arguments) {\n",
" const githubToken = args.githubToken || process.env.GITHUB_TOKEN || process.env.TOKEN;\n",
" if (!githubToken) {\n",
" console.error(\n",
" chalk.red('No Github token set. Please set the `GITHUB_TOKEN` environment variable.'));\n",
" console.error(chalk.red('Alternatively, pass the `--github-token` command line flag.'));\n",
" console.error(chalk.yellow(`You can generate a token here: ${GITHUB_TOKEN_GENERATE_URL}`));\n",
" process.exit(1);\n",
" }\n",
"\n",
" await mergePullRequest(args.prNumber, githubToken);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" error(red('No Github token set. Please set the `GITHUB_TOKEN` environment variable.'));\n",
" error(red('Alternatively, pass the `--github-token` command line flag.'));\n",
" error(yellow(`You can generate a token here: ${GITHUB_TOKEN_GENERATE_URL}`));\n"
],
"file_path": "dev-infra/pr/merge/cli.ts",
"type": "replace",
"edit_start_line_idx": 24
} | // BannerComponent as initially generated by the CLI
// #docregion
import { Component } from '@angular/core';
@Component({
selector: 'app-banner',
template: `<p>banner works!</p>`,
styles: []
})
export class BannerComponent { }
| aio/content/examples/testing/src/app/banner/banner-initial.component.ts | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.00017442555690649897,
0.00017341911734547466,
0.00017241267778445035,
0.00017341911734547466,
0.0000010064395610243082
] |
{
"id": 3,
"code_window": [
" */\n",
"\n",
"import * as Octokit from '@octokit/rest';\n",
"import {spawnSync, SpawnSyncOptions, SpawnSyncReturns} from 'child_process';\n",
"import {MergeConfigWithRemote} from './config';\n",
"\n",
"/** Error for failed Github API requests. */\n",
"export class GithubApiRequestError extends Error {\n",
" constructor(public status: number, message: string) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"import {info} from '../../utils/console';\n",
"\n"
],
"file_path": "dev-infra/pr/merge/git.ts",
"type": "add",
"edit_start_line_idx": 10
} | /**
* @license
* Copyright Google LLC 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 chalk from 'chalk';
import {getRepoBaseDir} from '../../utils/config';
import {promptConfirm} from '../../utils/console';
import {loadAndValidateConfig, MergeConfigWithRemote} from './config';
import {GithubApiRequestError} from './git';
import {MergeResult, MergeStatus, PullRequestMergeTask} from './task';
/** URL to the Github page where personal access tokens can be generated. */
export const GITHUB_TOKEN_GENERATE_URL = `https://github.com/settings/tokens`;
/**
* Merges a given pull request based on labels configured in the given merge configuration.
* Pull requests can be merged with different strategies such as the Github API merge
* strategy, or the local autosquash strategy. Either strategy has benefits and downsides.
* More information on these strategies can be found in their dedicated strategy classes.
*
* See {@link GithubApiMergeStrategy} and {@link AutosquashMergeStrategy}
*
* @param prNumber Number of the pull request that should be merged.
* @param githubToken Github token used for merging (i.e. fetching and pushing)
* @param projectRoot Path to the local Git project that is used for merging.
* @param config Configuration for merging pull requests.
*/
export async function mergePullRequest(
prNumber: number, githubToken: string, projectRoot: string = getRepoBaseDir(),
config?: MergeConfigWithRemote) {
// If no explicit configuration has been specified, we load and validate
// the configuration from the shared dev-infra configuration.
if (config === undefined) {
const {config: _config, errors} = loadAndValidateConfig();
if (errors) {
console.error(chalk.red('Invalid configuration:'));
errors.forEach(desc => console.error(chalk.yellow(` - ${desc}`)));
process.exit(1);
}
config = _config!;
}
const api = new PullRequestMergeTask(projectRoot, config, githubToken);
// Perform the merge. Force mode can be activated through a command line flag.
// Alternatively, if the merge fails with non-fatal failures, the script
// will prompt whether it should rerun in force mode.
if (!await performMerge(false)) {
process.exit(1);
}
/** Performs the merge and returns whether it was successful or not. */
async function performMerge(ignoreFatalErrors: boolean): Promise<boolean> {
try {
const result = await api.merge(prNumber, ignoreFatalErrors);
return await handleMergeResult(result, ignoreFatalErrors);
} catch (e) {
// Catch errors to the Github API for invalid requests. We want to
// exit the script with a better explanation of the error.
if (e instanceof GithubApiRequestError && e.status === 401) {
console.error(chalk.red('Github API request failed. ' + e.message));
console.error(chalk.yellow('Please ensure that your provided token is valid.'));
console.error(chalk.yellow(`You can generate a token here: ${GITHUB_TOKEN_GENERATE_URL}`));
process.exit(1);
}
throw e;
}
}
/**
* Prompts whether the specified pull request should be forcibly merged. If so, merges
* the specified pull request forcibly (ignoring non-critical failures).
* @returns Whether the specified pull request has been forcibly merged.
*/
async function promptAndPerformForceMerge(): Promise<boolean> {
if (await promptConfirm('Do you want to forcibly proceed with merging?')) {
// Perform the merge in force mode. This means that non-fatal failures
// are ignored and the merge continues.
return performMerge(true);
}
return false;
}
/**
* Handles the merge result by printing console messages, exiting the process
* based on the result, or by restarting the merge if force mode has been enabled.
* @returns Whether the merge was successful or not.
*/
async function handleMergeResult(result: MergeResult, disableForceMergePrompt = false) {
const {failure, status} = result;
const canForciblyMerge = failure && failure.nonFatal;
switch (status) {
case MergeStatus.SUCCESS:
console.info(chalk.green(`Successfully merged the pull request: ${prNumber}`));
return true;
case MergeStatus.DIRTY_WORKING_DIR:
console.error(chalk.red(
`Local working repository not clean. Please make sure there are ` +
`no uncommitted changes.`));
return false;
case MergeStatus.UNKNOWN_GIT_ERROR:
console.error(chalk.red(
'An unknown Git error has been thrown. Please check the output ' +
'above for details.'));
return false;
case MergeStatus.FAILED:
console.error(chalk.yellow(`Could not merge the specified pull request.`));
console.error(chalk.red(failure!.message));
if (canForciblyMerge && !disableForceMergePrompt) {
console.info();
console.info(chalk.yellow('The pull request above failed due to non-critical errors.'));
console.info(chalk.yellow(`This error can be forcibly ignored if desired.`));
return await promptAndPerformForceMerge();
}
return false;
default:
throw Error(`Unexpected merge result: ${status}`);
}
}
}
| dev-infra/pr/merge/index.ts | 1 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.9992449283599854,
0.15413552522659302,
0.00016701356798876077,
0.00026521916151978076,
0.36033132672309875
] |
{
"id": 3,
"code_window": [
" */\n",
"\n",
"import * as Octokit from '@octokit/rest';\n",
"import {spawnSync, SpawnSyncOptions, SpawnSyncReturns} from 'child_process';\n",
"import {MergeConfigWithRemote} from './config';\n",
"\n",
"/** Error for failed Github API requests. */\n",
"export class GithubApiRequestError extends Error {\n",
" constructor(public status: number, message: string) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"import {info} from '../../utils/console';\n",
"\n"
],
"file_path": "dev-infra/pr/merge/git.ts",
"type": "add",
"edit_start_line_idx": 10
} | /**
* @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 {fakeAsync, tick} from '@angular/core/testing';
import {beforeEach, describe, expect, it} from '@angular/core/testing/src/testing_internal';
import {FormBuilder, Validators} from '@angular/forms';
import {of} from 'rxjs';
(function() {
function syncValidator(_: any /** TODO #9100 */): any /** TODO #9100 */ {
return null;
}
function asyncValidator(_: any /** TODO #9100 */) {
return Promise.resolve(null);
}
describe('Form Builder', () => {
let b: FormBuilder;
beforeEach(() => {
b = new FormBuilder();
});
it('should create controls from a value', () => {
const g = b.group({'login': 'some value'});
expect(g.controls['login'].value).toEqual('some value');
});
it('should create controls from a boxed value', () => {
const g = b.group({'login': {value: 'some value', disabled: true}});
expect(g.controls['login'].value).toEqual('some value');
expect(g.controls['login'].disabled).toEqual(true);
});
it('should create controls from an array', () => {
const g = b.group(
{'login': ['some value'], 'password': ['some value', syncValidator, asyncValidator]});
expect(g.controls['login'].value).toEqual('some value');
expect(g.controls['password'].value).toEqual('some value');
expect(g.controls['password'].validator).toEqual(syncValidator);
expect(g.controls['password'].asyncValidator).toEqual(asyncValidator);
});
it('should use controls whose form state is a primitive value', () => {
const g = b.group({'login': b.control('some value', syncValidator, asyncValidator)});
expect(g.controls['login'].value).toEqual('some value');
expect(g.controls['login'].validator).toBe(syncValidator);
expect(g.controls['login'].asyncValidator).toBe(asyncValidator);
});
it('should support controls with no validators and whose form state is null', () => {
const g = b.group({'login': b.control(null)});
expect(g.controls['login'].value).toBeNull();
expect(g.controls['login'].validator).toBeNull();
expect(g.controls['login'].asyncValidator).toBeNull();
});
it('should support controls with validators and whose form state is null', () => {
const g = b.group({'login': b.control(null, syncValidator, asyncValidator)});
expect(g.controls['login'].value).toBeNull();
expect(g.controls['login'].validator).toBe(syncValidator);
expect(g.controls['login'].asyncValidator).toBe(asyncValidator);
});
it('should support controls with no validators and whose form state is undefined', () => {
const g = b.group({'login': b.control(undefined)});
expect(g.controls['login'].value).toBeNull();
expect(g.controls['login'].validator).toBeNull();
expect(g.controls['login'].asyncValidator).toBeNull();
});
it('should support controls with validators and whose form state is undefined', () => {
const g = b.group({'login': b.control(undefined, syncValidator, asyncValidator)});
expect(g.controls['login'].value).toBeNull();
expect(g.controls['login'].validator).toBe(syncValidator);
expect(g.controls['login'].asyncValidator).toBe(asyncValidator);
});
it('should create groups with a custom validator', () => {
const g = b.group(
{'login': 'some value'}, {'validator': syncValidator, 'asyncValidator': asyncValidator});
expect(g.validator).toBe(syncValidator);
expect(g.asyncValidator).toBe(asyncValidator);
});
it('should create control arrays', () => {
const c = b.control('three');
const e = b.control(null);
const f = b.control(undefined);
const a = b.array(
['one', ['two', syncValidator], c, b.array(['four']), e, f], syncValidator, asyncValidator);
expect(a.value).toEqual(['one', 'two', 'three', ['four'], null, null]);
expect(a.validator).toBe(syncValidator);
expect(a.asyncValidator).toBe(asyncValidator);
});
it('should create control arrays with multiple async validators', fakeAsync(() => {
function asyncValidator1() {
return of({'async1': true});
}
function asyncValidator2() {
return of({'async2': true});
}
const a = b.array(['one', 'two'], null, [asyncValidator1, asyncValidator2]);
expect(a.value).toEqual(['one', 'two']);
tick();
expect(a.errors).toEqual({'async1': true, 'async2': true});
}));
it('should create control arrays with multiple sync validators', () => {
function syncValidator1() {
return {'sync1': true};
}
function syncValidator2() {
return {'sync2': true};
}
const a = b.array(['one', 'two'], [syncValidator1, syncValidator2]);
expect(a.value).toEqual(['one', 'two']);
expect(a.errors).toEqual({'sync1': true, 'sync2': true});
});
describe('updateOn', () => {
it('should default to on change', () => {
const c = b.control('');
expect(c.updateOn).toEqual('change');
});
it('should default to on change with an options obj', () => {
const c = b.control('', {validators: Validators.required});
expect(c.updateOn).toEqual('change');
});
it('should set updateOn when updating on blur', () => {
const c = b.control('', {updateOn: 'blur'});
expect(c.updateOn).toEqual('blur');
});
describe('in groups and arrays', () => {
it('should default to group updateOn when not set in control', () => {
const g = b.group({one: b.control(''), two: b.control('')}, {updateOn: 'blur'});
expect(g.get('one')!.updateOn).toEqual('blur');
expect(g.get('two')!.updateOn).toEqual('blur');
});
it('should default to array updateOn when not set in control', () => {
const a = b.array([b.control(''), b.control('')], {updateOn: 'blur'});
expect(a.get([0])!.updateOn).toEqual('blur');
expect(a.get([1])!.updateOn).toEqual('blur');
});
it('should set updateOn with nested groups', () => {
const g = b.group(
{
group: b.group({one: b.control(''), two: b.control('')}),
},
{updateOn: 'blur'});
expect(g.get('group.one')!.updateOn).toEqual('blur');
expect(g.get('group.two')!.updateOn).toEqual('blur');
expect(g.get('group')!.updateOn).toEqual('blur');
});
it('should set updateOn with nested arrays', () => {
const g = b.group(
{
arr: b.array([b.control(''), b.control('')]),
},
{updateOn: 'blur'});
expect(g.get(['arr', 0])!.updateOn).toEqual('blur');
expect(g.get(['arr', 1])!.updateOn).toEqual('blur');
expect(g.get('arr')!.updateOn).toEqual('blur');
});
it('should allow control updateOn to override group updateOn', () => {
const g = b.group(
{one: b.control('', {updateOn: 'change'}), two: b.control('')}, {updateOn: 'blur'});
expect(g.get('one')!.updateOn).toEqual('change');
expect(g.get('two')!.updateOn).toEqual('blur');
});
it('should set updateOn with complex setup', () => {
const g = b.group({
group: b.group(
{one: b.control('', {updateOn: 'change'}), two: b.control('')}, {updateOn: 'blur'}),
groupTwo: b.group({one: b.control('')}, {updateOn: 'submit'}),
three: b.control('')
});
expect(g.get('group.one')!.updateOn).toEqual('change');
expect(g.get('group.two')!.updateOn).toEqual('blur');
expect(g.get('groupTwo.one')!.updateOn).toEqual('submit');
expect(g.get('three')!.updateOn).toEqual('change');
});
});
});
});
})();
| packages/forms/test/form_builder_spec.ts | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.00018171811825595796,
0.00017671952082309872,
0.00016252597561106086,
0.00017795400344766676,
0.000003857314368360676
] |
{
"id": 3,
"code_window": [
" */\n",
"\n",
"import * as Octokit from '@octokit/rest';\n",
"import {spawnSync, SpawnSyncOptions, SpawnSyncReturns} from 'child_process';\n",
"import {MergeConfigWithRemote} from './config';\n",
"\n",
"/** Error for failed Github API requests. */\n",
"export class GithubApiRequestError extends Error {\n",
" constructor(public status: number, message: string) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"import {info} from '../../utils/console';\n",
"\n"
],
"file_path": "dev-infra/pr/merge/git.ts",
"type": "add",
"edit_start_line_idx": 10
} | /**
* @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
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
const u = undefined;
function plural(n) {
if (n === 0) return 0;
if (n === 1) return 1;
if (n === 2) return 2;
if (n % 100 === Math.floor(n % 100) && n % 100 >= 3 && n % 100 <= 10) return 3;
if (n % 100 === Math.floor(n % 100) && n % 100 >= 11 && n % 100 <= 99) return 4;
return 5;
}
global.ng.common.locales['ar-bh'] = [
'ar-BH',
[['ุต', 'ู
'], u, u],
[['ุต', 'ู
'], u, ['ุตุจุงุญูุง', 'ู
ุณุงุกู']],
[
['ุญ', 'ู', 'ุซ', 'ุฑ', 'ุฎ', 'ุฌ', 'ุณ'],
[
'ุงูุฃุญุฏ', 'ุงูุงุซููู', 'ุงูุซูุงุซุงุก', 'ุงูุฃุฑุจุนุงุก', 'ุงูุฎู
ูุณ',
'ุงูุฌู
ุนุฉ', 'ุงูุณุจุช'
],
u,
['ุฃุญุฏ', 'ุฅุซููู', 'ุซูุงุซุงุก', 'ุฃุฑุจุนุงุก', 'ุฎู
ูุณ', 'ุฌู
ุนุฉ', 'ุณุจุช']
],
u,
[
['ู', 'ู', 'ู
', 'ุฃ', 'ู', 'ู', 'ู', 'ุบ', 'ุณ', 'ู', 'ุจ', 'ุฏ'],
[
'ููุงูุฑ', 'ูุจุฑุงูุฑ', 'ู
ุงุฑุณ', 'ุฃุจุฑูู', 'ู
ุงูู', 'ููููู',
'ููููู', 'ุฃุบุณุทุณ', 'ุณุจุชู
ุจุฑ', 'ุฃูุชูุจุฑ', 'ูููู
ุจุฑ', 'ุฏูุณู
ุจุฑ'
],
u
],
u,
[['ู.ู
', 'ู
'], u, ['ูุจู ุงูู
ููุงุฏ', 'ู
ููุงุฏู']],
6,
[5, 6],
['d\u200f/M\u200f/y', 'dd\u200f/MM\u200f/y', 'd MMMM y', 'EEEEุ d MMMM y'],
['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'],
['{1} {0}', u, u, u],
[
'.', ',', ';', '\u200e%\u200e', '\u200e+', '\u200e-', 'E', 'ร', 'โฐ', 'โ',
'ููุณย ุฑูู
ูุง', ':'
],
['#,##0.###', '#,##0%', 'ยคย #,##0.00', '#E0'],
'BHD',
'ุฏ.ุจ.\u200f',
'ุฏููุงุฑ ุจุญุฑููู',
{
'AED': ['ุฏ.ุฅ.\u200f'],
'ARS': [u, 'AR$'],
'AUD': ['AU$'],
'BBD': [u, 'BB$'],
'BHD': ['ุฏ.ุจ.\u200f'],
'BMD': [u, 'BM$'],
'BND': [u, 'BN$'],
'BSD': [u, 'BS$'],
'BZD': [u, 'BZ$'],
'CAD': ['CA$'],
'CLP': [u, 'CL$'],
'CNY': ['CNยฅ'],
'COP': [u, 'CO$'],
'CUP': [u, 'CU$'],
'DOP': [u, 'DO$'],
'DZD': ['ุฏ.ุฌ.\u200f'],
'EGP': ['ุฌ.ู
.\u200f', 'Eยฃ'],
'FJD': [u, 'FJ$'],
'GBP': ['UKยฃ'],
'GYD': [u, 'GY$'],
'HKD': ['HK$'],
'IQD': ['ุฏ.ุน.\u200f'],
'IRR': ['ุฑ.ุฅ.'],
'JMD': [u, 'JM$'],
'JOD': ['ุฏ.ุฃ.\u200f'],
'JPY': ['JPยฅ'],
'KWD': ['ุฏ.ู.\u200f'],
'KYD': [u, 'KY$'],
'LBP': ['ู.ู.\u200f', 'Lยฃ'],
'LRD': [u, '$LR'],
'LYD': ['ุฏ.ู.\u200f'],
'MAD': ['ุฏ.ู
.\u200f'],
'MRU': ['ุฃ.ู
.'],
'MXN': ['MX$'],
'NZD': ['NZ$'],
'OMR': ['ุฑ.ุน.\u200f'],
'QAR': ['ุฑ.ู.\u200f'],
'SAR': ['ุฑ.ุณ.\u200f'],
'SBD': [u, 'SB$'],
'SDD': ['ุฏ.ุณ.\u200f'],
'SDG': ['ุฌ.ุณ.'],
'SRD': [u, 'SR$'],
'SYP': ['ู.ุณ.\u200f', 'ยฃ'],
'THB': ['เธฟ'],
'TND': ['ุฏ.ุช.\u200f'],
'TTD': [u, 'TT$'],
'TWD': ['NT$'],
'USD': ['US$'],
'UYU': [u, 'UY$'],
'XXX': ['***'],
'YER': ['ุฑ.ู.\u200f']
},
'rtl',
plural,
[
[
[
'ูุฌุฑูุง', 'ุตุจุงุญูุง', 'ุธูุฑูุง', 'ุจุนุฏ ุงูุธูุฑ', 'ู
ุณุงุกู',
'ู
ูุชุตู ุงูููู', 'ูููุงู'
],
[
'ูุฌุฑูุง', 'ุต', 'ุธูุฑูุง', 'ุจุนุฏ ุงูุธูุฑ', 'ู
ุณุงุกู',
'ู
ูุชุตู ุงูููู', 'ูููุงู'
],
[
'ูุฌุฑูุง', 'ุตุจุงุญูุง', 'ุธูุฑูุง', 'ุจุนุฏ ุงูุธูุฑ', 'ู
ุณุงุกู',
'ู
ูุชุตู ุงูููู', 'ูููุงู'
]
],
u,
[
['03:00', '06:00'], ['06:00', '12:00'], ['12:00', '13:00'], ['13:00', '18:00'],
['18:00', '24:00'], ['00:00', '01:00'], ['01:00', '03:00']
]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
| packages/common/locales/global/ar-BH.js | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.0001780165039235726,
0.0001743897155392915,
0.00016943093214649707,
0.0001747101778164506,
0.0000021776454559585545
] |
{
"id": 3,
"code_window": [
" */\n",
"\n",
"import * as Octokit from '@octokit/rest';\n",
"import {spawnSync, SpawnSyncOptions, SpawnSyncReturns} from 'child_process';\n",
"import {MergeConfigWithRemote} from './config';\n",
"\n",
"/** Error for failed Github API requests. */\n",
"export class GithubApiRequestError extends Error {\n",
" constructor(public status: number, message: string) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"import {info} from '../../utils/console';\n",
"\n"
],
"file_path": "dev-infra/pr/merge/git.ts",
"type": "add",
"edit_start_line_idx": 10
} | /**
* @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 {ElementRef, Injector, SimpleChanges} from '@angular/core';
import {DirectiveRequireProperty, element as angularElement, IAugmentedJQuery, ICloneAttachFunction, ICompileService, IController, IControllerService, IDirective, IHttpBackendService, IInjectorService, ILinkFn, IScope, ITemplateCacheService, SingleOrListOrMap} from './angular1';
import {$COMPILE, $CONTROLLER, $HTTP_BACKEND, $INJECTOR, $TEMPLATE_CACHE} from './constants';
import {controllerKey, directiveNormalize, isFunction} from './util';
// Constants
const REQUIRE_PREFIX_RE = /^(\^\^?)?(\?)?(\^\^?)?/;
// Interfaces
export interface IBindingDestination {
[key: string]: any;
$onChanges?: (changes: SimpleChanges) => void;
}
export interface IControllerInstance extends IBindingDestination {
$doCheck?: () => void;
$onDestroy?: () => void;
$onInit?: () => void;
$postLink?: () => void;
}
// Classes
export class UpgradeHelper {
public readonly $injector: IInjectorService;
public readonly element: Element;
public readonly $element: IAugmentedJQuery;
public readonly directive: IDirective;
private readonly $compile: ICompileService;
private readonly $controller: IControllerService;
constructor(
private injector: Injector, private name: string, elementRef: ElementRef,
directive?: IDirective) {
this.$injector = injector.get($INJECTOR);
this.$compile = this.$injector.get($COMPILE);
this.$controller = this.$injector.get($CONTROLLER);
this.element = elementRef.nativeElement;
this.$element = angularElement(this.element);
this.directive = directive || UpgradeHelper.getDirective(this.$injector, name);
}
static getDirective($injector: IInjectorService, name: string): IDirective {
const directives: IDirective[] = $injector.get(name + 'Directive');
if (directives.length > 1) {
throw new Error(`Only support single directive definition for: ${name}`);
}
const directive = directives[0];
// AngularJS will transform `link: xyz` to `compile: () => xyz`. So we can only tell there was a
// user-defined `compile` if there is no `link`. In other cases, we will just ignore `compile`.
if (directive.compile && !directive.link) notSupported(name, 'compile');
if (directive.replace) notSupported(name, 'replace');
if (directive.terminal) notSupported(name, 'terminal');
return directive;
}
static getTemplate(
$injector: IInjectorService, directive: IDirective, fetchRemoteTemplate = false,
$element?: IAugmentedJQuery): string|Promise<string> {
if (directive.template !== undefined) {
return getOrCall<string>(directive.template, $element);
} else if (directive.templateUrl) {
const $templateCache = $injector.get($TEMPLATE_CACHE) as ITemplateCacheService;
const url = getOrCall<string>(directive.templateUrl, $element);
const template = $templateCache.get(url);
if (template !== undefined) {
return template;
} else if (!fetchRemoteTemplate) {
throw new Error('loading directive templates asynchronously is not supported');
}
return new Promise((resolve, reject) => {
const $httpBackend = $injector.get($HTTP_BACKEND) as IHttpBackendService;
$httpBackend('GET', url, null, (status: number, response: string) => {
if (status === 200) {
resolve($templateCache.put(url, response));
} else {
reject(`GET component template from '${url}' returned '${status}: ${response}'`);
}
});
});
} else {
throw new Error(`Directive '${directive.name}' is not a component, it is missing template.`);
}
}
buildController(controllerType: IController, $scope: IScope) {
// TODO: Document that we do not pre-assign bindings on the controller instance.
// Quoted properties below so that this code can be optimized with Closure Compiler.
const locals = {'$scope': $scope, '$element': this.$element};
const controller = this.$controller(controllerType, locals, null, this.directive.controllerAs);
this.$element.data!(controllerKey(this.directive.name!), controller);
return controller;
}
compileTemplate(template?: string): ILinkFn {
if (template === undefined) {
template =
UpgradeHelper.getTemplate(this.$injector, this.directive, false, this.$element) as string;
}
return this.compileHtml(template);
}
onDestroy($scope: IScope, controllerInstance?: any) {
if (controllerInstance && isFunction(controllerInstance.$onDestroy)) {
controllerInstance.$onDestroy();
}
$scope.$destroy();
// Clean the jQuery/jqLite data on the component+child elements.
// Equivelent to how jQuery/jqLite invoke `cleanData` on an Element (this.element)
// https://github.com/jquery/jquery/blob/e743cbd28553267f955f71ea7248377915613fd9/src/manipulation.js#L223
// https://github.com/angular/angular.js/blob/26ddc5f830f902a3d22f4b2aab70d86d4d688c82/src/jqLite.js#L306-L312
// `cleanData` will invoke the AngularJS `$destroy` DOM event
// https://github.com/angular/angular.js/blob/26ddc5f830f902a3d22f4b2aab70d86d4d688c82/src/Angular.js#L1911-L1924
angularElement.cleanData([this.element]);
angularElement.cleanData(this.element.querySelectorAll('*'));
}
prepareTransclusion(): ILinkFn|undefined {
const transclude = this.directive.transclude;
const contentChildNodes = this.extractChildNodes();
const attachChildrenFn: ILinkFn = (scope, cloneAttachFn) => {
// Since AngularJS v1.5.8, `cloneAttachFn` will try to destroy the transclusion scope if
// `$template` is empty. Since the transcluded content comes from Angular, not AngularJS,
// there will be no transclusion scope here.
// Provide a dummy `scope.$destroy()` method to prevent `cloneAttachFn` from throwing.
scope = scope || {$destroy: () => undefined};
return cloneAttachFn!($template, scope);
};
let $template = contentChildNodes;
if (transclude) {
const slots = Object.create(null);
if (typeof transclude === 'object') {
$template = [];
const slotMap = Object.create(null);
const filledSlots = Object.create(null);
// Parse the element selectors.
Object.keys(transclude).forEach(slotName => {
let selector = transclude[slotName];
const optional = selector.charAt(0) === '?';
selector = optional ? selector.substring(1) : selector;
slotMap[selector] = slotName;
slots[slotName] = null; // `null`: Defined but not yet filled.
filledSlots[slotName] = optional; // Consider optional slots as filled.
});
// Add the matching elements into their slot.
contentChildNodes.forEach(node => {
const slotName = slotMap[directiveNormalize(node.nodeName.toLowerCase())];
if (slotName) {
filledSlots[slotName] = true;
slots[slotName] = slots[slotName] || [];
slots[slotName].push(node);
} else {
$template.push(node);
}
});
// Check for required slots that were not filled.
Object.keys(filledSlots).forEach(slotName => {
if (!filledSlots[slotName]) {
throw new Error(`Required transclusion slot '${slotName}' on directive: ${this.name}`);
}
});
Object.keys(slots).filter(slotName => slots[slotName]).forEach(slotName => {
const nodes = slots[slotName];
slots[slotName] = (scope: IScope, cloneAttach: ICloneAttachFunction) => {
return cloneAttach!(nodes, scope);
};
});
}
// Attach `$$slots` to default slot transclude fn.
attachChildrenFn.$$slots = slots;
// AngularJS v1.6+ ignores empty or whitespace-only transcluded text nodes. But Angular
// removes all text content after the first interpolation and updates it later, after
// evaluating the expressions. This would result in AngularJS failing to recognize text
// nodes that start with an interpolation as transcluded content and use the fallback
// content instead.
// To avoid this issue, we add a
// [zero-width non-joiner character](https://en.wikipedia.org/wiki/Zero-width_non-joiner)
// to empty text nodes (which can only be a result of Angular removing their initial content).
// NOTE: Transcluded text content that starts with whitespace followed by an interpolation
// will still fail to be detected by AngularJS v1.6+
$template.forEach(node => {
if (node.nodeType === Node.TEXT_NODE && !node.nodeValue) {
node.nodeValue = '\u200C';
}
});
}
return attachChildrenFn;
}
resolveAndBindRequiredControllers(controllerInstance: IControllerInstance|null) {
const directiveRequire = this.getDirectiveRequire();
const requiredControllers = this.resolveRequire(directiveRequire);
if (controllerInstance && this.directive.bindToController && isMap(directiveRequire)) {
const requiredControllersMap = requiredControllers as {[key: string]: IControllerInstance};
Object.keys(requiredControllersMap).forEach(key => {
controllerInstance[key] = requiredControllersMap[key];
});
}
return requiredControllers;
}
private compileHtml(html: string): ILinkFn {
this.element.innerHTML = html;
return this.$compile(this.element.childNodes);
}
private extractChildNodes(): Node[] {
const childNodes: Node[] = [];
let childNode: Node|null;
while (childNode = this.element.firstChild) {
this.element.removeChild(childNode);
childNodes.push(childNode);
}
return childNodes;
}
private getDirectiveRequire(): DirectiveRequireProperty {
const require = this.directive.require || (this.directive.controller && this.directive.name)!;
if (isMap(require)) {
Object.keys(require).forEach(key => {
const value = require[key];
const match = value.match(REQUIRE_PREFIX_RE)!;
const name = value.substring(match[0].length);
if (!name) {
require[key] = match[0] + key;
}
});
}
return require;
}
private resolveRequire(require: DirectiveRequireProperty, controllerInstance?: any):
SingleOrListOrMap<IControllerInstance>|null {
if (!require) {
return null;
} else if (Array.isArray(require)) {
return require.map(req => this.resolveRequire(req));
} else if (typeof require === 'object') {
const value: {[key: string]: IControllerInstance} = {};
Object.keys(require).forEach(key => value[key] = this.resolveRequire(require[key])!);
return value;
} else if (typeof require === 'string') {
const match = require.match(REQUIRE_PREFIX_RE)!;
const inheritType = match[1] || match[3];
const name = require.substring(match[0].length);
const isOptional = !!match[2];
const searchParents = !!inheritType;
const startOnParent = inheritType === '^^';
const ctrlKey = controllerKey(name);
const elem = startOnParent ? this.$element.parent!() : this.$element;
const value = searchParents ? elem.inheritedData!(ctrlKey) : elem.data!(ctrlKey);
if (!value && !isOptional) {
throw new Error(
`Unable to find required '${require}' in upgraded directive '${this.name}'.`);
}
return value;
} else {
throw new Error(
`Unrecognized 'require' syntax on upgraded directive '${this.name}': ${require}`);
}
}
}
function getOrCall<T>(property: T|Function, ...args: any[]): T {
return isFunction(property) ? property(...args) : property;
}
// NOTE: Only works for `typeof T !== 'object'`.
function isMap<T>(value: SingleOrListOrMap<T>): value is {[key: string]: T} {
return value && !Array.isArray(value) && typeof value === 'object';
}
function notSupported(name: string, feature: string) {
throw new Error(`Upgraded directive '${name}' contains unsupported feature: '${feature}'.`);
}
| packages/upgrade/src/common/src/upgrade_helper.ts | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.0001766332716215402,
0.0001716047408990562,
0.0001636744855204597,
0.00017224324983544648,
0.000003824087343673455
] |
{
"id": 4,
"code_window": [
" runGraceful(args: string[], options: SpawnSyncOptions = {}): SpawnSyncReturns<string> {\n",
" // To improve the debugging experience in case something fails, we print all executed\n",
" // Git commands. Note that we do not want to print the token if is contained in the\n",
" // command. It's common to share errors with others if the tool failed.\n",
" console.info('Executing: git', this.omitGithubTokenFromMessage(args.join(' ')));\n",
"\n",
" const result = spawnSync('git', args, {\n",
" cwd: this._projectRoot,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" info('Executing: git', this.omitGithubTokenFromMessage(args.join(' ')));\n"
],
"file_path": "dev-infra/pr/merge/git.ts",
"type": "replace",
"edit_start_line_idx": 76
} | /**
* @license
* Copyright Google LLC 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 * as Octokit from '@octokit/rest';
import {spawnSync, SpawnSyncOptions, SpawnSyncReturns} from 'child_process';
import {MergeConfigWithRemote} from './config';
/** Error for failed Github API requests. */
export class GithubApiRequestError extends Error {
constructor(public status: number, message: string) {
super(message);
}
}
/** Error for failed Git commands. */
export class GitCommandError extends Error {
constructor(client: GitClient, public args: string[]) {
// Errors are not guaranteed to be caught. To ensure that we don't
// accidentally leak the Github token that might be used in a command,
// we sanitize the command that will be part of the error message.
super(`Command failed: git ${client.omitGithubTokenFromMessage(args.join(' '))}`);
}
}
export class GitClient {
/** Short-hand for accessing the remote configuration. */
remoteConfig = this._config.remote;
/** Octokit request parameters object for targeting the configured remote. */
remoteParams = {owner: this.remoteConfig.owner, repo: this.remoteConfig.name};
/** URL that resolves to the configured repository. */
repoGitUrl = this.remoteConfig.useSsh ?
`[email protected]:${this.remoteConfig.owner}/${this.remoteConfig.name}.git` :
`https://${this._githubToken}@github.com/${this.remoteConfig.owner}/${
this.remoteConfig.name}.git`;
/** Instance of the authenticated Github octokit API. */
api: Octokit;
/** Regular expression that matches the provided Github token. */
private _tokenRegex = new RegExp(this._githubToken, 'g');
constructor(
private _projectRoot: string, private _githubToken: string,
private _config: MergeConfigWithRemote) {
this.api = new Octokit({auth: _githubToken});
this.api.hook.error('request', error => {
// Wrap API errors in a known error class. This allows us to
// expect Github API errors better and in a non-ambiguous way.
throw new GithubApiRequestError(error.status, error.message);
});
}
/** Executes the given git command. Throws if the command fails. */
run(args: string[], options?: SpawnSyncOptions): Omit<SpawnSyncReturns<string>, 'status'> {
const result = this.runGraceful(args, options);
if (result.status !== 0) {
throw new GitCommandError(this, args);
}
// Omit `status` from the type so that it's obvious that the status is never
// non-zero as explained in the method description.
return result as Omit<SpawnSyncReturns<string>, 'status'>;
}
/**
* Spawns a given Git command process. Does not throw if the command fails. Additionally,
* if there is any stderr output, the output will be printed. This makes it easier to
* debug failed commands.
*/
runGraceful(args: string[], options: SpawnSyncOptions = {}): SpawnSyncReturns<string> {
// To improve the debugging experience in case something fails, we print all executed
// Git commands. Note that we do not want to print the token if is contained in the
// command. It's common to share errors with others if the tool failed.
console.info('Executing: git', this.omitGithubTokenFromMessage(args.join(' ')));
const result = spawnSync('git', args, {
cwd: this._projectRoot,
stdio: 'pipe',
...options,
// Encoding is always `utf8` and not overridable. This ensures that this method
// always returns `string` as output instead of buffers.
encoding: 'utf8',
});
if (result.stderr !== null) {
// Git sometimes prints the command if it failed. This means that it could
// potentially leak the Github token used for accessing the remote. To avoid
// printing a token, we sanitize the string before printing the stderr output.
process.stderr.write(this.omitGithubTokenFromMessage(result.stderr));
}
return result;
}
/** Whether the given branch contains the specified SHA. */
hasCommit(branchName: string, sha: string): boolean {
return this.run(['branch', branchName, '--contains', sha]).stdout !== '';
}
/** Gets the currently checked out branch. */
getCurrentBranch(): string {
return this.run(['rev-parse', '--abbrev-ref', 'HEAD']).stdout.trim();
}
/** Gets whether the current Git repository has uncommitted changes. */
hasUncommittedChanges(): boolean {
return this.runGraceful(['diff-index', '--quiet', 'HEAD']).status !== 0;
}
/** Sanitizes a given message by omitting the provided Github token if present. */
omitGithubTokenFromMessage(value: string): string {
return value.replace(this._tokenRegex, '<TOKEN>');
}
}
| dev-infra/pr/merge/git.ts | 1 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.9983080625534058,
0.48609817028045654,
0.00017089524772018194,
0.45365092158317566,
0.47617849707603455
] |
{
"id": 4,
"code_window": [
" runGraceful(args: string[], options: SpawnSyncOptions = {}): SpawnSyncReturns<string> {\n",
" // To improve the debugging experience in case something fails, we print all executed\n",
" // Git commands. Note that we do not want to print the token if is contained in the\n",
" // command. It's common to share errors with others if the tool failed.\n",
" console.info('Executing: git', this.omitGithubTokenFromMessage(args.join(' ')));\n",
"\n",
" const result = spawnSync('git', args, {\n",
" cwd: this._projectRoot,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" info('Executing: git', this.omitGithubTokenFromMessage(args.join(' ')));\n"
],
"file_path": "dev-infra/pr/merge/git.ts",
"type": "replace",
"edit_start_line_idx": 76
} | import '../preview-server';
import './mock-external-apis';
| aio/aio-builds-setup/dockerbuild/scripts-js/lib/verify-setup/start-test-preview-server.ts | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.000172266096342355,
0.000172266096342355,
0.000172266096342355,
0.000172266096342355,
0
] |
{
"id": 4,
"code_window": [
" runGraceful(args: string[], options: SpawnSyncOptions = {}): SpawnSyncReturns<string> {\n",
" // To improve the debugging experience in case something fails, we print all executed\n",
" // Git commands. Note that we do not want to print the token if is contained in the\n",
" // command. It's common to share errors with others if the tool failed.\n",
" console.info('Executing: git', this.omitGithubTokenFromMessage(args.join(' ')));\n",
"\n",
" const result = spawnSync('git', args, {\n",
" cwd: this._projectRoot,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" info('Executing: git', this.omitGithubTokenFromMessage(args.join(' ')));\n"
],
"file_path": "dev-infra/pr/merge/git.ts",
"type": "replace",
"edit_start_line_idx": 76
} | /**
* @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 {global} from '../../src/util/global';
// Not yet available in TypeScript: https://github.com/Microsoft/TypeScript/pull/29332
declare var globalThis: any /** TODO #9100 */;
{
describe('global', () => {
it('should be global this value', () => {
const _global = new Function('return this')();
expect(global).toBe(_global);
});
if (typeof globalThis !== 'undefined') {
it('should use globalThis as global reference', () => {
expect(global).toBe(globalThis);
});
}
});
}
| packages/core/test/util/global_spec.ts | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.0001722864544717595,
0.00017085945000872016,
0.00016864985809661448,
0.00017164206656161696,
0.000001584416509103903
] |
{
"id": 4,
"code_window": [
" runGraceful(args: string[], options: SpawnSyncOptions = {}): SpawnSyncReturns<string> {\n",
" // To improve the debugging experience in case something fails, we print all executed\n",
" // Git commands. Note that we do not want to print the token if is contained in the\n",
" // command. It's common to share errors with others if the tool failed.\n",
" console.info('Executing: git', this.omitGithubTokenFromMessage(args.join(' ')));\n",
"\n",
" const result = spawnSync('git', args, {\n",
" cwd: this._projectRoot,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" info('Executing: git', this.omitGithubTokenFromMessage(args.join(' ')));\n"
],
"file_path": "dev-infra/pr/merge/git.ts",
"type": "replace",
"edit_start_line_idx": 76
} | /**
* @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 {StaticProvider} from '@angular/core';
import {describe, expect, it} from '@angular/core/testing/src/testing_internal';
import {ConsoleReporter, Injector, MeasureValues, SampleDescription} from '../../index';
{
describe('console reporter', () => {
let reporter: ConsoleReporter;
let log: string[];
function createReporter(
{columnWidth = null, sampleId = null, descriptions = null, metrics = null}: {
columnWidth?: number|null,
sampleId?: string|null,
descriptions?: {[key: string]: any}[]|null,
metrics?: {[key: string]: any}|null
}) {
log = [];
if (!descriptions) {
descriptions = [];
}
if (sampleId == null) {
sampleId = 'null';
}
const providers: StaticProvider[] = [
ConsoleReporter.PROVIDERS, {
provide: SampleDescription,
useValue: new SampleDescription(sampleId, descriptions, metrics!)
},
{provide: ConsoleReporter.PRINT, useValue: (line: string) => log.push(line)}
];
if (columnWidth != null) {
providers.push({provide: ConsoleReporter.COLUMN_WIDTH, useValue: columnWidth});
}
reporter = Injector.create(providers).get(ConsoleReporter);
}
it('should print the sample id, description and table header', () => {
createReporter({
columnWidth: 8,
sampleId: 'someSample',
descriptions: [{'a': 1, 'b': 2}],
metrics: {'m1': 'some desc', 'm2': 'some other desc'}
});
expect(log).toEqual([
'BENCHMARK someSample',
'Description:',
'- a: 1',
'- b: 2',
'Metrics:',
'- m1: some desc',
'- m2: some other desc',
'',
' m1 | m2',
'-------- | --------',
]);
});
it('should print a table row', () => {
createReporter({columnWidth: 8, metrics: {'a': '', 'b': ''}});
log = [];
reporter.reportMeasureValues(mv(0, 0, {'a': 1.23, 'b': 2}));
expect(log).toEqual([' 1.23 | 2.00']);
});
it('should print the table footer and stats when there is a valid sample', () => {
createReporter({columnWidth: 8, metrics: {'a': '', 'b': ''}});
log = [];
reporter.reportSample([], [mv(0, 0, {'a': 3, 'b': 6}), mv(1, 1, {'a': 5, 'b': 9})]);
expect(log).toEqual(['======== | ========', '4.00+-25% | 7.50+-20%']);
});
it('should print the coefficient of variation only when it is meaningful', () => {
createReporter({columnWidth: 8, metrics: {'a': '', 'b': ''}});
log = [];
reporter.reportSample([], [mv(0, 0, {'a': 3, 'b': 0}), mv(1, 1, {'a': 5, 'b': 0})]);
expect(log).toEqual(['======== | ========', '4.00+-25% | 0.00']);
});
});
}
function mv(runIndex: number, time: number, values: {[key: string]: number}) {
return new MeasureValues(runIndex, new Date(time), values);
}
| packages/benchpress/test/reporter/console_reporter_spec.ts | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.00017418437346350402,
0.00017205651965923607,
0.00016988988500088453,
0.00017190711514558643,
0.0000013977667094877688
] |
{
"id": 5,
"code_window": [
" *\n",
" * Use of this source code is governed by an MIT-style license that can be\n",
" * found in the LICENSE file at https://angular.io/license\n",
" */\n",
"\n",
"import chalk from 'chalk';\n",
"\n",
"import {getRepoBaseDir} from '../../utils/config';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "dev-infra/pr/merge/index.ts",
"type": "replace",
"edit_start_line_idx": 8
} | /**
* @license
* Copyright Google LLC 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 chalk from 'chalk';
import {getRepoBaseDir} from '../../utils/config';
import {promptConfirm} from '../../utils/console';
import {loadAndValidateConfig, MergeConfigWithRemote} from './config';
import {GithubApiRequestError} from './git';
import {MergeResult, MergeStatus, PullRequestMergeTask} from './task';
/** URL to the Github page where personal access tokens can be generated. */
export const GITHUB_TOKEN_GENERATE_URL = `https://github.com/settings/tokens`;
/**
* Merges a given pull request based on labels configured in the given merge configuration.
* Pull requests can be merged with different strategies such as the Github API merge
* strategy, or the local autosquash strategy. Either strategy has benefits and downsides.
* More information on these strategies can be found in their dedicated strategy classes.
*
* See {@link GithubApiMergeStrategy} and {@link AutosquashMergeStrategy}
*
* @param prNumber Number of the pull request that should be merged.
* @param githubToken Github token used for merging (i.e. fetching and pushing)
* @param projectRoot Path to the local Git project that is used for merging.
* @param config Configuration for merging pull requests.
*/
export async function mergePullRequest(
prNumber: number, githubToken: string, projectRoot: string = getRepoBaseDir(),
config?: MergeConfigWithRemote) {
// If no explicit configuration has been specified, we load and validate
// the configuration from the shared dev-infra configuration.
if (config === undefined) {
const {config: _config, errors} = loadAndValidateConfig();
if (errors) {
console.error(chalk.red('Invalid configuration:'));
errors.forEach(desc => console.error(chalk.yellow(` - ${desc}`)));
process.exit(1);
}
config = _config!;
}
const api = new PullRequestMergeTask(projectRoot, config, githubToken);
// Perform the merge. Force mode can be activated through a command line flag.
// Alternatively, if the merge fails with non-fatal failures, the script
// will prompt whether it should rerun in force mode.
if (!await performMerge(false)) {
process.exit(1);
}
/** Performs the merge and returns whether it was successful or not. */
async function performMerge(ignoreFatalErrors: boolean): Promise<boolean> {
try {
const result = await api.merge(prNumber, ignoreFatalErrors);
return await handleMergeResult(result, ignoreFatalErrors);
} catch (e) {
// Catch errors to the Github API for invalid requests. We want to
// exit the script with a better explanation of the error.
if (e instanceof GithubApiRequestError && e.status === 401) {
console.error(chalk.red('Github API request failed. ' + e.message));
console.error(chalk.yellow('Please ensure that your provided token is valid.'));
console.error(chalk.yellow(`You can generate a token here: ${GITHUB_TOKEN_GENERATE_URL}`));
process.exit(1);
}
throw e;
}
}
/**
* Prompts whether the specified pull request should be forcibly merged. If so, merges
* the specified pull request forcibly (ignoring non-critical failures).
* @returns Whether the specified pull request has been forcibly merged.
*/
async function promptAndPerformForceMerge(): Promise<boolean> {
if (await promptConfirm('Do you want to forcibly proceed with merging?')) {
// Perform the merge in force mode. This means that non-fatal failures
// are ignored and the merge continues.
return performMerge(true);
}
return false;
}
/**
* Handles the merge result by printing console messages, exiting the process
* based on the result, or by restarting the merge if force mode has been enabled.
* @returns Whether the merge was successful or not.
*/
async function handleMergeResult(result: MergeResult, disableForceMergePrompt = false) {
const {failure, status} = result;
const canForciblyMerge = failure && failure.nonFatal;
switch (status) {
case MergeStatus.SUCCESS:
console.info(chalk.green(`Successfully merged the pull request: ${prNumber}`));
return true;
case MergeStatus.DIRTY_WORKING_DIR:
console.error(chalk.red(
`Local working repository not clean. Please make sure there are ` +
`no uncommitted changes.`));
return false;
case MergeStatus.UNKNOWN_GIT_ERROR:
console.error(chalk.red(
'An unknown Git error has been thrown. Please check the output ' +
'above for details.'));
return false;
case MergeStatus.FAILED:
console.error(chalk.yellow(`Could not merge the specified pull request.`));
console.error(chalk.red(failure!.message));
if (canForciblyMerge && !disableForceMergePrompt) {
console.info();
console.info(chalk.yellow('The pull request above failed due to non-critical errors.'));
console.info(chalk.yellow(`This error can be forcibly ignored if desired.`));
return await promptAndPerformForceMerge();
}
return false;
default:
throw Error(`Unexpected merge result: ${status}`);
}
}
}
| dev-infra/pr/merge/index.ts | 1 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.0003517070726957172,
0.00019230593170505017,
0.00016597039939370006,
0.00017595113604329526,
0.00004749040090246126
] |
{
"id": 5,
"code_window": [
" *\n",
" * Use of this source code is governed by an MIT-style license that can be\n",
" * found in the LICENSE file at https://angular.io/license\n",
" */\n",
"\n",
"import chalk from 'chalk';\n",
"\n",
"import {getRepoBaseDir} from '../../utils/config';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "dev-infra/pr/merge/index.ts",
"type": "replace",
"edit_start_line_idx": 8
} | /**
* @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 {patchMethod, patchProperty, patchPrototype, zoneSymbol} from '../../lib/common/utils';
describe('utils', function() {
describe('patchMethod', () => {
it('should patch target where the method is defined', () => {
let args: any[]|undefined;
let self: any;
class Type {
method(..._args: any[]) {
args = _args;
self = this;
return 'OK';
}
}
const method = Type.prototype.method;
let delegateMethod: Function;
let delegateSymbol: string;
const instance = new Type();
expect(patchMethod(instance, 'method', (delegate: Function, symbol: string, name: string) => {
expect(name).toEqual('method');
delegateMethod = delegate;
delegateSymbol = symbol;
return function(self, args) {
return delegate.apply(self, ['patch', args[0]]);
};
})).toBe(delegateMethod!);
expect(instance.method('a0')).toEqual('OK');
expect(args).toEqual(['patch', 'a0']);
expect(self).toBe(instance);
expect(delegateMethod!).toBe(method);
expect(delegateSymbol!).toEqual(zoneSymbol('method'));
expect((Type.prototype as any)[delegateSymbol!]).toBe(method);
});
it('should not double patch', () => {
const Type = function() {};
const method = Type.prototype.method = function() {};
patchMethod(Type.prototype, 'method', (delegate) => {
return function(self, args: any[]) {
return delegate.apply(self, ['patch', ...args]);
};
});
const pMethod = Type.prototype.method;
expect(pMethod).not.toBe(method);
patchMethod(Type.prototype, 'method', (delegate) => {
return function(self, args) {
return delegate.apply(self, ['patch', ...args]);
};
});
expect(pMethod).toBe(Type.prototype.method);
});
it('should not patch property which is not configurable', () => {
const TestType = function() {};
const originalDefineProperty = (Object as any)[zoneSymbol('defineProperty')];
if (originalDefineProperty) {
originalDefineProperty(
TestType.prototype, 'nonConfigurableProperty',
{configurable: false, writable: true, value: 'test'});
} else {
Object.defineProperty(
TestType.prototype, 'nonConfigurableProperty',
{configurable: false, writable: true, value: 'test'});
}
patchProperty(TestType.prototype, 'nonConfigurableProperty');
const desc = Object.getOwnPropertyDescriptor(TestType.prototype, 'nonConfigurableProperty');
expect(desc!.writable).toBeTruthy();
expect(!desc!.get).toBeTruthy();
});
});
describe('patchPrototype', () => {
it('non configurable property desc should be patched', () => {
'use strict';
const TestFunction: any = function() {};
const log: string[] = [];
Object.defineProperties(TestFunction.prototype, {
'property1': {
value: function Property1(callback: Function) {
Zone.root.run(callback);
},
writable: true,
configurable: true,
enumerable: true
},
'property2': {
value: function Property2(callback: Function) {
Zone.root.run(callback);
},
writable: true,
configurable: false,
enumerable: true
}
});
const zone = Zone.current.fork({name: 'patch'});
zone.run(() => {
const instance = new TestFunction();
instance.property1(() => {
log.push('property1' + Zone.current.name);
});
instance.property2(() => {
log.push('property2' + Zone.current.name);
});
});
expect(log).toEqual(['property1<root>', 'property2<root>']);
log.length = 0;
patchPrototype(TestFunction.prototype, ['property1', 'property2']);
zone.run(() => {
const instance = new TestFunction();
instance.property1(() => {
log.push('property1' + Zone.current.name);
});
instance.property2(() => {
log.push('property2' + Zone.current.name);
});
});
expect(log).toEqual(['property1patch', 'property2patch']);
});
it('non writable property desc should not be patched', () => {
'use strict';
const TestFunction: any = function() {};
const log: string[] = [];
Object.defineProperties(TestFunction.prototype, {
'property1': {
value: function Property1(callback: Function) {
Zone.root.run(callback);
},
writable: true,
configurable: true,
enumerable: true
},
'property2': {
value: function Property2(callback: Function) {
Zone.root.run(callback);
},
writable: false,
configurable: true,
enumerable: true
}
});
const zone = Zone.current.fork({name: 'patch'});
zone.run(() => {
const instance = new TestFunction();
instance.property1(() => {
log.push('property1' + Zone.current.name);
});
instance.property2(() => {
log.push('property2' + Zone.current.name);
});
});
expect(log).toEqual(['property1<root>', 'property2<root>']);
log.length = 0;
patchPrototype(TestFunction.prototype, ['property1', 'property2']);
zone.run(() => {
const instance = new TestFunction();
instance.property1(() => {
log.push('property1' + Zone.current.name);
});
instance.property2(() => {
log.push('property2' + Zone.current.name);
});
});
expect(log).toEqual(['property1patch', 'property2<root>']);
});
it('readonly property desc should not be patched', () => {
'use strict';
const TestFunction: any = function() {};
const log: string[] = [];
Object.defineProperties(TestFunction.prototype, {
'property1': {
get: function() {
if (!this._property1) {
this._property1 = function Property2(callback: Function) {
Zone.root.run(callback);
};
}
return this._property1;
},
set: function(func: Function) {
this._property1 = func;
},
configurable: true,
enumerable: true
},
'property2': {
get: function() {
return function Property2(callback: Function) {
Zone.root.run(callback);
};
},
configurable: true,
enumerable: true
}
});
const zone = Zone.current.fork({name: 'patch'});
zone.run(() => {
const instance = new TestFunction();
instance.property1(() => {
log.push('property1' + Zone.current.name);
});
instance.property2(() => {
log.push('property2' + Zone.current.name);
});
});
expect(log).toEqual(['property1<root>', 'property2<root>']);
log.length = 0;
patchPrototype(TestFunction.prototype, ['property1', 'property2']);
zone.run(() => {
const instance = new TestFunction();
instance.property1(() => {
log.push('property1' + Zone.current.name);
});
instance.property2(() => {
log.push('property2' + Zone.current.name);
});
});
expect(log).toEqual(['property1patch', 'property2<root>']);
});
it('non writable method should not be patched', () => {
'use strict';
const TestFunction: any = function() {};
const log: string[] = [];
Object.defineProperties(TestFunction.prototype, {
'property2': {
value: function Property2(callback: Function) {
Zone.root.run(callback);
},
writable: false,
configurable: true,
enumerable: true
}
});
const zone = Zone.current.fork({name: 'patch'});
zone.run(() => {
const instance = new TestFunction();
instance.property2(() => {
log.push('property2' + Zone.current.name);
});
});
expect(log).toEqual(['property2<root>']);
log.length = 0;
patchMethod(
TestFunction.prototype, 'property2',
function(delegate: Function, delegateName: string, name: string) {
return function(self: any, args: any) {
log.push('patched property2');
};
});
zone.run(() => {
const instance = new TestFunction();
instance.property2(() => {
log.push('property2' + Zone.current.name);
});
});
expect(log).toEqual(['property2<root>']);
});
it('readonly method should not be patched', () => {
'use strict';
const TestFunction: any = function() {};
const log: string[] = [];
Object.defineProperties(TestFunction.prototype, {
'property2': {
get: function() {
return function Property2(callback: Function) {
Zone.root.run(callback);
};
},
configurable: true,
enumerable: true
}
});
const zone = Zone.current.fork({name: 'patch'});
zone.run(() => {
const instance = new TestFunction();
instance.property2(() => {
log.push('property2' + Zone.current.name);
});
});
expect(log).toEqual(['property2<root>']);
log.length = 0;
patchMethod(
TestFunction.prototype, 'property2',
function(delegate: Function, delegateName: string, name: string) {
return function(self: any, args: any) {
log.push('patched property2');
};
});
zone.run(() => {
const instance = new TestFunction();
instance.property2(() => {
log.push('property2' + Zone.current.name);
});
});
expect(log).toEqual(['property2<root>']);
});
});
});
| packages/zone.js/test/common/util.spec.ts | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.00018081899906974286,
0.00017542428395245224,
0.0001655824889894575,
0.000175725290318951,
0.000002849317979780608
] |
{
"id": 5,
"code_window": [
" *\n",
" * Use of this source code is governed by an MIT-style license that can be\n",
" * found in the LICENSE file at https://angular.io/license\n",
" */\n",
"\n",
"import chalk from 'chalk';\n",
"\n",
"import {getRepoBaseDir} from '../../utils/config';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "dev-infra/pr/merge/index.ts",
"type": "replace",
"edit_start_line_idx": 8
} | import { Component } from '@angular/core';
import { LoggerService } from '../core/logger.service';
import { SpinnerService } from '../core/spinner/spinner.service';
@Component({
selector: 'toh-heroes',
templateUrl: './heroes.component.html'
})
export class HeroesComponent {
heroes: any[];
constructor(
private loggerService: LoggerService,
private spinnerService: SpinnerService
) { }
getHeroes() {
this.loggerService.log(`Getting heroes`);
this.spinnerService.show();
setTimeout(() => {
this.heroes = [
{ id: 1, name: 'Windstorm' },
{ id: 2, name: 'Bombasto' },
{ id: 3, name: 'Magneta' },
{ id: 4, name: 'Tornado' }
];
this.loggerService.log(`We have ${HeroesComponent.length} heroes`);
this.spinnerService.hide();
}, 2000);
}
}
| aio/content/examples/styleguide/src/04-11/app/heroes/heroes.component.ts | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.0001805717620300129,
0.00017696680151857436,
0.00017338964971713722,
0.00017695288988761604,
0.000002542436504882062
] |
{
"id": 5,
"code_window": [
" *\n",
" * Use of this source code is governed by an MIT-style license that can be\n",
" * found in the LICENSE file at https://angular.io/license\n",
" */\n",
"\n",
"import chalk from 'chalk';\n",
"\n",
"import {getRepoBaseDir} from '../../utils/config';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "dev-infra/pr/merge/index.ts",
"type": "replace",
"edit_start_line_idx": 8
} | /**
* @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 {assertEqual, throwError} from '../../util/assert';
import {CharCode} from '../../util/char_code';
/**
* Stores the locations of key/value indexes while parsing styling.
*
* In case of `cssText` parsing the indexes are like so:
* ```
* "key1: value1; key2: value2; key3: value3"
* ^ ^ ^ ^ ^
* | | | | +-- textEnd
* | | | +---------------- valueEnd
* | | +---------------------- value
* | +------------------------ keyEnd
* +---------------------------- key
* ```
*
* In case of `className` parsing the indexes are like so:
* ```
* "key1 key2 key3"
* ^ ^ ^
* | | +-- textEnd
* | +------------------------ keyEnd
* +---------------------------- key
* ```
* NOTE: `value` and `valueEnd` are used only for styles, not classes.
*/
interface ParserState {
textEnd: number;
key: number;
keyEnd: number;
value: number;
valueEnd: number;
}
// Global state of the parser. (This makes parser non-reentrant, but that is not an issue)
const parserState: ParserState = {
textEnd: 0,
key: 0,
keyEnd: 0,
value: 0,
valueEnd: 0,
};
/**
* Retrieves the last parsed `key` of style.
* @param text the text to substring the key from.
*/
export function getLastParsedKey(text: string): string {
return text.substring(parserState.key, parserState.keyEnd);
}
/**
* Retrieves the last parsed `value` of style.
* @param text the text to substring the key from.
*/
export function getLastParsedValue(text: string): string {
return text.substring(parserState.value, parserState.valueEnd);
}
/**
* Initializes `className` string for parsing and parses the first token.
*
* This function is intended to be used in this format:
* ```
* for (let i = parseClassName(text); i >= 0; i = parseClassNameNext(text, i)) {
* const key = getLastParsedKey();
* ...
* }
* ```
* @param text `className` to parse
* @returns index where the next invocation of `parseClassNameNext` should resume.
*/
export function parseClassName(text: string): number {
resetParserState(text);
return parseClassNameNext(text, consumeWhitespace(text, 0, parserState.textEnd));
}
/**
* Parses next `className` token.
*
* This function is intended to be used in this format:
* ```
* for (let i = parseClassName(text); i >= 0; i = parseClassNameNext(text, i)) {
* const key = getLastParsedKey();
* ...
* }
* ```
*
* @param text `className` to parse
* @param index where the parsing should resume.
* @returns index where the next invocation of `parseClassNameNext` should resume.
*/
export function parseClassNameNext(text: string, index: number): number {
const end = parserState.textEnd;
if (end === index) {
return -1;
}
index = parserState.keyEnd = consumeClassToken(text, parserState.key = index, end);
return consumeWhitespace(text, index, end);
}
/**
* Initializes `cssText` string for parsing and parses the first key/values.
*
* This function is intended to be used in this format:
* ```
* for (let i = parseStyle(text); i >= 0; i = parseStyleNext(text, i))) {
* const key = getLastParsedKey();
* const value = getLastParsedValue();
* ...
* }
* ```
* @param text `cssText` to parse
* @returns index where the next invocation of `parseStyleNext` should resume.
*/
export function parseStyle(text: string): number {
resetParserState(text);
return parseStyleNext(text, consumeWhitespace(text, 0, parserState.textEnd));
}
/**
* Parses the next `cssText` key/values.
*
* This function is intended to be used in this format:
* ```
* for (let i = parseStyle(text); i >= 0; i = parseStyleNext(text, i))) {
* const key = getLastParsedKey();
* const value = getLastParsedValue();
* ...
* }
*
* @param text `cssText` to parse
* @param index where the parsing should resume.
* @returns index where the next invocation of `parseStyleNext` should resume.
*/
export function parseStyleNext(text: string, startIndex: number): number {
const end = parserState.textEnd;
let index = parserState.key = consumeWhitespace(text, startIndex, end);
if (end === index) {
// we reached an end so just quit
return -1;
}
index = parserState.keyEnd = consumeStyleKey(text, index, end);
index = consumeSeparator(text, index, end, CharCode.COLON);
index = parserState.value = consumeWhitespace(text, index, end);
index = parserState.valueEnd = consumeStyleValue(text, index, end);
return consumeSeparator(text, index, end, CharCode.SEMI_COLON);
}
/**
* Reset the global state of the styling parser.
* @param text The styling text to parse.
*/
export function resetParserState(text: string): void {
parserState.key = 0;
parserState.keyEnd = 0;
parserState.value = 0;
parserState.valueEnd = 0;
parserState.textEnd = text.length;
}
/**
* Returns index of next non-whitespace character.
*
* @param text Text to scan
* @param startIndex Starting index of character where the scan should start.
* @param endIndex Ending index of character where the scan should end.
* @returns Index of next non-whitespace character (May be the same as `start` if no whitespace at
* that location.)
*/
export function consumeWhitespace(text: string, startIndex: number, endIndex: number): number {
while (startIndex < endIndex && text.charCodeAt(startIndex) <= CharCode.SPACE) {
startIndex++;
}
return startIndex;
}
/**
* Returns index of last char in class token.
*
* @param text Text to scan
* @param startIndex Starting index of character where the scan should start.
* @param endIndex Ending index of character where the scan should end.
* @returns Index after last char in class token.
*/
export function consumeClassToken(text: string, startIndex: number, endIndex: number): number {
while (startIndex < endIndex && text.charCodeAt(startIndex) > CharCode.SPACE) {
startIndex++;
}
return startIndex;
}
/**
* Consumes all of the characters belonging to style key and token.
*
* @param text Text to scan
* @param startIndex Starting index of character where the scan should start.
* @param endIndex Ending index of character where the scan should end.
* @returns Index after last style key character.
*/
export function consumeStyleKey(text: string, startIndex: number, endIndex: number): number {
let ch: number;
while (startIndex < endIndex &&
((ch = text.charCodeAt(startIndex)) === CharCode.DASH || ch === CharCode.UNDERSCORE ||
((ch & CharCode.UPPER_CASE) >= CharCode.A && (ch & CharCode.UPPER_CASE) <= CharCode.Z))) {
startIndex++;
}
return startIndex;
}
/**
* Consumes all whitespace and the separator `:` after the style key.
*
* @param text Text to scan
* @param startIndex Starting index of character where the scan should start.
* @param endIndex Ending index of character where the scan should end.
* @returns Index after separator and surrounding whitespace.
*/
export function consumeSeparator(
text: string, startIndex: number, endIndex: number, separator: number): number {
startIndex = consumeWhitespace(text, startIndex, endIndex);
if (startIndex < endIndex) {
if (ngDevMode && text.charCodeAt(startIndex) !== separator) {
malformedStyleError(text, String.fromCharCode(separator), startIndex);
}
startIndex++;
}
return startIndex;
}
/**
* Consumes style value honoring `url()` and `""` text.
*
* @param text Text to scan
* @param startIndex Starting index of character where the scan should start.
* @param endIndex Ending index of character where the scan should end.
* @returns Index after last style value character.
*/
export function consumeStyleValue(text: string, startIndex: number, endIndex: number): number {
let ch1 = -1; // 1st previous character
let ch2 = -1; // 2nd previous character
let ch3 = -1; // 3rd previous character
let i = startIndex;
let lastChIndex = i;
while (i < endIndex) {
const ch: number = text.charCodeAt(i++);
if (ch === CharCode.SEMI_COLON) {
return lastChIndex;
} else if (ch === CharCode.DOUBLE_QUOTE || ch === CharCode.SINGLE_QUOTE) {
lastChIndex = i = consumeQuotedText(text, ch, i, endIndex);
} else if (
startIndex ===
i - 4 && // We have seen only 4 characters so far "URL(" (Ignore "foo_URL()")
ch3 === CharCode.U &&
ch2 === CharCode.R && ch1 === CharCode.L && ch === CharCode.OPEN_PAREN) {
lastChIndex = i = consumeQuotedText(text, CharCode.CLOSE_PAREN, i, endIndex);
} else if (ch > CharCode.SPACE) {
// if we have a non-whitespace character then capture its location
lastChIndex = i;
}
ch3 = ch2;
ch2 = ch1;
ch1 = ch & CharCode.UPPER_CASE;
}
return lastChIndex;
}
/**
* Consumes all of the quoted characters.
*
* @param text Text to scan
* @param quoteCharCode CharCode of either `"` or `'` quote or `)` for `url(...)`.
* @param startIndex Starting index of character where the scan should start.
* @param endIndex Ending index of character where the scan should end.
* @returns Index after quoted characters.
*/
export function consumeQuotedText(
text: string, quoteCharCode: number, startIndex: number, endIndex: number): number {
let ch1 = -1; // 1st previous character
let index = startIndex;
while (index < endIndex) {
const ch = text.charCodeAt(index++);
if (ch == quoteCharCode && ch1 !== CharCode.BACK_SLASH) {
return index;
}
if (ch == CharCode.BACK_SLASH && ch1 === CharCode.BACK_SLASH) {
// two back slashes cancel each other out. For example `"\\"` should properly end the
// quotation. (It should not assume that the last `"` is escaped.)
ch1 = 0;
} else {
ch1 = ch;
}
}
throw ngDevMode ? malformedStyleError(text, String.fromCharCode(quoteCharCode), endIndex) :
new Error();
}
function malformedStyleError(text: string, expecting: string, index: number): never {
ngDevMode && assertEqual(typeof text === 'string', true, 'String expected here');
throw throwError(
`Malformed style at location ${index} in string '` + text.substring(0, index) + '[>>' +
text.substring(index, index + 1) + '<<]' + text.substr(index + 1) +
`'. Expecting '${expecting}'.`);
}
| packages/core/src/render3/styling/styling_parser.ts | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.00018042512238025665,
0.00017286496586166322,
0.00016538400086574256,
0.00017302796186413616,
0.0000030006892757228343
] |
{
"id": 6,
"code_window": [
"\n",
"import {getRepoBaseDir} from '../../utils/config';\n",
"import {promptConfirm} from '../../utils/console';\n",
"\n",
"import {loadAndValidateConfig, MergeConfigWithRemote} from './config';\n",
"import {GithubApiRequestError} from './git';\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {error, green, info, promptConfirm, red, yellow} from '../../utils/console';\n"
],
"file_path": "dev-infra/pr/merge/index.ts",
"type": "replace",
"edit_start_line_idx": 11
} | /**
* @license
* Copyright Google LLC 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 * as Octokit from '@octokit/rest';
import {spawnSync, SpawnSyncOptions, SpawnSyncReturns} from 'child_process';
import {MergeConfigWithRemote} from './config';
/** Error for failed Github API requests. */
export class GithubApiRequestError extends Error {
constructor(public status: number, message: string) {
super(message);
}
}
/** Error for failed Git commands. */
export class GitCommandError extends Error {
constructor(client: GitClient, public args: string[]) {
// Errors are not guaranteed to be caught. To ensure that we don't
// accidentally leak the Github token that might be used in a command,
// we sanitize the command that will be part of the error message.
super(`Command failed: git ${client.omitGithubTokenFromMessage(args.join(' '))}`);
}
}
export class GitClient {
/** Short-hand for accessing the remote configuration. */
remoteConfig = this._config.remote;
/** Octokit request parameters object for targeting the configured remote. */
remoteParams = {owner: this.remoteConfig.owner, repo: this.remoteConfig.name};
/** URL that resolves to the configured repository. */
repoGitUrl = this.remoteConfig.useSsh ?
`[email protected]:${this.remoteConfig.owner}/${this.remoteConfig.name}.git` :
`https://${this._githubToken}@github.com/${this.remoteConfig.owner}/${
this.remoteConfig.name}.git`;
/** Instance of the authenticated Github octokit API. */
api: Octokit;
/** Regular expression that matches the provided Github token. */
private _tokenRegex = new RegExp(this._githubToken, 'g');
constructor(
private _projectRoot: string, private _githubToken: string,
private _config: MergeConfigWithRemote) {
this.api = new Octokit({auth: _githubToken});
this.api.hook.error('request', error => {
// Wrap API errors in a known error class. This allows us to
// expect Github API errors better and in a non-ambiguous way.
throw new GithubApiRequestError(error.status, error.message);
});
}
/** Executes the given git command. Throws if the command fails. */
run(args: string[], options?: SpawnSyncOptions): Omit<SpawnSyncReturns<string>, 'status'> {
const result = this.runGraceful(args, options);
if (result.status !== 0) {
throw new GitCommandError(this, args);
}
// Omit `status` from the type so that it's obvious that the status is never
// non-zero as explained in the method description.
return result as Omit<SpawnSyncReturns<string>, 'status'>;
}
/**
* Spawns a given Git command process. Does not throw if the command fails. Additionally,
* if there is any stderr output, the output will be printed. This makes it easier to
* debug failed commands.
*/
runGraceful(args: string[], options: SpawnSyncOptions = {}): SpawnSyncReturns<string> {
// To improve the debugging experience in case something fails, we print all executed
// Git commands. Note that we do not want to print the token if is contained in the
// command. It's common to share errors with others if the tool failed.
console.info('Executing: git', this.omitGithubTokenFromMessage(args.join(' ')));
const result = spawnSync('git', args, {
cwd: this._projectRoot,
stdio: 'pipe',
...options,
// Encoding is always `utf8` and not overridable. This ensures that this method
// always returns `string` as output instead of buffers.
encoding: 'utf8',
});
if (result.stderr !== null) {
// Git sometimes prints the command if it failed. This means that it could
// potentially leak the Github token used for accessing the remote. To avoid
// printing a token, we sanitize the string before printing the stderr output.
process.stderr.write(this.omitGithubTokenFromMessage(result.stderr));
}
return result;
}
/** Whether the given branch contains the specified SHA. */
hasCommit(branchName: string, sha: string): boolean {
return this.run(['branch', branchName, '--contains', sha]).stdout !== '';
}
/** Gets the currently checked out branch. */
getCurrentBranch(): string {
return this.run(['rev-parse', '--abbrev-ref', 'HEAD']).stdout.trim();
}
/** Gets whether the current Git repository has uncommitted changes. */
hasUncommittedChanges(): boolean {
return this.runGraceful(['diff-index', '--quiet', 'HEAD']).status !== 0;
}
/** Sanitizes a given message by omitting the provided Github token if present. */
omitGithubTokenFromMessage(value: string): string {
return value.replace(this._tokenRegex, '<TOKEN>');
}
}
| dev-infra/pr/merge/git.ts | 1 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.0028149329591542482,
0.0005579459830187261,
0.0001653423678362742,
0.00018517588614486158,
0.0007574585033580661
] |
{
"id": 6,
"code_window": [
"\n",
"import {getRepoBaseDir} from '../../utils/config';\n",
"import {promptConfirm} from '../../utils/console';\n",
"\n",
"import {loadAndValidateConfig, MergeConfigWithRemote} from './config';\n",
"import {GithubApiRequestError} from './git';\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {error, green, info, promptConfirm, red, yellow} from '../../utils/console';\n"
],
"file_path": "dev-infra/pr/merge/index.ts",
"type": "replace",
"edit_start_line_idx": 11
} | /**
* @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 {CompileNgModuleMetadata, CompileTypeMetadata, identifierName} from '../compile_metadata';
import {CompileMetadataResolver} from '../metadata_resolver';
import * as o from '../output/output_ast';
import {OutputContext} from '../util';
import {Identifiers as R3} from './r3_identifiers';
/**
* Write a Renderer2 compatibility module factory to the output context.
*/
export function compileModuleFactory(
outputCtx: OutputContext, module: CompileNgModuleMetadata,
backPatchReferenceOf: (module: CompileTypeMetadata) => o.Expression,
resolver: CompileMetadataResolver) {
const ngModuleFactoryVar = `${identifierName(module.type)}NgFactory`;
const parentInjector = 'parentInjector';
const createFunction = o.fn(
[new o.FnParam(parentInjector, o.DYNAMIC_TYPE)],
[new o.IfStmt(
o.THIS_EXPR.prop(R3.PATCH_DEPS).notIdentical(o.literal(true, o.INFERRED_TYPE)),
[
o.THIS_EXPR.prop(R3.PATCH_DEPS).set(o.literal(true, o.INFERRED_TYPE)).toStmt(),
backPatchReferenceOf(module.type).callFn([]).toStmt()
])],
o.INFERRED_TYPE, null, `${ngModuleFactoryVar}_Create`);
const moduleFactoryLiteral = o.literalMap([
{key: 'moduleType', value: outputCtx.importExpr(module.type.reference), quoted: false},
{key: 'create', value: createFunction, quoted: false}
]);
outputCtx.statements.push(
o.variable(ngModuleFactoryVar).set(moduleFactoryLiteral).toDeclStmt(o.DYNAMIC_TYPE, [
o.StmtModifier.Exported, o.StmtModifier.Final
]));
}
| packages/compiler/src/render3/r3_module_factory_compiler.ts | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.00017495623615104705,
0.00017110275803133845,
0.00016617498476989567,
0.00017240380111616105,
0.0000033901828828675207
] |
{
"id": 6,
"code_window": [
"\n",
"import {getRepoBaseDir} from '../../utils/config';\n",
"import {promptConfirm} from '../../utils/console';\n",
"\n",
"import {loadAndValidateConfig, MergeConfigWithRemote} from './config';\n",
"import {GithubApiRequestError} from './git';\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {error, green, info, promptConfirm, red, yellow} from '../../utils/console';\n"
],
"file_path": "dev-infra/pr/merge/index.ts",
"type": "replace",
"edit_start_line_idx": 11
} | /**
* @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 {AbsoluteFsPath, FileSystem} from '../../../../src/ngtsc/file_system';
/**
* Returns true if the given `path` is a directory (not a symlink) and actually exists.
*
* @param fs the current filesystem
* @param path the path to check
*/
export function isLocalDirectory(fs: FileSystem, path: AbsoluteFsPath): boolean {
if (fs.exists(path)) {
const stat = fs.lstat(path);
return stat.isDirectory();
} else {
return false;
}
}
| packages/compiler-cli/ngcc/src/writing/cleaning/utils.ts | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.00017662046593613923,
0.00017408285930287093,
0.00017233230755664408,
0.0001732957607600838,
0.0000018369723875366617
] |
{
"id": 6,
"code_window": [
"\n",
"import {getRepoBaseDir} from '../../utils/config';\n",
"import {promptConfirm} from '../../utils/console';\n",
"\n",
"import {loadAndValidateConfig, MergeConfigWithRemote} from './config';\n",
"import {GithubApiRequestError} from './git';\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {error, green, info, promptConfirm, red, yellow} from '../../utils/console';\n"
],
"file_path": "dev-infra/pr/merge/index.ts",
"type": "replace",
"edit_start_line_idx": 11
} | export * from './heroes';
export * from './app.component';
| aio/content/examples/styleguide/src/07-01/app/index.ts | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.00017321911582257599,
0.00017321911582257599,
0.00017321911582257599,
0.00017321911582257599,
0
] |
{
"id": 7,
"code_window": [
" // If no explicit configuration has been specified, we load and validate\n",
" // the configuration from the shared dev-infra configuration.\n",
" if (config === undefined) {\n",
" const {config: _config, errors} = loadAndValidateConfig();\n",
" if (errors) {\n",
" console.error(chalk.red('Invalid configuration:'));\n",
" errors.forEach(desc => console.error(chalk.yellow(` - ${desc}`)));\n",
" process.exit(1);\n",
" }\n",
" config = _config!;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" error(red('Invalid configuration:'));\n",
" errors.forEach(desc => error(yellow(` - ${desc}`)));\n"
],
"file_path": "dev-infra/pr/merge/index.ts",
"type": "replace",
"edit_start_line_idx": 42
} | /**
* @license
* Copyright Google LLC 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 * as Octokit from '@octokit/rest';
import {spawnSync, SpawnSyncOptions, SpawnSyncReturns} from 'child_process';
import {MergeConfigWithRemote} from './config';
/** Error for failed Github API requests. */
export class GithubApiRequestError extends Error {
constructor(public status: number, message: string) {
super(message);
}
}
/** Error for failed Git commands. */
export class GitCommandError extends Error {
constructor(client: GitClient, public args: string[]) {
// Errors are not guaranteed to be caught. To ensure that we don't
// accidentally leak the Github token that might be used in a command,
// we sanitize the command that will be part of the error message.
super(`Command failed: git ${client.omitGithubTokenFromMessage(args.join(' '))}`);
}
}
export class GitClient {
/** Short-hand for accessing the remote configuration. */
remoteConfig = this._config.remote;
/** Octokit request parameters object for targeting the configured remote. */
remoteParams = {owner: this.remoteConfig.owner, repo: this.remoteConfig.name};
/** URL that resolves to the configured repository. */
repoGitUrl = this.remoteConfig.useSsh ?
`[email protected]:${this.remoteConfig.owner}/${this.remoteConfig.name}.git` :
`https://${this._githubToken}@github.com/${this.remoteConfig.owner}/${
this.remoteConfig.name}.git`;
/** Instance of the authenticated Github octokit API. */
api: Octokit;
/** Regular expression that matches the provided Github token. */
private _tokenRegex = new RegExp(this._githubToken, 'g');
constructor(
private _projectRoot: string, private _githubToken: string,
private _config: MergeConfigWithRemote) {
this.api = new Octokit({auth: _githubToken});
this.api.hook.error('request', error => {
// Wrap API errors in a known error class. This allows us to
// expect Github API errors better and in a non-ambiguous way.
throw new GithubApiRequestError(error.status, error.message);
});
}
/** Executes the given git command. Throws if the command fails. */
run(args: string[], options?: SpawnSyncOptions): Omit<SpawnSyncReturns<string>, 'status'> {
const result = this.runGraceful(args, options);
if (result.status !== 0) {
throw new GitCommandError(this, args);
}
// Omit `status` from the type so that it's obvious that the status is never
// non-zero as explained in the method description.
return result as Omit<SpawnSyncReturns<string>, 'status'>;
}
/**
* Spawns a given Git command process. Does not throw if the command fails. Additionally,
* if there is any stderr output, the output will be printed. This makes it easier to
* debug failed commands.
*/
runGraceful(args: string[], options: SpawnSyncOptions = {}): SpawnSyncReturns<string> {
// To improve the debugging experience in case something fails, we print all executed
// Git commands. Note that we do not want to print the token if is contained in the
// command. It's common to share errors with others if the tool failed.
console.info('Executing: git', this.omitGithubTokenFromMessage(args.join(' ')));
const result = spawnSync('git', args, {
cwd: this._projectRoot,
stdio: 'pipe',
...options,
// Encoding is always `utf8` and not overridable. This ensures that this method
// always returns `string` as output instead of buffers.
encoding: 'utf8',
});
if (result.stderr !== null) {
// Git sometimes prints the command if it failed. This means that it could
// potentially leak the Github token used for accessing the remote. To avoid
// printing a token, we sanitize the string before printing the stderr output.
process.stderr.write(this.omitGithubTokenFromMessage(result.stderr));
}
return result;
}
/** Whether the given branch contains the specified SHA. */
hasCommit(branchName: string, sha: string): boolean {
return this.run(['branch', branchName, '--contains', sha]).stdout !== '';
}
/** Gets the currently checked out branch. */
getCurrentBranch(): string {
return this.run(['rev-parse', '--abbrev-ref', 'HEAD']).stdout.trim();
}
/** Gets whether the current Git repository has uncommitted changes. */
hasUncommittedChanges(): boolean {
return this.runGraceful(['diff-index', '--quiet', 'HEAD']).status !== 0;
}
/** Sanitizes a given message by omitting the provided Github token if present. */
omitGithubTokenFromMessage(value: string): string {
return value.replace(this._tokenRegex, '<TOKEN>');
}
}
| dev-infra/pr/merge/git.ts | 1 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.00018308372818864882,
0.00017110200133174658,
0.00016430980758741498,
0.00017152735381387174,
0.0000050159583224740345
] |
{
"id": 7,
"code_window": [
" // If no explicit configuration has been specified, we load and validate\n",
" // the configuration from the shared dev-infra configuration.\n",
" if (config === undefined) {\n",
" const {config: _config, errors} = loadAndValidateConfig();\n",
" if (errors) {\n",
" console.error(chalk.red('Invalid configuration:'));\n",
" errors.forEach(desc => console.error(chalk.yellow(` - ${desc}`)));\n",
" process.exit(1);\n",
" }\n",
" config = _config!;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" error(red('Invalid configuration:'));\n",
" errors.forEach(desc => error(yellow(` - ${desc}`)));\n"
],
"file_path": "dev-infra/pr/merge/index.ts",
"type": "replace",
"edit_start_line_idx": 42
} | /**
* @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
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
const u = undefined;
function plural(n) { return 5; }
global.ng.common.locales['ccp'] = [
'ccp',
[['AM', 'PM'], u, u],
u,
[
['๐ข๐ง', '๐ฅ๐ง', '๐๐ง', '๐๐ช', '๐๐ณ๐ข๐จ', '๐ฅ๐ช', '๐ฅ๐ง'],
[
'๐ข๐ง๐๐จ', '๐ฅ๐ง๐๐ด', '๐๐ง๐๐๐ง๐ฃ๐ด', '๐๐ช๐๐ด',
'๐๐ณ๐ข๐จ๐ฅ๐ช๐๐ด', '๐ฅ๐ช๐๐ด๐๐ฎ๐ข๐ด', '๐ฅ๐ง๐๐จ'
],
[
'๐ข๐ง๐๐จ๐๐ข๐ด', '๐ฅ๐ง๐๐ด๐๐ข๐ด',
'๐๐ง๐๐๐ง๐ฃ๐ด๐๐ข๐ด', '๐๐ช๐๐ด๐๐ข๐ด',
'๐๐ณ๐ข๐จ๐ฅ๐ช๐๐ด๐๐ข๐ด',
'๐ฅ๐ช๐๐ด๐๐ฎ๐ข๐ด๐๐ข๐ด', '๐ฅ๐ง๐๐จ๐๐ข๐ด'
],
[
'๐ข๐ง๐๐จ', '๐ฅ๐ง๐๐ด', '๐๐ง๐๐๐ง๐ฃ๐ด', '๐๐ช๐๐ด',
'๐๐ณ๐ข๐จ๐ฅ๐ช๐๐ด', '๐ฅ๐ช๐๐ด๐๐ฎ๐ข๐ด', '๐ฅ๐ง๐๐จ'
]
],
u,
[
[
'๐', '๐๐ฌ', '๐', '๐๐ฌ', '๐๐ฌ', '๐๐ช๐๐ด', '๐๐ช', '๐',
'๐ฅ๐ฌ', '๐๐ง', '๐๐ง', '๐๐จ'
],
[
'๐๐๐ช', '๐๐ฌ๐๐ด', '๐๐ข๐ด๐๐ง',
'๐๐ฌ๐๐ณ๐ข๐จ๐ฃ๐ด', '๐๐ฌ', '๐๐ช๐๐ด', '๐๐ช๐ฃ๐ญ',
'๐๐๐ง๐๐ด๐๐ด', '๐ฅ๐ฌ๐๐ด๐๐ฌ๐๐ด๐๐ง๐ข๐ด',
'๐๐ง๐๐ด๐๐ฎ๐๐ง๐ข๐ด', '๐๐ง๐๐ฌ๐๐ด๐๐ง๐ข๐ด',
'๐๐จ๐ฅ๐ฌ๐๐ด๐๐ข๐ด'
],
[
'๐๐๐ช๐ ๐ข๐จ', '๐๐ฌ๐๐ด๐๐ณ๐ข๐ช๐ ๐ข๐จ',
'๐๐ข๐ด๐๐ง', '๐๐ฌ๐๐ณ๐ข๐จ๐ฃ๐ด', '๐๐ฌ', '๐๐ช๐๐ด',
'๐๐ช๐ฃ๐ญ', '๐๐๐ง๐๐ด๐๐ด',
'๐ฅ๐ฌ๐๐ด๐๐ฌ๐๐ด๐๐ง๐ข๐ด',
'๐๐ง๐๐ด๐๐ฌ๐๐ง๐ข๐ด', '๐๐ง๐๐ฌ๐๐ด๐๐ง๐ข๐ด',
'๐๐จ๐ฅ๐ฌ๐๐ด๐๐ง๐ข๐ด'
]
],
[
[
'๐', '๐๐ฌ', '๐', '๐๐ฌ', '๐๐ฌ', '๐๐ช๐๐ด', '๐๐ช', '๐',
'๐ฅ๐ฌ', '๐๐ง', '๐๐ง', '๐๐จ'
],
[
'๐๐๐ช๐ ๐ข๐จ', '๐๐ฌ๐๐ด๐๐ณ๐ข๐ช๐ ๐ข๐จ',
'๐๐ข๐ด๐๐ง', '๐๐ฌ๐๐ณ๐ข๐จ๐ฃ๐ด', '๐๐ฌ', '๐๐ช๐๐ด',
'๐๐ช๐ฃ๐ญ', '๐๐๐ง๐๐ด๐๐ด',
'๐ฅ๐ฌ๐๐ด๐๐ฌ๐๐ด๐๐ง๐ข๐ด',
'๐๐ง๐๐ด๐๐ฎ๐๐ง๐ข๐ด', '๐๐ง๐๐ฌ๐๐ด๐๐ง๐ข๐ด',
'๐๐จ๐ฅ๐ฌ๐๐ด๐๐ง๐ข๐ด'
],
u
],
[
[
'๐๐ณ๐ข๐จ๐๐ด๐๐ด๐๐ซ๐ข๐ด๐๐ง',
'๐๐ณ๐ข๐จ๐๐ด๐๐๐ด๐๐ง'
],
u, u
],
0,
[6, 0],
['d/M/yy', 'd MMM, y', 'd MMMM, y', 'EEEE, d MMMM, y'],
['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'],
['{1} {0}', u, u, u],
['.', ',', ';', '%', '+', '-', 'E', 'ร', 'โฐ', 'โ', 'NaN', ':'],
['#,##,##0.###', '#,##,##0%', '#,##,##0.00ยค', '#E0'],
'BDT',
'เงณ',
'๐๐๐ฃ๐๐ฌ๐ฅ๐จ ๐๐ฌ๐',
{
'BDT': ['เงณ'],
'JPY': ['JPยฅ', 'ยฅ'],
'STD': [u, 'Db'],
'THB': ['เธฟ'],
'TWD': ['NT$'],
'USD': ['US$', '$']
},
'ltr',
plural,
[
[
[
'๐๐ง๐๐ณ๐ ๐๐๐ง๐ฃ๐ณ๐ ๐ฌ', '๐๐ฌ๐๐ณ๐ ๐ฌ',
'๐๐จ๐๐ช๐๐ณ๐ ', '๐๐ฌ๐ฃ๐ณ๐ ๐ฌ', '๐ฅ๐๐ง๐๐ณ๐ ',
'๐ข๐ฌ๐๐ด'
],
u, u
],
u,
[
['04:00', '06:00'], ['06:00', '12:00'], ['12:00', '16:00'], ['16:00', '18:00'],
['18:00', '20:00'], ['20:00', '04:00']
]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
| packages/common/locales/global/ccp.js | 0 | https://github.com/angular/angular/commit/e28f13a102fca24ca74870ac53ad4651203c5f67 | [
0.0003761818225029856,
0.00018672426813282073,
0.00016350834630429745,
0.0001722342276480049,
0.000054802585509605706
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.