hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
listlengths 5
5
|
---|---|---|---|---|---|
{
"id": 2,
"code_window": [
"{\n",
" \"throws\": \"A semicolon is required after a class property (3:0)\",\n",
" \"plugins\": [\"classProperties\"]\n",
"}"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"throws\": \"A semicolon is required after a class property (2:6)\",\n"
],
"file_path": "packages/babylon/test/fixtures/experimental/class-properties/semicolons-required-without-value/options.json",
"type": "replace",
"edit_start_line_idx": 1
} | x = {"__proto__": 2 } | packages/babylon/test/fixtures/esprima/expression-primary/object/migrated_0027.js | 0 | https://github.com/babel/babel/commit/f31099f383b52cf4fe1786188f6421529dea865b | [
0.00017118621326517314,
0.00017118621326517314,
0.00017118621326517314,
0.00017118621326517314,
0
]
|
{
"id": 2,
"code_window": [
"{\n",
" \"throws\": \"A semicolon is required after a class property (3:0)\",\n",
" \"plugins\": [\"classProperties\"]\n",
"}"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"throws\": \"A semicolon is required after a class property (2:6)\",\n"
],
"file_path": "packages/babylon/test/fixtures/experimental/class-properties/semicolons-required-without-value/options.json",
"type": "replace",
"edit_start_line_idx": 1
} | import {bar} from "foo";
import {bar2, baz} from "foo";
import {bar as baz2} from "foo";
import {bar as baz3, xyz} from "foo";
bar;
bar2;
baz;
baz2;
baz3;
xyz;
| packages/babel-plugin-transform-es2015-modules-amd/test/fixtures/amd/imports-named/actual.js | 0 | https://github.com/babel/babel/commit/f31099f383b52cf4fe1786188f6421529dea865b | [
0.00017780852795112878,
0.0001737092825351283,
0.0001696100371191278,
0.0001737092825351283,
0.000004099245416000485
]
|
{
"id": 0,
"code_window": [
"import { basename, posix } from 'path';\n",
"import * as vscode from 'vscode';\n",
"import { Utils } from 'vscode-uri';\n",
"import { coalesce } from '../utils/arrays';\n",
"import { exists } from '../utils/fs';\n",
"\n",
"function mapChildren<R>(node: jsonc.Node | undefined, f: (x: jsonc.Node) => R): R[] {\n",
"\treturn node && node.type === 'array' && node.children\n",
"\t\t? node.children.map(f)\n",
"\t\t: [];\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { exists, looksLikeAbsoluteWindowsPath } from '../utils/fs';\n"
],
"file_path": "extensions/typescript-language-features/src/languageFeatures/tsconfig.ts",
"type": "replace",
"edit_start_line_idx": 10
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import * as fileSchemes from '../configuration/fileSchemes';
/**
* Maps of file resources
*
* Attempts to handle correct mapping on both case sensitive and case in-sensitive
* file systems.
*/
export class ResourceMap<T> {
private static readonly defaultPathNormalizer = (resource: vscode.Uri): string => {
if (resource.scheme === fileSchemes.file) {
return resource.fsPath;
}
return resource.toString(true);
};
private readonly _map = new Map<string, { readonly resource: vscode.Uri; value: T }>();
constructor(
protected readonly _normalizePath: (resource: vscode.Uri) => string | undefined = ResourceMap.defaultPathNormalizer,
protected readonly config: {
readonly onCaseInsensitiveFileSystem: boolean;
},
) { }
public get size() {
return this._map.size;
}
public has(resource: vscode.Uri): boolean {
const file = this.toKey(resource);
return !!file && this._map.has(file);
}
public get(resource: vscode.Uri): T | undefined {
const file = this.toKey(resource);
if (!file) {
return undefined;
}
const entry = this._map.get(file);
return entry ? entry.value : undefined;
}
public set(resource: vscode.Uri, value: T) {
const file = this.toKey(resource);
if (!file) {
return;
}
const entry = this._map.get(file);
if (entry) {
entry.value = value;
} else {
this._map.set(file, { resource, value });
}
}
public delete(resource: vscode.Uri): void {
const file = this.toKey(resource);
if (file) {
this._map.delete(file);
}
}
public clear(): void {
this._map.clear();
}
public get values(): Iterable<T> {
return Array.from(this._map.values(), x => x.value);
}
public get entries(): Iterable<{ resource: vscode.Uri; value: T }> {
return this._map.values();
}
private toKey(resource: vscode.Uri): string | undefined {
const key = this._normalizePath(resource);
if (!key) {
return key;
}
return this.isCaseInsensitivePath(key) ? key.toLowerCase() : key;
}
private isCaseInsensitivePath(path: string) {
if (isWindowsPath(path)) {
return true;
}
return path[0] === '/' && this.config.onCaseInsensitiveFileSystem;
}
}
function isWindowsPath(path: string): boolean {
return /^[a-zA-Z]:[\/\\]/.test(path);
}
| extensions/typescript-language-features/src/utils/resourceMap.ts | 1 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.0010065180249512196,
0.0002761519281193614,
0.00016284802404697984,
0.00016823483747430146,
0.00023968543973751366
]
|
{
"id": 0,
"code_window": [
"import { basename, posix } from 'path';\n",
"import * as vscode from 'vscode';\n",
"import { Utils } from 'vscode-uri';\n",
"import { coalesce } from '../utils/arrays';\n",
"import { exists } from '../utils/fs';\n",
"\n",
"function mapChildren<R>(node: jsonc.Node | undefined, f: (x: jsonc.Node) => R): R[] {\n",
"\treturn node && node.type === 'array' && node.children\n",
"\t\t? node.children.map(f)\n",
"\t\t: [];\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { exists, looksLikeAbsoluteWindowsPath } from '../utils/fs';\n"
],
"file_path": "extensions/typescript-language-features/src/languageFeatures/tsconfig.ts",
"type": "replace",
"edit_start_line_idx": 10
} | {
"displayName": "Razor Language Basics",
"description": "Provides syntax highlighting, bracket matching and folding in Razor files."
}
| extensions/razor/package.nls.json | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.0001711470540612936,
0.0001711470540612936,
0.0001711470540612936,
0.0001711470540612936,
0
]
|
{
"id": 0,
"code_window": [
"import { basename, posix } from 'path';\n",
"import * as vscode from 'vscode';\n",
"import { Utils } from 'vscode-uri';\n",
"import { coalesce } from '../utils/arrays';\n",
"import { exists } from '../utils/fs';\n",
"\n",
"function mapChildren<R>(node: jsonc.Node | undefined, f: (x: jsonc.Node) => R): R[] {\n",
"\treturn node && node.type === 'array' && node.children\n",
"\t\t? node.children.map(f)\n",
"\t\t: [];\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { exists, looksLikeAbsoluteWindowsPath } from '../utils/fs';\n"
],
"file_path": "extensions/typescript-language-features/src/languageFeatures/tsconfig.ts",
"type": "replace",
"edit_start_line_idx": 10
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IDisposable } from 'vs/base/common/lifecycle';
import type { derived } from 'vs/base/common/observableImpl/derived';
import { getLogger } from 'vs/base/common/observableImpl/logging';
export interface IObservable<T, TChange = unknown> {
/**
* Returns the current value.
*
* Calls {@link IObserver.handleChange} if the observable notices that the value changed.
* Must not be called from {@link IObserver.handleChange}!
*/
get(): T;
/**
* Forces the observable to check for and report changes.
*
* Has the same effect as calling {@link IObservable.get}, but does not force the observable
* to actually construct the value, e.g. if change deltas are used.
* Calls {@link IObserver.handleChange} if the observable notices that the value changed.
* Must not be called from {@link IObserver.handleChange}!
*/
reportChanges(): void;
/**
* Adds the observer to the set of subscribed observers.
* This method is idempotent.
*/
addObserver(observer: IObserver): void;
/**
* Removes the observer from the set of subscribed observers.
* This method is idempotent.
*/
removeObserver(observer: IObserver): void;
/**
* Reads the current value and subscribes to this observable.
*
* Just calls {@link IReader.readObservable} if a reader is given, otherwise {@link IObservable.get}
* (see {@link ConvenientObservable.read}).
*/
read(reader: IReader | undefined): T;
/**
* Creates a derived observable that depends on this observable.
* Use the reader to read other observables
* (see {@link ConvenientObservable.map}).
*/
map<TNew>(fn: (value: T, reader: IReader) => TNew): IObservable<TNew>;
/**
* A human-readable name for debugging purposes.
*/
readonly debugName: string;
/**
* This property captures the type of the change object. Do not use it at runtime!
*/
readonly TChange: TChange;
}
export interface IReader {
/**
* Reads the value of an observable and subscribes to it.
*/
readObservable<T>(observable: IObservable<T, any>): T;
}
/**
* Represents an observer that can be subscribed to an observable.
*
* If an observer is subscribed to an observable and that observable didn't signal
* a change through one of the observer methods, the observer can assume that the
* observable didn't change.
* If an observable reported a possible change, {@link IObservable.reportChanges} forces
* the observable to report an actual change if there was one.
*/
export interface IObserver {
/**
* Signals that the given observable might have changed and a transaction potentially modifying that observable started.
* Before the given observable can call this method again, is must call {@link IObserver.endUpdate}.
*
* The method {@link IObservable.reportChanges} can be used to force the observable to report the changes.
*/
beginUpdate<T>(observable: IObservable<T>): void;
/**
* Signals that the transaction that potentially modified the given observable ended.
*/
endUpdate<T>(observable: IObservable<T>): void;
/**
* Signals that the given observable might have changed.
* The method {@link IObservable.reportChanges} can be used to force the observable to report the changes.
*
* Implementations must not call into other observables, as they might not have received this event yet!
* The change should be processed lazily or in {@link IObserver.endUpdate}.
*/
handlePossibleChange<T>(observable: IObservable<T>): void;
/**
* Signals that the given observable changed.
*
* Implementations must not call into other observables, as they might not have received this event yet!
* The change should be processed lazily or in {@link IObserver.endUpdate}.
*/
handleChange<T, TChange>(observable: IObservable<T, TChange>, change: TChange): void;
}
export interface ISettable<T, TChange = void> {
set(value: T, transaction: ITransaction | undefined, change: TChange): void;
}
export interface ITransaction {
/**
* Calls {@link Observer.beginUpdate} immediately
* and {@link Observer.endUpdate} when the transaction ends.
*/
updateObserver(observer: IObserver, observable: IObservable<any, any>): void;
}
let _derived: typeof derived;
/**
* @internal
* This is to allow splitting files.
*/
export function _setDerived(derived: typeof _derived) {
_derived = derived;
}
export abstract class ConvenientObservable<T, TChange> implements IObservable<T, TChange> {
get TChange(): TChange { return null!; }
public abstract get(): T;
public reportChanges(): void {
this.get();
}
public abstract addObserver(observer: IObserver): void;
public abstract removeObserver(observer: IObserver): void;
/** @sealed */
public read(reader: IReader | undefined): T {
if (reader) {
return reader.readObservable(this);
} else {
return this.get();
}
}
/** @sealed */
public map<TNew>(fn: (value: T, reader: IReader) => TNew): IObservable<TNew> {
return _derived(
() => {
const name = getFunctionName(fn);
return name !== undefined ? name : `${this.debugName} (mapped)`;
},
(reader) => fn(this.read(reader), reader)
);
}
public abstract get debugName(): string;
}
export abstract class BaseObservable<T, TChange = void> extends ConvenientObservable<T, TChange> {
protected readonly observers = new Set<IObserver>();
public addObserver(observer: IObserver): void {
const len = this.observers.size;
this.observers.add(observer);
if (len === 0) {
this.onFirstObserverAdded();
}
}
public removeObserver(observer: IObserver): void {
const deleted = this.observers.delete(observer);
if (deleted && this.observers.size === 0) {
this.onLastObserverRemoved();
}
}
protected onFirstObserverAdded(): void { }
protected onLastObserverRemoved(): void { }
}
export function transaction(fn: (tx: ITransaction) => void, getDebugName?: () => string): void {
const tx = new TransactionImpl(fn, getDebugName);
try {
getLogger()?.handleBeginTransaction(tx);
fn(tx);
} finally {
tx.finish();
getLogger()?.handleEndTransaction();
}
}
export function subtransaction(tx: ITransaction | undefined, fn: (tx: ITransaction) => void, getDebugName?: () => string): void {
if (!tx) {
transaction(fn, getDebugName);
} else {
fn(tx);
}
}
export class TransactionImpl implements ITransaction {
private updatingObservers: { observer: IObserver; observable: IObservable<any> }[] | null = [];
constructor(private readonly fn: Function, private readonly _getDebugName?: () => string) { }
public getDebugName(): string | undefined {
if (this._getDebugName) {
return this._getDebugName();
}
return getFunctionName(this.fn);
}
public updateObserver(observer: IObserver, observable: IObservable<any>): void {
this.updatingObservers!.push({ observer, observable });
observer.beginUpdate(observable);
}
public finish(): void {
const updatingObservers = this.updatingObservers!;
// Prevent anyone from updating observers from now on.
this.updatingObservers = null;
for (const { observer, observable } of updatingObservers) {
observer.endUpdate(observable);
}
}
}
export function getFunctionName(fn: Function): string | undefined {
const fnSrc = fn.toString();
// Pattern: /** @description ... */
const regexp = /\/\*\*\s*@description\s*([^*]*)\*\//;
const match = regexp.exec(fnSrc);
const result = match ? match[1] : undefined;
return result?.trim();
}
export interface ISettableObservable<T, TChange = void> extends IObservable<T, TChange>, ISettable<T, TChange> {
}
export function observableValue<T, TChange = void>(name: string, initialValue: T): ISettableObservable<T, TChange> {
return new ObservableValue(name, initialValue);
}
export class ObservableValue<T, TChange = void>
extends BaseObservable<T, TChange>
implements ISettableObservable<T, TChange>
{
protected _value: T;
constructor(public readonly debugName: string, initialValue: T) {
super();
this._value = initialValue;
}
public get(): T {
return this._value;
}
public set(value: T, tx: ITransaction | undefined, change: TChange): void {
if (this._value === value) {
return;
}
let _tx: TransactionImpl | undefined;
if (!tx) {
tx = _tx = new TransactionImpl(() => { }, () => `Setting ${this.debugName}`);
}
try {
const oldValue = this._value;
this._setValue(value);
getLogger()?.handleObservableChanged(this, { oldValue, newValue: value, change, didChange: true });
for (const observer of this.observers) {
tx.updateObserver(observer, this);
observer.handleChange(this, change);
}
} finally {
if (_tx) {
_tx.finish();
}
}
}
override toString(): string {
return `${this.debugName}: ${this._value}`;
}
protected _setValue(newValue: T): void {
this._value = newValue;
}
}
export function disposableObservableValue<T extends IDisposable | undefined, TChange = void>(name: string, initialValue: T): ISettableObservable<T, TChange> & IDisposable {
return new DisposableObservableValue(name, initialValue);
}
export class DisposableObservableValue<T extends IDisposable | undefined, TChange = void> extends ObservableValue<T, TChange> implements IDisposable {
protected override _setValue(newValue: T): void {
if (this._value === newValue) {
return;
}
if (this._value) {
this._value.dispose();
}
this._value = newValue;
}
public dispose(): void {
this._value?.dispose();
}
}
export interface IChangeContext {
readonly changedObservable: IObservable<any, any>;
readonly change: unknown;
didChange<T, TChange>(observable: IObservable<T, TChange>): this is { change: TChange };
}
export interface IChangeTracker {
/**
* Returns if this change should cause an invalidation.
* Can record the changes to just process deltas.
*/
handleChange(context: IChangeContext): boolean;
}
| src/vs/base/common/observableImpl/base.ts | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.00021468887280207127,
0.00017177857807837427,
0.0001617150119272992,
0.00017079495592042804,
0.000008425330634054262
]
|
{
"id": 0,
"code_window": [
"import { basename, posix } from 'path';\n",
"import * as vscode from 'vscode';\n",
"import { Utils } from 'vscode-uri';\n",
"import { coalesce } from '../utils/arrays';\n",
"import { exists } from '../utils/fs';\n",
"\n",
"function mapChildren<R>(node: jsonc.Node | undefined, f: (x: jsonc.Node) => R): R[] {\n",
"\treturn node && node.type === 'array' && node.children\n",
"\t\t? node.children.map(f)\n",
"\t\t: [];\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { exists, looksLikeAbsoluteWindowsPath } from '../utils/fs';\n"
],
"file_path": "extensions/typescript-language-features/src/languageFeatures/tsconfig.ts",
"type": "replace",
"edit_start_line_idx": 10
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as objects from 'vs/base/common/objects';
import { Registry } from 'vs/platform/registry/common/platform';
import { IJSONSchema } from 'vs/base/common/jsonSchema';
import { ExtensionsRegistry, IExtensionPointUser } from 'vs/workbench/services/extensions/common/extensionsRegistry';
import { IConfigurationNode, IConfigurationRegistry, Extensions, validateProperty, ConfigurationScope, OVERRIDE_PROPERTY_REGEX, IConfigurationDefaults, configurationDefaultsSchemaId, IConfigurationDelta } from 'vs/platform/configuration/common/configurationRegistry';
import { IJSONContributionRegistry, Extensions as JSONExtensions } from 'vs/platform/jsonschemas/common/jsonContributionRegistry';
import { workspaceSettingsSchemaId, launchSchemaId, tasksSchemaId } from 'vs/workbench/services/configuration/common/configuration';
import { isObject } from 'vs/base/common/types';
import { ExtensionIdentifierMap } from 'vs/platform/extensions/common/extensions';
import { IStringDictionary } from 'vs/base/common/collections';
const jsonRegistry = Registry.as<IJSONContributionRegistry>(JSONExtensions.JSONContribution);
const configurationRegistry = Registry.as<IConfigurationRegistry>(Extensions.Configuration);
const configurationEntrySchema: IJSONSchema = {
type: 'object',
defaultSnippets: [{ body: { title: '', properties: {} } }],
properties: {
title: {
description: nls.localize('vscode.extension.contributes.configuration.title', 'A title for the current category of settings. This label will be rendered in the Settings editor as a subheading. If the title is the same as the extension display name, then the category will be grouped under the main extension heading.'),
type: 'string'
},
order: {
description: nls.localize('vscode.extension.contributes.configuration.order', 'When specified, gives the order of this category of settings relative to other categories.'),
type: 'integer'
},
properties: {
description: nls.localize('vscode.extension.contributes.configuration.properties', 'Description of the configuration properties.'),
type: 'object',
propertyNames: {
pattern: '\\S+',
patternErrorMessage: nls.localize('vscode.extension.contributes.configuration.property.empty', 'Property should not be empty.'),
},
additionalProperties: {
anyOf: [
{
title: nls.localize('vscode.extension.contributes.configuration.properties.schema', 'Schema of the configuration property.'),
$ref: 'http://json-schema.org/draft-07/schema#'
},
{
type: 'object',
properties: {
scope: {
type: 'string',
enum: ['application', 'machine', 'window', 'resource', 'language-overridable', 'machine-overridable'],
default: 'window',
enumDescriptions: [
nls.localize('scope.application.description', "Configuration that can be configured only in the user settings."),
nls.localize('scope.machine.description', "Configuration that can be configured only in the user settings or only in the remote settings."),
nls.localize('scope.window.description', "Configuration that can be configured in the user, remote or workspace settings."),
nls.localize('scope.resource.description', "Configuration that can be configured in the user, remote, workspace or folder settings."),
nls.localize('scope.language-overridable.description', "Resource configuration that can be configured in language specific settings."),
nls.localize('scope.machine-overridable.description', "Machine configuration that can be configured also in workspace or folder settings.")
],
markdownDescription: nls.localize('scope.description', "Scope in which the configuration is applicable. Available scopes are `application`, `machine`, `window`, `resource`, and `machine-overridable`.")
},
enumDescriptions: {
type: 'array',
items: {
type: 'string',
},
description: nls.localize('scope.enumDescriptions', 'Descriptions for enum values')
},
markdownEnumDescriptions: {
type: 'array',
items: {
type: 'string',
},
description: nls.localize('scope.markdownEnumDescriptions', 'Descriptions for enum values in the markdown format.')
},
enumItemLabels: {
type: 'array',
items: {
type: 'string'
},
markdownDescription: nls.localize('scope.enumItemLabels', 'Labels for enum values to be displayed in the Settings editor. When specified, the {0} values still show after the labels, but less prominently.', '`enum`')
},
markdownDescription: {
type: 'string',
description: nls.localize('scope.markdownDescription', 'The description in the markdown format.')
},
deprecationMessage: {
type: 'string',
description: nls.localize('scope.deprecationMessage', 'If set, the property is marked as deprecated and the given message is shown as an explanation.')
},
markdownDeprecationMessage: {
type: 'string',
description: nls.localize('scope.markdownDeprecationMessage', 'If set, the property is marked as deprecated and the given message is shown as an explanation in the markdown format.')
},
editPresentation: {
type: 'string',
enum: ['singlelineText', 'multilineText'],
enumDescriptions: [
nls.localize('scope.singlelineText.description', 'The value will be shown in an inputbox.'),
nls.localize('scope.multilineText.description', 'The value will be shown in a textarea.')
],
default: 'singlelineText',
description: nls.localize('scope.editPresentation', 'When specified, controls the presentation format of the string setting.')
},
order: {
type: 'integer',
description: nls.localize('scope.order', 'When specified, gives the order of this setting relative to other settings within the same category. Settings with an order property will be placed before settings without this property set.')
},
ignoreSync: {
type: 'boolean',
description: nls.localize('scope.ignoreSync', 'When enabled, Settings Sync will not sync the user value of this configuration by default.')
},
}
}
]
}
}
}
};
// build up a delta across two ext points and only apply it once
let _configDelta: IConfigurationDelta | undefined;
// BEGIN VSCode extension point `configurationDefaults`
const defaultConfigurationExtPoint = ExtensionsRegistry.registerExtensionPoint<IConfigurationNode>({
extensionPoint: 'configurationDefaults',
jsonSchema: {
$ref: configurationDefaultsSchemaId,
}
});
defaultConfigurationExtPoint.setHandler((extensions, { added, removed }) => {
if (_configDelta) {
// HIGHLY unlikely, but just in case
configurationRegistry.deltaConfiguration(_configDelta);
}
const configNow = _configDelta = {};
// schedule a HIGHLY unlikely task in case only the default configurations EXT point changes
queueMicrotask(() => {
if (_configDelta === configNow) {
configurationRegistry.deltaConfiguration(_configDelta);
_configDelta = undefined;
}
});
if (removed.length) {
const removedDefaultConfigurations = removed.map<IConfigurationDefaults>(extension => ({ overrides: objects.deepClone(extension.value), source: { id: extension.description.identifier.value, displayName: extension.description.displayName } }));
_configDelta.removedDefaults = removedDefaultConfigurations;
}
if (added.length) {
const registeredProperties = configurationRegistry.getConfigurationProperties();
const allowedScopes = [ConfigurationScope.MACHINE_OVERRIDABLE, ConfigurationScope.WINDOW, ConfigurationScope.RESOURCE, ConfigurationScope.LANGUAGE_OVERRIDABLE];
const addedDefaultConfigurations = added.map<IConfigurationDefaults>(extension => {
const overrides: IStringDictionary<any> = objects.deepClone(extension.value);
for (const key of Object.keys(overrides)) {
if (!OVERRIDE_PROPERTY_REGEX.test(key)) {
const registeredPropertyScheme = registeredProperties[key];
if (registeredPropertyScheme?.scope && !allowedScopes.includes(registeredPropertyScheme.scope)) {
extension.collector.warn(nls.localize('config.property.defaultConfiguration.warning', "Cannot register configuration defaults for '{0}'. Only defaults for machine-overridable, window, resource and language overridable scoped settings are supported.", key));
delete overrides[key];
}
}
}
return { overrides, source: { id: extension.description.identifier.value, displayName: extension.description.displayName } };
});
_configDelta.addedDefaults = addedDefaultConfigurations;
}
});
// END VSCode extension point `configurationDefaults`
// BEGIN VSCode extension point `configuration`
const configurationExtPoint = ExtensionsRegistry.registerExtensionPoint<IConfigurationNode>({
extensionPoint: 'configuration',
deps: [defaultConfigurationExtPoint],
jsonSchema: {
description: nls.localize('vscode.extension.contributes.configuration', 'Contributes configuration settings.'),
oneOf: [
configurationEntrySchema,
{
type: 'array',
items: configurationEntrySchema
}
]
}
});
const extensionConfigurations: ExtensionIdentifierMap<IConfigurationNode[]> = new ExtensionIdentifierMap<IConfigurationNode[]>();
configurationExtPoint.setHandler((extensions, { added, removed }) => {
// HIGHLY unlikely (only configuration but not defaultConfiguration EXT point changes)
_configDelta ??= {};
if (removed.length) {
const removedConfigurations: IConfigurationNode[] = [];
for (const extension of removed) {
removedConfigurations.push(...(extensionConfigurations.get(extension.description.identifier) || []));
extensionConfigurations.delete(extension.description.identifier);
}
_configDelta.removedConfigurations = removedConfigurations;
}
const seenProperties = new Set<string>();
function handleConfiguration(node: IConfigurationNode, extension: IExtensionPointUser<any>): IConfigurationNode[] {
const configurations: IConfigurationNode[] = [];
const configuration = objects.deepClone(node);
if (configuration.title && (typeof configuration.title !== 'string')) {
extension.collector.error(nls.localize('invalid.title', "'configuration.title' must be a string"));
}
validateProperties(configuration, extension);
configuration.id = node.id || extension.description.identifier.value;
configuration.extensionInfo = { id: extension.description.identifier.value, displayName: extension.description.displayName };
configuration.restrictedProperties = extension.description.capabilities?.untrustedWorkspaces?.supported === 'limited' ? extension.description.capabilities?.untrustedWorkspaces.restrictedConfigurations : undefined;
configuration.title = configuration.title || extension.description.displayName || extension.description.identifier.value;
configurations.push(configuration);
return configurations;
}
function validateProperties(configuration: IConfigurationNode, extension: IExtensionPointUser<any>): void {
const properties = configuration.properties;
if (properties) {
if (typeof properties !== 'object') {
extension.collector.error(nls.localize('invalid.properties', "'configuration.properties' must be an object"));
configuration.properties = {};
}
for (const key in properties) {
const propertyConfiguration = properties[key];
const message = validateProperty(key, propertyConfiguration);
if (message) {
delete properties[key];
extension.collector.warn(message);
continue;
}
if (seenProperties.has(key)) {
delete properties[key];
extension.collector.warn(nls.localize('config.property.duplicate', "Cannot register '{0}'. This property is already registered.", key));
continue;
}
if (!isObject(propertyConfiguration)) {
delete properties[key];
extension.collector.error(nls.localize('invalid.property', "configuration.properties property '{0}' must be an object", key));
continue;
}
seenProperties.add(key);
if (propertyConfiguration.scope) {
if (propertyConfiguration.scope.toString() === 'application') {
propertyConfiguration.scope = ConfigurationScope.APPLICATION;
} else if (propertyConfiguration.scope.toString() === 'machine') {
propertyConfiguration.scope = ConfigurationScope.MACHINE;
} else if (propertyConfiguration.scope.toString() === 'resource') {
propertyConfiguration.scope = ConfigurationScope.RESOURCE;
} else if (propertyConfiguration.scope.toString() === 'machine-overridable') {
propertyConfiguration.scope = ConfigurationScope.MACHINE_OVERRIDABLE;
} else if (propertyConfiguration.scope.toString() === 'language-overridable') {
propertyConfiguration.scope = ConfigurationScope.LANGUAGE_OVERRIDABLE;
} else {
propertyConfiguration.scope = ConfigurationScope.WINDOW;
}
} else {
propertyConfiguration.scope = ConfigurationScope.WINDOW;
}
}
}
const subNodes = configuration.allOf;
if (subNodes) {
extension.collector.error(nls.localize('invalid.allOf', "'configuration.allOf' is deprecated and should no longer be used. Instead, pass multiple configuration sections as an array to the 'configuration' contribution point."));
for (const node of subNodes) {
validateProperties(node, extension);
}
}
}
if (added.length) {
const addedConfigurations: IConfigurationNode[] = [];
for (const extension of added) {
const configurations: IConfigurationNode[] = [];
const value = <IConfigurationNode | IConfigurationNode[]>extension.value;
if (Array.isArray(value)) {
value.forEach(v => configurations.push(...handleConfiguration(v, extension)));
} else {
configurations.push(...handleConfiguration(value, extension));
}
extensionConfigurations.set(extension.description.identifier, configurations);
addedConfigurations.push(...configurations);
}
_configDelta.addedConfigurations = addedConfigurations;
}
configurationRegistry.deltaConfiguration(_configDelta);
_configDelta = undefined;
});
// END VSCode extension point `configuration`
jsonRegistry.registerSchema('vscode://schemas/workspaceConfig', {
allowComments: true,
allowTrailingCommas: true,
default: {
folders: [
{
path: ''
}
],
settings: {
}
},
required: ['folders'],
properties: {
'folders': {
minItems: 0,
uniqueItems: true,
description: nls.localize('workspaceConfig.folders.description', "List of folders to be loaded in the workspace."),
items: {
type: 'object',
defaultSnippets: [{ body: { path: '$1' } }],
oneOf: [{
properties: {
path: {
type: 'string',
description: nls.localize('workspaceConfig.path.description', "A file path. e.g. `/root/folderA` or `./folderA` for a relative path that will be resolved against the location of the workspace file.")
},
name: {
type: 'string',
description: nls.localize('workspaceConfig.name.description', "An optional name for the folder. ")
}
},
required: ['path']
}, {
properties: {
uri: {
type: 'string',
description: nls.localize('workspaceConfig.uri.description', "URI of the folder")
},
name: {
type: 'string',
description: nls.localize('workspaceConfig.name.description', "An optional name for the folder. ")
}
},
required: ['uri']
}]
}
},
'settings': {
type: 'object',
default: {},
description: nls.localize('workspaceConfig.settings.description', "Workspace settings"),
$ref: workspaceSettingsSchemaId
},
'launch': {
type: 'object',
default: { configurations: [], compounds: [] },
description: nls.localize('workspaceConfig.launch.description', "Workspace launch configurations"),
$ref: launchSchemaId
},
'tasks': {
type: 'object',
default: { version: '2.0.0', tasks: [] },
description: nls.localize('workspaceConfig.tasks.description', "Workspace task configurations"),
$ref: tasksSchemaId
},
'extensions': {
type: 'object',
default: {},
description: nls.localize('workspaceConfig.extensions.description', "Workspace extensions"),
$ref: 'vscode://schemas/extensions'
},
'remoteAuthority': {
type: 'string',
doNotSuggest: true,
description: nls.localize('workspaceConfig.remoteAuthority', "The remote server where the workspace is located."),
},
'transient': {
type: 'boolean',
doNotSuggest: true,
description: nls.localize('workspaceConfig.transient', "A transient workspace will disappear when restarting or reloading."),
}
},
errorMessage: nls.localize('unknownWorkspaceProperty', "Unknown workspace configuration property")
});
| src/vs/workbench/api/common/configurationExtensionPoint.ts | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.00028135778848081827,
0.00017580552957952023,
0.0001633705833228305,
0.00017229402146767825,
0.000019501620045048185
]
|
{
"id": 1,
"code_window": [
"\t\t}\n",
"\n",
"\t\tconst extendsValue: string = extendsNode.value;\n",
"\t\tif (extendsValue.startsWith('/')) {\n",
"\t\t\treturn undefined;\n",
"\t\t}\n",
"\n",
"\t\tconst args: OpenExtendsLinkCommandArgs = {\n",
"\t\t\tresourceUri: { ...document.uri.toJSON(), $mid: undefined }, // Prevent VS Code from trying to transform the uri\n",
"\t\t\textendsValue: extendsValue\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "extensions/typescript-language-features/src/languageFeatures/tsconfig.ts",
"type": "replace",
"edit_start_line_idx": 50
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import * as fileSchemes from '../configuration/fileSchemes';
/**
* Maps of file resources
*
* Attempts to handle correct mapping on both case sensitive and case in-sensitive
* file systems.
*/
export class ResourceMap<T> {
private static readonly defaultPathNormalizer = (resource: vscode.Uri): string => {
if (resource.scheme === fileSchemes.file) {
return resource.fsPath;
}
return resource.toString(true);
};
private readonly _map = new Map<string, { readonly resource: vscode.Uri; value: T }>();
constructor(
protected readonly _normalizePath: (resource: vscode.Uri) => string | undefined = ResourceMap.defaultPathNormalizer,
protected readonly config: {
readonly onCaseInsensitiveFileSystem: boolean;
},
) { }
public get size() {
return this._map.size;
}
public has(resource: vscode.Uri): boolean {
const file = this.toKey(resource);
return !!file && this._map.has(file);
}
public get(resource: vscode.Uri): T | undefined {
const file = this.toKey(resource);
if (!file) {
return undefined;
}
const entry = this._map.get(file);
return entry ? entry.value : undefined;
}
public set(resource: vscode.Uri, value: T) {
const file = this.toKey(resource);
if (!file) {
return;
}
const entry = this._map.get(file);
if (entry) {
entry.value = value;
} else {
this._map.set(file, { resource, value });
}
}
public delete(resource: vscode.Uri): void {
const file = this.toKey(resource);
if (file) {
this._map.delete(file);
}
}
public clear(): void {
this._map.clear();
}
public get values(): Iterable<T> {
return Array.from(this._map.values(), x => x.value);
}
public get entries(): Iterable<{ resource: vscode.Uri; value: T }> {
return this._map.values();
}
private toKey(resource: vscode.Uri): string | undefined {
const key = this._normalizePath(resource);
if (!key) {
return key;
}
return this.isCaseInsensitivePath(key) ? key.toLowerCase() : key;
}
private isCaseInsensitivePath(path: string) {
if (isWindowsPath(path)) {
return true;
}
return path[0] === '/' && this.config.onCaseInsensitiveFileSystem;
}
}
function isWindowsPath(path: string): boolean {
return /^[a-zA-Z]:[\/\\]/.test(path);
}
| extensions/typescript-language-features/src/utils/resourceMap.ts | 1 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.0007110697333700955,
0.0002665436186362058,
0.00016447830421384424,
0.0001810703834053129,
0.00018177495803683996
]
|
{
"id": 1,
"code_window": [
"\t\t}\n",
"\n",
"\t\tconst extendsValue: string = extendsNode.value;\n",
"\t\tif (extendsValue.startsWith('/')) {\n",
"\t\t\treturn undefined;\n",
"\t\t}\n",
"\n",
"\t\tconst args: OpenExtendsLinkCommandArgs = {\n",
"\t\t\tresourceUri: { ...document.uri.toJSON(), $mid: undefined }, // Prevent VS Code from trying to transform the uri\n",
"\t\t\textendsValue: extendsValue\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "extensions/typescript-language-features/src/languageFeatures/tsconfig.ts",
"type": "replace",
"edit_start_line_idx": 50
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'vscode' {
// https://github.com/microsoft/vscode/issues/109277
/**
* Details if an `ExternalUriOpener` can open a uri.
*
* The priority is also used to rank multiple openers against each other and determine
* if an opener should be selected automatically or if the user should be prompted to
* select an opener.
*
* The editor will try to use the best available opener, as sorted by `ExternalUriOpenerPriority`.
* If there are multiple potential "best" openers for a URI, then the user will be prompted
* to select an opener.
*/
export enum ExternalUriOpenerPriority {
/**
* The opener is disabled and will never be shown to users.
*
* Note that the opener can still be used if the user specifically
* configures it in their settings.
*/
None = 0,
/**
* The opener can open the uri but will not cause a prompt on its own
* since the editor always contributes a built-in `Default` opener.
*/
Option = 1,
/**
* The opener can open the uri.
*
* The editor's built-in opener has `Default` priority. This means that any additional `Default`
* openers will cause the user to be prompted to select from a list of all potential openers.
*/
Default = 2,
/**
* The opener can open the uri and should be automatically selected over any
* default openers, include the built-in one from the editor.
*
* A preferred opener will be automatically selected if no other preferred openers
* are available. If multiple preferred openers are available, then the user
* is shown a prompt with all potential openers (not just preferred openers).
*/
Preferred = 3,
}
/**
* Handles opening uris to external resources, such as http(s) links.
*
* Extensions can implement an `ExternalUriOpener` to open `http` links to a webserver
* inside of the editor instead of having the link be opened by the web browser.
*
* Currently openers may only be registered for `http` and `https` uris.
*/
export interface ExternalUriOpener {
/**
* Check if the opener can open a uri.
*
* @param uri The uri being opened. This is the uri that the user clicked on. It has
* not yet gone through port forwarding.
* @param token Cancellation token indicating that the result is no longer needed.
*
* @return Priority indicating if the opener can open the external uri.
*/
canOpenExternalUri(uri: Uri, token: CancellationToken): ExternalUriOpenerPriority | Thenable<ExternalUriOpenerPriority>;
/**
* Open a uri.
*
* This is invoked when:
*
* - The user clicks a link which does not have an assigned opener. In this case, first `canOpenExternalUri`
* is called and if the user selects this opener, then `openExternalUri` is called.
* - The user sets the default opener for a link in their settings and then visits a link.
*
* @param resolvedUri The uri to open. This uri may have been transformed by port forwarding, so it
* may not match the original uri passed to `canOpenExternalUri`. Use `ctx.originalUri` to check the
* original uri.
* @param ctx Additional information about the uri being opened.
* @param token Cancellation token indicating that opening has been canceled.
*
* @return Thenable indicating that the opening has completed.
*/
openExternalUri(resolvedUri: Uri, ctx: OpenExternalUriContext, token: CancellationToken): Thenable<void> | void;
}
/**
* Additional information about the uri being opened.
*/
interface OpenExternalUriContext {
/**
* The uri that triggered the open.
*
* This is the original uri that the user clicked on or that was passed to `openExternal.`
* Due to port forwarding, this may not match the `resolvedUri` passed to `openExternalUri`.
*/
readonly sourceUri: Uri;
}
/**
* Additional metadata about a registered `ExternalUriOpener`.
*/
interface ExternalUriOpenerMetadata {
/**
* List of uri schemes the opener is triggered for.
*
* Currently only `http` and `https` are supported.
*/
readonly schemes: readonly string[];
/**
* Text displayed to the user that explains what the opener does.
*
* For example, 'Open in browser preview'
*/
readonly label: string;
}
namespace window {
/**
* Register a new `ExternalUriOpener`.
*
* When a uri is about to be opened, an `onOpenExternalUri:SCHEME` activation event is fired.
*
* @param id Unique id of the opener, such as `myExtension.browserPreview`. This is used in settings
* and commands to identify the opener.
* @param opener Opener to register.
* @param metadata Additional information about the opener.
*
* @returns Disposable that unregisters the opener.
*/
export function registerExternalUriOpener(id: string, opener: ExternalUriOpener, metadata: ExternalUriOpenerMetadata): Disposable;
}
interface OpenExternalOptions {
/**
* Allows using openers contributed by extensions through `registerExternalUriOpener`
* when opening the resource.
*
* If `true`, the editor will check if any contributed openers can handle the
* uri, and fallback to the default opener behavior.
*
* If it is string, this specifies the id of the `ExternalUriOpener`
* that should be used if it is available. Use `'default'` to force the editor's
* standard external opener to be used.
*/
readonly allowContributedOpeners?: boolean | string;
}
namespace env {
export function openExternal(target: Uri, options?: OpenExternalOptions): Thenable<boolean>;
}
}
| src/vscode-dts/vscode.proposed.externalUriOpener.d.ts | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.001461993670091033,
0.0003092702536378056,
0.00016328446508850902,
0.000182146075530909,
0.0003035875561181456
]
|
{
"id": 1,
"code_window": [
"\t\t}\n",
"\n",
"\t\tconst extendsValue: string = extendsNode.value;\n",
"\t\tif (extendsValue.startsWith('/')) {\n",
"\t\t\treturn undefined;\n",
"\t\t}\n",
"\n",
"\t\tconst args: OpenExtendsLinkCommandArgs = {\n",
"\t\t\tresourceUri: { ...document.uri.toJSON(), $mid: undefined }, // Prevent VS Code from trying to transform the uri\n",
"\t\t\textendsValue: extendsValue\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "extensions/typescript-language-features/src/languageFeatures/tsconfig.ts",
"type": "replace",
"edit_start_line_idx": 50
} | /*---------------------------------------------------------------------------------------------
* 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 * as labels from 'vs/base/common/labels';
import { isMacintosh, isWindows, OperatingSystem } from 'vs/base/common/platform';
import { URI } from 'vs/base/common/uri';
suite('Labels', () => {
(!isWindows ? test.skip : test)('shorten - windows', () => {
// nothing to shorten
assert.deepStrictEqual(labels.shorten(['a']), ['a']);
assert.deepStrictEqual(labels.shorten(['a', 'b']), ['a', 'b']);
assert.deepStrictEqual(labels.shorten(['a', 'b', 'c']), ['a', 'b', 'c']);
assert.deepStrictEqual(labels.shorten(['\\\\x\\a', '\\\\x\\a']), ['\\\\x\\a', '\\\\x\\a']);
assert.deepStrictEqual(labels.shorten(['C:\\a', 'C:\\b']), ['C:\\a', 'C:\\b']);
// completely different paths
assert.deepStrictEqual(labels.shorten(['a\\b', 'c\\d', 'e\\f']), ['…\\b', '…\\d', '…\\f']);
// same beginning
assert.deepStrictEqual(labels.shorten(['a', 'a\\b']), ['a', '…\\b']);
assert.deepStrictEqual(labels.shorten(['a\\b', 'a\\b\\c']), ['…\\b', '…\\c']);
assert.deepStrictEqual(labels.shorten(['a', 'a\\b', 'a\\b\\c']), ['a', '…\\b', '…\\c']);
assert.deepStrictEqual(labels.shorten(['x:\\a\\b', 'x:\\a\\c']), ['x:\\…\\b', 'x:\\…\\c']);
assert.deepStrictEqual(labels.shorten(['\\\\a\\b', '\\\\a\\c']), ['\\\\a\\b', '\\\\a\\c']);
// same ending
assert.deepStrictEqual(labels.shorten(['a', 'b\\a']), ['a', 'b\\…']);
assert.deepStrictEqual(labels.shorten(['a\\b\\c', 'd\\b\\c']), ['a\\…', 'd\\…']);
assert.deepStrictEqual(labels.shorten(['a\\b\\c\\d', 'f\\b\\c\\d']), ['a\\…', 'f\\…']);
assert.deepStrictEqual(labels.shorten(['d\\e\\a\\b\\c', 'd\\b\\c']), ['…\\a\\…', 'd\\b\\…']);
assert.deepStrictEqual(labels.shorten(['a\\b\\c\\d', 'a\\f\\b\\c\\d']), ['a\\b\\…', '…\\f\\…']);
assert.deepStrictEqual(labels.shorten(['a\\b\\a', 'b\\b\\a']), ['a\\b\\…', 'b\\b\\…']);
assert.deepStrictEqual(labels.shorten(['d\\f\\a\\b\\c', 'h\\d\\b\\c']), ['…\\a\\…', 'h\\…']);
assert.deepStrictEqual(labels.shorten(['a\\b\\c', 'x:\\0\\a\\b\\c']), ['a\\b\\c', 'x:\\0\\…']);
assert.deepStrictEqual(labels.shorten(['x:\\a\\b\\c', 'x:\\0\\a\\b\\c']), ['x:\\a\\…', 'x:\\0\\…']);
assert.deepStrictEqual(labels.shorten(['x:\\a\\b', 'y:\\a\\b']), ['x:\\…', 'y:\\…']);
assert.deepStrictEqual(labels.shorten(['x:\\a', 'x:\\c']), ['x:\\a', 'x:\\c']);
assert.deepStrictEqual(labels.shorten(['x:\\a\\b', 'y:\\x\\a\\b']), ['x:\\…', 'y:\\…']);
assert.deepStrictEqual(labels.shorten(['\\\\x\\b', '\\\\y\\b']), ['\\\\x\\…', '\\\\y\\…']);
assert.deepStrictEqual(labels.shorten(['\\\\x\\a', '\\\\x\\b']), ['\\\\x\\a', '\\\\x\\b']);
// same name ending
assert.deepStrictEqual(labels.shorten(['a\\b', 'a\\c', 'a\\e-b']), ['…\\b', '…\\c', '…\\e-b']);
// same in the middle
assert.deepStrictEqual(labels.shorten(['a\\b\\c', 'd\\b\\e']), ['…\\c', '…\\e']);
// case-sensetive
assert.deepStrictEqual(labels.shorten(['a\\b\\c', 'd\\b\\C']), ['…\\c', '…\\C']);
// empty or null
assert.deepStrictEqual(labels.shorten(['', null!]), ['.\\', null]);
assert.deepStrictEqual(labels.shorten(['a', 'a\\b', 'a\\b\\c', 'd\\b\\c', 'd\\b']), ['a', 'a\\b', 'a\\b\\c', 'd\\b\\c', 'd\\b']);
assert.deepStrictEqual(labels.shorten(['a', 'a\\b', 'b']), ['a', 'a\\b', 'b']);
assert.deepStrictEqual(labels.shorten(['', 'a', 'b', 'b\\c', 'a\\c']), ['.\\', 'a', 'b', 'b\\c', 'a\\c']);
assert.deepStrictEqual(labels.shorten(['src\\vs\\workbench\\parts\\execution\\electron-sandbox', 'src\\vs\\workbench\\parts\\execution\\electron-sandbox\\something', 'src\\vs\\workbench\\parts\\terminal\\electron-sandbox']), ['…\\execution\\electron-sandbox', '…\\something', '…\\terminal\\…']);
});
(isWindows ? test.skip : test)('shorten - not windows', () => {
// nothing to shorten
assert.deepStrictEqual(labels.shorten(['a']), ['a']);
assert.deepStrictEqual(labels.shorten(['a', 'b']), ['a', 'b']);
assert.deepStrictEqual(labels.shorten(['/a', '/b']), ['/a', '/b']);
assert.deepStrictEqual(labels.shorten(['~/a/b/c', '~/a/b/c']), ['~/a/b/c', '~/a/b/c']);
assert.deepStrictEqual(labels.shorten(['a', 'b', 'c']), ['a', 'b', 'c']);
// completely different paths
assert.deepStrictEqual(labels.shorten(['a/b', 'c/d', 'e/f']), ['…/b', '…/d', '…/f']);
// same beginning
assert.deepStrictEqual(labels.shorten(['a', 'a/b']), ['a', '…/b']);
assert.deepStrictEqual(labels.shorten(['a/b', 'a/b/c']), ['…/b', '…/c']);
assert.deepStrictEqual(labels.shorten(['a', 'a/b', 'a/b/c']), ['a', '…/b', '…/c']);
assert.deepStrictEqual(labels.shorten(['/a/b', '/a/c']), ['/a/b', '/a/c']);
// same ending
assert.deepStrictEqual(labels.shorten(['a', 'b/a']), ['a', 'b/…']);
assert.deepStrictEqual(labels.shorten(['a/b/c', 'd/b/c']), ['a/…', 'd/…']);
assert.deepStrictEqual(labels.shorten(['a/b/c/d', 'f/b/c/d']), ['a/…', 'f/…']);
assert.deepStrictEqual(labels.shorten(['d/e/a/b/c', 'd/b/c']), ['…/a/…', 'd/b/…']);
assert.deepStrictEqual(labels.shorten(['a/b/c/d', 'a/f/b/c/d']), ['a/b/…', '…/f/…']);
assert.deepStrictEqual(labels.shorten(['a/b/a', 'b/b/a']), ['a/b/…', 'b/b/…']);
assert.deepStrictEqual(labels.shorten(['d/f/a/b/c', 'h/d/b/c']), ['…/a/…', 'h/…']);
assert.deepStrictEqual(labels.shorten(['/x/b', '/y/b']), ['/x/…', '/y/…']);
// same name ending
assert.deepStrictEqual(labels.shorten(['a/b', 'a/c', 'a/e-b']), ['…/b', '…/c', '…/e-b']);
// same in the middle
assert.deepStrictEqual(labels.shorten(['a/b/c', 'd/b/e']), ['…/c', '…/e']);
// case-sensitive
assert.deepStrictEqual(labels.shorten(['a/b/c', 'd/b/C']), ['…/c', '…/C']);
// empty or null
assert.deepStrictEqual(labels.shorten(['', null!]), ['./', null]);
assert.deepStrictEqual(labels.shorten(['a', 'a/b', 'a/b/c', 'd/b/c', 'd/b']), ['a', 'a/b', 'a/b/c', 'd/b/c', 'd/b']);
assert.deepStrictEqual(labels.shorten(['a', 'a/b', 'b']), ['a', 'a/b', 'b']);
assert.deepStrictEqual(labels.shorten(['', 'a', 'b', 'b/c', 'a/c']), ['./', 'a', 'b', 'b/c', 'a/c']);
});
test('template', () => {
// simple
assert.strictEqual(labels.template('Foo Bar'), 'Foo Bar');
assert.strictEqual(labels.template('Foo${}Bar'), 'FooBar');
assert.strictEqual(labels.template('$FooBar'), '');
assert.strictEqual(labels.template('}FooBar'), '}FooBar');
assert.strictEqual(labels.template('Foo ${one} Bar', { one: 'value' }), 'Foo value Bar');
assert.strictEqual(labels.template('Foo ${one} Bar ${two}', { one: 'value', two: 'other value' }), 'Foo value Bar other value');
// conditional separator
assert.strictEqual(labels.template('Foo${separator}Bar'), 'FooBar');
assert.strictEqual(labels.template('Foo${separator}Bar', { separator: { label: ' - ' } }), 'Foo - Bar');
assert.strictEqual(labels.template('${separator}Foo${separator}Bar', { value: 'something', separator: { label: ' - ' } }), 'Foo - Bar');
assert.strictEqual(labels.template('${value} Foo${separator}Bar', { value: 'something', separator: { label: ' - ' } }), 'something Foo - Bar');
// real world example (macOS)
let t = '${activeEditorShort}${separator}${rootName}';
assert.strictEqual(labels.template(t, { activeEditorShort: '', rootName: '', separator: { label: ' - ' } }), '');
assert.strictEqual(labels.template(t, { activeEditorShort: '', rootName: 'root', separator: { label: ' - ' } }), 'root');
assert.strictEqual(labels.template(t, { activeEditorShort: 'markdown.txt', rootName: 'root', separator: { label: ' - ' } }), 'markdown.txt - root');
// real world example (other)
t = '${dirty}${activeEditorShort}${separator}${rootName}${separator}${appName}';
assert.strictEqual(labels.template(t, { dirty: '', activeEditorShort: '', rootName: '', appName: '', separator: { label: ' - ' } }), '');
assert.strictEqual(labels.template(t, { dirty: '', activeEditorShort: '', rootName: '', appName: 'Visual Studio Code', separator: { label: ' - ' } }), 'Visual Studio Code');
assert.strictEqual(labels.template(t, { dirty: '', activeEditorShort: 'Untitled-1', rootName: '', appName: 'Visual Studio Code', separator: { label: ' - ' } }), 'Untitled-1 - Visual Studio Code');
assert.strictEqual(labels.template(t, { dirty: '', activeEditorShort: '', rootName: 'monaco', appName: 'Visual Studio Code', separator: { label: ' - ' } }), 'monaco - Visual Studio Code');
assert.strictEqual(labels.template(t, { dirty: '', activeEditorShort: 'somefile.txt', rootName: 'monaco', appName: 'Visual Studio Code', separator: { label: ' - ' } }), 'somefile.txt - monaco - Visual Studio Code');
assert.strictEqual(labels.template(t, { dirty: '* ', activeEditorShort: 'somefile.txt', rootName: 'monaco', appName: 'Visual Studio Code', separator: { label: ' - ' } }), '* somefile.txt - monaco - Visual Studio Code');
// real world example (other)
t = '${dirty}${activeEditorShort}${separator}${rootNameShort}${separator}${appName}';
assert.strictEqual(labels.template(t, { dirty: '', activeEditorShort: '', rootName: 'monaco (Workspace)', rootNameShort: 'monaco', appName: 'Visual Studio Code', separator: { label: ' - ' } }), 'monaco - Visual Studio Code');
});
test('mnemonicButtonLabel', () => {
assert.strictEqual(labels.mnemonicButtonLabel('Hello World'), 'Hello World');
assert.strictEqual(labels.mnemonicButtonLabel(''), '');
if (isWindows) {
assert.strictEqual(labels.mnemonicButtonLabel('Hello & World'), 'Hello && World');
assert.strictEqual(labels.mnemonicButtonLabel('Do &¬ Save & Continue'), 'Do ¬ Save && Continue');
} else if (isMacintosh) {
assert.strictEqual(labels.mnemonicButtonLabel('Hello & World'), 'Hello & World');
assert.strictEqual(labels.mnemonicButtonLabel('Do &¬ Save & Continue'), 'Do not Save & Continue');
} else {
assert.strictEqual(labels.mnemonicButtonLabel('Hello & World'), 'Hello & World');
assert.strictEqual(labels.mnemonicButtonLabel('Do &¬ Save & Continue'), 'Do _not Save & Continue');
}
});
test('getPathLabel', () => {
const winFileUri = URI.file('c:/some/folder/file.txt');
const nixFileUri = URI.file('/some/folder/file.txt');
const uncFileUri = URI.file('c:/some/folder/file.txt').with({ authority: 'auth' });
const remoteFileUri = URI.file('/some/folder/file.txt').with({ scheme: 'vscode-test', authority: 'auth' });
// Basics
assert.strictEqual(labels.getPathLabel(winFileUri, { os: OperatingSystem.Windows }), 'C:\\some\\folder\\file.txt');
assert.strictEqual(labels.getPathLabel(winFileUri, { os: OperatingSystem.Macintosh }), 'c:/some/folder/file.txt');
assert.strictEqual(labels.getPathLabel(winFileUri, { os: OperatingSystem.Linux }), 'c:/some/folder/file.txt');
assert.strictEqual(labels.getPathLabel(nixFileUri, { os: OperatingSystem.Windows }), '\\some\\folder\\file.txt');
assert.strictEqual(labels.getPathLabel(nixFileUri, { os: OperatingSystem.Macintosh }), '/some/folder/file.txt');
assert.strictEqual(labels.getPathLabel(nixFileUri, { os: OperatingSystem.Linux }), '/some/folder/file.txt');
assert.strictEqual(labels.getPathLabel(uncFileUri, { os: OperatingSystem.Windows }), '\\\\auth\\c:\\some\\folder\\file.txt');
assert.strictEqual(labels.getPathLabel(uncFileUri, { os: OperatingSystem.Macintosh }), '/auth/c:/some/folder/file.txt');
assert.strictEqual(labels.getPathLabel(uncFileUri, { os: OperatingSystem.Linux }), '/auth/c:/some/folder/file.txt');
assert.strictEqual(labels.getPathLabel(remoteFileUri, { os: OperatingSystem.Windows }), '\\some\\folder\\file.txt');
assert.strictEqual(labels.getPathLabel(remoteFileUri, { os: OperatingSystem.Macintosh }), '/some/folder/file.txt');
assert.strictEqual(labels.getPathLabel(remoteFileUri, { os: OperatingSystem.Linux }), '/some/folder/file.txt');
// Tildify
const nixUserHome = URI.file('/some');
const remoteUserHome = URI.file('/some').with({ scheme: 'vscode-test', authority: 'auth' });
assert.strictEqual(labels.getPathLabel(nixFileUri, { os: OperatingSystem.Windows, tildify: { userHome: nixUserHome } }), '\\some\\folder\\file.txt');
assert.strictEqual(labels.getPathLabel(nixFileUri, { os: OperatingSystem.Macintosh, tildify: { userHome: nixUserHome } }), '~/folder/file.txt');
assert.strictEqual(labels.getPathLabel(nixFileUri, { os: OperatingSystem.Linux, tildify: { userHome: nixUserHome } }), '~/folder/file.txt');
assert.strictEqual(labels.getPathLabel(nixFileUri, { os: OperatingSystem.Windows, tildify: { userHome: remoteUserHome } }), '\\some\\folder\\file.txt');
assert.strictEqual(labels.getPathLabel(nixFileUri, { os: OperatingSystem.Macintosh, tildify: { userHome: remoteUserHome } }), '~/folder/file.txt');
assert.strictEqual(labels.getPathLabel(nixFileUri, { os: OperatingSystem.Linux, tildify: { userHome: remoteUserHome } }), '~/folder/file.txt');
const nixUntitledUri = URI.file('/some/folder/file.txt').with({ scheme: 'untitled' });
assert.strictEqual(labels.getPathLabel(nixUntitledUri, { os: OperatingSystem.Windows, tildify: { userHome: nixUserHome } }), '\\some\\folder\\file.txt');
assert.strictEqual(labels.getPathLabel(nixUntitledUri, { os: OperatingSystem.Macintosh, tildify: { userHome: nixUserHome } }), '~/folder/file.txt');
assert.strictEqual(labels.getPathLabel(nixUntitledUri, { os: OperatingSystem.Linux, tildify: { userHome: nixUserHome } }), '~/folder/file.txt');
assert.strictEqual(labels.getPathLabel(nixUntitledUri, { os: OperatingSystem.Windows, tildify: { userHome: remoteUserHome } }), '\\some\\folder\\file.txt');
assert.strictEqual(labels.getPathLabel(nixUntitledUri, { os: OperatingSystem.Macintosh, tildify: { userHome: remoteUserHome } }), '~/folder/file.txt');
assert.strictEqual(labels.getPathLabel(nixUntitledUri, { os: OperatingSystem.Linux, tildify: { userHome: remoteUserHome } }), '~/folder/file.txt');
// Relative
const winFolder = URI.file('c:/some');
const winRelativePathProvider: labels.IRelativePathProvider = {
getWorkspace() { return { folders: [{ uri: winFolder }] }; },
getWorkspaceFolder(resource) { return { uri: winFolder }; }
};
assert.strictEqual(labels.getPathLabel(winFileUri, { os: OperatingSystem.Windows, relative: winRelativePathProvider }), 'folder\\file.txt');
assert.strictEqual(labels.getPathLabel(winFileUri, { os: OperatingSystem.Macintosh, relative: winRelativePathProvider }), 'folder/file.txt');
assert.strictEqual(labels.getPathLabel(winFileUri, { os: OperatingSystem.Linux, relative: winRelativePathProvider }), 'folder/file.txt');
const nixFolder = URI.file('/some');
const nixRelativePathProvider: labels.IRelativePathProvider = {
getWorkspace() { return { folders: [{ uri: nixFolder }] }; },
getWorkspaceFolder(resource) { return { uri: nixFolder }; }
};
assert.strictEqual(labels.getPathLabel(nixFileUri, { os: OperatingSystem.Windows, relative: nixRelativePathProvider }), 'folder\\file.txt');
assert.strictEqual(labels.getPathLabel(nixFileUri, { os: OperatingSystem.Macintosh, relative: nixRelativePathProvider }), 'folder/file.txt');
assert.strictEqual(labels.getPathLabel(nixFileUri, { os: OperatingSystem.Linux, relative: nixRelativePathProvider }), 'folder/file.txt');
assert.strictEqual(labels.getPathLabel(nixUntitledUri, { os: OperatingSystem.Windows, relative: nixRelativePathProvider }), 'folder\\file.txt');
assert.strictEqual(labels.getPathLabel(nixUntitledUri, { os: OperatingSystem.Macintosh, relative: nixRelativePathProvider }), 'folder/file.txt');
assert.strictEqual(labels.getPathLabel(nixUntitledUri, { os: OperatingSystem.Linux, relative: nixRelativePathProvider }), 'folder/file.txt');
});
});
| src/vs/base/test/common/labels.test.ts | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.00017668446525931358,
0.0001724000758258626,
0.00016584717377554625,
0.00017242657486349344,
0.0000026227910439047264
]
|
{
"id": 1,
"code_window": [
"\t\t}\n",
"\n",
"\t\tconst extendsValue: string = extendsNode.value;\n",
"\t\tif (extendsValue.startsWith('/')) {\n",
"\t\t\treturn undefined;\n",
"\t\t}\n",
"\n",
"\t\tconst args: OpenExtendsLinkCommandArgs = {\n",
"\t\t\tresourceUri: { ...document.uri.toJSON(), $mid: undefined }, // Prevent VS Code from trying to transform the uri\n",
"\t\t\textendsValue: extendsValue\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "extensions/typescript-language-features/src/languageFeatures/tsconfig.ts",
"type": "replace",
"edit_start_line_idx": 50
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ITextSearchResult } from 'vs/workbench/services/search/common/search';
import { TextSearchPreviewOptions } from 'vs/workbench/services/search/common/searchExtTypes';
import { Range } from 'vs/editor/common/core/range';
export const getFileResults = (
bytes: Uint8Array,
pattern: RegExp,
options: {
beforeContext: number;
afterContext: number;
previewOptions: TextSearchPreviewOptions | undefined;
remainingResultQuota: number;
}
): ITextSearchResult[] => {
let text: string;
if (bytes[0] === 0xff && bytes[1] === 0xfe) {
text = new TextDecoder('utf-16le').decode(bytes);
} else if (bytes[0] === 0xfe && bytes[1] === 0xff) {
text = new TextDecoder('utf-16be').decode(bytes);
} else {
text = new TextDecoder('utf8').decode(bytes);
if (text.slice(0, 1000).includes('\uFFFD') && bytes.includes(0)) {
return [];
}
}
const results: ITextSearchResult[] = [];
const patternIndecies: { matchStartIndex: number; matchedText: string }[] = [];
let patternMatch: RegExpExecArray | null = null;
let remainingResultQuota = options.remainingResultQuota;
while (remainingResultQuota >= 0 && (patternMatch = pattern.exec(text))) {
patternIndecies.push({ matchStartIndex: patternMatch.index, matchedText: patternMatch[0] });
remainingResultQuota--;
}
if (patternIndecies.length) {
const contextLinesNeeded = new Set<number>();
const resultLines = new Set<number>();
const lineRanges: { start: number; end: number }[] = [];
const readLine = (lineNumber: number) => text.slice(lineRanges[lineNumber].start, lineRanges[lineNumber].end);
let prevLineEnd = 0;
let lineEndingMatch: RegExpExecArray | null = null;
const lineEndRegex = /\r?\n/g;
while ((lineEndingMatch = lineEndRegex.exec(text))) {
lineRanges.push({ start: prevLineEnd, end: lineEndingMatch.index });
prevLineEnd = lineEndingMatch.index + lineEndingMatch[0].length;
}
if (prevLineEnd < text.length) { lineRanges.push({ start: prevLineEnd, end: text.length }); }
let startLine = 0;
for (const { matchStartIndex, matchedText } of patternIndecies) {
if (remainingResultQuota < 0) {
break;
}
while (Boolean(lineRanges[startLine + 1]) && matchStartIndex > lineRanges[startLine].end) {
startLine++;
}
let endLine = startLine;
while (Boolean(lineRanges[endLine + 1]) && matchStartIndex + matchedText.length > lineRanges[endLine].end) {
endLine++;
}
if (options.beforeContext) {
for (let contextLine = Math.max(0, startLine - options.beforeContext); contextLine < startLine; contextLine++) {
contextLinesNeeded.add(contextLine);
}
}
let previewText = '';
let offset = 0;
for (let matchLine = startLine; matchLine <= endLine; matchLine++) {
let previewLine = readLine(matchLine);
if (options.previewOptions?.charsPerLine && previewLine.length > options.previewOptions.charsPerLine) {
offset = Math.max(matchStartIndex - lineRanges[startLine].start - 20, 0);
previewLine = previewLine.substr(offset, options.previewOptions.charsPerLine);
}
previewText += `${previewLine}\n`;
resultLines.add(matchLine);
}
const fileRange = new Range(
startLine,
matchStartIndex - lineRanges[startLine].start,
endLine,
matchStartIndex + matchedText.length - lineRanges[endLine].start
);
const previewRange = new Range(
0,
matchStartIndex - lineRanges[startLine].start - offset,
endLine - startLine,
matchStartIndex + matchedText.length - lineRanges[endLine].start - (endLine === startLine ? offset : 0)
);
const match: ITextSearchResult = {
ranges: fileRange,
preview: { text: previewText, matches: previewRange },
};
results.push(match);
if (options.afterContext) {
for (let contextLine = endLine + 1; contextLine <= Math.min(endLine + options.afterContext, lineRanges.length - 1); contextLine++) {
contextLinesNeeded.add(contextLine);
}
}
}
for (const contextLine of contextLinesNeeded) {
if (!resultLines.has(contextLine)) {
results.push({
text: readLine(contextLine),
lineNumber: contextLine + 1,
});
}
}
}
return results;
};
| src/vs/workbench/services/search/common/getFileResults.ts | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.0002332145522814244,
0.00017440394731238484,
0.0001601482945261523,
0.0001703119050944224,
0.000017324091459158808
]
|
{
"id": 2,
"code_window": [
"// Reference: https://github.com/microsoft/TypeScript/blob/febfd442cdba343771f478cf433b0892f213ad2f/src/compiler/commandLineParser.ts#L3005\n",
"/**\n",
"* @returns Returns undefined in case of lack of result while trying to resolve from node_modules\n",
"*/\n",
"async function getTsconfigPath(baseDirUri: vscode.Uri, extendsValue: string): Promise<vscode.Uri | undefined> {\n",
"\t// Don't take into account a case, where tsconfig might be resolved from the root (see the reference)\n",
"\t// e.g. C:/projects/shared-tsconfig/tsconfig.json (note that C: prefix is optional)\n",
"\n",
"\tconst isRelativePath = ['./', '../'].some(str => extendsValue.startsWith(str));\n",
"\tif (isRelativePath) {\n",
"\t\tconst absolutePath = vscode.Uri.joinPath(baseDirUri, extendsValue);\n",
"\t\tif (await exists(absolutePath) || absolutePath.path.endsWith('.json')) {\n",
"\t\t\treturn absolutePath;\n",
"\t\t}\n",
"\t\treturn absolutePath.with({\n",
"\t\t\tpath: `${absolutePath.path}.json`\n",
"\t\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tasync function resolve(absolutePath: vscode.Uri): Promise<vscode.Uri> {\n",
"\t\tif (absolutePath.path.endsWith('.json') || await exists(absolutePath)) {\n"
],
"file_path": "extensions/typescript-language-features/src/languageFeatures/tsconfig.ts",
"type": "replace",
"edit_start_line_idx": 163
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as jsonc from 'jsonc-parser';
import { basename, posix } from 'path';
import * as vscode from 'vscode';
import { Utils } from 'vscode-uri';
import { coalesce } from '../utils/arrays';
import { exists } from '../utils/fs';
function mapChildren<R>(node: jsonc.Node | undefined, f: (x: jsonc.Node) => R): R[] {
return node && node.type === 'array' && node.children
? node.children.map(f)
: [];
}
const openExtendsLinkCommandId = '_typescript.openExtendsLink';
type OpenExtendsLinkCommandArgs = {
readonly resourceUri: vscode.Uri;
readonly extendsValue: string;
};
class TsconfigLinkProvider implements vscode.DocumentLinkProvider {
public provideDocumentLinks(
document: vscode.TextDocument,
_token: vscode.CancellationToken
): vscode.DocumentLink[] {
const root = jsonc.parseTree(document.getText());
if (!root) {
return [];
}
return coalesce([
this.getExtendsLink(document, root),
...this.getFilesLinks(document, root),
...this.getReferencesLinks(document, root)
]);
}
private getExtendsLink(document: vscode.TextDocument, root: jsonc.Node): vscode.DocumentLink | undefined {
const extendsNode = jsonc.findNodeAtLocation(root, ['extends']);
if (!this.isPathValue(extendsNode)) {
return undefined;
}
const extendsValue: string = extendsNode.value;
if (extendsValue.startsWith('/')) {
return undefined;
}
const args: OpenExtendsLinkCommandArgs = {
resourceUri: { ...document.uri.toJSON(), $mid: undefined }, // Prevent VS Code from trying to transform the uri
extendsValue: extendsValue
};
const link = new vscode.DocumentLink(
this.getRange(document, extendsNode),
vscode.Uri.parse(`command:${openExtendsLinkCommandId}?${JSON.stringify(args)}`));
link.tooltip = vscode.l10n.t("Follow link");
return link;
}
private getFilesLinks(document: vscode.TextDocument, root: jsonc.Node) {
return mapChildren(
jsonc.findNodeAtLocation(root, ['files']),
child => this.pathNodeToLink(document, child));
}
private getReferencesLinks(document: vscode.TextDocument, root: jsonc.Node) {
return mapChildren(
jsonc.findNodeAtLocation(root, ['references']),
child => {
const pathNode = jsonc.findNodeAtLocation(child, ['path']);
if (!this.isPathValue(pathNode)) {
return undefined;
}
return new vscode.DocumentLink(this.getRange(document, pathNode),
basename(pathNode.value).endsWith('.json')
? this.getFileTarget(document, pathNode)
: this.getFolderTarget(document, pathNode));
});
}
private pathNodeToLink(
document: vscode.TextDocument,
node: jsonc.Node | undefined
): vscode.DocumentLink | undefined {
return this.isPathValue(node)
? new vscode.DocumentLink(this.getRange(document, node), this.getFileTarget(document, node))
: undefined;
}
private isPathValue(extendsNode: jsonc.Node | undefined): extendsNode is jsonc.Node {
return extendsNode
&& extendsNode.type === 'string'
&& extendsNode.value
&& !(extendsNode.value as string).includes('*'); // don't treat globs as links.
}
private getFileTarget(document: vscode.TextDocument, node: jsonc.Node): vscode.Uri {
return vscode.Uri.joinPath(Utils.dirname(document.uri), node.value);
}
private getFolderTarget(document: vscode.TextDocument, node: jsonc.Node): vscode.Uri {
return vscode.Uri.joinPath(Utils.dirname(document.uri), node.value, 'tsconfig.json');
}
private getRange(document: vscode.TextDocument, node: jsonc.Node) {
const offset = node.offset;
const start = document.positionAt(offset + 1);
const end = document.positionAt(offset + (node.length - 1));
return new vscode.Range(start, end);
}
}
async function resolveNodeModulesPath(baseDirUri: vscode.Uri, pathCandidates: string[]): Promise<vscode.Uri | undefined> {
let currentUri = baseDirUri;
const baseCandidate = pathCandidates[0];
const sepIndex = baseCandidate.startsWith('@') ? 2 : 1;
const moduleBasePath = baseCandidate.split(posix.sep).slice(0, sepIndex).join(posix.sep);
while (true) {
const moduleAbsoluteUrl = vscode.Uri.joinPath(currentUri, 'node_modules', moduleBasePath);
let moduleStat: vscode.FileStat | undefined;
try {
moduleStat = await vscode.workspace.fs.stat(moduleAbsoluteUrl);
} catch (err) {
// noop
}
if (moduleStat && (moduleStat.type & vscode.FileType.Directory)) {
for (const uriCandidate of pathCandidates
.map((relativePath) => relativePath.split(posix.sep).slice(sepIndex).join(posix.sep))
// skip empty paths within module
.filter(Boolean)
.map((relativeModulePath) => vscode.Uri.joinPath(moduleAbsoluteUrl, relativeModulePath))
) {
if (await exists(uriCandidate)) {
return uriCandidate;
}
}
// Continue to looking for potentially another version
}
const oldUri = currentUri;
currentUri = vscode.Uri.joinPath(currentUri, '..');
// Can't go next. Reached the system root
if (oldUri.path === currentUri.path) {
return;
}
}
}
// Reference: https://github.com/microsoft/TypeScript/blob/febfd442cdba343771f478cf433b0892f213ad2f/src/compiler/commandLineParser.ts#L3005
/**
* @returns Returns undefined in case of lack of result while trying to resolve from node_modules
*/
async function getTsconfigPath(baseDirUri: vscode.Uri, extendsValue: string): Promise<vscode.Uri | undefined> {
// Don't take into account a case, where tsconfig might be resolved from the root (see the reference)
// e.g. C:/projects/shared-tsconfig/tsconfig.json (note that C: prefix is optional)
const isRelativePath = ['./', '../'].some(str => extendsValue.startsWith(str));
if (isRelativePath) {
const absolutePath = vscode.Uri.joinPath(baseDirUri, extendsValue);
if (await exists(absolutePath) || absolutePath.path.endsWith('.json')) {
return absolutePath;
}
return absolutePath.with({
path: `${absolutePath.path}.json`
});
}
// Otherwise resolve like a module
return resolveNodeModulesPath(baseDirUri, [
extendsValue,
...extendsValue.endsWith('.json') ? [] : [
`${extendsValue}.json`,
`${extendsValue}/tsconfig.json`,
]
]);
}
export function register() {
const patterns: vscode.GlobPattern[] = [
'**/[jt]sconfig.json',
'**/[jt]sconfig.*.json',
];
const languages = ['json', 'jsonc'];
const selector: vscode.DocumentSelector =
languages.map(language => patterns.map((pattern): vscode.DocumentFilter => ({ language, pattern })))
.flat();
return vscode.Disposable.from(
vscode.commands.registerCommand(openExtendsLinkCommandId, async ({ resourceUri, extendsValue, }: OpenExtendsLinkCommandArgs) => {
const tsconfigPath = await getTsconfigPath(Utils.dirname(vscode.Uri.from(resourceUri)), extendsValue);
if (tsconfigPath === undefined) {
vscode.window.showErrorMessage(vscode.l10n.t("Failed to resolve {0} as module", extendsValue));
return;
}
// Will suggest to create a .json variant if it doesn't exist yet (but only for relative paths)
await vscode.commands.executeCommand('vscode.open', tsconfigPath);
}),
vscode.languages.registerDocumentLinkProvider(selector, new TsconfigLinkProvider()),
);
}
| extensions/typescript-language-features/src/languageFeatures/tsconfig.ts | 1 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.9991602897644043,
0.13791482150554657,
0.00016268598847091198,
0.0004747173807118088,
0.3387088477611542
]
|
{
"id": 2,
"code_window": [
"// Reference: https://github.com/microsoft/TypeScript/blob/febfd442cdba343771f478cf433b0892f213ad2f/src/compiler/commandLineParser.ts#L3005\n",
"/**\n",
"* @returns Returns undefined in case of lack of result while trying to resolve from node_modules\n",
"*/\n",
"async function getTsconfigPath(baseDirUri: vscode.Uri, extendsValue: string): Promise<vscode.Uri | undefined> {\n",
"\t// Don't take into account a case, where tsconfig might be resolved from the root (see the reference)\n",
"\t// e.g. C:/projects/shared-tsconfig/tsconfig.json (note that C: prefix is optional)\n",
"\n",
"\tconst isRelativePath = ['./', '../'].some(str => extendsValue.startsWith(str));\n",
"\tif (isRelativePath) {\n",
"\t\tconst absolutePath = vscode.Uri.joinPath(baseDirUri, extendsValue);\n",
"\t\tif (await exists(absolutePath) || absolutePath.path.endsWith('.json')) {\n",
"\t\t\treturn absolutePath;\n",
"\t\t}\n",
"\t\treturn absolutePath.with({\n",
"\t\t\tpath: `${absolutePath.path}.json`\n",
"\t\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tasync function resolve(absolutePath: vscode.Uri): Promise<vscode.Uri> {\n",
"\t\tif (absolutePath.path.endsWith('.json') || await exists(absolutePath)) {\n"
],
"file_path": "extensions/typescript-language-features/src/languageFeatures/tsconfig.ts",
"type": "replace",
"edit_start_line_idx": 163
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { LineTokens } from 'vs/editor/common/tokens/lineTokens';
import { StandardTokenType } from 'vs/editor/common/encodedTokenAttributes';
export function createScopedLineTokens(context: LineTokens, offset: number): ScopedLineTokens {
const tokenCount = context.getCount();
const tokenIndex = context.findTokenIndexAtOffset(offset);
const desiredLanguageId = context.getLanguageId(tokenIndex);
let lastTokenIndex = tokenIndex;
while (lastTokenIndex + 1 < tokenCount && context.getLanguageId(lastTokenIndex + 1) === desiredLanguageId) {
lastTokenIndex++;
}
let firstTokenIndex = tokenIndex;
while (firstTokenIndex > 0 && context.getLanguageId(firstTokenIndex - 1) === desiredLanguageId) {
firstTokenIndex--;
}
return new ScopedLineTokens(
context,
desiredLanguageId,
firstTokenIndex,
lastTokenIndex + 1,
context.getStartOffset(firstTokenIndex),
context.getEndOffset(lastTokenIndex)
);
}
export class ScopedLineTokens {
_scopedLineTokensBrand: void = undefined;
public readonly languageId: string;
private readonly _actual: LineTokens;
private readonly _firstTokenIndex: number;
private readonly _lastTokenIndex: number;
public readonly firstCharOffset: number;
private readonly _lastCharOffset: number;
constructor(
actual: LineTokens,
languageId: string,
firstTokenIndex: number,
lastTokenIndex: number,
firstCharOffset: number,
lastCharOffset: number
) {
this._actual = actual;
this.languageId = languageId;
this._firstTokenIndex = firstTokenIndex;
this._lastTokenIndex = lastTokenIndex;
this.firstCharOffset = firstCharOffset;
this._lastCharOffset = lastCharOffset;
}
public getLineContent(): string {
const actualLineContent = this._actual.getLineContent();
return actualLineContent.substring(this.firstCharOffset, this._lastCharOffset);
}
public getActualLineContentBefore(offset: number): string {
const actualLineContent = this._actual.getLineContent();
return actualLineContent.substring(0, this.firstCharOffset + offset);
}
public getTokenCount(): number {
return this._lastTokenIndex - this._firstTokenIndex;
}
public findTokenIndexAtOffset(offset: number): number {
return this._actual.findTokenIndexAtOffset(offset + this.firstCharOffset) - this._firstTokenIndex;
}
public getStandardTokenType(tokenIndex: number): StandardTokenType {
return this._actual.getStandardTokenType(tokenIndex + this._firstTokenIndex);
}
}
const enum IgnoreBracketsInTokens {
value = StandardTokenType.Comment | StandardTokenType.String | StandardTokenType.RegEx
}
export function ignoreBracketsInToken(standardTokenType: StandardTokenType): boolean {
return (standardTokenType & IgnoreBracketsInTokens.value) !== 0;
}
| src/vs/editor/common/languages/supports.ts | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.00020428630523383617,
0.00017091982590500265,
0.00016236580268014222,
0.0001670368219492957,
0.000012122682164772414
]
|
{
"id": 2,
"code_window": [
"// Reference: https://github.com/microsoft/TypeScript/blob/febfd442cdba343771f478cf433b0892f213ad2f/src/compiler/commandLineParser.ts#L3005\n",
"/**\n",
"* @returns Returns undefined in case of lack of result while trying to resolve from node_modules\n",
"*/\n",
"async function getTsconfigPath(baseDirUri: vscode.Uri, extendsValue: string): Promise<vscode.Uri | undefined> {\n",
"\t// Don't take into account a case, where tsconfig might be resolved from the root (see the reference)\n",
"\t// e.g. C:/projects/shared-tsconfig/tsconfig.json (note that C: prefix is optional)\n",
"\n",
"\tconst isRelativePath = ['./', '../'].some(str => extendsValue.startsWith(str));\n",
"\tif (isRelativePath) {\n",
"\t\tconst absolutePath = vscode.Uri.joinPath(baseDirUri, extendsValue);\n",
"\t\tif (await exists(absolutePath) || absolutePath.path.endsWith('.json')) {\n",
"\t\t\treturn absolutePath;\n",
"\t\t}\n",
"\t\treturn absolutePath.with({\n",
"\t\t\tpath: `${absolutePath.path}.json`\n",
"\t\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tasync function resolve(absolutePath: vscode.Uri): Promise<vscode.Uri> {\n",
"\t\tif (absolutePath.path.endsWith('.json') || await exists(absolutePath)) {\n"
],
"file_path": "extensions/typescript-language-features/src/languageFeatures/tsconfig.ts",
"type": "replace",
"edit_start_line_idx": 163
} | {
"comments": {
"lineComment": "//",
"blockComment": [ "/*", "*/" ]
},
"brackets": [
["{", "}"],
["[", "]"],
["(", ")"]
],
"autoClosingPairs": [
["{", "}"],
["[", "]"],
["(", ")"],
{ "open": "\"", "close": "\"", "notIn": ["string"] },
{ "open": "'", "close": "'", "notIn": ["string"] }
],
"surroundingPairs": [
["{", "}"],
["[", "]"],
["(", ")"],
["\"", "\""],
["'", "'"]
]
}
| extensions/objective-c/language-configuration.json | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.00016938699991442263,
0.00016825448255985975,
0.00016648712335154414,
0.00016888930986169726,
0.0000012661174650929752
]
|
{
"id": 2,
"code_window": [
"// Reference: https://github.com/microsoft/TypeScript/blob/febfd442cdba343771f478cf433b0892f213ad2f/src/compiler/commandLineParser.ts#L3005\n",
"/**\n",
"* @returns Returns undefined in case of lack of result while trying to resolve from node_modules\n",
"*/\n",
"async function getTsconfigPath(baseDirUri: vscode.Uri, extendsValue: string): Promise<vscode.Uri | undefined> {\n",
"\t// Don't take into account a case, where tsconfig might be resolved from the root (see the reference)\n",
"\t// e.g. C:/projects/shared-tsconfig/tsconfig.json (note that C: prefix is optional)\n",
"\n",
"\tconst isRelativePath = ['./', '../'].some(str => extendsValue.startsWith(str));\n",
"\tif (isRelativePath) {\n",
"\t\tconst absolutePath = vscode.Uri.joinPath(baseDirUri, extendsValue);\n",
"\t\tif (await exists(absolutePath) || absolutePath.path.endsWith('.json')) {\n",
"\t\t\treturn absolutePath;\n",
"\t\t}\n",
"\t\treturn absolutePath.with({\n",
"\t\t\tpath: `${absolutePath.path}.json`\n",
"\t\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tasync function resolve(absolutePath: vscode.Uri): Promise<vscode.Uri> {\n",
"\t\tif (absolutePath.path.endsWith('.json') || await exists(absolutePath)) {\n"
],
"file_path": "extensions/typescript-language-features/src/languageFeatures/tsconfig.ts",
"type": "replace",
"edit_start_line_idx": 163
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IStringDictionary } from 'vs/base/common/collections';
import { Event } from 'vs/base/common/event';
export const enum ExtensionRecommendationReason {
Workspace,
File,
Executable,
WorkspaceConfig,
DynamicWorkspace,
Experimental,
Application,
}
export interface IExtensionRecommendationReason {
reasonId: ExtensionRecommendationReason;
reasonText: string;
}
export const IExtensionRecommendationsService = createDecorator<IExtensionRecommendationsService>('extensionRecommendationsService');
export interface IExtensionRecommendationsService {
readonly _serviceBrand: undefined;
readonly onDidChangeRecommendations: Event<void>;
getAllRecommendationsWithReason(): IStringDictionary<IExtensionRecommendationReason>;
getImportantRecommendations(): Promise<string[]>;
getOtherRecommendations(): Promise<string[]>;
getFileBasedRecommendations(): string[];
getExeBasedRecommendations(exe?: string): Promise<{ important: string[]; others: string[] }>;
getConfigBasedRecommendations(): Promise<{ important: string[]; others: string[] }>;
getWorkspaceRecommendations(): Promise<string[]>;
getKeymapRecommendations(): string[];
getLanguageRecommendations(): string[];
getRemoteRecommendations(): string[];
}
export type IgnoredRecommendationChangeNotification = {
extensionId: string;
isRecommended: boolean;
};
export const IExtensionIgnoredRecommendationsService = createDecorator<IExtensionIgnoredRecommendationsService>('IExtensionIgnoredRecommendationsService');
export interface IExtensionIgnoredRecommendationsService {
readonly _serviceBrand: undefined;
onDidChangeIgnoredRecommendations: Event<void>;
readonly ignoredRecommendations: string[];
onDidChangeGlobalIgnoredRecommendation: Event<IgnoredRecommendationChangeNotification>;
readonly globalIgnoredRecommendations: string[];
toggleGlobalIgnoredRecommendation(extensionId: string, ignore: boolean): void;
}
| src/vs/workbench/services/extensionRecommendations/common/extensionRecommendations.ts | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.00017365586245432496,
0.00016614966443739831,
0.00016176499775610864,
0.00016476053860969841,
0.000003743670276890043
]
|
{
"id": 3,
"code_window": [
"\t\t\tpath: `${absolutePath.path}.json`\n",
"\t\t});\n",
"\t}\n",
"\n",
"\t// Otherwise resolve like a module\n",
"\treturn resolveNodeModulesPath(baseDirUri, [\n",
"\t\textendsValue,\n",
"\t\t...extendsValue.endsWith('.json') ? [] : [\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tconst isRelativePath = ['./', '../'].some(str => extendsValue.startsWith(str));\n",
"\tif (isRelativePath) {\n",
"\t\treturn resolve(vscode.Uri.joinPath(baseDirUri, extendsValue));\n",
"\t}\n",
"\n",
"\tif (extendsValue.startsWith('/') || looksLikeAbsoluteWindowsPath(extendsValue)) {\n",
"\t\treturn resolve(vscode.Uri.file(extendsValue));\n",
"\t}\n",
"\n"
],
"file_path": "extensions/typescript-language-features/src/languageFeatures/tsconfig.ts",
"type": "add",
"edit_start_line_idx": 177
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as jsonc from 'jsonc-parser';
import { basename, posix } from 'path';
import * as vscode from 'vscode';
import { Utils } from 'vscode-uri';
import { coalesce } from '../utils/arrays';
import { exists } from '../utils/fs';
function mapChildren<R>(node: jsonc.Node | undefined, f: (x: jsonc.Node) => R): R[] {
return node && node.type === 'array' && node.children
? node.children.map(f)
: [];
}
const openExtendsLinkCommandId = '_typescript.openExtendsLink';
type OpenExtendsLinkCommandArgs = {
readonly resourceUri: vscode.Uri;
readonly extendsValue: string;
};
class TsconfigLinkProvider implements vscode.DocumentLinkProvider {
public provideDocumentLinks(
document: vscode.TextDocument,
_token: vscode.CancellationToken
): vscode.DocumentLink[] {
const root = jsonc.parseTree(document.getText());
if (!root) {
return [];
}
return coalesce([
this.getExtendsLink(document, root),
...this.getFilesLinks(document, root),
...this.getReferencesLinks(document, root)
]);
}
private getExtendsLink(document: vscode.TextDocument, root: jsonc.Node): vscode.DocumentLink | undefined {
const extendsNode = jsonc.findNodeAtLocation(root, ['extends']);
if (!this.isPathValue(extendsNode)) {
return undefined;
}
const extendsValue: string = extendsNode.value;
if (extendsValue.startsWith('/')) {
return undefined;
}
const args: OpenExtendsLinkCommandArgs = {
resourceUri: { ...document.uri.toJSON(), $mid: undefined }, // Prevent VS Code from trying to transform the uri
extendsValue: extendsValue
};
const link = new vscode.DocumentLink(
this.getRange(document, extendsNode),
vscode.Uri.parse(`command:${openExtendsLinkCommandId}?${JSON.stringify(args)}`));
link.tooltip = vscode.l10n.t("Follow link");
return link;
}
private getFilesLinks(document: vscode.TextDocument, root: jsonc.Node) {
return mapChildren(
jsonc.findNodeAtLocation(root, ['files']),
child => this.pathNodeToLink(document, child));
}
private getReferencesLinks(document: vscode.TextDocument, root: jsonc.Node) {
return mapChildren(
jsonc.findNodeAtLocation(root, ['references']),
child => {
const pathNode = jsonc.findNodeAtLocation(child, ['path']);
if (!this.isPathValue(pathNode)) {
return undefined;
}
return new vscode.DocumentLink(this.getRange(document, pathNode),
basename(pathNode.value).endsWith('.json')
? this.getFileTarget(document, pathNode)
: this.getFolderTarget(document, pathNode));
});
}
private pathNodeToLink(
document: vscode.TextDocument,
node: jsonc.Node | undefined
): vscode.DocumentLink | undefined {
return this.isPathValue(node)
? new vscode.DocumentLink(this.getRange(document, node), this.getFileTarget(document, node))
: undefined;
}
private isPathValue(extendsNode: jsonc.Node | undefined): extendsNode is jsonc.Node {
return extendsNode
&& extendsNode.type === 'string'
&& extendsNode.value
&& !(extendsNode.value as string).includes('*'); // don't treat globs as links.
}
private getFileTarget(document: vscode.TextDocument, node: jsonc.Node): vscode.Uri {
return vscode.Uri.joinPath(Utils.dirname(document.uri), node.value);
}
private getFolderTarget(document: vscode.TextDocument, node: jsonc.Node): vscode.Uri {
return vscode.Uri.joinPath(Utils.dirname(document.uri), node.value, 'tsconfig.json');
}
private getRange(document: vscode.TextDocument, node: jsonc.Node) {
const offset = node.offset;
const start = document.positionAt(offset + 1);
const end = document.positionAt(offset + (node.length - 1));
return new vscode.Range(start, end);
}
}
async function resolveNodeModulesPath(baseDirUri: vscode.Uri, pathCandidates: string[]): Promise<vscode.Uri | undefined> {
let currentUri = baseDirUri;
const baseCandidate = pathCandidates[0];
const sepIndex = baseCandidate.startsWith('@') ? 2 : 1;
const moduleBasePath = baseCandidate.split(posix.sep).slice(0, sepIndex).join(posix.sep);
while (true) {
const moduleAbsoluteUrl = vscode.Uri.joinPath(currentUri, 'node_modules', moduleBasePath);
let moduleStat: vscode.FileStat | undefined;
try {
moduleStat = await vscode.workspace.fs.stat(moduleAbsoluteUrl);
} catch (err) {
// noop
}
if (moduleStat && (moduleStat.type & vscode.FileType.Directory)) {
for (const uriCandidate of pathCandidates
.map((relativePath) => relativePath.split(posix.sep).slice(sepIndex).join(posix.sep))
// skip empty paths within module
.filter(Boolean)
.map((relativeModulePath) => vscode.Uri.joinPath(moduleAbsoluteUrl, relativeModulePath))
) {
if (await exists(uriCandidate)) {
return uriCandidate;
}
}
// Continue to looking for potentially another version
}
const oldUri = currentUri;
currentUri = vscode.Uri.joinPath(currentUri, '..');
// Can't go next. Reached the system root
if (oldUri.path === currentUri.path) {
return;
}
}
}
// Reference: https://github.com/microsoft/TypeScript/blob/febfd442cdba343771f478cf433b0892f213ad2f/src/compiler/commandLineParser.ts#L3005
/**
* @returns Returns undefined in case of lack of result while trying to resolve from node_modules
*/
async function getTsconfigPath(baseDirUri: vscode.Uri, extendsValue: string): Promise<vscode.Uri | undefined> {
// Don't take into account a case, where tsconfig might be resolved from the root (see the reference)
// e.g. C:/projects/shared-tsconfig/tsconfig.json (note that C: prefix is optional)
const isRelativePath = ['./', '../'].some(str => extendsValue.startsWith(str));
if (isRelativePath) {
const absolutePath = vscode.Uri.joinPath(baseDirUri, extendsValue);
if (await exists(absolutePath) || absolutePath.path.endsWith('.json')) {
return absolutePath;
}
return absolutePath.with({
path: `${absolutePath.path}.json`
});
}
// Otherwise resolve like a module
return resolveNodeModulesPath(baseDirUri, [
extendsValue,
...extendsValue.endsWith('.json') ? [] : [
`${extendsValue}.json`,
`${extendsValue}/tsconfig.json`,
]
]);
}
export function register() {
const patterns: vscode.GlobPattern[] = [
'**/[jt]sconfig.json',
'**/[jt]sconfig.*.json',
];
const languages = ['json', 'jsonc'];
const selector: vscode.DocumentSelector =
languages.map(language => patterns.map((pattern): vscode.DocumentFilter => ({ language, pattern })))
.flat();
return vscode.Disposable.from(
vscode.commands.registerCommand(openExtendsLinkCommandId, async ({ resourceUri, extendsValue, }: OpenExtendsLinkCommandArgs) => {
const tsconfigPath = await getTsconfigPath(Utils.dirname(vscode.Uri.from(resourceUri)), extendsValue);
if (tsconfigPath === undefined) {
vscode.window.showErrorMessage(vscode.l10n.t("Failed to resolve {0} as module", extendsValue));
return;
}
// Will suggest to create a .json variant if it doesn't exist yet (but only for relative paths)
await vscode.commands.executeCommand('vscode.open', tsconfigPath);
}),
vscode.languages.registerDocumentLinkProvider(selector, new TsconfigLinkProvider()),
);
}
| extensions/typescript-language-features/src/languageFeatures/tsconfig.ts | 1 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.5540888905525208,
0.025909660384058952,
0.0001657069515204057,
0.00017458820366300642,
0.11526356637477875
]
|
{
"id": 3,
"code_window": [
"\t\t\tpath: `${absolutePath.path}.json`\n",
"\t\t});\n",
"\t}\n",
"\n",
"\t// Otherwise resolve like a module\n",
"\treturn resolveNodeModulesPath(baseDirUri, [\n",
"\t\textendsValue,\n",
"\t\t...extendsValue.endsWith('.json') ? [] : [\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tconst isRelativePath = ['./', '../'].some(str => extendsValue.startsWith(str));\n",
"\tif (isRelativePath) {\n",
"\t\treturn resolve(vscode.Uri.joinPath(baseDirUri, extendsValue));\n",
"\t}\n",
"\n",
"\tif (extendsValue.startsWith('/') || looksLikeAbsoluteWindowsPath(extendsValue)) {\n",
"\t\treturn resolve(vscode.Uri.file(extendsValue));\n",
"\t}\n",
"\n"
],
"file_path": "extensions/typescript-language-features/src/languageFeatures/tsconfig.ts",
"type": "add",
"edit_start_line_idx": 177
} | #!/usr/bin/env bash
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
if [[ "$OSTYPE" == "darwin"* ]]; then
realpath() { [[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"; }
VSCODE_PATH=$(dirname $(dirname $(dirname $(dirname $(dirname $(realpath "$0"))))))
else
VSCODE_PATH=$(dirname $(dirname $(dirname $(dirname $(dirname $(readlink -f $0))))))
fi
PROD_NAME="Code Server - Dev"
VERSION=""
COMMIT=""
EXEC_NAME=""
CLI_SCRIPT="$VSCODE_PATH/out/server-cli.js"
node "$CLI_SCRIPT" "$PROD_NAME" "$VERSION" "$COMMIT" "$EXEC_NAME" "--openExternal" "$@"
| resources/server/bin-dev/helpers/browser.sh | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.00016744887398090214,
0.00016566325211897492,
0.00016387764480896294,
0.00016566325211897492,
0.000001785614585969597
]
|
{
"id": 3,
"code_window": [
"\t\t\tpath: `${absolutePath.path}.json`\n",
"\t\t});\n",
"\t}\n",
"\n",
"\t// Otherwise resolve like a module\n",
"\treturn resolveNodeModulesPath(baseDirUri, [\n",
"\t\textendsValue,\n",
"\t\t...extendsValue.endsWith('.json') ? [] : [\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tconst isRelativePath = ['./', '../'].some(str => extendsValue.startsWith(str));\n",
"\tif (isRelativePath) {\n",
"\t\treturn resolve(vscode.Uri.joinPath(baseDirUri, extendsValue));\n",
"\t}\n",
"\n",
"\tif (extendsValue.startsWith('/') || looksLikeAbsoluteWindowsPath(extendsValue)) {\n",
"\t\treturn resolve(vscode.Uri.file(extendsValue));\n",
"\t}\n",
"\n"
],
"file_path": "extensions/typescript-language-features/src/languageFeatures/tsconfig.ts",
"type": "add",
"edit_start_line_idx": 177
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as path from 'path';
import * as testRunner from '../../../../test/integration/electron/testrunner';
const options: import('mocha').MochaOptions = {
ui: 'tdd',
color: true,
timeout: 60000
};
// These integration tests is being run in multiple environments (electron, web, remote)
// so we need to set the suite name based on the environment as the suite name is used
// for the test results file name
let suite = '';
if (process.env.VSCODE_BROWSER) {
suite = `${process.env.VSCODE_BROWSER} Browser Integration Markdown Tests`;
} else if (process.env.REMOTE_VSCODE) {
suite = 'Remote Integration Markdown Tests';
} else {
suite = 'Integration Markdown Tests';
}
if (process.env.BUILD_ARTIFACTSTAGINGDIRECTORY) {
options.reporter = 'mocha-multi-reporters';
options.reporterOptions = {
reporterEnabled: 'spec, mocha-junit-reporter',
mochaJunitReporterReporterOptions: {
testsuitesTitle: `${suite} ${process.platform}`,
mochaFile: path.join(process.env.BUILD_ARTIFACTSTAGINGDIRECTORY, `test-results/${process.platform}-${process.arch}-${suite.toLowerCase().replace(/[^\w]/g, '-')}-results.xml`)
}
};
}
testRunner.configure(options);
export = testRunner;
| extensions/markdown-language-features/src/test/index.ts | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.00017444632248952985,
0.0001715690887067467,
0.00016819199663586915,
0.0001713155215838924,
0.0000021902526441408554
]
|
{
"id": 3,
"code_window": [
"\t\t\tpath: `${absolutePath.path}.json`\n",
"\t\t});\n",
"\t}\n",
"\n",
"\t// Otherwise resolve like a module\n",
"\treturn resolveNodeModulesPath(baseDirUri, [\n",
"\t\textendsValue,\n",
"\t\t...extendsValue.endsWith('.json') ? [] : [\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tconst isRelativePath = ['./', '../'].some(str => extendsValue.startsWith(str));\n",
"\tif (isRelativePath) {\n",
"\t\treturn resolve(vscode.Uri.joinPath(baseDirUri, extendsValue));\n",
"\t}\n",
"\n",
"\tif (extendsValue.startsWith('/') || looksLikeAbsoluteWindowsPath(extendsValue)) {\n",
"\t\treturn resolve(vscode.Uri.file(extendsValue));\n",
"\t}\n",
"\n"
],
"file_path": "extensions/typescript-language-features/src/languageFeatures/tsconfig.ts",
"type": "add",
"edit_start_line_idx": 177
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Event } from 'vs/base/common/event';
import { IJSONSchema } from 'vs/base/common/jsonSchema';
import { KeyCode } from 'vs/base/common/keyCodes';
import { ResolvedKeybinding, Keybinding } from 'vs/base/common/keybindings';
import { IContextKeyService, IContextKeyServiceTarget } from 'vs/platform/contextkey/common/contextkey';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ResolutionResult } from 'vs/platform/keybinding/common/keybindingResolver';
import { ResolvedKeybindingItem } from 'vs/platform/keybinding/common/resolvedKeybindingItem';
export interface IUserFriendlyKeybinding {
key: string;
command: string;
args?: any;
when?: string;
}
export interface IKeyboardEvent {
readonly _standardKeyboardEventBrand: true;
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly altKey: boolean;
readonly metaKey: boolean;
readonly altGraphKey: boolean;
readonly keyCode: KeyCode;
readonly code: string;
}
export interface KeybindingsSchemaContribution {
readonly onDidChange?: Event<void>;
getSchemaAdditions(): IJSONSchema[];
}
export const IKeybindingService = createDecorator<IKeybindingService>('keybindingService');
export interface IKeybindingService {
readonly _serviceBrand: undefined;
readonly inChordMode: boolean;
onDidUpdateKeybindings: Event<void>;
/**
* Returns none, one or many (depending on keyboard layout)!
*/
resolveKeybinding(keybinding: Keybinding): ResolvedKeybinding[];
resolveKeyboardEvent(keyboardEvent: IKeyboardEvent): ResolvedKeybinding;
resolveUserBinding(userBinding: string): ResolvedKeybinding[];
/**
* Resolve and dispatch `keyboardEvent` and invoke the command.
*/
dispatchEvent(e: IKeyboardEvent, target: IContextKeyServiceTarget): boolean;
/**
* Resolve and dispatch `keyboardEvent`, but do not invoke the command or change inner state.
*/
softDispatch(keyboardEvent: IKeyboardEvent, target: IContextKeyServiceTarget): ResolutionResult;
dispatchByUserSettingsLabel(userSettingsLabel: string, target: IContextKeyServiceTarget): void;
/**
* Look up keybindings for a command.
* Use `lookupKeybinding` if you are interested in the preferred keybinding.
*/
lookupKeybindings(commandId: string): ResolvedKeybinding[];
/**
* Look up the preferred (last defined) keybinding for a command.
* @returns The preferred keybinding or null if the command is not bound.
*/
lookupKeybinding(commandId: string, context?: IContextKeyService): ResolvedKeybinding | undefined;
getDefaultKeybindingsContent(): string;
getDefaultKeybindings(): readonly ResolvedKeybindingItem[];
getKeybindings(): readonly ResolvedKeybindingItem[];
customKeybindingsCount(): number;
/**
* Will the given key event produce a character that's rendered on screen, e.g. in a
* text box. *Note* that the results of this function can be incorrect.
*/
mightProducePrintableCharacter(event: IKeyboardEvent): boolean;
registerSchemaContribution(contribution: KeybindingsSchemaContribution): void;
toggleLogging(): boolean;
_dumpDebugInfo(): string;
_dumpDebugInfoJSON(): string;
}
| src/vs/platform/keybinding/common/keybinding.ts | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.00021895341342315078,
0.00017353800649289042,
0.00016499226330779493,
0.00016864680219441652,
0.000014511309018416796
]
|
{
"id": 4,
"code_window": [
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
"import * as vscode from 'vscode';\n",
"\n",
"export const exists = async (resource: vscode.Uri): Promise<boolean> => {\n",
"\ttry {\n",
"\t\tconst stat = await vscode.workspace.fs.stat(resource);\n",
"\t\t// stat.type is an enum flag\n",
"\t\treturn !!(stat.type & vscode.FileType.File);\n",
"\t} catch {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export async function exists(resource: vscode.Uri): Promise<boolean> {\n"
],
"file_path": "extensions/typescript-language-features/src/utils/fs.ts",
"type": "replace",
"edit_start_line_idx": 7
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as jsonc from 'jsonc-parser';
import { basename, posix } from 'path';
import * as vscode from 'vscode';
import { Utils } from 'vscode-uri';
import { coalesce } from '../utils/arrays';
import { exists } from '../utils/fs';
function mapChildren<R>(node: jsonc.Node | undefined, f: (x: jsonc.Node) => R): R[] {
return node && node.type === 'array' && node.children
? node.children.map(f)
: [];
}
const openExtendsLinkCommandId = '_typescript.openExtendsLink';
type OpenExtendsLinkCommandArgs = {
readonly resourceUri: vscode.Uri;
readonly extendsValue: string;
};
class TsconfigLinkProvider implements vscode.DocumentLinkProvider {
public provideDocumentLinks(
document: vscode.TextDocument,
_token: vscode.CancellationToken
): vscode.DocumentLink[] {
const root = jsonc.parseTree(document.getText());
if (!root) {
return [];
}
return coalesce([
this.getExtendsLink(document, root),
...this.getFilesLinks(document, root),
...this.getReferencesLinks(document, root)
]);
}
private getExtendsLink(document: vscode.TextDocument, root: jsonc.Node): vscode.DocumentLink | undefined {
const extendsNode = jsonc.findNodeAtLocation(root, ['extends']);
if (!this.isPathValue(extendsNode)) {
return undefined;
}
const extendsValue: string = extendsNode.value;
if (extendsValue.startsWith('/')) {
return undefined;
}
const args: OpenExtendsLinkCommandArgs = {
resourceUri: { ...document.uri.toJSON(), $mid: undefined }, // Prevent VS Code from trying to transform the uri
extendsValue: extendsValue
};
const link = new vscode.DocumentLink(
this.getRange(document, extendsNode),
vscode.Uri.parse(`command:${openExtendsLinkCommandId}?${JSON.stringify(args)}`));
link.tooltip = vscode.l10n.t("Follow link");
return link;
}
private getFilesLinks(document: vscode.TextDocument, root: jsonc.Node) {
return mapChildren(
jsonc.findNodeAtLocation(root, ['files']),
child => this.pathNodeToLink(document, child));
}
private getReferencesLinks(document: vscode.TextDocument, root: jsonc.Node) {
return mapChildren(
jsonc.findNodeAtLocation(root, ['references']),
child => {
const pathNode = jsonc.findNodeAtLocation(child, ['path']);
if (!this.isPathValue(pathNode)) {
return undefined;
}
return new vscode.DocumentLink(this.getRange(document, pathNode),
basename(pathNode.value).endsWith('.json')
? this.getFileTarget(document, pathNode)
: this.getFolderTarget(document, pathNode));
});
}
private pathNodeToLink(
document: vscode.TextDocument,
node: jsonc.Node | undefined
): vscode.DocumentLink | undefined {
return this.isPathValue(node)
? new vscode.DocumentLink(this.getRange(document, node), this.getFileTarget(document, node))
: undefined;
}
private isPathValue(extendsNode: jsonc.Node | undefined): extendsNode is jsonc.Node {
return extendsNode
&& extendsNode.type === 'string'
&& extendsNode.value
&& !(extendsNode.value as string).includes('*'); // don't treat globs as links.
}
private getFileTarget(document: vscode.TextDocument, node: jsonc.Node): vscode.Uri {
return vscode.Uri.joinPath(Utils.dirname(document.uri), node.value);
}
private getFolderTarget(document: vscode.TextDocument, node: jsonc.Node): vscode.Uri {
return vscode.Uri.joinPath(Utils.dirname(document.uri), node.value, 'tsconfig.json');
}
private getRange(document: vscode.TextDocument, node: jsonc.Node) {
const offset = node.offset;
const start = document.positionAt(offset + 1);
const end = document.positionAt(offset + (node.length - 1));
return new vscode.Range(start, end);
}
}
async function resolveNodeModulesPath(baseDirUri: vscode.Uri, pathCandidates: string[]): Promise<vscode.Uri | undefined> {
let currentUri = baseDirUri;
const baseCandidate = pathCandidates[0];
const sepIndex = baseCandidate.startsWith('@') ? 2 : 1;
const moduleBasePath = baseCandidate.split(posix.sep).slice(0, sepIndex).join(posix.sep);
while (true) {
const moduleAbsoluteUrl = vscode.Uri.joinPath(currentUri, 'node_modules', moduleBasePath);
let moduleStat: vscode.FileStat | undefined;
try {
moduleStat = await vscode.workspace.fs.stat(moduleAbsoluteUrl);
} catch (err) {
// noop
}
if (moduleStat && (moduleStat.type & vscode.FileType.Directory)) {
for (const uriCandidate of pathCandidates
.map((relativePath) => relativePath.split(posix.sep).slice(sepIndex).join(posix.sep))
// skip empty paths within module
.filter(Boolean)
.map((relativeModulePath) => vscode.Uri.joinPath(moduleAbsoluteUrl, relativeModulePath))
) {
if (await exists(uriCandidate)) {
return uriCandidate;
}
}
// Continue to looking for potentially another version
}
const oldUri = currentUri;
currentUri = vscode.Uri.joinPath(currentUri, '..');
// Can't go next. Reached the system root
if (oldUri.path === currentUri.path) {
return;
}
}
}
// Reference: https://github.com/microsoft/TypeScript/blob/febfd442cdba343771f478cf433b0892f213ad2f/src/compiler/commandLineParser.ts#L3005
/**
* @returns Returns undefined in case of lack of result while trying to resolve from node_modules
*/
async function getTsconfigPath(baseDirUri: vscode.Uri, extendsValue: string): Promise<vscode.Uri | undefined> {
// Don't take into account a case, where tsconfig might be resolved from the root (see the reference)
// e.g. C:/projects/shared-tsconfig/tsconfig.json (note that C: prefix is optional)
const isRelativePath = ['./', '../'].some(str => extendsValue.startsWith(str));
if (isRelativePath) {
const absolutePath = vscode.Uri.joinPath(baseDirUri, extendsValue);
if (await exists(absolutePath) || absolutePath.path.endsWith('.json')) {
return absolutePath;
}
return absolutePath.with({
path: `${absolutePath.path}.json`
});
}
// Otherwise resolve like a module
return resolveNodeModulesPath(baseDirUri, [
extendsValue,
...extendsValue.endsWith('.json') ? [] : [
`${extendsValue}.json`,
`${extendsValue}/tsconfig.json`,
]
]);
}
export function register() {
const patterns: vscode.GlobPattern[] = [
'**/[jt]sconfig.json',
'**/[jt]sconfig.*.json',
];
const languages = ['json', 'jsonc'];
const selector: vscode.DocumentSelector =
languages.map(language => patterns.map((pattern): vscode.DocumentFilter => ({ language, pattern })))
.flat();
return vscode.Disposable.from(
vscode.commands.registerCommand(openExtendsLinkCommandId, async ({ resourceUri, extendsValue, }: OpenExtendsLinkCommandArgs) => {
const tsconfigPath = await getTsconfigPath(Utils.dirname(vscode.Uri.from(resourceUri)), extendsValue);
if (tsconfigPath === undefined) {
vscode.window.showErrorMessage(vscode.l10n.t("Failed to resolve {0} as module", extendsValue));
return;
}
// Will suggest to create a .json variant if it doesn't exist yet (but only for relative paths)
await vscode.commands.executeCommand('vscode.open', tsconfigPath);
}),
vscode.languages.registerDocumentLinkProvider(selector, new TsconfigLinkProvider()),
);
}
| extensions/typescript-language-features/src/languageFeatures/tsconfig.ts | 1 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.9981459379196167,
0.13592344522476196,
0.0001620745606487617,
0.0002313037111889571,
0.3401993215084076
]
|
{
"id": 4,
"code_window": [
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
"import * as vscode from 'vscode';\n",
"\n",
"export const exists = async (resource: vscode.Uri): Promise<boolean> => {\n",
"\ttry {\n",
"\t\tconst stat = await vscode.workspace.fs.stat(resource);\n",
"\t\t// stat.type is an enum flag\n",
"\t\treturn !!(stat.type & vscode.FileType.File);\n",
"\t} catch {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export async function exists(resource: vscode.Uri): Promise<boolean> {\n"
],
"file_path": "extensions/typescript-language-features/src/utils/fs.ts",
"type": "replace",
"edit_start_line_idx": 7
} | /*---------------------------------------------------------------------------------------------
* 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 { URI } from 'vs/base/common/uri';
import { getWorkspaceIdentifier, getSingleFolderWorkspaceIdentifier } from 'vs/workbench/services/workspaces/browser/workspaces';
suite('Workspaces', () => {
test('workspace identifiers are stable', function () {
// workspace identifier
assert.strictEqual(getWorkspaceIdentifier(URI.parse('vscode-remote:/hello/test')).id, '474434e4');
// single folder identifier
assert.strictEqual(getSingleFolderWorkspaceIdentifier(URI.parse('vscode-remote:/hello/test'))?.id, '474434e4');
});
});
| src/vs/workbench/services/workspaces/test/browser/workspaces.test.ts | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.00016767320630606264,
0.00016670723562128842,
0.00016574125038459897,
0.00016670723562128842,
9.659779607318342e-7
]
|
{
"id": 4,
"code_window": [
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
"import * as vscode from 'vscode';\n",
"\n",
"export const exists = async (resource: vscode.Uri): Promise<boolean> => {\n",
"\ttry {\n",
"\t\tconst stat = await vscode.workspace.fs.stat(resource);\n",
"\t\t// stat.type is an enum flag\n",
"\t\treturn !!(stat.type & vscode.FileType.File);\n",
"\t} catch {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export async function exists(resource: vscode.Uri): Promise<boolean> {\n"
],
"file_path": "extensions/typescript-language-features/src/utils/fs.ts",
"type": "replace",
"edit_start_line_idx": 7
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Uri, workspace, Disposable } from 'vscode';
import { RequestType, BaseLanguageClient } from 'vscode-languageclient';
import { Runtime } from './htmlClient';
export namespace FsStatRequest {
export const type: RequestType<string, FileStat, any> = new RequestType('fs/stat');
}
export namespace FsReadDirRequest {
export const type: RequestType<string, [string, FileType][], any> = new RequestType('fs/readDir');
}
export function serveFileSystemRequests(client: BaseLanguageClient, runtime: Runtime): Disposable {
const disposables = [];
disposables.push(client.onRequest(FsReadDirRequest.type, (uriString: string) => {
const uri = Uri.parse(uriString);
if (uri.scheme === 'file' && runtime.fileFs) {
return runtime.fileFs.readDirectory(uriString);
}
return workspace.fs.readDirectory(uri);
}));
disposables.push(client.onRequest(FsStatRequest.type, (uriString: string) => {
const uri = Uri.parse(uriString);
if (uri.scheme === 'file' && runtime.fileFs) {
return runtime.fileFs.stat(uriString);
}
return workspace.fs.stat(uri);
}));
return Disposable.from(...disposables);
}
export enum FileType {
/**
* The file type is unknown.
*/
Unknown = 0,
/**
* A regular file.
*/
File = 1,
/**
* A directory.
*/
Directory = 2,
/**
* A symbolic link to a file.
*/
SymbolicLink = 64
}
export interface FileStat {
/**
* The type of the file, e.g. is a regular file, a directory, or symbolic link
* to a file.
*/
type: FileType;
/**
* The creation timestamp in milliseconds elapsed since January 1, 1970 00:00:00 UTC.
*/
ctime: number;
/**
* The modification timestamp in milliseconds elapsed since January 1, 1970 00:00:00 UTC.
*/
mtime: number;
/**
* The size in bytes.
*/
size: number;
}
export interface FileSystemProvider {
stat(uri: string): Promise<FileStat>;
readDirectory(uri: string): Promise<[string, FileType][]>;
}
| extensions/html-language-features/client/src/requests.ts | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.6612801551818848,
0.08613879978656769,
0.00016590395534876734,
0.0004963484243489802,
0.21752916276454926
]
|
{
"id": 4,
"code_window": [
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
"import * as vscode from 'vscode';\n",
"\n",
"export const exists = async (resource: vscode.Uri): Promise<boolean> => {\n",
"\ttry {\n",
"\t\tconst stat = await vscode.workspace.fs.stat(resource);\n",
"\t\t// stat.type is an enum flag\n",
"\t\treturn !!(stat.type & vscode.FileType.File);\n",
"\t} catch {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export async function exists(resource: vscode.Uri): Promise<boolean> {\n"
],
"file_path": "extensions/typescript-language-features/src/utils/fs.ts",
"type": "replace",
"edit_start_line_idx": 7
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
export const enum RecommendationSource {
FILE = 1,
WORKSPACE = 2,
EXE = 3
}
export interface IExtensionRecommendations {
source: RecommendationSource;
extensions: string[];
name: string;
searchValue?: string;
}
export function RecommendationSourceToString(source: RecommendationSource) {
switch (source) {
case RecommendationSource.FILE: return 'file';
case RecommendationSource.WORKSPACE: return 'workspace';
case RecommendationSource.EXE: return 'exe';
}
}
export const enum RecommendationsNotificationResult {
Ignored = 'ignored',
Cancelled = 'cancelled',
TooMany = 'toomany',
IncompatibleWindow = 'incompatibleWindow',
Accepted = 'reacted',
}
export const IExtensionRecommendationNotificationService = createDecorator<IExtensionRecommendationNotificationService>('IExtensionRecommendationNotificationService');
export interface IExtensionRecommendationNotificationService {
readonly _serviceBrand: undefined;
readonly ignoredRecommendations: string[];
hasToIgnoreRecommendationNotifications(): boolean;
promptImportantExtensionsInstallNotification(recommendations: IExtensionRecommendations): Promise<RecommendationsNotificationResult>;
promptWorkspaceRecommendations(recommendations: string[]): Promise<void>;
}
| src/vs/platform/extensionRecommendations/common/extensionRecommendations.ts | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.0002522492432035506,
0.00018517771968618035,
0.00016658351523801684,
0.00016764474275987595,
0.0000335975200869143
]
|
{
"id": 5,
"code_window": [
"\t} catch {\n",
"\t\treturn false;\n",
"\t}\n",
"};\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
"}\n",
"\n",
"export function looksLikeAbsoluteWindowsPath(path: string): boolean {\n",
"\treturn /^[a-zA-Z]:[\\/\\\\]/.test(path);\n",
"}"
],
"file_path": "extensions/typescript-language-features/src/utils/fs.ts",
"type": "replace",
"edit_start_line_idx": 15
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as jsonc from 'jsonc-parser';
import { basename, posix } from 'path';
import * as vscode from 'vscode';
import { Utils } from 'vscode-uri';
import { coalesce } from '../utils/arrays';
import { exists } from '../utils/fs';
function mapChildren<R>(node: jsonc.Node | undefined, f: (x: jsonc.Node) => R): R[] {
return node && node.type === 'array' && node.children
? node.children.map(f)
: [];
}
const openExtendsLinkCommandId = '_typescript.openExtendsLink';
type OpenExtendsLinkCommandArgs = {
readonly resourceUri: vscode.Uri;
readonly extendsValue: string;
};
class TsconfigLinkProvider implements vscode.DocumentLinkProvider {
public provideDocumentLinks(
document: vscode.TextDocument,
_token: vscode.CancellationToken
): vscode.DocumentLink[] {
const root = jsonc.parseTree(document.getText());
if (!root) {
return [];
}
return coalesce([
this.getExtendsLink(document, root),
...this.getFilesLinks(document, root),
...this.getReferencesLinks(document, root)
]);
}
private getExtendsLink(document: vscode.TextDocument, root: jsonc.Node): vscode.DocumentLink | undefined {
const extendsNode = jsonc.findNodeAtLocation(root, ['extends']);
if (!this.isPathValue(extendsNode)) {
return undefined;
}
const extendsValue: string = extendsNode.value;
if (extendsValue.startsWith('/')) {
return undefined;
}
const args: OpenExtendsLinkCommandArgs = {
resourceUri: { ...document.uri.toJSON(), $mid: undefined }, // Prevent VS Code from trying to transform the uri
extendsValue: extendsValue
};
const link = new vscode.DocumentLink(
this.getRange(document, extendsNode),
vscode.Uri.parse(`command:${openExtendsLinkCommandId}?${JSON.stringify(args)}`));
link.tooltip = vscode.l10n.t("Follow link");
return link;
}
private getFilesLinks(document: vscode.TextDocument, root: jsonc.Node) {
return mapChildren(
jsonc.findNodeAtLocation(root, ['files']),
child => this.pathNodeToLink(document, child));
}
private getReferencesLinks(document: vscode.TextDocument, root: jsonc.Node) {
return mapChildren(
jsonc.findNodeAtLocation(root, ['references']),
child => {
const pathNode = jsonc.findNodeAtLocation(child, ['path']);
if (!this.isPathValue(pathNode)) {
return undefined;
}
return new vscode.DocumentLink(this.getRange(document, pathNode),
basename(pathNode.value).endsWith('.json')
? this.getFileTarget(document, pathNode)
: this.getFolderTarget(document, pathNode));
});
}
private pathNodeToLink(
document: vscode.TextDocument,
node: jsonc.Node | undefined
): vscode.DocumentLink | undefined {
return this.isPathValue(node)
? new vscode.DocumentLink(this.getRange(document, node), this.getFileTarget(document, node))
: undefined;
}
private isPathValue(extendsNode: jsonc.Node | undefined): extendsNode is jsonc.Node {
return extendsNode
&& extendsNode.type === 'string'
&& extendsNode.value
&& !(extendsNode.value as string).includes('*'); // don't treat globs as links.
}
private getFileTarget(document: vscode.TextDocument, node: jsonc.Node): vscode.Uri {
return vscode.Uri.joinPath(Utils.dirname(document.uri), node.value);
}
private getFolderTarget(document: vscode.TextDocument, node: jsonc.Node): vscode.Uri {
return vscode.Uri.joinPath(Utils.dirname(document.uri), node.value, 'tsconfig.json');
}
private getRange(document: vscode.TextDocument, node: jsonc.Node) {
const offset = node.offset;
const start = document.positionAt(offset + 1);
const end = document.positionAt(offset + (node.length - 1));
return new vscode.Range(start, end);
}
}
async function resolveNodeModulesPath(baseDirUri: vscode.Uri, pathCandidates: string[]): Promise<vscode.Uri | undefined> {
let currentUri = baseDirUri;
const baseCandidate = pathCandidates[0];
const sepIndex = baseCandidate.startsWith('@') ? 2 : 1;
const moduleBasePath = baseCandidate.split(posix.sep).slice(0, sepIndex).join(posix.sep);
while (true) {
const moduleAbsoluteUrl = vscode.Uri.joinPath(currentUri, 'node_modules', moduleBasePath);
let moduleStat: vscode.FileStat | undefined;
try {
moduleStat = await vscode.workspace.fs.stat(moduleAbsoluteUrl);
} catch (err) {
// noop
}
if (moduleStat && (moduleStat.type & vscode.FileType.Directory)) {
for (const uriCandidate of pathCandidates
.map((relativePath) => relativePath.split(posix.sep).slice(sepIndex).join(posix.sep))
// skip empty paths within module
.filter(Boolean)
.map((relativeModulePath) => vscode.Uri.joinPath(moduleAbsoluteUrl, relativeModulePath))
) {
if (await exists(uriCandidate)) {
return uriCandidate;
}
}
// Continue to looking for potentially another version
}
const oldUri = currentUri;
currentUri = vscode.Uri.joinPath(currentUri, '..');
// Can't go next. Reached the system root
if (oldUri.path === currentUri.path) {
return;
}
}
}
// Reference: https://github.com/microsoft/TypeScript/blob/febfd442cdba343771f478cf433b0892f213ad2f/src/compiler/commandLineParser.ts#L3005
/**
* @returns Returns undefined in case of lack of result while trying to resolve from node_modules
*/
async function getTsconfigPath(baseDirUri: vscode.Uri, extendsValue: string): Promise<vscode.Uri | undefined> {
// Don't take into account a case, where tsconfig might be resolved from the root (see the reference)
// e.g. C:/projects/shared-tsconfig/tsconfig.json (note that C: prefix is optional)
const isRelativePath = ['./', '../'].some(str => extendsValue.startsWith(str));
if (isRelativePath) {
const absolutePath = vscode.Uri.joinPath(baseDirUri, extendsValue);
if (await exists(absolutePath) || absolutePath.path.endsWith('.json')) {
return absolutePath;
}
return absolutePath.with({
path: `${absolutePath.path}.json`
});
}
// Otherwise resolve like a module
return resolveNodeModulesPath(baseDirUri, [
extendsValue,
...extendsValue.endsWith('.json') ? [] : [
`${extendsValue}.json`,
`${extendsValue}/tsconfig.json`,
]
]);
}
export function register() {
const patterns: vscode.GlobPattern[] = [
'**/[jt]sconfig.json',
'**/[jt]sconfig.*.json',
];
const languages = ['json', 'jsonc'];
const selector: vscode.DocumentSelector =
languages.map(language => patterns.map((pattern): vscode.DocumentFilter => ({ language, pattern })))
.flat();
return vscode.Disposable.from(
vscode.commands.registerCommand(openExtendsLinkCommandId, async ({ resourceUri, extendsValue, }: OpenExtendsLinkCommandArgs) => {
const tsconfigPath = await getTsconfigPath(Utils.dirname(vscode.Uri.from(resourceUri)), extendsValue);
if (tsconfigPath === undefined) {
vscode.window.showErrorMessage(vscode.l10n.t("Failed to resolve {0} as module", extendsValue));
return;
}
// Will suggest to create a .json variant if it doesn't exist yet (but only for relative paths)
await vscode.commands.executeCommand('vscode.open', tsconfigPath);
}),
vscode.languages.registerDocumentLinkProvider(selector, new TsconfigLinkProvider()),
);
}
| extensions/typescript-language-features/src/languageFeatures/tsconfig.ts | 1 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.001389864832162857,
0.00022674819047097117,
0.00016353953105863184,
0.00016841365140862763,
0.0002540849964134395
]
|
{
"id": 5,
"code_window": [
"\t} catch {\n",
"\t\treturn false;\n",
"\t}\n",
"};\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
"}\n",
"\n",
"export function looksLikeAbsoluteWindowsPath(path: string): boolean {\n",
"\treturn /^[a-zA-Z]:[\\/\\\\]/.test(path);\n",
"}"
],
"file_path": "extensions/typescript-language-features/src/utils/fs.ts",
"type": "replace",
"edit_start_line_idx": 15
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as path from 'path';
import * as fs from 'fs';
import { makeUniversalApp } from 'vscode-universal-bundler';
import { spawn } from '@malept/cross-spawn-promise';
const root = path.dirname(path.dirname(__dirname));
async function main(buildDir?: string) {
const arch = process.env['VSCODE_ARCH'];
if (!buildDir) {
throw new Error('Build dir not provided');
}
const product = JSON.parse(fs.readFileSync(path.join(root, 'product.json'), 'utf8'));
const appName = product.nameLong + '.app';
const x64AppPath = path.join(buildDir, 'VSCode-darwin-x64', appName);
const arm64AppPath = path.join(buildDir, 'VSCode-darwin-arm64', appName);
const x64AsarPath = path.join(x64AppPath, 'Contents', 'Resources', 'app', 'node_modules.asar');
const arm64AsarPath = path.join(arm64AppPath, 'Contents', 'Resources', 'app', 'node_modules.asar');
const outAppPath = path.join(buildDir, `VSCode-darwin-${arch}`, appName);
const productJsonPath = path.resolve(outAppPath, 'Contents', 'Resources', 'app', 'product.json');
await makeUniversalApp({
x64AppPath,
arm64AppPath,
x64AsarPath,
arm64AsarPath,
filesToSkip: [
'product.json',
'Credits.rtf',
'CodeResources',
'fsevents.node',
'Info.plist', // TODO@deepak1556: regressed with 11.4.2 internal builds
'MainMenu.nib', // Generated sequence is not deterministic with Xcode 13
'.npmrc'
],
outAppPath,
force: true
});
const productJson = JSON.parse(fs.readFileSync(productJsonPath, 'utf8'));
Object.assign(productJson, {
darwinUniversalAssetId: 'darwin-universal'
});
fs.writeFileSync(productJsonPath, JSON.stringify(productJson, null, '\t'));
// Verify if native module architecture is correct
const findOutput = await spawn('find', [outAppPath, '-name', 'keytar.node']);
const lipoOutput = await spawn('lipo', ['-archs', findOutput.replace(/\n$/, '')]);
if (lipoOutput.replace(/\n$/, '') !== 'x86_64 arm64') {
throw new Error(`Invalid arch, got : ${lipoOutput}`);
}
}
if (require.main === module) {
main(process.argv[2]).catch(err => {
console.error(err);
process.exit(1);
});
}
| build/darwin/create-universal-app.ts | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.00019254465587437153,
0.00017607559857424349,
0.00016660701658111066,
0.00017212769307661802,
0.000009057279385160655
]
|
{
"id": 5,
"code_window": [
"\t} catch {\n",
"\t\treturn false;\n",
"\t}\n",
"};\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
"}\n",
"\n",
"export function looksLikeAbsoluteWindowsPath(path: string): boolean {\n",
"\treturn /^[a-zA-Z]:[\\/\\\\]/.test(path);\n",
"}"
],
"file_path": "extensions/typescript-language-features/src/utils/fs.ts",
"type": "replace",
"edit_start_line_idx": 15
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI } from 'vs/base/common/uri';
import { IListService } from 'vs/platform/list/browser/listService';
import { OpenEditor, ISortOrderConfiguration } from 'vs/workbench/contrib/files/common/files';
import { EditorResourceAccessor, SideBySideEditor, IEditorIdentifier } from 'vs/workbench/common/editor';
import { List } from 'vs/base/browser/ui/list/listWidget';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { ExplorerItem } from 'vs/workbench/contrib/files/common/explorerModel';
import { coalesce } from 'vs/base/common/arrays';
import { AsyncDataTree } from 'vs/base/browser/ui/tree/asyncDataTree';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IEditableData } from 'vs/workbench/common/views';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ResourceFileEdit } from 'vs/editor/browser/services/bulkEditService';
import { ProgressLocation } from 'vs/platform/progress/common/progress';
export interface IExplorerService {
readonly _serviceBrand: undefined;
readonly roots: ExplorerItem[];
readonly sortOrderConfiguration: ISortOrderConfiguration;
getContext(respectMultiSelection: boolean, ignoreNestedChildren?: boolean): ExplorerItem[];
hasViewFocus(): boolean;
setEditable(stat: ExplorerItem, data: IEditableData | null): Promise<void>;
getEditable(): { stat: ExplorerItem; data: IEditableData } | undefined;
getEditableData(stat: ExplorerItem): IEditableData | undefined;
// If undefined is passed checks if any element is currently being edited.
isEditable(stat: ExplorerItem | undefined): boolean;
findClosest(resource: URI): ExplorerItem | null;
findClosestRoot(resource: URI): ExplorerItem | null;
refresh(): Promise<void>;
setToCopy(stats: ExplorerItem[], cut: boolean): Promise<void>;
isCut(stat: ExplorerItem): boolean;
applyBulkEdit(edit: ResourceFileEdit[], options: { undoLabel: string; progressLabel: string; confirmBeforeUndo?: boolean; progressLocation?: ProgressLocation.Explorer | ProgressLocation.Window }): Promise<void>;
/**
* Selects and reveal the file element provided by the given resource if its found in the explorer.
* Will try to resolve the path in case the explorer is not yet expanded to the file yet.
*/
select(resource: URI, reveal?: boolean | string): Promise<void>;
registerView(contextAndRefreshProvider: IExplorerView): void;
}
export const IExplorerService = createDecorator<IExplorerService>('explorerService');
export interface IExplorerView {
getContext(respectMultiSelection: boolean): ExplorerItem[];
refresh(recursive: boolean, item?: ExplorerItem): Promise<void>;
selectResource(resource: URI | undefined, reveal?: boolean | string): Promise<void>;
setTreeInput(): Promise<void>;
itemsCopied(tats: ExplorerItem[], cut: boolean, previousCut: ExplorerItem[] | undefined): void;
setEditable(stat: ExplorerItem, isEditing: boolean): Promise<void>;
isItemVisible(item: ExplorerItem): boolean;
isItemCollapsed(item: ExplorerItem): boolean;
hasFocus(): boolean;
}
function getFocus(listService: IListService): unknown | undefined {
const list = listService.lastFocusedList;
if (list?.getHTMLElement() === document.activeElement) {
let focus: unknown;
if (list instanceof List) {
const focused = list.getFocusedElements();
if (focused.length) {
focus = focused[0];
}
} else if (list instanceof AsyncDataTree) {
const focused = list.getFocus();
if (focused.length) {
focus = focused[0];
}
}
return focus;
}
return undefined;
}
// Commands can get executed from a command palette, from a context menu or from some list using a keybinding
// To cover all these cases we need to properly compute the resource on which the command is being executed
export function getResourceForCommand(resource: URI | object | undefined, listService: IListService, editorService: IEditorService): URI | undefined {
if (URI.isUri(resource)) {
return resource;
}
const focus = getFocus(listService);
if (focus instanceof ExplorerItem) {
return focus.resource;
} else if (focus instanceof OpenEditor) {
return focus.getResource();
}
return EditorResourceAccessor.getOriginalUri(editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
}
export function getMultiSelectedResources(resource: URI | object | undefined, listService: IListService, editorService: IEditorService, explorerService: IExplorerService): Array<URI> {
const list = listService.lastFocusedList;
if (list?.getHTMLElement() === document.activeElement) {
// Explorer
if (list instanceof AsyncDataTree && list.getFocus().every(item => item instanceof ExplorerItem)) {
// Explorer
const context = explorerService.getContext(true, true);
if (context.length) {
return context.map(c => c.resource);
}
}
// Open editors view
if (list instanceof List) {
const selection = coalesce(list.getSelectedElements().filter(s => s instanceof OpenEditor).map((oe: OpenEditor) => oe.getResource()));
const focusedElements = list.getFocusedElements();
const focus = focusedElements.length ? focusedElements[0] : undefined;
let mainUriStr: string | undefined = undefined;
if (URI.isUri(resource)) {
mainUriStr = resource.toString();
} else if (focus instanceof OpenEditor) {
const focusedResource = focus.getResource();
mainUriStr = focusedResource ? focusedResource.toString() : undefined;
}
// We only respect the selection if it contains the main element.
if (selection.some(s => s.toString() === mainUriStr)) {
return selection;
}
}
}
const result = getResourceForCommand(resource, listService, editorService);
return !!result ? [result] : [];
}
export function getOpenEditorsViewMultiSelection(listService: IListService, editorGroupService: IEditorGroupsService): Array<IEditorIdentifier> | undefined {
const list = listService.lastFocusedList;
if (list?.getHTMLElement() === document.activeElement) {
// Open editors view
if (list instanceof List) {
const selection = coalesce(list.getSelectedElements().filter(s => s instanceof OpenEditor));
const focusedElements = list.getFocusedElements();
const focus = focusedElements.length ? focusedElements[0] : undefined;
let mainEditor: IEditorIdentifier | undefined = undefined;
if (focus instanceof OpenEditor) {
mainEditor = focus;
}
// We only respect the selection if it contains the main element.
if (selection.some(s => s === mainEditor)) {
return selection;
}
}
}
return undefined;
}
| src/vs/workbench/contrib/files/browser/files.ts | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.00017256545834243298,
0.00016810413217172027,
0.00016483863873872906,
0.00016783304454293102,
0.0000017159519529741374
]
|
{
"id": 5,
"code_window": [
"\t} catch {\n",
"\t\treturn false;\n",
"\t}\n",
"};\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
"}\n",
"\n",
"export function looksLikeAbsoluteWindowsPath(path: string): boolean {\n",
"\treturn /^[a-zA-Z]:[\\/\\\\]/.test(path);\n",
"}"
],
"file_path": "extensions/typescript-language-features/src/utils/fs.ts",
"type": "replace",
"edit_start_line_idx": 15
} | build/**
test/**
cgmanifest.json
| extensions/html/.vscodeignore | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.0001720482687233016,
0.0001720482687233016,
0.0001720482687233016,
0.0001720482687233016,
0
]
|
{
"id": 6,
"code_window": [
" * Licensed under the MIT License. See License.txt in the project root for license information.\n",
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
"import * as vscode from 'vscode';\n",
"import * as fileSchemes from '../configuration/fileSchemes';\n",
"\n",
"/**\n",
" * Maps of file resources\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { looksLikeAbsoluteWindowsPath } from './fs';\n"
],
"file_path": "extensions/typescript-language-features/src/utils/resourceMap.ts",
"type": "add",
"edit_start_line_idx": 7
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import * as fileSchemes from '../configuration/fileSchemes';
/**
* Maps of file resources
*
* Attempts to handle correct mapping on both case sensitive and case in-sensitive
* file systems.
*/
export class ResourceMap<T> {
private static readonly defaultPathNormalizer = (resource: vscode.Uri): string => {
if (resource.scheme === fileSchemes.file) {
return resource.fsPath;
}
return resource.toString(true);
};
private readonly _map = new Map<string, { readonly resource: vscode.Uri; value: T }>();
constructor(
protected readonly _normalizePath: (resource: vscode.Uri) => string | undefined = ResourceMap.defaultPathNormalizer,
protected readonly config: {
readonly onCaseInsensitiveFileSystem: boolean;
},
) { }
public get size() {
return this._map.size;
}
public has(resource: vscode.Uri): boolean {
const file = this.toKey(resource);
return !!file && this._map.has(file);
}
public get(resource: vscode.Uri): T | undefined {
const file = this.toKey(resource);
if (!file) {
return undefined;
}
const entry = this._map.get(file);
return entry ? entry.value : undefined;
}
public set(resource: vscode.Uri, value: T) {
const file = this.toKey(resource);
if (!file) {
return;
}
const entry = this._map.get(file);
if (entry) {
entry.value = value;
} else {
this._map.set(file, { resource, value });
}
}
public delete(resource: vscode.Uri): void {
const file = this.toKey(resource);
if (file) {
this._map.delete(file);
}
}
public clear(): void {
this._map.clear();
}
public get values(): Iterable<T> {
return Array.from(this._map.values(), x => x.value);
}
public get entries(): Iterable<{ resource: vscode.Uri; value: T }> {
return this._map.values();
}
private toKey(resource: vscode.Uri): string | undefined {
const key = this._normalizePath(resource);
if (!key) {
return key;
}
return this.isCaseInsensitivePath(key) ? key.toLowerCase() : key;
}
private isCaseInsensitivePath(path: string) {
if (isWindowsPath(path)) {
return true;
}
return path[0] === '/' && this.config.onCaseInsensitiveFileSystem;
}
}
function isWindowsPath(path: string): boolean {
return /^[a-zA-Z]:[\/\\]/.test(path);
}
| extensions/typescript-language-features/src/utils/resourceMap.ts | 1 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.000325928907841444,
0.00018423065193928778,
0.00016557729395572096,
0.00017013792239595205,
0.00004489067941904068
]
|
{
"id": 6,
"code_window": [
" * Licensed under the MIT License. See License.txt in the project root for license information.\n",
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
"import * as vscode from 'vscode';\n",
"import * as fileSchemes from '../configuration/fileSchemes';\n",
"\n",
"/**\n",
" * Maps of file resources\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { looksLikeAbsoluteWindowsPath } from './fs';\n"
],
"file_path": "extensions/typescript-language-features/src/utils/resourceMap.ts",
"type": "add",
"edit_start_line_idx": 7
} | The MIT License (MIT)
Copyright (c) <2013> <Elegant Themes, Inc.>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. | extensions/vscode-colorize-tests/producticons/mit_license.txt | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.00017142518481705338,
0.00016796833369880915,
0.00016273936489596963,
0.0001697404368314892,
0.000003760863592106034
]
|
{
"id": 6,
"code_window": [
" * Licensed under the MIT License. See License.txt in the project root for license information.\n",
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
"import * as vscode from 'vscode';\n",
"import * as fileSchemes from '../configuration/fileSchemes';\n",
"\n",
"/**\n",
" * Maps of file resources\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { looksLikeAbsoluteWindowsPath } from './fs';\n"
],
"file_path": "extensions/typescript-language-features/src/utils/resourceMap.ts",
"type": "add",
"edit_start_line_idx": 7
} | /*---------------------------------------------------------------------------------------------
* 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 { CoreNavigationCommands } from 'vs/editor/browser/coreCommands';
import { CursorMove } from 'vs/editor/common/cursor/cursorMoveCommands';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
import { withTestCodeEditor, ITestCodeEditor } from 'vs/editor/test/browser/testCodeEditor';
import { ViewModel } from 'vs/editor/common/viewModel/viewModelImpl';
suite('Cursor move command test', () => {
const TEXT = [
' \tMy First Line\t ',
'\tMy Second Line',
' Third Line🐶',
'',
'1'
].join('\n');
function executeTest(callback: (editor: ITestCodeEditor, viewModel: ViewModel) => void): void {
withTestCodeEditor(TEXT, {}, (editor, viewModel) => {
callback(editor, viewModel);
});
}
test('move left should move to left character', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 8);
moveLeft(viewModel);
cursorEqual(viewModel, 1, 7);
});
});
test('move left should move to left by n characters', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 8);
moveLeft(viewModel, 3);
cursorEqual(viewModel, 1, 5);
});
});
test('move left should move to left by half line', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 8);
moveLeft(viewModel, 1, CursorMove.RawUnit.HalfLine);
cursorEqual(viewModel, 1, 1);
});
});
test('move left moves to previous line', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 2, 3);
moveLeft(viewModel, 10);
cursorEqual(viewModel, 1, 21);
});
});
test('move right should move to right character', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 5);
moveRight(viewModel);
cursorEqual(viewModel, 1, 6);
});
});
test('move right should move to right by n characters', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 2);
moveRight(viewModel, 6);
cursorEqual(viewModel, 1, 8);
});
});
test('move right should move to right by half line', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 4);
moveRight(viewModel, 1, CursorMove.RawUnit.HalfLine);
cursorEqual(viewModel, 1, 14);
});
});
test('move right moves to next line', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 8);
moveRight(viewModel, 100);
cursorEqual(viewModel, 2, 1);
});
});
test('move to first character of line from middle', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 8);
moveToLineStart(viewModel);
cursorEqual(viewModel, 1, 1);
});
});
test('move to first character of line from first non white space character', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 6);
moveToLineStart(viewModel);
cursorEqual(viewModel, 1, 1);
});
});
test('move to first character of line from first character', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 1);
moveToLineStart(viewModel);
cursorEqual(viewModel, 1, 1);
});
});
test('move to first non white space character of line from middle', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 8);
moveToLineFirstNonWhitespaceCharacter(viewModel);
cursorEqual(viewModel, 1, 6);
});
});
test('move to first non white space character of line from first non white space character', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 6);
moveToLineFirstNonWhitespaceCharacter(viewModel);
cursorEqual(viewModel, 1, 6);
});
});
test('move to first non white space character of line from first character', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 1);
moveToLineFirstNonWhitespaceCharacter(viewModel);
cursorEqual(viewModel, 1, 6);
});
});
test('move to end of line from middle', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 8);
moveToLineEnd(viewModel);
cursorEqual(viewModel, 1, 21);
});
});
test('move to end of line from last non white space character', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 19);
moveToLineEnd(viewModel);
cursorEqual(viewModel, 1, 21);
});
});
test('move to end of line from line end', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 21);
moveToLineEnd(viewModel);
cursorEqual(viewModel, 1, 21);
});
});
test('move to last non white space character from middle', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 8);
moveToLineLastNonWhitespaceCharacter(viewModel);
cursorEqual(viewModel, 1, 19);
});
});
test('move to last non white space character from last non white space character', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 19);
moveToLineLastNonWhitespaceCharacter(viewModel);
cursorEqual(viewModel, 1, 19);
});
});
test('move to last non white space character from line end', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 21);
moveToLineLastNonWhitespaceCharacter(viewModel);
cursorEqual(viewModel, 1, 19);
});
});
test('move to center of line not from center', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 8);
moveToLineCenter(viewModel);
cursorEqual(viewModel, 1, 11);
});
});
test('move to center of line from center', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 11);
moveToLineCenter(viewModel);
cursorEqual(viewModel, 1, 11);
});
});
test('move to center of line from start', () => {
executeTest((editor, viewModel) => {
moveToLineStart(viewModel);
moveToLineCenter(viewModel);
cursorEqual(viewModel, 1, 11);
});
});
test('move to center of line from end', () => {
executeTest((editor, viewModel) => {
moveToLineEnd(viewModel);
moveToLineCenter(viewModel);
cursorEqual(viewModel, 1, 11);
});
});
test('move up by cursor move command', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 3, 5);
cursorEqual(viewModel, 3, 5);
moveUp(viewModel, 2);
cursorEqual(viewModel, 1, 5);
moveUp(viewModel, 1);
cursorEqual(viewModel, 1, 1);
});
});
test('move up by model line cursor move command', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 3, 5);
cursorEqual(viewModel, 3, 5);
moveUpByModelLine(viewModel, 2);
cursorEqual(viewModel, 1, 5);
moveUpByModelLine(viewModel, 1);
cursorEqual(viewModel, 1, 1);
});
});
test('move down by model line cursor move command', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 3, 5);
cursorEqual(viewModel, 3, 5);
moveDownByModelLine(viewModel, 2);
cursorEqual(viewModel, 5, 2);
moveDownByModelLine(viewModel, 1);
cursorEqual(viewModel, 5, 2);
});
});
test('move up with selection by cursor move command', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 3, 5);
cursorEqual(viewModel, 3, 5);
moveUp(viewModel, 1, true);
cursorEqual(viewModel, 2, 2, 3, 5);
moveUp(viewModel, 1, true);
cursorEqual(viewModel, 1, 5, 3, 5);
});
});
test('move up and down with tabs by cursor move command', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 1, 5);
cursorEqual(viewModel, 1, 5);
moveDown(viewModel, 4);
cursorEqual(viewModel, 5, 2);
moveUp(viewModel, 1);
cursorEqual(viewModel, 4, 1);
moveUp(viewModel, 1);
cursorEqual(viewModel, 3, 5);
moveUp(viewModel, 1);
cursorEqual(viewModel, 2, 2);
moveUp(viewModel, 1);
cursorEqual(viewModel, 1, 5);
});
});
test('move up and down with end of lines starting from a long one by cursor move command', () => {
executeTest((editor, viewModel) => {
moveToEndOfLine(viewModel);
cursorEqual(viewModel, 1, 21);
moveToEndOfLine(viewModel);
cursorEqual(viewModel, 1, 21);
moveDown(viewModel, 2);
cursorEqual(viewModel, 3, 17);
moveDown(viewModel, 1);
cursorEqual(viewModel, 4, 1);
moveDown(viewModel, 1);
cursorEqual(viewModel, 5, 2);
moveUp(viewModel, 4);
cursorEqual(viewModel, 1, 21);
});
});
test('move to view top line moves to first visible line if it is first line', () => {
executeTest((editor, viewModel) => {
viewModel.getCompletelyVisibleViewRange = () => new Range(1, 1, 10, 1);
moveTo(viewModel, 2, 2);
moveToTop(viewModel);
cursorEqual(viewModel, 1, 6);
});
});
test('move to view top line moves to top visible line when first line is not visible', () => {
executeTest((editor, viewModel) => {
viewModel.getCompletelyVisibleViewRange = () => new Range(2, 1, 10, 1);
moveTo(viewModel, 4, 1);
moveToTop(viewModel);
cursorEqual(viewModel, 2, 2);
});
});
test('move to view top line moves to nth line from top', () => {
executeTest((editor, viewModel) => {
viewModel.getCompletelyVisibleViewRange = () => new Range(1, 1, 10, 1);
moveTo(viewModel, 4, 1);
moveToTop(viewModel, 3);
cursorEqual(viewModel, 3, 5);
});
});
test('move to view top line moves to last line if n is greater than last visible line number', () => {
executeTest((editor, viewModel) => {
viewModel.getCompletelyVisibleViewRange = () => new Range(1, 1, 3, 1);
moveTo(viewModel, 2, 2);
moveToTop(viewModel, 4);
cursorEqual(viewModel, 3, 5);
});
});
test('move to view center line moves to the center line', () => {
executeTest((editor, viewModel) => {
viewModel.getCompletelyVisibleViewRange = () => new Range(3, 1, 3, 1);
moveTo(viewModel, 2, 2);
moveToCenter(viewModel);
cursorEqual(viewModel, 3, 5);
});
});
test('move to view bottom line moves to last visible line if it is last line', () => {
executeTest((editor, viewModel) => {
viewModel.getCompletelyVisibleViewRange = () => new Range(1, 1, 5, 1);
moveTo(viewModel, 2, 2);
moveToBottom(viewModel);
cursorEqual(viewModel, 5, 1);
});
});
test('move to view bottom line moves to last visible line when last line is not visible', () => {
executeTest((editor, viewModel) => {
viewModel.getCompletelyVisibleViewRange = () => new Range(2, 1, 3, 1);
moveTo(viewModel, 2, 2);
moveToBottom(viewModel);
cursorEqual(viewModel, 3, 5);
});
});
test('move to view bottom line moves to nth line from bottom', () => {
executeTest((editor, viewModel) => {
viewModel.getCompletelyVisibleViewRange = () => new Range(1, 1, 5, 1);
moveTo(viewModel, 4, 1);
moveToBottom(viewModel, 3);
cursorEqual(viewModel, 3, 5);
});
});
test('move to view bottom line moves to first line if n is lesser than first visible line number', () => {
executeTest((editor, viewModel) => {
viewModel.getCompletelyVisibleViewRange = () => new Range(2, 1, 5, 1);
moveTo(viewModel, 4, 1);
moveToBottom(viewModel, 5);
cursorEqual(viewModel, 2, 2);
});
});
});
suite('Cursor move by blankline test', () => {
const TEXT = [
' \tMy First Line\t ',
'\tMy Second Line',
' Third Line🐶',
'',
'1',
'2',
'3',
'',
' ',
'a',
'b',
].join('\n');
function executeTest(callback: (editor: ITestCodeEditor, viewModel: ViewModel) => void): void {
withTestCodeEditor(TEXT, {}, (editor, viewModel) => {
callback(editor, viewModel);
});
}
test('move down should move to start of next blank line', () => {
executeTest((editor, viewModel) => {
moveDownByBlankLine(viewModel, false);
cursorEqual(viewModel, 4, 1);
});
});
test('move up should move to start of previous blank line', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 7, 1);
moveUpByBlankLine(viewModel, false);
cursorEqual(viewModel, 4, 1);
});
});
test('move down should skip over whitespace if already on blank line', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 8, 1);
moveDownByBlankLine(viewModel, false);
cursorEqual(viewModel, 11, 1);
});
});
test('move up should skip over whitespace if already on blank line', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 9, 1);
moveUpByBlankLine(viewModel, false);
cursorEqual(viewModel, 4, 1);
});
});
test('move up should go to first column of first line if not empty', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 2, 1);
moveUpByBlankLine(viewModel, false);
cursorEqual(viewModel, 1, 1);
});
});
test('move down should go to first column of last line if not empty', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 10, 1);
moveDownByBlankLine(viewModel, false);
cursorEqual(viewModel, 11, 1);
});
});
test('select down should select to start of next blank line', () => {
executeTest((editor, viewModel) => {
moveDownByBlankLine(viewModel, true);
selectionEqual(viewModel.getSelection(), 4, 1, 1, 1);
});
});
test('select up should select to start of previous blank line', () => {
executeTest((editor, viewModel) => {
moveTo(viewModel, 7, 1);
moveUpByBlankLine(viewModel, true);
selectionEqual(viewModel.getSelection(), 4, 1, 7, 1);
});
});
});
// Move command
function move(viewModel: ViewModel, args: any) {
CoreNavigationCommands.CursorMove.runCoreEditorCommand(viewModel, args);
}
function moveToLineStart(viewModel: ViewModel) {
move(viewModel, { to: CursorMove.RawDirection.WrappedLineStart });
}
function moveToLineFirstNonWhitespaceCharacter(viewModel: ViewModel) {
move(viewModel, { to: CursorMove.RawDirection.WrappedLineFirstNonWhitespaceCharacter });
}
function moveToLineCenter(viewModel: ViewModel) {
move(viewModel, { to: CursorMove.RawDirection.WrappedLineColumnCenter });
}
function moveToLineEnd(viewModel: ViewModel) {
move(viewModel, { to: CursorMove.RawDirection.WrappedLineEnd });
}
function moveToLineLastNonWhitespaceCharacter(viewModel: ViewModel) {
move(viewModel, { to: CursorMove.RawDirection.WrappedLineLastNonWhitespaceCharacter });
}
function moveLeft(viewModel: ViewModel, value?: number, by?: string, select?: boolean) {
move(viewModel, { to: CursorMove.RawDirection.Left, by: by, value: value, select: select });
}
function moveRight(viewModel: ViewModel, value?: number, by?: string, select?: boolean) {
move(viewModel, { to: CursorMove.RawDirection.Right, by: by, value: value, select: select });
}
function moveUp(viewModel: ViewModel, noOfLines: number = 1, select?: boolean) {
move(viewModel, { to: CursorMove.RawDirection.Up, by: CursorMove.RawUnit.WrappedLine, value: noOfLines, select: select });
}
function moveUpByBlankLine(viewModel: ViewModel, select?: boolean) {
move(viewModel, { to: CursorMove.RawDirection.PrevBlankLine, by: CursorMove.RawUnit.WrappedLine, select: select });
}
function moveUpByModelLine(viewModel: ViewModel, noOfLines: number = 1, select?: boolean) {
move(viewModel, { to: CursorMove.RawDirection.Up, value: noOfLines, select: select });
}
function moveDown(viewModel: ViewModel, noOfLines: number = 1, select?: boolean) {
move(viewModel, { to: CursorMove.RawDirection.Down, by: CursorMove.RawUnit.WrappedLine, value: noOfLines, select: select });
}
function moveDownByBlankLine(viewModel: ViewModel, select?: boolean) {
move(viewModel, { to: CursorMove.RawDirection.NextBlankLine, by: CursorMove.RawUnit.WrappedLine, select: select });
}
function moveDownByModelLine(viewModel: ViewModel, noOfLines: number = 1, select?: boolean) {
move(viewModel, { to: CursorMove.RawDirection.Down, value: noOfLines, select: select });
}
function moveToTop(viewModel: ViewModel, noOfLines: number = 1, select?: boolean) {
move(viewModel, { to: CursorMove.RawDirection.ViewPortTop, value: noOfLines, select: select });
}
function moveToCenter(viewModel: ViewModel, select?: boolean) {
move(viewModel, { to: CursorMove.RawDirection.ViewPortCenter, select: select });
}
function moveToBottom(viewModel: ViewModel, noOfLines: number = 1, select?: boolean) {
move(viewModel, { to: CursorMove.RawDirection.ViewPortBottom, value: noOfLines, select: select });
}
function cursorEqual(viewModel: ViewModel, posLineNumber: number, posColumn: number, selLineNumber: number = posLineNumber, selColumn: number = posColumn) {
positionEqual(viewModel.getPosition(), posLineNumber, posColumn);
selectionEqual(viewModel.getSelection(), posLineNumber, posColumn, selLineNumber, selColumn);
}
function positionEqual(position: Position, lineNumber: number, column: number) {
assert.deepStrictEqual(position, new Position(lineNumber, column), 'position equal');
}
function selectionEqual(selection: Selection, posLineNumber: number, posColumn: number, selLineNumber: number, selColumn: number) {
assert.deepStrictEqual({
selectionStartLineNumber: selection.selectionStartLineNumber,
selectionStartColumn: selection.selectionStartColumn,
positionLineNumber: selection.positionLineNumber,
positionColumn: selection.positionColumn
}, {
selectionStartLineNumber: selLineNumber,
selectionStartColumn: selColumn,
positionLineNumber: posLineNumber,
positionColumn: posColumn
}, 'selection equal');
}
function moveTo(viewModel: ViewModel, lineNumber: number, column: number, inSelectionMode: boolean = false) {
if (inSelectionMode) {
CoreNavigationCommands.MoveToSelect.runCoreEditorCommand(viewModel, {
position: new Position(lineNumber, column)
});
} else {
CoreNavigationCommands.MoveTo.runCoreEditorCommand(viewModel, {
position: new Position(lineNumber, column)
});
}
}
function moveToEndOfLine(viewModel: ViewModel, inSelectionMode: boolean = false) {
if (inSelectionMode) {
CoreNavigationCommands.CursorEndSelect.runCoreEditorCommand(viewModel, {});
} else {
CoreNavigationCommands.CursorEnd.runCoreEditorCommand(viewModel, {});
}
}
| src/vs/editor/test/browser/controller/cursorMoveCommand.test.ts | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.0001792033581295982,
0.00017523275164421648,
0.0001682707661530003,
0.00017538700194563717,
0.0000017529797560200677
]
|
{
"id": 6,
"code_window": [
" * Licensed under the MIT License. See License.txt in the project root for license information.\n",
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
"import * as vscode from 'vscode';\n",
"import * as fileSchemes from '../configuration/fileSchemes';\n",
"\n",
"/**\n",
" * Maps of file resources\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { looksLikeAbsoluteWindowsPath } from './fs';\n"
],
"file_path": "extensions/typescript-language-features/src/utils/resourceMap.ts",
"type": "add",
"edit_start_line_idx": 7
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export function getSpaceCnt(str: string, tabSize: number) {
let spacesCnt = 0;
for (let i = 0; i < str.length; i++) {
if (str.charAt(i) === '\t') {
spacesCnt += tabSize;
} else {
spacesCnt++;
}
}
return spacesCnt;
}
export function generateIndent(spacesCnt: number, tabSize: number, insertSpaces: boolean) {
spacesCnt = spacesCnt < 0 ? 0 : spacesCnt;
let result = '';
if (!insertSpaces) {
const tabsCnt = Math.floor(spacesCnt / tabSize);
spacesCnt = spacesCnt % tabSize;
for (let i = 0; i < tabsCnt; i++) {
result += '\t';
}
}
for (let i = 0; i < spacesCnt; i++) {
result += ' ';
}
return result;
} | src/vs/editor/contrib/indentation/browser/indentUtils.ts | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.0001761104358593002,
0.00017353167640976608,
0.00016972310550045222,
0.00017414656758774072,
0.000002596966851342586
]
|
{
"id": 7,
"code_window": [
"\t\treturn this.isCaseInsensitivePath(key) ? key.toLowerCase() : key;\n",
"\t}\n",
"\n",
"\tprivate isCaseInsensitivePath(path: string) {\n",
"\t\tif (isWindowsPath(path)) {\n",
"\t\t\treturn true;\n",
"\t\t}\n",
"\t\treturn path[0] === '/' && this.config.onCaseInsensitiveFileSystem;\n",
"\t}\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tif (looksLikeAbsoluteWindowsPath(path)) {\n"
],
"file_path": "extensions/typescript-language-features/src/utils/resourceMap.ts",
"type": "replace",
"edit_start_line_idx": 91
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import * as fileSchemes from '../configuration/fileSchemes';
/**
* Maps of file resources
*
* Attempts to handle correct mapping on both case sensitive and case in-sensitive
* file systems.
*/
export class ResourceMap<T> {
private static readonly defaultPathNormalizer = (resource: vscode.Uri): string => {
if (resource.scheme === fileSchemes.file) {
return resource.fsPath;
}
return resource.toString(true);
};
private readonly _map = new Map<string, { readonly resource: vscode.Uri; value: T }>();
constructor(
protected readonly _normalizePath: (resource: vscode.Uri) => string | undefined = ResourceMap.defaultPathNormalizer,
protected readonly config: {
readonly onCaseInsensitiveFileSystem: boolean;
},
) { }
public get size() {
return this._map.size;
}
public has(resource: vscode.Uri): boolean {
const file = this.toKey(resource);
return !!file && this._map.has(file);
}
public get(resource: vscode.Uri): T | undefined {
const file = this.toKey(resource);
if (!file) {
return undefined;
}
const entry = this._map.get(file);
return entry ? entry.value : undefined;
}
public set(resource: vscode.Uri, value: T) {
const file = this.toKey(resource);
if (!file) {
return;
}
const entry = this._map.get(file);
if (entry) {
entry.value = value;
} else {
this._map.set(file, { resource, value });
}
}
public delete(resource: vscode.Uri): void {
const file = this.toKey(resource);
if (file) {
this._map.delete(file);
}
}
public clear(): void {
this._map.clear();
}
public get values(): Iterable<T> {
return Array.from(this._map.values(), x => x.value);
}
public get entries(): Iterable<{ resource: vscode.Uri; value: T }> {
return this._map.values();
}
private toKey(resource: vscode.Uri): string | undefined {
const key = this._normalizePath(resource);
if (!key) {
return key;
}
return this.isCaseInsensitivePath(key) ? key.toLowerCase() : key;
}
private isCaseInsensitivePath(path: string) {
if (isWindowsPath(path)) {
return true;
}
return path[0] === '/' && this.config.onCaseInsensitiveFileSystem;
}
}
function isWindowsPath(path: string): boolean {
return /^[a-zA-Z]:[\/\\]/.test(path);
}
| extensions/typescript-language-features/src/utils/resourceMap.ts | 1 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.997381865978241,
0.23112598061561584,
0.00016660240362398326,
0.00017369611305184662,
0.3909757137298584
]
|
{
"id": 7,
"code_window": [
"\t\treturn this.isCaseInsensitivePath(key) ? key.toLowerCase() : key;\n",
"\t}\n",
"\n",
"\tprivate isCaseInsensitivePath(path: string) {\n",
"\t\tif (isWindowsPath(path)) {\n",
"\t\t\treturn true;\n",
"\t\t}\n",
"\t\treturn path[0] === '/' && this.config.onCaseInsensitiveFileSystem;\n",
"\t}\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tif (looksLikeAbsoluteWindowsPath(path)) {\n"
],
"file_path": "extensions/typescript-language-features/src/utils/resourceMap.ts",
"type": "replace",
"edit_start_line_idx": 91
} | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
"@gar/promisify@^1.0.1":
version "1.1.3"
resolved "https://registry.yarnpkg.com/@gar/promisify/-/promisify-1.1.3.tgz#555193ab2e3bb3b6adc3d551c9c030d9e860daf6"
integrity sha512-k2Ty1JcVojjJFwrg/ThKi2ujJ7XNLYaFGNB/bWT9wGR+oSMJHMa5w+CUq6p/pVrKeNNgA7pCqEcjSnHVoqJQFw==
"@npmcli/fs@^1.0.0":
version "1.1.1"
resolved "https://registry.yarnpkg.com/@npmcli/fs/-/fs-1.1.1.tgz#72f719fe935e687c56a4faecf3c03d06ba593257"
integrity sha512-8KG5RD0GVP4ydEzRn/I4BNDuxDtqVbOdm8675T49OIG/NGhaK0pjPX7ZcDlvKYbA+ulvVK3ztfcF4uBdOxuJbQ==
dependencies:
"@gar/promisify" "^1.0.1"
semver "^7.3.5"
"@npmcli/move-file@^1.0.1":
version "1.1.2"
resolved "https://registry.yarnpkg.com/@npmcli/move-file/-/move-file-1.1.2.tgz#1a82c3e372f7cae9253eb66d72543d6b8685c674"
integrity sha512-1SUf/Cg2GzGDyaf15aR9St9TWlb+XvbZXWpDx8YKs7MLzMH/BCeopv+y9vzrzgkfykCGuWOlSu3mZhj2+FQcrg==
dependencies:
mkdirp "^1.0.4"
rimraf "^3.0.2"
"@tootallnate/once@1":
version "1.1.2"
resolved "https://registry.yarnpkg.com/@tootallnate/once/-/once-1.1.2.tgz#ccb91445360179a04e7fe6aff78c00ffc1eeaf82"
integrity sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==
abbrev@1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8"
integrity sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==
agent-base@6, agent-base@^6.0.2:
version "6.0.2"
resolved "https://registry.yarnpkg.com/agent-base/-/agent-base-6.0.2.tgz#49fff58577cfee3f37176feab4c22e00f86d7f77"
integrity sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==
dependencies:
debug "4"
agentkeepalive@^4.1.3:
version "4.2.1"
resolved "https://registry.yarnpkg.com/agentkeepalive/-/agentkeepalive-4.2.1.tgz#a7975cbb9f83b367f06c90cc51ff28fe7d499717"
integrity sha512-Zn4cw2NEqd+9fiSVWMscnjyQ1a8Yfoc5oBajLeo5w+YBHgDUcEBY2hS4YpTz6iN5f/2zQiktcuM6tS8x1p9dpA==
dependencies:
debug "^4.1.0"
depd "^1.1.2"
humanize-ms "^1.2.1"
aggregate-error@^3.0.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/aggregate-error/-/aggregate-error-3.1.0.tgz#92670ff50f5359bdb7a3e0d40d0ec30c5737687a"
integrity sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==
dependencies:
clean-stack "^2.0.0"
indent-string "^4.0.0"
ansi-regex@^5.0.1:
version "5.0.1"
resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304"
integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==
"aproba@^1.0.3 || ^2.0.0":
version "2.0.0"
resolved "https://registry.yarnpkg.com/aproba/-/aproba-2.0.0.tgz#52520b8ae5b569215b354efc0caa3fe1e45a8adc"
integrity sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==
are-we-there-yet@^3.0.0:
version "3.0.1"
resolved "https://registry.yarnpkg.com/are-we-there-yet/-/are-we-there-yet-3.0.1.tgz#679df222b278c64f2cdba1175cdc00b0d96164bd"
integrity sha512-QZW4EDmGwlYur0Yyf/b2uGucHQMa8aFUP7eu9ddR73vvhFyt4V0Vl3QHPcTNJ8l6qYOBdxgXdnBXQrHilfRQBg==
dependencies:
delegates "^1.0.0"
readable-stream "^3.6.0"
balanced-match@^1.0.0:
version "1.0.2"
resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee"
integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==
brace-expansion@^1.1.7:
version "1.1.11"
resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd"
integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==
dependencies:
balanced-match "^1.0.0"
concat-map "0.0.1"
cacache@^15.2.0:
version "15.3.0"
resolved "https://registry.yarnpkg.com/cacache/-/cacache-15.3.0.tgz#dc85380fb2f556fe3dda4c719bfa0ec875a7f1eb"
integrity sha512-VVdYzXEn+cnbXpFgWs5hTT7OScegHVmLhJIR8Ufqk3iFD6A6j5iSX1KuBTfNEv4tdJWE2PzA6IVFtcLC7fN9wQ==
dependencies:
"@npmcli/fs" "^1.0.0"
"@npmcli/move-file" "^1.0.1"
chownr "^2.0.0"
fs-minipass "^2.0.0"
glob "^7.1.4"
infer-owner "^1.0.4"
lru-cache "^6.0.0"
minipass "^3.1.1"
minipass-collect "^1.0.2"
minipass-flush "^1.0.5"
minipass-pipeline "^1.2.2"
mkdirp "^1.0.3"
p-map "^4.0.0"
promise-inflight "^1.0.1"
rimraf "^3.0.2"
ssri "^8.0.1"
tar "^6.0.2"
unique-filename "^1.1.1"
chownr@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/chownr/-/chownr-2.0.0.tgz#15bfbe53d2eab4cf70f18a8cd68ebe5b3cb1dece"
integrity sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==
clean-stack@^2.0.0:
version "2.2.0"
resolved "https://registry.yarnpkg.com/clean-stack/-/clean-stack-2.2.0.tgz#ee8472dbb129e727b31e8a10a427dee9dfe4008b"
integrity sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==
color-support@^1.1.3:
version "1.1.3"
resolved "https://registry.yarnpkg.com/color-support/-/color-support-1.1.3.tgz#93834379a1cc9a0c61f82f52f0d04322251bd5a2"
integrity sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==
[email protected]:
version "0.0.1"
resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b"
integrity sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==
console-control-strings@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/console-control-strings/-/console-control-strings-1.1.0.tgz#3d7cf4464db6446ea644bf4b39507f9851008e8e"
integrity sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==
debug@4, debug@^4.1.0, debug@^4.3.3:
version "4.3.4"
resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865"
integrity sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==
dependencies:
ms "2.1.2"
delegates@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/delegates/-/delegates-1.0.0.tgz#84c6e159b81904fdca59a0ef44cd870d31250f9a"
integrity sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==
depd@^1.1.2:
version "1.1.2"
resolved "https://registry.yarnpkg.com/depd/-/depd-1.1.2.tgz#9bcd52e14c097763e749b274c4346ed2e560b5a9"
integrity sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ==
emoji-regex@^8.0.0:
version "8.0.0"
resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37"
integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==
encoding@^0.1.12:
version "0.1.13"
resolved "https://registry.yarnpkg.com/encoding/-/encoding-0.1.13.tgz#56574afdd791f54a8e9b2785c0582a2d26210fa9"
integrity sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==
dependencies:
iconv-lite "^0.6.2"
env-paths@^2.2.0:
version "2.2.1"
resolved "https://registry.yarnpkg.com/env-paths/-/env-paths-2.2.1.tgz#420399d416ce1fbe9bc0a07c62fa68d67fd0f8f2"
integrity sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==
err-code@^2.0.2:
version "2.0.3"
resolved "https://registry.yarnpkg.com/err-code/-/err-code-2.0.3.tgz#23c2f3b756ffdfc608d30e27c9a941024807e7f9"
integrity sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==
fs-minipass@^2.0.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/fs-minipass/-/fs-minipass-2.1.0.tgz#7f5036fdbf12c63c169190cbe4199c852271f9fb"
integrity sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==
dependencies:
minipass "^3.0.0"
fs.realpath@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f"
integrity sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==
gauge@^4.0.3:
version "4.0.4"
resolved "https://registry.yarnpkg.com/gauge/-/gauge-4.0.4.tgz#52ff0652f2bbf607a989793d53b751bef2328dce"
integrity sha512-f9m+BEN5jkg6a0fZjleidjN51VE1X+mPFQ2DJ0uv1V39oCLCbsGe6yjbBnp7eK7z/+GAon99a3nHuqbuuthyPg==
dependencies:
aproba "^1.0.3 || ^2.0.0"
color-support "^1.1.3"
console-control-strings "^1.1.0"
has-unicode "^2.0.1"
signal-exit "^3.0.7"
string-width "^4.2.3"
strip-ansi "^6.0.1"
wide-align "^1.1.5"
glob@^7.1.3, glob@^7.1.4:
version "7.2.3"
resolved "https://registry.yarnpkg.com/glob/-/glob-7.2.3.tgz#b8df0fb802bbfa8e89bd1d938b4e16578ed44f2b"
integrity sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==
dependencies:
fs.realpath "^1.0.0"
inflight "^1.0.4"
inherits "2"
minimatch "^3.1.1"
once "^1.3.0"
path-is-absolute "^1.0.0"
graceful-fs@^4.2.6:
version "4.2.10"
resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.10.tgz#147d3a006da4ca3ce14728c7aefc287c367d7a6c"
integrity sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==
has-unicode@^2.0.1:
version "2.0.1"
resolved "https://registry.yarnpkg.com/has-unicode/-/has-unicode-2.0.1.tgz#e0e6fe6a28cf51138855e086d1691e771de2a8b9"
integrity sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==
http-cache-semantics@^4.1.0:
version "4.1.1"
resolved "https://registry.yarnpkg.com/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz#abe02fcb2985460bf0323be664436ec3476a6d5a"
integrity sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ==
http-proxy-agent@^4.0.1:
version "4.0.1"
resolved "https://registry.yarnpkg.com/http-proxy-agent/-/http-proxy-agent-4.0.1.tgz#8a8c8ef7f5932ccf953c296ca8291b95aa74aa3a"
integrity sha512-k0zdNgqWTGA6aeIRVpvfVob4fL52dTfaehylg0Y4UvSySvOq/Y+BOyPrgpUrA7HylqvU8vIZGsRuXmspskV0Tg==
dependencies:
"@tootallnate/once" "1"
agent-base "6"
debug "4"
https-proxy-agent@^5.0.0:
version "5.0.1"
resolved "https://registry.yarnpkg.com/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz#c59ef224a04fe8b754f3db0063a25ea30d0005d6"
integrity sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==
dependencies:
agent-base "6"
debug "4"
humanize-ms@^1.2.1:
version "1.2.1"
resolved "https://registry.yarnpkg.com/humanize-ms/-/humanize-ms-1.2.1.tgz#c46e3159a293f6b896da29316d8b6fe8bb79bbed"
integrity sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==
dependencies:
ms "^2.0.0"
iconv-lite@^0.6.2:
version "0.6.3"
resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.6.3.tgz#a52f80bf38da1952eb5c681790719871a1a72501"
integrity sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==
dependencies:
safer-buffer ">= 2.1.2 < 3.0.0"
imurmurhash@^0.1.4:
version "0.1.4"
resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea"
integrity sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==
indent-string@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/indent-string/-/indent-string-4.0.0.tgz#624f8f4497d619b2d9768531d58f4122854d7251"
integrity sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==
infer-owner@^1.0.4:
version "1.0.4"
resolved "https://registry.yarnpkg.com/infer-owner/-/infer-owner-1.0.4.tgz#c4cefcaa8e51051c2a40ba2ce8a3d27295af9467"
integrity sha512-IClj+Xz94+d7irH5qRyfJonOdfTzuDaifE6ZPWfx0N0+/ATZCbuTPq2prFl526urkQd90WyUKIh1DfBQ2hMz9A==
inflight@^1.0.4:
version "1.0.6"
resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9"
integrity sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==
dependencies:
once "^1.3.0"
wrappy "1"
inherits@2, inherits@^2.0.3:
version "2.0.4"
resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c"
integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==
ip@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/ip/-/ip-2.0.0.tgz#4cf4ab182fee2314c75ede1276f8c80b479936da"
integrity sha512-WKa+XuLG1A1R0UWhl2+1XQSi+fZWMsYKffMZTTYsiZaUD8k2yDAj5atimTUD2TZkyCkNEeYE5NhFZmupOGtjYQ==
is-fullwidth-code-point@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d"
integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==
is-lambda@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/is-lambda/-/is-lambda-1.0.1.tgz#3d9877899e6a53efc0160504cde15f82e6f061d5"
integrity sha512-z7CMFGNrENq5iFB9Bqo64Xk6Y9sg+epq1myIcdHaGnbMTYOxvzsEtdYqQUylB7LxfkvgrrjP32T6Ywciio9UIQ==
isexe@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10"
integrity sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==
lru-cache@^6.0.0:
version "6.0.0"
resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-6.0.0.tgz#6d6fe6570ebd96aaf90fcad1dafa3b2566db3a94"
integrity sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==
dependencies:
yallist "^4.0.0"
make-fetch-happen@^9.1.0:
version "9.1.0"
resolved "https://registry.yarnpkg.com/make-fetch-happen/-/make-fetch-happen-9.1.0.tgz#53085a09e7971433e6765f7971bf63f4e05cb968"
integrity sha512-+zopwDy7DNknmwPQplem5lAZX/eCOzSvSNNcSKm5eVwTkOBzoktEfXsa9L23J/GIRhxRsaxzkPEhrJEpE2F4Gg==
dependencies:
agentkeepalive "^4.1.3"
cacache "^15.2.0"
http-cache-semantics "^4.1.0"
http-proxy-agent "^4.0.1"
https-proxy-agent "^5.0.0"
is-lambda "^1.0.1"
lru-cache "^6.0.0"
minipass "^3.1.3"
minipass-collect "^1.0.2"
minipass-fetch "^1.3.2"
minipass-flush "^1.0.5"
minipass-pipeline "^1.2.4"
negotiator "^0.6.2"
promise-retry "^2.0.1"
socks-proxy-agent "^6.0.0"
ssri "^8.0.0"
minimatch@^3.1.1:
version "3.1.2"
resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.2.tgz#19cd194bfd3e428f049a70817c038d89ab4be35b"
integrity sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==
dependencies:
brace-expansion "^1.1.7"
minipass-collect@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/minipass-collect/-/minipass-collect-1.0.2.tgz#22b813bf745dc6edba2576b940022ad6edc8c617"
integrity sha512-6T6lH0H8OG9kITm/Jm6tdooIbogG9e0tLgpY6mphXSm/A9u8Nq1ryBG+Qspiub9LjWlBPsPS3tWQ/Botq4FdxA==
dependencies:
minipass "^3.0.0"
minipass-fetch@^1.3.2:
version "1.4.1"
resolved "https://registry.yarnpkg.com/minipass-fetch/-/minipass-fetch-1.4.1.tgz#d75e0091daac1b0ffd7e9d41629faff7d0c1f1b6"
integrity sha512-CGH1eblLq26Y15+Azk7ey4xh0J/XfJfrCox5LDJiKqI2Q2iwOLOKrlmIaODiSQS8d18jalF6y2K2ePUm0CmShw==
dependencies:
minipass "^3.1.0"
minipass-sized "^1.0.3"
minizlib "^2.0.0"
optionalDependencies:
encoding "^0.1.12"
minipass-flush@^1.0.5:
version "1.0.5"
resolved "https://registry.yarnpkg.com/minipass-flush/-/minipass-flush-1.0.5.tgz#82e7135d7e89a50ffe64610a787953c4c4cbb373"
integrity sha512-JmQSYYpPUqX5Jyn1mXaRwOda1uQ8HP5KAT/oDSLCzt1BYRhQU0/hDtsB1ufZfEEzMZ9aAVmsBw8+FWsIXlClWw==
dependencies:
minipass "^3.0.0"
minipass-pipeline@^1.2.2, minipass-pipeline@^1.2.4:
version "1.2.4"
resolved "https://registry.yarnpkg.com/minipass-pipeline/-/minipass-pipeline-1.2.4.tgz#68472f79711c084657c067c5c6ad93cddea8214c"
integrity sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A==
dependencies:
minipass "^3.0.0"
minipass-sized@^1.0.3:
version "1.0.3"
resolved "https://registry.yarnpkg.com/minipass-sized/-/minipass-sized-1.0.3.tgz#70ee5a7c5052070afacfbc22977ea79def353b70"
integrity sha512-MbkQQ2CTiBMlA2Dm/5cY+9SWFEN8pzzOXi6rlM5Xxq0Yqbda5ZQy9sU75a673FE9ZK0Zsbr6Y5iP6u9nktfg2g==
dependencies:
minipass "^3.0.0"
minipass@^3.0.0, minipass@^3.1.0, minipass@^3.1.1, minipass@^3.1.3:
version "3.3.6"
resolved "https://registry.yarnpkg.com/minipass/-/minipass-3.3.6.tgz#7bba384db3a1520d18c9c0e5251c3444e95dd94a"
integrity sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==
dependencies:
yallist "^4.0.0"
minipass@^4.0.0:
version "4.0.3"
resolved "https://registry.yarnpkg.com/minipass/-/minipass-4.0.3.tgz#00bfbaf1e16e35e804f4aa31a7c1f6b8d9f0ee72"
integrity sha512-OW2r4sQ0sI+z5ckEt5c1Tri4xTgZwYDxpE54eqWlQloQRoWtXjqt9udJ5Z4dSv7wK+nfFI7FRXyCpBSft+gpFw==
minizlib@^2.0.0, minizlib@^2.1.1:
version "2.1.2"
resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-2.1.2.tgz#e90d3466ba209b932451508a11ce3d3632145931"
integrity sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==
dependencies:
minipass "^3.0.0"
yallist "^4.0.0"
mkdirp@^1.0.3, mkdirp@^1.0.4:
version "1.0.4"
resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e"
integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==
[email protected]:
version "2.1.2"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009"
integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==
ms@^2.0.0:
version "2.1.3"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2"
integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==
negotiator@^0.6.2:
version "0.6.3"
resolved "https://registry.yarnpkg.com/negotiator/-/negotiator-0.6.3.tgz#58e323a72fedc0d6f9cd4d31fe49f51479590ccd"
integrity sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==
node-gyp@^8.4.1:
version "8.4.1"
resolved "https://registry.yarnpkg.com/node-gyp/-/node-gyp-8.4.1.tgz#3d49308fc31f768180957d6b5746845fbd429937"
integrity sha512-olTJRgUtAb/hOXG0E93wZDs5YiJlgbXxTwQAFHyNlRsXQnYzUaF2aGgujZbw+hR8aF4ZG/rST57bWMWD16jr9w==
dependencies:
env-paths "^2.2.0"
glob "^7.1.4"
graceful-fs "^4.2.6"
make-fetch-happen "^9.1.0"
nopt "^5.0.0"
npmlog "^6.0.0"
rimraf "^3.0.2"
semver "^7.3.5"
tar "^6.1.2"
which "^2.0.2"
nopt@^5.0.0:
version "5.0.0"
resolved "https://registry.yarnpkg.com/nopt/-/nopt-5.0.0.tgz#530942bb58a512fccafe53fe210f13a25355dc88"
integrity sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==
dependencies:
abbrev "1"
npmlog@^6.0.0:
version "6.0.2"
resolved "https://registry.yarnpkg.com/npmlog/-/npmlog-6.0.2.tgz#c8166017a42f2dea92d6453168dd865186a70830"
integrity sha512-/vBvz5Jfr9dT/aFWd0FIRf+T/Q2WBsLENygUaFUqstqsycmZAP/t5BvFJTK0viFmSUxiUKTUplWy5vt+rvKIxg==
dependencies:
are-we-there-yet "^3.0.0"
console-control-strings "^1.1.0"
gauge "^4.0.3"
set-blocking "^2.0.0"
once@^1.3.0:
version "1.4.0"
resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1"
integrity sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==
dependencies:
wrappy "1"
p-map@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/p-map/-/p-map-4.0.0.tgz#bb2f95a5eda2ec168ec9274e06a747c3e2904d2b"
integrity sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ==
dependencies:
aggregate-error "^3.0.0"
path-is-absolute@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f"
integrity sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==
promise-inflight@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/promise-inflight/-/promise-inflight-1.0.1.tgz#98472870bf228132fcbdd868129bad12c3c029e3"
integrity sha512-6zWPyEOFaQBJYcGMHBKTKJ3u6TBsnMFOIZSa6ce1e/ZrrsOlnHRHbabMjLiBYKp+n44X9eUI6VUPaukCXHuG4g==
promise-retry@^2.0.1:
version "2.0.1"
resolved "https://registry.yarnpkg.com/promise-retry/-/promise-retry-2.0.1.tgz#ff747a13620ab57ba688f5fc67855410c370da22"
integrity sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==
dependencies:
err-code "^2.0.2"
retry "^0.12.0"
readable-stream@^3.6.0:
version "3.6.0"
resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.6.0.tgz#337bbda3adc0706bd3e024426a286d4b4b2c9198"
integrity sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==
dependencies:
inherits "^2.0.3"
string_decoder "^1.1.1"
util-deprecate "^1.0.1"
retry@^0.12.0:
version "0.12.0"
resolved "https://registry.yarnpkg.com/retry/-/retry-0.12.0.tgz#1b42a6266a21f07421d1b0b54b7dc167b01c013b"
integrity sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==
rimraf@^3.0.2:
version "3.0.2"
resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-3.0.2.tgz#f1a5402ba6220ad52cc1282bac1ae3aa49fd061a"
integrity sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==
dependencies:
glob "^7.1.3"
safe-buffer@~5.2.0:
version "5.2.1"
resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6"
integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==
"safer-buffer@>= 2.1.2 < 3.0.0":
version "2.1.2"
resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a"
integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==
semver@^7.3.5:
version "7.3.8"
resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.8.tgz#07a78feafb3f7b32347d725e33de7e2a2df67798"
integrity sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A==
dependencies:
lru-cache "^6.0.0"
set-blocking@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7"
integrity sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==
signal-exit@^3.0.7:
version "3.0.7"
resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.7.tgz#a9a1767f8af84155114eaabd73f99273c8f59ad9"
integrity sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==
smart-buffer@^4.2.0:
version "4.2.0"
resolved "https://registry.yarnpkg.com/smart-buffer/-/smart-buffer-4.2.0.tgz#6e1d71fa4f18c05f7d0ff216dd16a481d0e8d9ae"
integrity sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==
socks-proxy-agent@^6.0.0:
version "6.2.1"
resolved "https://registry.yarnpkg.com/socks-proxy-agent/-/socks-proxy-agent-6.2.1.tgz#2687a31f9d7185e38d530bef1944fe1f1496d6ce"
integrity sha512-a6KW9G+6B3nWZ1yB8G7pJwL3ggLy1uTzKAgCb7ttblwqdz9fMGJUuTy3uFzEP48FAs9FLILlmzDlE2JJhVQaXQ==
dependencies:
agent-base "^6.0.2"
debug "^4.3.3"
socks "^2.6.2"
socks@^2.6.2:
version "2.7.1"
resolved "https://registry.yarnpkg.com/socks/-/socks-2.7.1.tgz#d8e651247178fde79c0663043e07240196857d55"
integrity sha512-7maUZy1N7uo6+WVEX6psASxtNlKaNVMlGQKkG/63nEDdLOWNbiUMoLK7X4uYoLhQstau72mLgfEWcXcwsaHbYQ==
dependencies:
ip "^2.0.0"
smart-buffer "^4.2.0"
ssri@^8.0.0, ssri@^8.0.1:
version "8.0.1"
resolved "https://registry.yarnpkg.com/ssri/-/ssri-8.0.1.tgz#638e4e439e2ffbd2cd289776d5ca457c4f51a2af"
integrity sha512-97qShzy1AiyxvPNIkLWoGua7xoQzzPjQ0HAH4B0rWKo7SZ6USuPcrUiAFrws0UH8RrbWmgq3LMTObhPIHbbBeQ==
dependencies:
minipass "^3.1.1"
"string-width@^1.0.2 || 2 || 3 || 4", string-width@^4.2.3:
version "4.2.3"
resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010"
integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==
dependencies:
emoji-regex "^8.0.0"
is-fullwidth-code-point "^3.0.0"
strip-ansi "^6.0.1"
string_decoder@^1.1.1:
version "1.3.0"
resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.3.0.tgz#42f114594a46cf1a8e30b0a84f56c78c3edac21e"
integrity sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==
dependencies:
safe-buffer "~5.2.0"
strip-ansi@^6.0.1:
version "6.0.1"
resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9"
integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
dependencies:
ansi-regex "^5.0.1"
tar@^6.0.2, tar@^6.1.2:
version "6.1.13"
resolved "https://registry.yarnpkg.com/tar/-/tar-6.1.13.tgz#46e22529000f612180601a6fe0680e7da508847b"
integrity sha512-jdIBIN6LTIe2jqzay/2vtYLlBHa3JF42ot3h1dW8Q0PaAG4v8rm0cvpVePtau5C6OKXGGcgO9q2AMNSWxiLqKw==
dependencies:
chownr "^2.0.0"
fs-minipass "^2.0.0"
minipass "^4.0.0"
minizlib "^2.1.1"
mkdirp "^1.0.3"
yallist "^4.0.0"
unique-filename@^1.1.1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/unique-filename/-/unique-filename-1.1.1.tgz#1d69769369ada0583103a1e6ae87681b56573230"
integrity sha512-Vmp0jIp2ln35UTXuryvjzkjGdRyf9b2lTXuSYUiPmzRcl3FDtYqAwOnTJkAngD9SWhnoJzDbTKwaOrZ+STtxNQ==
dependencies:
unique-slug "^2.0.0"
unique-slug@^2.0.0:
version "2.0.2"
resolved "https://registry.yarnpkg.com/unique-slug/-/unique-slug-2.0.2.tgz#baabce91083fc64e945b0f3ad613e264f7cd4e6c"
integrity sha512-zoWr9ObaxALD3DOPfjPSqxt4fnZiWblxHIgeWqW8x7UqDzEtHEQLzji2cuJYQFCU6KmoJikOYAZlrTHHebjx2w==
dependencies:
imurmurhash "^0.1.4"
util-deprecate@^1.0.1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf"
integrity sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==
which@^2.0.2:
version "2.0.2"
resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1"
integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==
dependencies:
isexe "^2.0.0"
wide-align@^1.1.5:
version "1.1.5"
resolved "https://registry.yarnpkg.com/wide-align/-/wide-align-1.1.5.tgz#df1d4c206854369ecf3c9a4898f1b23fbd9d15d3"
integrity sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==
dependencies:
string-width "^1.0.2 || 2 || 3 || 4"
wrappy@1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f"
integrity sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==
yallist@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72"
integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==
| build/npm/gyp/yarn.lock | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.00017201855371240526,
0.00016710143245290965,
0.00016288466576952487,
0.00016700130072422326,
0.000002542692527640611
]
|
{
"id": 7,
"code_window": [
"\t\treturn this.isCaseInsensitivePath(key) ? key.toLowerCase() : key;\n",
"\t}\n",
"\n",
"\tprivate isCaseInsensitivePath(path: string) {\n",
"\t\tif (isWindowsPath(path)) {\n",
"\t\t\treturn true;\n",
"\t\t}\n",
"\t\treturn path[0] === '/' && this.config.onCaseInsensitiveFileSystem;\n",
"\t}\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tif (looksLikeAbsoluteWindowsPath(path)) {\n"
],
"file_path": "extensions/typescript-language-features/src/utils/resourceMap.ts",
"type": "replace",
"edit_start_line_idx": 91
} | /*---------------------------------------------------------------------------------------------
* 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 { NullLogService } from 'vs/platform/log/common/log';
import { merge } from 'vs/platform/userDataSync/common/globalStateMerge';
suite('GlobalStateMerge', () => {
test('merge when local and remote are same with one value and local is not synced yet', async () => {
const local = { 'a': { version: 1, value: 'a' } };
const remote = { 'a': { version: 1, value: 'a' } };
const actual = merge(local, remote, null, { machine: [], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, {});
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, null);
});
test('merge when local and remote are same with multiple entries and local is not synced yet', async () => {
const local = { 'a': { version: 1, value: 'a' }, 'b': { version: 1, value: 'b' } };
const remote = { 'a': { version: 1, value: 'a' }, 'b': { version: 1, value: 'b' } };
const actual = merge(local, remote, null, { machine: [], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, {});
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, null);
});
test('merge when local and remote are same with multiple entries in different order and local is not synced yet', async () => {
const local = { 'a': { version: 1, value: 'a' }, 'b': { version: 1, value: 'b' } };
const remote = { 'b': { version: 1, value: 'b' }, 'a': { version: 1, value: 'a' } };
const actual = merge(local, remote, null, { machine: [], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, {});
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, null);
});
test('merge when local and remote are same with different base content', async () => {
const local = { 'a': { version: 1, value: 'a' }, 'b': { version: 1, value: 'b' } };
const remote = { 'b': { version: 1, value: 'b' }, 'a': { version: 1, value: 'a' } };
const base = { 'b': { version: 1, value: 'a' } };
const actual = merge(local, remote, base, { machine: [], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, {});
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, null);
});
test('merge when a new entry is added to remote and local has not synced yet', async () => {
const local = { 'a': { version: 1, value: 'a' } };
const remote = { 'b': { version: 1, value: 'b' }, 'a': { version: 1, value: 'a' } };
const actual = merge(local, remote, null, { machine: [], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, { 'b': { version: 1, value: 'b' } });
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, null);
});
test('merge when multiple new entries are added to remote and local is not synced yet', async () => {
const local = {};
const remote = { 'b': { version: 1, value: 'b' }, 'a': { version: 1, value: 'a' } };
const actual = merge(local, remote, null, { machine: [], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, { 'b': { version: 1, value: 'b' }, 'a': { version: 1, value: 'a' } });
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, null);
});
test('merge when new entry is added to remote from base and local has not changed', async () => {
const local = { 'a': { version: 1, value: 'a' } };
const remote = { 'b': { version: 1, value: 'b' }, 'a': { version: 1, value: 'a' } };
const actual = merge(local, remote, local, { machine: [], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, { 'b': { version: 1, value: 'b' } });
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, null);
});
test('merge when an entry is removed from remote from base and local has not changed', async () => {
const local = { 'b': { version: 1, value: 'b' }, 'a': { version: 1, value: 'a' } };
const remote = { 'a': { version: 1, value: 'a' } };
const actual = merge(local, remote, local, { machine: [], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, {});
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, ['b']);
assert.deepStrictEqual(actual.remote.all, null);
});
test('merge when all entries are removed from base and local has not changed', async () => {
const local = { 'b': { version: 1, value: 'b' }, 'a': { version: 1, value: 'a' } };
const remote = {};
const actual = merge(local, remote, local, { machine: [], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, {});
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, ['b', 'a']);
assert.deepStrictEqual(actual.remote.all, null);
});
test('merge when an entry is updated in remote from base and local has not changed', async () => {
const local = { 'a': { version: 1, value: 'a' } };
const remote = { 'a': { version: 1, value: 'b' } };
const actual = merge(local, remote, local, { machine: [], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, {});
assert.deepStrictEqual(actual.local.updated, { 'a': { version: 1, value: 'b' } });
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, null);
});
test('merge when remote has moved forwarded with multiple changes and local stays with base', async () => {
const local = { 'a': { version: 1, value: 'a' }, 'b': { version: 1, value: 'b' } };
const remote = { 'a': { version: 1, value: 'd' }, 'c': { version: 1, value: 'c' } };
const actual = merge(local, remote, local, { machine: [], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, { 'c': { version: 1, value: 'c' } });
assert.deepStrictEqual(actual.local.updated, { 'a': { version: 1, value: 'd' } });
assert.deepStrictEqual(actual.local.removed, ['b']);
assert.deepStrictEqual(actual.remote.all, null);
});
test('merge when new entries are added to local and local is not synced yet', async () => {
const local = { 'a': { version: 1, value: 'a' }, 'b': { version: 1, value: 'b' } };
const remote = { 'a': { version: 1, value: 'a' } };
const actual = merge(local, remote, null, { machine: [], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, {});
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, local);
});
test('merge when multiple new entries are added to local from base and remote is not changed', async () => {
const local = { 'a': { version: 1, value: 'a' }, 'b': { version: 1, value: 'b' }, 'c': { version: 1, value: 'c' } };
const remote = { 'a': { version: 1, value: 'a' } };
const actual = merge(local, remote, remote, { machine: [], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, {});
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, local);
});
test('merge when an entry is removed from local from base and remote has not changed', async () => {
const local = { 'a': { version: 1, value: 'a' } };
const remote = { 'a': { version: 1, value: 'a' }, 'b': { version: 1, value: 'b' } };
const actual = merge(local, remote, remote, { machine: [], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, {});
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, local);
});
test('merge when an entry is updated in local from base and remote has not changed', async () => {
const local = { 'a': { version: 1, value: 'b' } };
const remote = { 'a': { version: 1, value: 'a' } };
const actual = merge(local, remote, remote, { machine: [], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, {});
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, local);
});
test('merge when local has moved forwarded with multiple changes and remote stays with base', async () => {
const local = { 'a': { version: 1, value: 'd' }, 'b': { version: 1, value: 'b' } };
const remote = { 'a': { version: 1, value: 'a' }, 'c': { version: 1, value: 'c' } };
const actual = merge(local, remote, remote, { machine: [], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, {});
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, local);
});
test('merge when local and remote with one entry but different value and local is not synced yet', async () => {
const local = { 'a': { version: 1, value: 'a' } };
const remote = { 'a': { version: 1, value: 'b' } };
const actual = merge(local, remote, null, { machine: [], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, {});
assert.deepStrictEqual(actual.local.updated, { 'a': { version: 1, value: 'b' } });
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, null);
});
test('merge when the entry is removed in remote but updated in local and a new entry is added in remote', async () => {
const base = { 'a': { version: 1, value: 'a' }, 'b': { version: 1, value: 'b' } };
const local = { 'a': { version: 1, value: 'a' }, 'b': { version: 1, value: 'd' } };
const remote = { 'a': { version: 1, value: 'a' }, 'c': { version: 1, value: 'c' } };
const actual = merge(local, remote, base, { machine: [], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, { 'c': { version: 1, value: 'c' } });
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, { 'a': { version: 1, value: 'a' }, 'c': { version: 1, value: 'c' }, 'b': { version: 1, value: 'd' } });
});
test('merge with single entry and local is empty', async () => {
const base = { 'a': { version: 1, value: 'a' } };
const local = {};
const remote = { 'a': { version: 1, value: 'b' } };
const actual = merge(local, remote, base, { machine: [], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, {});
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, local);
});
test('merge when local and remote has moved forward with conflicts', async () => {
const base = { 'a': { version: 1, value: 'a' } };
const local = { 'a': { version: 1, value: 'd' } };
const remote = { 'a': { version: 1, value: 'b' } };
const actual = merge(local, remote, base, { machine: [], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, {});
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, local);
});
test('merge when a new entry is added to remote but scoped to machine locally and local is not synced yet', async () => {
const local = { 'a': { version: 1, value: 'a' } };
const remote = { 'b': { version: 1, value: 'b' }, 'a': { version: 1, value: 'a' } };
const actual = merge(local, remote, null, { machine: ['b'], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, {});
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, null);
});
test('merge when an entry is updated to remote but scoped to machine locally', async () => {
const local = { 'a': { version: 1, value: 'a' } };
const remote = { 'a': { version: 1, value: 'b' } };
const actual = merge(local, remote, local, { machine: ['a'], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, {});
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, null);
});
test('merge when a local value is removed and scoped to machine locally', async () => {
const base = { 'a': { version: 1, value: 'a' }, 'b': { version: 1, value: 'b' } };
const local = { 'a': { version: 1, value: 'a' } };
const remote = { 'b': { version: 1, value: 'b' }, 'a': { version: 1, value: 'a' } };
const actual = merge(local, remote, base, { machine: ['b'], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, {});
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, local);
});
test('merge when local moved forwared by changing a key to machine scope', async () => {
const base = { 'a': { version: 1, value: 'a' }, 'b': { version: 1, value: 'b' } };
const remote = { 'a': { version: 1, value: 'a' }, 'b': { version: 1, value: 'b' } };
const local = { 'a': { version: 1, value: 'a' } };
const actual = merge(local, remote, base, { machine: ['b'], unregistered: [] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, {});
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, local);
});
test('merge should not remove remote keys if not registered', async () => {
const local = { 'a': { version: 1, value: 'a' }, 'b': { version: 1, value: 'b' } };
const base = { 'a': { version: 1, value: 'a' }, 'c': { version: 1, value: 'c' } };
const remote = { 'a': { version: 1, value: 'a' }, 'c': { version: 1, value: 'c' } };
const actual = merge(local, remote, base, { machine: [], unregistered: ['c'] }, new NullLogService());
assert.deepStrictEqual(actual.local.added, {});
assert.deepStrictEqual(actual.local.updated, {});
assert.deepStrictEqual(actual.local.removed, []);
assert.deepStrictEqual(actual.remote.all, { 'a': { version: 1, value: 'a' }, 'b': { version: 1, value: 'b' }, 'c': { version: 1, value: 'c' } });
});
});
| src/vs/platform/userDataSync/test/common/globalStateMerge.test.ts | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.00017651119560468942,
0.00017336659948341548,
0.00016908379620872438,
0.00017369157285429537,
0.0000019309647996124113
]
|
{
"id": 7,
"code_window": [
"\t\treturn this.isCaseInsensitivePath(key) ? key.toLowerCase() : key;\n",
"\t}\n",
"\n",
"\tprivate isCaseInsensitivePath(path: string) {\n",
"\t\tif (isWindowsPath(path)) {\n",
"\t\t\treturn true;\n",
"\t\t}\n",
"\t\treturn path[0] === '/' && this.config.onCaseInsensitiveFileSystem;\n",
"\t}\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tif (looksLikeAbsoluteWindowsPath(path)) {\n"
],
"file_path": "extensions/typescript-language-features/src/utils/resourceMap.ts",
"type": "replace",
"edit_start_line_idx": 91
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { KeyCode } from 'vs/base/common/keyCodes';
import { Disposable } from 'vs/base/common/lifecycle';
import { isMacintosh } from 'vs/base/common/platform';
import 'vs/css!./dnd';
import { ICodeEditor, IEditorMouseEvent, IMouseTarget, IPartialEditorMouseEvent, MouseTargetType } from 'vs/editor/browser/editorBrowser';
import { EditorContributionInstantiation, registerEditorContribution } from 'vs/editor/browser/editorExtensions';
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget';
import { EditorOption } from 'vs/editor/common/config/editorOptions';
import { CursorChangeReason } from 'vs/editor/common/cursorEvents';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
import { IEditorContribution, IEditorDecorationsCollection, ScrollType } from 'vs/editor/common/editorCommon';
import { ModelDecorationOptions } from 'vs/editor/common/model/textModel';
import { DragAndDropCommand } from 'vs/editor/contrib/dnd/browser/dragAndDropCommand';
function hasTriggerModifier(e: IKeyboardEvent | IMouseEvent): boolean {
if (isMacintosh) {
return e.altKey;
} else {
return e.ctrlKey;
}
}
export class DragAndDropController extends Disposable implements IEditorContribution {
public static readonly ID = 'editor.contrib.dragAndDrop';
private readonly _editor: ICodeEditor;
private _dragSelection: Selection | null;
private readonly _dndDecorationIds: IEditorDecorationsCollection;
private _mouseDown: boolean;
private _modifierPressed: boolean;
static readonly TRIGGER_KEY_VALUE = isMacintosh ? KeyCode.Alt : KeyCode.Ctrl;
static get(editor: ICodeEditor): DragAndDropController | null {
return editor.getContribution<DragAndDropController>(DragAndDropController.ID);
}
constructor(editor: ICodeEditor) {
super();
this._editor = editor;
this._dndDecorationIds = this._editor.createDecorationsCollection();
this._register(this._editor.onMouseDown((e: IEditorMouseEvent) => this._onEditorMouseDown(e)));
this._register(this._editor.onMouseUp((e: IEditorMouseEvent) => this._onEditorMouseUp(e)));
this._register(this._editor.onMouseDrag((e: IEditorMouseEvent) => this._onEditorMouseDrag(e)));
this._register(this._editor.onMouseDrop((e: IPartialEditorMouseEvent) => this._onEditorMouseDrop(e)));
this._register(this._editor.onMouseDropCanceled(() => this._onEditorMouseDropCanceled()));
this._register(this._editor.onKeyDown((e: IKeyboardEvent) => this.onEditorKeyDown(e)));
this._register(this._editor.onKeyUp((e: IKeyboardEvent) => this.onEditorKeyUp(e)));
this._register(this._editor.onDidBlurEditorWidget(() => this.onEditorBlur()));
this._register(this._editor.onDidBlurEditorText(() => this.onEditorBlur()));
this._mouseDown = false;
this._modifierPressed = false;
this._dragSelection = null;
}
private onEditorBlur() {
this._removeDecoration();
this._dragSelection = null;
this._mouseDown = false;
this._modifierPressed = false;
}
private onEditorKeyDown(e: IKeyboardEvent): void {
if (!this._editor.getOption(EditorOption.dragAndDrop) || this._editor.getOption(EditorOption.columnSelection)) {
return;
}
if (hasTriggerModifier(e)) {
this._modifierPressed = true;
}
if (this._mouseDown && hasTriggerModifier(e)) {
this._editor.updateOptions({
mouseStyle: 'copy'
});
}
}
private onEditorKeyUp(e: IKeyboardEvent): void {
if (!this._editor.getOption(EditorOption.dragAndDrop) || this._editor.getOption(EditorOption.columnSelection)) {
return;
}
if (hasTriggerModifier(e)) {
this._modifierPressed = false;
}
if (this._mouseDown && e.keyCode === DragAndDropController.TRIGGER_KEY_VALUE) {
this._editor.updateOptions({
mouseStyle: 'default'
});
}
}
private _onEditorMouseDown(mouseEvent: IEditorMouseEvent): void {
this._mouseDown = true;
}
private _onEditorMouseUp(mouseEvent: IEditorMouseEvent): void {
this._mouseDown = false;
// Whenever users release the mouse, the drag and drop operation should finish and the cursor should revert to text.
this._editor.updateOptions({
mouseStyle: 'text'
});
}
private _onEditorMouseDrag(mouseEvent: IEditorMouseEvent): void {
const target = mouseEvent.target;
if (this._dragSelection === null) {
const selections = this._editor.getSelections() || [];
const possibleSelections = selections.filter(selection => target.position && selection.containsPosition(target.position));
if (possibleSelections.length === 1) {
this._dragSelection = possibleSelections[0];
} else {
return;
}
}
if (hasTriggerModifier(mouseEvent.event)) {
this._editor.updateOptions({
mouseStyle: 'copy'
});
} else {
this._editor.updateOptions({
mouseStyle: 'default'
});
}
if (target.position) {
if (this._dragSelection.containsPosition(target.position)) {
this._removeDecoration();
} else {
this.showAt(target.position);
}
}
}
private _onEditorMouseDropCanceled() {
this._editor.updateOptions({
mouseStyle: 'text'
});
this._removeDecoration();
this._dragSelection = null;
this._mouseDown = false;
}
private _onEditorMouseDrop(mouseEvent: IPartialEditorMouseEvent): void {
if (mouseEvent.target && (this._hitContent(mouseEvent.target) || this._hitMargin(mouseEvent.target)) && mouseEvent.target.position) {
const newCursorPosition = new Position(mouseEvent.target.position.lineNumber, mouseEvent.target.position.column);
if (this._dragSelection === null) {
let newSelections: Selection[] | null = null;
if (mouseEvent.event.shiftKey) {
const primarySelection = this._editor.getSelection();
if (primarySelection) {
const { selectionStartLineNumber, selectionStartColumn } = primarySelection;
newSelections = [new Selection(selectionStartLineNumber, selectionStartColumn, newCursorPosition.lineNumber, newCursorPosition.column)];
}
} else {
newSelections = (this._editor.getSelections() || []).map(selection => {
if (selection.containsPosition(newCursorPosition)) {
return new Selection(newCursorPosition.lineNumber, newCursorPosition.column, newCursorPosition.lineNumber, newCursorPosition.column);
} else {
return selection;
}
});
}
// Use `mouse` as the source instead of `api` and setting the reason to explicit (to behave like any other mouse operation).
(<CodeEditorWidget>this._editor).setSelections(newSelections || [], 'mouse', CursorChangeReason.Explicit);
} else if (!this._dragSelection.containsPosition(newCursorPosition) ||
(
(
hasTriggerModifier(mouseEvent.event) ||
this._modifierPressed
) && (
this._dragSelection.getEndPosition().equals(newCursorPosition) || this._dragSelection.getStartPosition().equals(newCursorPosition)
) // we allow users to paste content beside the selection
)) {
this._editor.pushUndoStop();
this._editor.executeCommand(DragAndDropController.ID, new DragAndDropCommand(this._dragSelection, newCursorPosition, hasTriggerModifier(mouseEvent.event) || this._modifierPressed));
this._editor.pushUndoStop();
}
}
this._editor.updateOptions({
mouseStyle: 'text'
});
this._removeDecoration();
this._dragSelection = null;
this._mouseDown = false;
}
private static readonly _DECORATION_OPTIONS = ModelDecorationOptions.register({
description: 'dnd-target',
className: 'dnd-target'
});
public showAt(position: Position): void {
this._dndDecorationIds.set([{
range: new Range(position.lineNumber, position.column, position.lineNumber, position.column),
options: DragAndDropController._DECORATION_OPTIONS
}]);
this._editor.revealPosition(position, ScrollType.Immediate);
}
private _removeDecoration(): void {
this._dndDecorationIds.clear();
}
private _hitContent(target: IMouseTarget): boolean {
return target.type === MouseTargetType.CONTENT_TEXT ||
target.type === MouseTargetType.CONTENT_EMPTY;
}
private _hitMargin(target: IMouseTarget): boolean {
return target.type === MouseTargetType.GUTTER_GLYPH_MARGIN ||
target.type === MouseTargetType.GUTTER_LINE_NUMBERS ||
target.type === MouseTargetType.GUTTER_LINE_DECORATIONS;
}
public override dispose(): void {
this._removeDecoration();
this._dragSelection = null;
this._mouseDown = false;
this._modifierPressed = false;
super.dispose();
}
}
registerEditorContribution(DragAndDropController.ID, DragAndDropController, EditorContributionInstantiation.BeforeFirstInteraction);
| src/vs/editor/contrib/dnd/browser/dnd.ts | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.0001818198652472347,
0.00017099909018725157,
0.0001654270599829033,
0.00017043700790964067,
0.000003879220003000228
]
|
{
"id": 8,
"code_window": [
"\t\t\treturn true;\n",
"\t\t}\n",
"\t\treturn path[0] === '/' && this.config.onCaseInsensitiveFileSystem;\n",
"\t}\n",
"}\n",
"\n",
"function isWindowsPath(path: string): boolean {\n",
"\treturn /^[a-zA-Z]:[\\/\\\\]/.test(path);\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [],
"file_path": "extensions/typescript-language-features/src/utils/resourceMap.ts",
"type": "replace",
"edit_start_line_idx": 97
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as jsonc from 'jsonc-parser';
import { basename, posix } from 'path';
import * as vscode from 'vscode';
import { Utils } from 'vscode-uri';
import { coalesce } from '../utils/arrays';
import { exists } from '../utils/fs';
function mapChildren<R>(node: jsonc.Node | undefined, f: (x: jsonc.Node) => R): R[] {
return node && node.type === 'array' && node.children
? node.children.map(f)
: [];
}
const openExtendsLinkCommandId = '_typescript.openExtendsLink';
type OpenExtendsLinkCommandArgs = {
readonly resourceUri: vscode.Uri;
readonly extendsValue: string;
};
class TsconfigLinkProvider implements vscode.DocumentLinkProvider {
public provideDocumentLinks(
document: vscode.TextDocument,
_token: vscode.CancellationToken
): vscode.DocumentLink[] {
const root = jsonc.parseTree(document.getText());
if (!root) {
return [];
}
return coalesce([
this.getExtendsLink(document, root),
...this.getFilesLinks(document, root),
...this.getReferencesLinks(document, root)
]);
}
private getExtendsLink(document: vscode.TextDocument, root: jsonc.Node): vscode.DocumentLink | undefined {
const extendsNode = jsonc.findNodeAtLocation(root, ['extends']);
if (!this.isPathValue(extendsNode)) {
return undefined;
}
const extendsValue: string = extendsNode.value;
if (extendsValue.startsWith('/')) {
return undefined;
}
const args: OpenExtendsLinkCommandArgs = {
resourceUri: { ...document.uri.toJSON(), $mid: undefined }, // Prevent VS Code from trying to transform the uri
extendsValue: extendsValue
};
const link = new vscode.DocumentLink(
this.getRange(document, extendsNode),
vscode.Uri.parse(`command:${openExtendsLinkCommandId}?${JSON.stringify(args)}`));
link.tooltip = vscode.l10n.t("Follow link");
return link;
}
private getFilesLinks(document: vscode.TextDocument, root: jsonc.Node) {
return mapChildren(
jsonc.findNodeAtLocation(root, ['files']),
child => this.pathNodeToLink(document, child));
}
private getReferencesLinks(document: vscode.TextDocument, root: jsonc.Node) {
return mapChildren(
jsonc.findNodeAtLocation(root, ['references']),
child => {
const pathNode = jsonc.findNodeAtLocation(child, ['path']);
if (!this.isPathValue(pathNode)) {
return undefined;
}
return new vscode.DocumentLink(this.getRange(document, pathNode),
basename(pathNode.value).endsWith('.json')
? this.getFileTarget(document, pathNode)
: this.getFolderTarget(document, pathNode));
});
}
private pathNodeToLink(
document: vscode.TextDocument,
node: jsonc.Node | undefined
): vscode.DocumentLink | undefined {
return this.isPathValue(node)
? new vscode.DocumentLink(this.getRange(document, node), this.getFileTarget(document, node))
: undefined;
}
private isPathValue(extendsNode: jsonc.Node | undefined): extendsNode is jsonc.Node {
return extendsNode
&& extendsNode.type === 'string'
&& extendsNode.value
&& !(extendsNode.value as string).includes('*'); // don't treat globs as links.
}
private getFileTarget(document: vscode.TextDocument, node: jsonc.Node): vscode.Uri {
return vscode.Uri.joinPath(Utils.dirname(document.uri), node.value);
}
private getFolderTarget(document: vscode.TextDocument, node: jsonc.Node): vscode.Uri {
return vscode.Uri.joinPath(Utils.dirname(document.uri), node.value, 'tsconfig.json');
}
private getRange(document: vscode.TextDocument, node: jsonc.Node) {
const offset = node.offset;
const start = document.positionAt(offset + 1);
const end = document.positionAt(offset + (node.length - 1));
return new vscode.Range(start, end);
}
}
async function resolveNodeModulesPath(baseDirUri: vscode.Uri, pathCandidates: string[]): Promise<vscode.Uri | undefined> {
let currentUri = baseDirUri;
const baseCandidate = pathCandidates[0];
const sepIndex = baseCandidate.startsWith('@') ? 2 : 1;
const moduleBasePath = baseCandidate.split(posix.sep).slice(0, sepIndex).join(posix.sep);
while (true) {
const moduleAbsoluteUrl = vscode.Uri.joinPath(currentUri, 'node_modules', moduleBasePath);
let moduleStat: vscode.FileStat | undefined;
try {
moduleStat = await vscode.workspace.fs.stat(moduleAbsoluteUrl);
} catch (err) {
// noop
}
if (moduleStat && (moduleStat.type & vscode.FileType.Directory)) {
for (const uriCandidate of pathCandidates
.map((relativePath) => relativePath.split(posix.sep).slice(sepIndex).join(posix.sep))
// skip empty paths within module
.filter(Boolean)
.map((relativeModulePath) => vscode.Uri.joinPath(moduleAbsoluteUrl, relativeModulePath))
) {
if (await exists(uriCandidate)) {
return uriCandidate;
}
}
// Continue to looking for potentially another version
}
const oldUri = currentUri;
currentUri = vscode.Uri.joinPath(currentUri, '..');
// Can't go next. Reached the system root
if (oldUri.path === currentUri.path) {
return;
}
}
}
// Reference: https://github.com/microsoft/TypeScript/blob/febfd442cdba343771f478cf433b0892f213ad2f/src/compiler/commandLineParser.ts#L3005
/**
* @returns Returns undefined in case of lack of result while trying to resolve from node_modules
*/
async function getTsconfigPath(baseDirUri: vscode.Uri, extendsValue: string): Promise<vscode.Uri | undefined> {
// Don't take into account a case, where tsconfig might be resolved from the root (see the reference)
// e.g. C:/projects/shared-tsconfig/tsconfig.json (note that C: prefix is optional)
const isRelativePath = ['./', '../'].some(str => extendsValue.startsWith(str));
if (isRelativePath) {
const absolutePath = vscode.Uri.joinPath(baseDirUri, extendsValue);
if (await exists(absolutePath) || absolutePath.path.endsWith('.json')) {
return absolutePath;
}
return absolutePath.with({
path: `${absolutePath.path}.json`
});
}
// Otherwise resolve like a module
return resolveNodeModulesPath(baseDirUri, [
extendsValue,
...extendsValue.endsWith('.json') ? [] : [
`${extendsValue}.json`,
`${extendsValue}/tsconfig.json`,
]
]);
}
export function register() {
const patterns: vscode.GlobPattern[] = [
'**/[jt]sconfig.json',
'**/[jt]sconfig.*.json',
];
const languages = ['json', 'jsonc'];
const selector: vscode.DocumentSelector =
languages.map(language => patterns.map((pattern): vscode.DocumentFilter => ({ language, pattern })))
.flat();
return vscode.Disposable.from(
vscode.commands.registerCommand(openExtendsLinkCommandId, async ({ resourceUri, extendsValue, }: OpenExtendsLinkCommandArgs) => {
const tsconfigPath = await getTsconfigPath(Utils.dirname(vscode.Uri.from(resourceUri)), extendsValue);
if (tsconfigPath === undefined) {
vscode.window.showErrorMessage(vscode.l10n.t("Failed to resolve {0} as module", extendsValue));
return;
}
// Will suggest to create a .json variant if it doesn't exist yet (but only for relative paths)
await vscode.commands.executeCommand('vscode.open', tsconfigPath);
}),
vscode.languages.registerDocumentLinkProvider(selector, new TsconfigLinkProvider()),
);
}
| extensions/typescript-language-features/src/languageFeatures/tsconfig.ts | 1 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.0017600901192054152,
0.0002819854416884482,
0.00016569052240811288,
0.00017186524928547442,
0.0003476131532806903
]
|
{
"id": 8,
"code_window": [
"\t\t\treturn true;\n",
"\t\t}\n",
"\t\treturn path[0] === '/' && this.config.onCaseInsensitiveFileSystem;\n",
"\t}\n",
"}\n",
"\n",
"function isWindowsPath(path: string): boolean {\n",
"\treturn /^[a-zA-Z]:[\\/\\\\]/.test(path);\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [],
"file_path": "extensions/typescript-language-features/src/utils/resourceMap.ts",
"type": "replace",
"edit_start_line_idx": 97
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
define({
Sleep: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
WakeUp: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
KeyA: {
value: 'a',
withShift: 'A',
withAltGr: 'a',
withShiftAltGr: 'A'
},
KeyB: {
value: 'b',
withShift: 'B',
withAltGr: 'b',
withShiftAltGr: 'B'
},
KeyC: {
value: 'c',
withShift: 'C',
withAltGr: 'c',
withShiftAltGr: 'C'
},
KeyD: {
value: 'd',
withShift: 'D',
withAltGr: 'd',
withShiftAltGr: 'D'
},
KeyE: {
value: 'e',
withShift: 'E',
withAltGr: 'e',
withShiftAltGr: 'E'
},
KeyF: {
value: 'f',
withShift: 'F',
withAltGr: 'f',
withShiftAltGr: 'F'
},
KeyG: {
value: 'g',
withShift: 'G',
withAltGr: 'g',
withShiftAltGr: 'G'
},
KeyH: {
value: 'h',
withShift: 'H',
withAltGr: 'h',
withShiftAltGr: 'H'
},
KeyI: {
value: 'i',
withShift: 'I',
withAltGr: 'i',
withShiftAltGr: 'I'
},
KeyJ: {
value: 'j',
withShift: 'J',
withAltGr: 'j',
withShiftAltGr: 'J'
},
KeyK: {
value: 'k',
withShift: 'K',
withAltGr: 'k',
withShiftAltGr: 'K'
},
KeyL: {
value: 'l',
withShift: 'L',
withAltGr: 'l',
withShiftAltGr: 'L'
},
KeyM: {
value: 'm',
withShift: 'M',
withAltGr: 'm',
withShiftAltGr: 'M'
},
KeyN: {
value: 'n',
withShift: 'N',
withAltGr: 'n',
withShiftAltGr: 'N'
},
KeyO: {
value: 'o',
withShift: 'O',
withAltGr: 'o',
withShiftAltGr: 'O'
},
KeyP: {
value: 'p',
withShift: 'P',
withAltGr: 'p',
withShiftAltGr: 'P'
},
KeyQ: {
value: 'q',
withShift: 'Q',
withAltGr: 'q',
withShiftAltGr: 'Q'
},
KeyR: {
value: 'r',
withShift: 'R',
withAltGr: 'r',
withShiftAltGr: 'R'
},
KeyS: {
value: 's',
withShift: 'S',
withAltGr: 's',
withShiftAltGr: 'S'
},
KeyT: {
value: 't',
withShift: 'T',
withAltGr: 't',
withShiftAltGr: 'T'
},
KeyU: {
value: 'u',
withShift: 'U',
withAltGr: 'u',
withShiftAltGr: 'U'
},
KeyV: {
value: 'v',
withShift: 'V',
withAltGr: 'v',
withShiftAltGr: 'V'
},
KeyW: {
value: 'w',
withShift: 'W',
withAltGr: 'w',
withShiftAltGr: 'W'
},
KeyX: {
value: 'x',
withShift: 'X',
withAltGr: 'x',
withShiftAltGr: 'X'
},
KeyY: {
value: 'y',
withShift: 'Y',
withAltGr: 'y',
withShiftAltGr: 'Y'
},
KeyZ: {
value: 'z',
withShift: 'Z',
withAltGr: 'z',
withShiftAltGr: 'Z'
},
Digit1: {
value: '1',
withShift: '!',
withAltGr: '1',
withShiftAltGr: '!'
},
Digit2: {
value: '2',
withShift: '@',
withAltGr: '2',
withShiftAltGr: '@'
},
Digit3: {
value: '3',
withShift: '#',
withAltGr: '3',
withShiftAltGr: '#'
},
Digit4: {
value: '4',
withShift: '$',
withAltGr: '4',
withShiftAltGr: '$'
},
Digit5: {
value: '5',
withShift: '%',
withAltGr: '5',
withShiftAltGr: '%'
},
Digit6: {
value: '6',
withShift: '^',
withAltGr: '6',
withShiftAltGr: '^'
},
Digit7: {
value: '7',
withShift: '&',
withAltGr: '7',
withShiftAltGr: '&'
},
Digit8: {
value: '8',
withShift: '*',
withAltGr: '8',
withShiftAltGr: '*'
},
Digit9: {
value: '9',
withShift: '(',
withAltGr: '9',
withShiftAltGr: '('
},
Digit0: {
value: '0',
withShift: ')',
withAltGr: '0',
withShiftAltGr: ')'
},
Enter: {
value: '\r',
withShift: '\r',
withAltGr: '\r',
withShiftAltGr: '\r'
},
Escape: {
value: '\u001b',
withShift: '\u001b',
withAltGr: '\u001b',
withShiftAltGr: '\u001b'
},
Backspace: {
value: '\b',
withShift: '\b',
withAltGr: '\b',
withShiftAltGr: '\b'
},
Tab: {
value: '\t',
withShift: '',
withAltGr: '\t',
withShiftAltGr: ''
},
Space: {
value: ' ',
withShift: ' ',
withAltGr: ' ',
withShiftAltGr: ' '
},
Minus: {
value: '-',
withShift: '_',
withAltGr: '-',
withShiftAltGr: '_'
},
Equal: {
value: '=',
withShift: '+',
withAltGr: '=',
withShiftAltGr: '+'
},
BracketLeft: {
value: '[',
withShift: '{',
withAltGr: '[',
withShiftAltGr: '{'
},
BracketRight: {
value: ']',
withShift: '}',
withAltGr: ']',
withShiftAltGr: '}'
},
Backslash: {
value: '\\',
withShift: '|',
withAltGr: '\\',
withShiftAltGr: '|'
},
Semicolon: {
value: ';',
withShift: ':',
withAltGr: ';',
withShiftAltGr: ':'
},
Quote: {
value: '\'',
withShift: '"',
withAltGr: '\'',
withShiftAltGr: '"'
},
Backquote: {
value: '`',
withShift: '~',
withAltGr: '`',
withShiftAltGr: '~'
},
Comma: {
value: ',',
withShift: '<',
withAltGr: ',',
withShiftAltGr: '<'
},
Period: {
value: '.',
withShift: '>',
withAltGr: '.',
withShiftAltGr: '>'
},
Slash: {
value: '/',
withShift: '?',
withAltGr: '/',
withShiftAltGr: '?'
},
CapsLock: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F1: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F2: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F3: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F4: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F5: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F6: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F7: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F8: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F9: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F10: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F11: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F12: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
PrintScreen: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
ScrollLock: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Pause: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Insert: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Home: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
PageUp: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Delete: {
value: '',
withShift: '',
withAltGr: '',
withShiftAltGr: ''
},
End: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
PageDown: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
ArrowRight: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
ArrowLeft: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
ArrowDown: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
ArrowUp: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
NumLock: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
NumpadDivide: {
value: '/',
withShift: '/',
withAltGr: '/',
withShiftAltGr: '/'
},
NumpadMultiply: {
value: '*',
withShift: '*',
withAltGr: '*',
withShiftAltGr: '*'
},
NumpadSubtract: {
value: '-',
withShift: '-',
withAltGr: '-',
withShiftAltGr: '-'
},
NumpadAdd: {
value: '+',
withShift: '+',
withAltGr: '+',
withShiftAltGr: '+'
},
NumpadEnter: {
value: '\r',
withShift: '\r',
withAltGr: '\r',
withShiftAltGr: '\r'
},
Numpad1: { value: '', withShift: '1', withAltGr: '', withShiftAltGr: '1' },
Numpad2: { value: '', withShift: '2', withAltGr: '', withShiftAltGr: '2' },
Numpad3: { value: '', withShift: '3', withAltGr: '', withShiftAltGr: '3' },
Numpad4: { value: '', withShift: '4', withAltGr: '', withShiftAltGr: '4' },
Numpad5: { value: '', withShift: '5', withAltGr: '', withShiftAltGr: '5' },
Numpad6: { value: '', withShift: '6', withAltGr: '', withShiftAltGr: '6' },
Numpad7: { value: '', withShift: '7', withAltGr: '', withShiftAltGr: '7' },
Numpad8: { value: '', withShift: '8', withAltGr: '', withShiftAltGr: '8' },
Numpad9: { value: '', withShift: '9', withAltGr: '', withShiftAltGr: '9' },
Numpad0: { value: '', withShift: '0', withAltGr: '', withShiftAltGr: '0' },
NumpadDecimal: { value: '', withShift: '.', withAltGr: '', withShiftAltGr: '.' },
IntlBackslash: {
value: '<',
withShift: '>',
withAltGr: '|',
withShiftAltGr: '¦'
},
ContextMenu: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Power: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
NumpadEqual: {
value: '=',
withShift: '=',
withAltGr: '=',
withShiftAltGr: '='
},
F13: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F14: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F15: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F16: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F17: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F18: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F19: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F20: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F21: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F22: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F23: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
F24: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Open: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Help: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Select: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Again: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Undo: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Cut: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Copy: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Paste: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Find: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
AudioVolumeMute: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
AudioVolumeUp: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
AudioVolumeDown: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
NumpadComma: {
value: '.',
withShift: '.',
withAltGr: '.',
withShiftAltGr: '.'
},
IntlRo: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
KanaMode: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
IntlYen: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Convert: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
NonConvert: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Lang1: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Lang2: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Lang3: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Lang4: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Lang5: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
NumpadParenLeft: {
value: '(',
withShift: '(',
withAltGr: '(',
withShiftAltGr: '('
},
NumpadParenRight: {
value: ')',
withShift: ')',
withAltGr: ')',
withShiftAltGr: ')'
},
ControlLeft: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
ShiftLeft: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
AltLeft: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
MetaLeft: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
ControlRight: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
ShiftRight: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
AltRight: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
MetaRight: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
BrightnessUp: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
BrightnessDown: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
MediaPlay: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
MediaRecord: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
MediaFastForward: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
MediaRewind: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
MediaTrackNext: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
MediaTrackPrevious: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
MediaStop: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
Eject: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
MediaPlayPause: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
MediaSelect: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
LaunchMail: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
LaunchApp2: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
LaunchApp1: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
SelectTask: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
LaunchScreenSaver: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
BrowserSearch: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
BrowserHome: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
BrowserBack: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
BrowserForward: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
BrowserStop: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
BrowserRefresh: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
BrowserFavorites: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
MailReply: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
MailForward: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' },
MailSend: { value: '', withShift: '', withAltGr: '', withShiftAltGr: '' }
}); | src/vs/workbench/services/keybinding/test/node/linux_en_us.js | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.00017192625091411173,
0.00016870243416633457,
0.0001629194593988359,
0.00016910370322875679,
0.000002050182956736535
]
|
{
"id": 8,
"code_window": [
"\t\t\treturn true;\n",
"\t\t}\n",
"\t\treturn path[0] === '/' && this.config.onCaseInsensitiveFileSystem;\n",
"\t}\n",
"}\n",
"\n",
"function isWindowsPath(path: string): boolean {\n",
"\treturn /^[a-zA-Z]:[\\/\\\\]/.test(path);\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [],
"file_path": "extensions/typescript-language-features/src/utils/resourceMap.ts",
"type": "replace",
"edit_start_line_idx": 97
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Toggle } from 'vs/base/browser/ui/toggle/toggle';
import { isMacintosh, OperatingSystem } from 'vs/base/common/platform';
import { ITextModel } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/model';
import { ITextModelContentProvider, ITextModelService } from 'vs/editor/common/services/resolverService';
import { localize } from 'vs/nls';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { IQuickInputButton, IQuickInputService, IQuickPickItem, IQuickPickSeparator } from 'vs/platform/quickinput/common/quickInput';
import { ITerminalCommand, TerminalCapability } from 'vs/platform/terminal/common/capabilities/capabilities';
import { collapseTildePath } from 'vs/platform/terminal/common/terminalEnvironment';
import { asCssVariable, inputActiveOptionBackground, inputActiveOptionBorder, inputActiveOptionForeground } from 'vs/platform/theme/common/colorRegistry';
import { ThemeIcon } from 'vs/base/common/themables';
import { ITerminalInstance } from 'vs/workbench/contrib/terminal/browser/terminal';
import { commandHistoryFuzzySearchIcon, commandHistoryOutputIcon, commandHistoryRemoveIcon } from 'vs/workbench/contrib/terminal/browser/terminalIcons';
import { getCommandHistory, getDirectoryHistory, getShellFileHistory } from 'vs/workbench/contrib/terminal/common/history';
import { TerminalStorageKeys } from 'vs/workbench/contrib/terminal/common/terminalStorageKeys';
import { terminalStrings } from 'vs/workbench/contrib/terminal/common/terminalStrings';
import { URI } from 'vs/base/common/uri';
import { fromNow } from 'vs/base/common/date';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { showWithPinnedItems } from 'vs/platform/quickinput/browser/quickPickPin';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { IContextKey } from 'vs/platform/contextkey/common/contextkey';
export async function showRunRecentQuickPick(
accessor: ServicesAccessor,
instance: ITerminalInstance,
terminalInRunCommandPicker: IContextKey<boolean>,
type: 'command' | 'cwd',
filterMode?: 'fuzzy' | 'contiguous',
value?: string
): Promise<void> {
if (!instance.xterm) {
return;
}
const editorService = accessor.get(IEditorService);
const instantiationService = accessor.get(IInstantiationService);
const quickInputService = accessor.get(IQuickInputService);
const storageService = accessor.get(IStorageService);
const runRecentStorageKey = `${TerminalStorageKeys.PinnedRecentCommandsPrefix}.${instance.shellType}`;
let placeholder: string;
type Item = IQuickPickItem & { command?: ITerminalCommand; rawLabel: string };
let items: (Item | IQuickPickItem & { rawLabel: string } | IQuickPickSeparator)[] = [];
const commandMap: Set<string> = new Set();
const removeFromCommandHistoryButton: IQuickInputButton = {
iconClass: ThemeIcon.asClassName(commandHistoryRemoveIcon),
tooltip: localize('removeCommand', "Remove from Command History")
};
const commandOutputButton: IQuickInputButton = {
iconClass: ThemeIcon.asClassName(commandHistoryOutputIcon),
tooltip: localize('viewCommandOutput', "View Command Output"),
alwaysVisible: false
};
if (type === 'command') {
placeholder = isMacintosh ? localize('selectRecentCommandMac', 'Select a command to run (hold Option-key to edit the command)') : localize('selectRecentCommand', 'Select a command to run (hold Alt-key to edit the command)');
const cmdDetection = instance.capabilities.get(TerminalCapability.CommandDetection);
const commands = cmdDetection?.commands;
// Current session history
const executingCommand = cmdDetection?.executingCommand;
if (executingCommand) {
commandMap.add(executingCommand);
}
function formatLabel(label: string) {
return label
// Replace new lines with "enter" symbol
.replace(/\r?\n/g, '\u23CE')
// Replace 3 or more spaces with midline horizontal ellipsis which looks similar
// to whitespace in the editor
.replace(/\s\s\s+/g, '\u22EF');
}
if (commands && commands.length > 0) {
for (const entry of commands) {
// Trim off any whitespace and/or line endings, replace new lines with the
// Downwards Arrow with Corner Leftwards symbol
const label = entry.command.trim();
if (label.length === 0 || commandMap.has(label)) {
continue;
}
let description = collapseTildePath(entry.cwd, instance.userHome, instance.os === OperatingSystem.Windows ? '\\' : '/');
if (entry.exitCode) {
// Since you cannot get the last command's exit code on pwsh, just whether it failed
// or not, -1 is treated specially as simply failed
if (entry.exitCode === -1) {
description += ' failed';
} else {
description += ` exitCode: ${entry.exitCode}`;
}
}
description = description.trim();
const buttons: IQuickInputButton[] = [commandOutputButton];
// Merge consecutive commands
const lastItem = items.length > 0 ? items[items.length - 1] : undefined;
if (lastItem?.type !== 'separator' && lastItem?.label === label) {
lastItem.id = entry.timestamp.toString();
lastItem.description = description;
continue;
}
items.push({
label: formatLabel(label),
rawLabel: label,
description,
id: entry.timestamp.toString(),
command: entry,
buttons: entry.hasOutput() ? buttons : undefined
});
commandMap.add(label);
}
items = items.reverse();
}
if (executingCommand) {
items.unshift({
label: formatLabel(executingCommand),
rawLabel: executingCommand,
description: cmdDetection.cwd
});
}
if (items.length > 0) {
items.unshift({ type: 'separator', label: terminalStrings.currentSessionCategory });
}
// Gather previous session history
const history = instantiationService.invokeFunction(getCommandHistory);
const previousSessionItems: (IQuickPickItem & { rawLabel: string })[] = [];
for (const [label, info] of history.entries) {
// Only add previous session item if it's not in this session
if (!commandMap.has(label) && info.shellType === instance.shellType) {
previousSessionItems.unshift({
label: formatLabel(label),
rawLabel: label,
buttons: [removeFromCommandHistoryButton]
});
commandMap.add(label);
}
}
if (previousSessionItems.length > 0) {
items.push(
{ type: 'separator', label: terminalStrings.previousSessionCategory },
...previousSessionItems
);
}
// Gather shell file history
const shellFileHistory = await instantiationService.invokeFunction(getShellFileHistory, instance.shellType);
const dedupedShellFileItems: (IQuickPickItem & { rawLabel: string })[] = [];
for (const label of shellFileHistory) {
if (!commandMap.has(label)) {
dedupedShellFileItems.unshift({
label: formatLabel(label),
rawLabel: label
});
}
}
if (dedupedShellFileItems.length > 0) {
items.push(
{ type: 'separator', label: localize('shellFileHistoryCategory', '{0} history', instance.shellType) },
...dedupedShellFileItems
);
}
} else {
placeholder = isMacintosh
? localize('selectRecentDirectoryMac', 'Select a directory to go to (hold Option-key to edit the command)')
: localize('selectRecentDirectory', 'Select a directory to go to (hold Alt-key to edit the command)');
const cwds = instance.capabilities.get(TerminalCapability.CwdDetection)?.cwds || [];
if (cwds && cwds.length > 0) {
for (const label of cwds) {
items.push({ label, rawLabel: label });
}
items = items.reverse();
items.unshift({ type: 'separator', label: terminalStrings.currentSessionCategory });
}
// Gather previous session history
const history = instantiationService.invokeFunction(getDirectoryHistory);
const previousSessionItems: (IQuickPickItem & { rawLabel: string })[] = [];
// Only add previous session item if it's not in this session and it matches the remote authority
for (const [label, info] of history.entries) {
if ((info === null || info.remoteAuthority === instance.remoteAuthority) && !cwds.includes(label)) {
previousSessionItems.unshift({
label,
rawLabel: label,
buttons: [removeFromCommandHistoryButton]
});
}
}
if (previousSessionItems.length > 0) {
items.push(
{ type: 'separator', label: terminalStrings.previousSessionCategory },
...previousSessionItems
);
}
}
if (items.length === 0) {
return;
}
const fuzzySearchToggle = new Toggle({
title: 'Fuzzy search',
icon: commandHistoryFuzzySearchIcon,
isChecked: filterMode === 'fuzzy',
inputActiveOptionBorder: asCssVariable(inputActiveOptionBorder),
inputActiveOptionForeground: asCssVariable(inputActiveOptionForeground),
inputActiveOptionBackground: asCssVariable(inputActiveOptionBackground)
});
fuzzySearchToggle.onChange(() => {
instantiationService.invokeFunction(showRunRecentQuickPick, instance, terminalInRunCommandPicker, type, fuzzySearchToggle.checked ? 'fuzzy' : 'contiguous', quickPick.value);
});
const outputProvider = instantiationService.createInstance(TerminalOutputProvider);
const quickPick = quickInputService.createQuickPick<IQuickPickItem & { rawLabel: string }>();
const originalItems = items;
quickPick.items = [...originalItems];
quickPick.sortByLabel = false;
quickPick.placeholder = placeholder;
quickPick.matchOnLabelMode = filterMode || 'contiguous';
quickPick.toggles = [fuzzySearchToggle];
quickPick.onDidTriggerItemButton(async e => {
if (e.button === removeFromCommandHistoryButton) {
if (type === 'command') {
instantiationService.invokeFunction(getCommandHistory)?.remove(e.item.label);
} else {
instantiationService.invokeFunction(getDirectoryHistory)?.remove(e.item.label);
}
} else if (e.button === commandOutputButton) {
const selectedCommand = (e.item as Item).command;
const output = selectedCommand?.getOutput();
if (output && selectedCommand?.command) {
const textContent = await outputProvider.provideTextContent(URI.from(
{
scheme: TerminalOutputProvider.scheme,
path: `${selectedCommand.command}... ${fromNow(selectedCommand.timestamp, true)}`,
fragment: output,
query: `terminal-output-${selectedCommand.timestamp}-${instance.instanceId}`
}));
if (textContent) {
await editorService.openEditor({
resource: textContent.uri
});
}
}
}
await instantiationService.invokeFunction(showRunRecentQuickPick, instance, terminalInRunCommandPicker, type, filterMode, value);
}
);
quickPick.onDidChangeValue(async value => {
if (!value) {
await instantiationService.invokeFunction(showRunRecentQuickPick, instance, terminalInRunCommandPicker, type, filterMode, value);
}
});
quickPick.onDidAccept(async () => {
const result = quickPick.activeItems[0];
let text: string;
if (type === 'cwd') {
text = `cd ${await instance.preparePathForShell(result.rawLabel)}`;
} else { // command
text = result.rawLabel;
}
quickPick.hide();
instance.runCommand(text, !quickPick.keyMods.alt);
if (quickPick.keyMods.alt) {
instance.focus();
}
});
if (value) {
quickPick.value = value;
}
return new Promise<void>(r => {
terminalInRunCommandPicker.set(true);
showWithPinnedItems(storageService, runRecentStorageKey, quickPick, true);
quickPick.onDidHide(() => {
terminalInRunCommandPicker.set(false);
r();
});
});
}
class TerminalOutputProvider implements ITextModelContentProvider {
static scheme = 'TERMINAL_OUTPUT';
constructor(
@ITextModelService textModelResolverService: ITextModelService,
@IModelService private readonly _modelService: IModelService
) {
textModelResolverService.registerTextModelContentProvider(TerminalOutputProvider.scheme, this);
}
async provideTextContent(resource: URI): Promise<ITextModel | null> {
const existing = this._modelService.getModel(resource);
if (existing && !existing.isDisposed()) {
return existing;
}
return this._modelService.createModel(resource.fragment, null, resource, false);
}
}
| src/vs/workbench/contrib/terminal/browser/terminalRunRecentQuickPick.ts | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.00841964315623045,
0.0004418744065333158,
0.0001633705833228305,
0.00016964401584118605,
0.0014570209896191955
]
|
{
"id": 8,
"code_window": [
"\t\t\treturn true;\n",
"\t\t}\n",
"\t\treturn path[0] === '/' && this.config.onCaseInsensitiveFileSystem;\n",
"\t}\n",
"}\n",
"\n",
"function isWindowsPath(path: string): boolean {\n",
"\treturn /^[a-zA-Z]:[\\/\\\\]/.test(path);\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [],
"file_path": "extensions/typescript-language-features/src/utils/resourceMap.ts",
"type": "replace",
"edit_start_line_idx": 97
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./media/extensionEditor';
import { localize } from 'vs/nls';
import * as arrays from 'vs/base/common/arrays';
import { OS, language } from 'vs/base/common/platform';
import { Event, Emitter } from 'vs/base/common/event';
import { Cache, CacheResult } from 'vs/base/common/cache';
import { Action, IAction } from 'vs/base/common/actions';
import { getErrorMessage, isCancellationError, onUnexpectedError } from 'vs/base/common/errors';
import { dispose, toDisposable, Disposable, DisposableStore, MutableDisposable } from 'vs/base/common/lifecycle';
import { append, $, join, addDisposableListener, setParentFlowTo, reset, Dimension } from 'vs/base/browser/dom';
import { EditorPane } from 'vs/workbench/browser/parts/editor/editorPane';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { IExtensionRecommendationsService } from 'vs/workbench/services/extensionRecommendations/common/extensionRecommendations';
import { ExtensionIdentifier, IExtensionManifest, IKeyBinding, IView, IViewContainer } from 'vs/platform/extensions/common/extensions';
import { KeyMod, KeyCode } from 'vs/base/common/keyCodes';
import { ResolvedKeybinding } from 'vs/base/common/keybindings';
import { ExtensionsInput, IExtensionEditorOptions } from 'vs/workbench/contrib/extensions/common/extensionsInput';
import { IExtensionsWorkbenchService, IExtensionsViewPaneContainer, VIEWLET_ID, IExtension, ExtensionContainers, ExtensionEditorTab, ExtensionState, IExtensionContainer } from 'vs/workbench/contrib/extensions/common/extensions';
import { RatingsWidget, InstallCountWidget, RemoteBadgeWidget, ExtensionWidget, ExtensionStatusWidget, ExtensionRecommendationWidget, SponsorWidget, onClick, VerifiedPublisherWidget } from 'vs/workbench/contrib/extensions/browser/extensionsWidgets';
import { IEditorOpenContext } from 'vs/workbench/common/editor';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
import {
UpdateAction, ReloadAction, EnableDropDownAction, DisableDropDownAction, ExtensionStatusLabelAction, SetFileIconThemeAction, SetColorThemeAction,
RemoteInstallAction, ExtensionStatusAction, LocalInstallAction, ToggleSyncExtensionAction, SetProductIconThemeAction,
ActionWithDropDownAction, InstallDropdownAction, InstallingLabelAction, UninstallAction, ExtensionActionWithDropdownActionViewItem, ExtensionDropDownAction,
InstallAnotherVersionAction, ExtensionEditorManageExtensionAction, WebInstallAction, SwitchToPreReleaseVersionAction, SwitchToReleasedVersionAction, MigrateDeprecatedExtensionAction, SetLanguageAction, ClearLanguageAction, SkipUpdateAction
} from 'vs/workbench/contrib/extensions/browser/extensionsActions';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { DomScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement';
import { IOpenerService, matchesScheme } from 'vs/platform/opener/common/opener';
import { IColorTheme, ICssStyleCollector, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { ThemeIcon } from 'vs/base/common/themables';
import { KeybindingLabel } from 'vs/base/browser/ui/keybindingLabel/keybindingLabel';
import { ContextKeyExpr, IContextKey, IContextKeyService, IScopedContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { Color } from 'vs/base/common/color';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { ExtensionsTree, ExtensionData, ExtensionsGridView, getExtensions } from 'vs/workbench/contrib/extensions/browser/extensionsViewer';
import { ShowCurrentReleaseNotesActionId } from 'vs/workbench/contrib/update/common/update';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { getDefaultValue } from 'vs/platform/configuration/common/configurationRegistry';
import { isUndefined } from 'vs/base/common/types';
import { IWebviewService, IWebview, KEYBINDING_CONTEXT_WEBVIEW_FIND_WIDGET_FOCUSED } from 'vs/workbench/contrib/webview/browser/webview';
import { generateUuid } from 'vs/base/common/uuid';
import { platform } from 'vs/base/common/process';
import { URI } from 'vs/base/common/uri';
import { Schemas } from 'vs/base/common/network';
import { DEFAULT_MARKDOWN_STYLES, renderMarkdownDocument } from 'vs/workbench/contrib/markdown/browser/markdownDocumentRenderer';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { TokenizationRegistry } from 'vs/editor/common/languages';
import { generateTokensCSSForColorMap } from 'vs/editor/common/languages/supports/tokenization';
import { buttonForeground, buttonHoverBackground, editorBackground, textLinkActiveForeground, textLinkForeground } from 'vs/platform/theme/common/colorRegistry';
import { registerAction2, Action2 } from 'vs/platform/actions/common/actions';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { Delegate } from 'vs/workbench/contrib/extensions/browser/extensionsList';
import { renderMarkdown } from 'vs/base/browser/markdownRenderer';
import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
import { errorIcon, infoIcon, preReleaseIcon, warningIcon } from 'vs/workbench/contrib/extensions/browser/extensionsIcons';
import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';
import { ViewContainerLocation } from 'vs/workbench/common/views';
import { IExtensionGalleryService, IGalleryExtension } from 'vs/platform/extensionManagement/common/extensionManagement';
import * as semver from 'vs/base/common/semver/semver';
import { defaultKeybindingLabelStyles } from 'vs/platform/theme/browser/defaultStyles';
class NavBar extends Disposable {
private _onChange = this._register(new Emitter<{ id: string | null; focus: boolean }>());
get onChange(): Event<{ id: string | null; focus: boolean }> { return this._onChange.event; }
private _currentId: string | null = null;
get currentId(): string | null { return this._currentId; }
private actions: Action[];
private actionbar: ActionBar;
constructor(container: HTMLElement) {
super();
const element = append(container, $('.navbar'));
this.actions = [];
this.actionbar = this._register(new ActionBar(element, { animated: false }));
}
push(id: string, label: string, tooltip: string): void {
const action = new Action(id, label, undefined, true, () => this.update(id, true));
action.tooltip = tooltip;
this.actions.push(action);
this.actionbar.push(action);
if (this.actions.length === 1) {
this.update(id);
}
}
clear(): void {
this.actions = dispose(this.actions);
this.actionbar.clear();
}
switch(id: string): boolean {
const action = this.actions.find(action => action.id === id);
if (action) {
action.run();
return true;
}
return false;
}
private update(id: string, focus?: boolean): void {
this._currentId = id;
this._onChange.fire({ id, focus: !!focus });
this.actions.forEach(a => a.checked = a.id === id);
}
}
interface ILayoutParticipant {
layout(): void;
}
interface IActiveElement {
focus(): void;
}
interface IExtensionEditorTemplate {
iconContainer: HTMLElement;
icon: HTMLImageElement;
name: HTMLElement;
preview: HTMLElement;
builtin: HTMLElement;
publisher: HTMLElement;
publisherDisplayName: HTMLElement;
installCount: HTMLElement;
rating: HTMLElement;
description: HTMLElement;
actionsAndStatusContainer: HTMLElement;
extensionActionBar: ActionBar;
navbar: NavBar;
content: HTMLElement;
header: HTMLElement;
extension: IExtension;
gallery: IGalleryExtension | null;
manifest: IExtensionManifest | null;
}
const enum WebviewIndex {
Readme,
Changelog
}
const CONTEXT_SHOW_PRE_RELEASE_VERSION = new RawContextKey<boolean>('showPreReleaseVersion', false);
abstract class ExtensionWithDifferentGalleryVersionWidget extends ExtensionWidget {
private _gallery: IGalleryExtension | null = null;
get gallery(): IGalleryExtension | null { return this._gallery; }
set gallery(gallery: IGalleryExtension | null) {
if (this.extension && gallery && !areSameExtensions(this.extension.identifier, gallery.identifier)) {
return;
}
this._gallery = gallery;
this.update();
}
}
class VersionWidget extends ExtensionWithDifferentGalleryVersionWidget {
private readonly element: HTMLElement;
constructor(container: HTMLElement) {
super();
this.element = append(container, $('code.version', { title: localize('extension version', "Extension Version") }));
this.render();
}
render(): void {
if (!this.extension || !semver.valid(this.extension.version)) {
return;
}
this.element.textContent = `v${this.gallery?.version ?? this.extension.version}`;
}
}
class PreReleaseTextWidget extends ExtensionWithDifferentGalleryVersionWidget {
private readonly element: HTMLElement;
constructor(container: HTMLElement) {
super();
this.element = append(container, $('span.pre-release'));
append(this.element, $('span' + ThemeIcon.asCSSSelector(preReleaseIcon)));
const textElement = append(this.element, $('span.pre-release-text'));
textElement.textContent = localize('preRelease', "Pre-Release");
this.render();
}
render(): void {
this.element.style.display = this.isPreReleaseVersion() ? 'inherit' : 'none';
}
private isPreReleaseVersion(): boolean {
if (!this.extension) {
return false;
}
if (this.gallery) {
return this.gallery.properties.isPreReleaseVersion;
}
return !!(this.extension.state === ExtensionState.Installed ? this.extension.local?.isPreReleaseVersion : this.extension.gallery?.properties.isPreReleaseVersion);
}
}
export class ExtensionEditor extends EditorPane {
static readonly ID: string = 'workbench.editor.extension';
private readonly _scopedContextKeyService = this._register(new MutableDisposable<IScopedContextKeyService>());
private template: IExtensionEditorTemplate | undefined;
private extensionReadme: Cache<string> | null;
private extensionChangelog: Cache<string> | null;
private extensionManifest: Cache<IExtensionManifest | null> | null;
// Some action bar items use a webview whose vertical scroll position we track in this map
private initialScrollProgress: Map<WebviewIndex, number> = new Map();
// Spot when an ExtensionEditor instance gets reused for a different extension, in which case the vertical scroll positions must be zeroed
private currentIdentifier: string = '';
private layoutParticipants: ILayoutParticipant[] = [];
private readonly contentDisposables = this._register(new DisposableStore());
private readonly transientDisposables = this._register(new DisposableStore());
private activeElement: IActiveElement | null = null;
private dimension: Dimension | undefined;
private showPreReleaseVersionContextKey: IContextKey<boolean> | undefined;
constructor(
@ITelemetryService telemetryService: ITelemetryService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IPaneCompositePartService private readonly paneCompositeService: IPaneCompositePartService,
@IExtensionsWorkbenchService private readonly extensionsWorkbenchService: IExtensionsWorkbenchService,
@IExtensionGalleryService private readonly extensionGalleryService: IExtensionGalleryService,
@IThemeService themeService: IThemeService,
@IKeybindingService private readonly keybindingService: IKeybindingService,
@INotificationService private readonly notificationService: INotificationService,
@IOpenerService private readonly openerService: IOpenerService,
@IExtensionRecommendationsService private readonly extensionRecommendationsService: IExtensionRecommendationsService,
@IStorageService storageService: IStorageService,
@IExtensionService private readonly extensionService: IExtensionService,
@IWebviewService private readonly webviewService: IWebviewService,
@ILanguageService private readonly languageService: ILanguageService,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
) {
super(ExtensionEditor.ID, telemetryService, themeService, storageService);
this.extensionReadme = null;
this.extensionChangelog = null;
this.extensionManifest = null;
}
override get scopedContextKeyService(): IContextKeyService | undefined {
return this._scopedContextKeyService.value;
}
protected createEditor(parent: HTMLElement): void {
const root = append(parent, $('.extension-editor'));
this._scopedContextKeyService.value = this.contextKeyService.createScoped(root);
this._scopedContextKeyService.value.createKey('inExtensionEditor', true);
this.showPreReleaseVersionContextKey = CONTEXT_SHOW_PRE_RELEASE_VERSION.bindTo(this._scopedContextKeyService.value);
root.tabIndex = 0; // this is required for the focus tracker on the editor
root.style.outline = 'none';
root.setAttribute('role', 'document');
const header = append(root, $('.header'));
const iconContainer = append(header, $('.icon-container'));
const icon = append(iconContainer, $<HTMLImageElement>('img.icon', { draggable: false }));
const remoteBadge = this.instantiationService.createInstance(RemoteBadgeWidget, iconContainer, true);
const details = append(header, $('.details'));
const title = append(details, $('.title'));
const name = append(title, $('span.name.clickable', { title: localize('name', "Extension name"), role: 'heading', tabIndex: 0 }));
const versionWidget = new VersionWidget(title);
const preReleaseWidget = new PreReleaseTextWidget(title);
const preview = append(title, $('span.preview', { title: localize('preview', "Preview") }));
preview.textContent = localize('preview', "Preview");
const builtin = append(title, $('span.builtin'));
builtin.textContent = localize('builtin', "Built-in");
const subtitle = append(details, $('.subtitle'));
const publisher = append(append(subtitle, $('.subtitle-entry')), $('.publisher.clickable', { title: localize('publisher', "Publisher"), tabIndex: 0 }));
publisher.setAttribute('role', 'button');
const publisherDisplayName = append(publisher, $('.publisher-name'));
const verifiedPublisherWidget = this.instantiationService.createInstance(VerifiedPublisherWidget, append(publisher, $('.verified-publisher')), false);
const installCount = append(append(subtitle, $('.subtitle-entry')), $('span.install', { title: localize('install count', "Install count"), tabIndex: 0 }));
const installCountWidget = this.instantiationService.createInstance(InstallCountWidget, installCount, false);
const rating = append(append(subtitle, $('.subtitle-entry')), $('span.rating.clickable', { title: localize('rating', "Rating"), tabIndex: 0 }));
rating.setAttribute('role', 'link'); // #132645
const ratingsWidget = this.instantiationService.createInstance(RatingsWidget, rating, false);
const sponsorWidget = this.instantiationService.createInstance(SponsorWidget, append(subtitle, $('.subtitle-entry')));
const widgets: ExtensionWidget[] = [
remoteBadge,
versionWidget,
preReleaseWidget,
verifiedPublisherWidget,
installCountWidget,
ratingsWidget,
sponsorWidget,
];
const description = append(details, $('.description'));
const installAction = this.instantiationService.createInstance(InstallDropdownAction);
const actions = [
this.instantiationService.createInstance(ReloadAction),
this.instantiationService.createInstance(ExtensionStatusLabelAction),
this.instantiationService.createInstance(ActionWithDropDownAction, 'extensions.updateActions', '',
[[this.instantiationService.createInstance(UpdateAction, true)], [this.instantiationService.createInstance(SkipUpdateAction)]]),
this.instantiationService.createInstance(SetColorThemeAction),
this.instantiationService.createInstance(SetFileIconThemeAction),
this.instantiationService.createInstance(SetProductIconThemeAction),
this.instantiationService.createInstance(SetLanguageAction),
this.instantiationService.createInstance(ClearLanguageAction),
this.instantiationService.createInstance(EnableDropDownAction),
this.instantiationService.createInstance(DisableDropDownAction),
this.instantiationService.createInstance(RemoteInstallAction, false),
this.instantiationService.createInstance(LocalInstallAction),
this.instantiationService.createInstance(WebInstallAction),
installAction,
this.instantiationService.createInstance(InstallingLabelAction),
this.instantiationService.createInstance(ActionWithDropDownAction, 'extensions.uninstall', UninstallAction.UninstallLabel, [
[
this.instantiationService.createInstance(MigrateDeprecatedExtensionAction, false),
this.instantiationService.createInstance(UninstallAction),
this.instantiationService.createInstance(InstallAnotherVersionAction),
]
]),
this.instantiationService.createInstance(SwitchToPreReleaseVersionAction, false),
this.instantiationService.createInstance(SwitchToReleasedVersionAction, false),
this.instantiationService.createInstance(ToggleSyncExtensionAction),
new ExtensionEditorManageExtensionAction(this.scopedContextKeyService || this.contextKeyService, this.instantiationService),
];
const actionsAndStatusContainer = append(details, $('.actions-status-container'));
const extensionActionBar = this._register(new ActionBar(actionsAndStatusContainer, {
animated: false,
actionViewItemProvider: (action: IAction) => {
if (action instanceof ExtensionDropDownAction) {
return action.createActionViewItem();
}
if (action instanceof ActionWithDropDownAction) {
return new ExtensionActionWithDropdownActionViewItem(action, { icon: true, label: true, menuActionsOrProvider: { getActions: () => action.menuActions }, menuActionClassNames: (action.class || '').split(' ') }, this.contextMenuService);
}
return undefined;
},
focusOnlyEnabledItems: true
}));
extensionActionBar.push(actions, { icon: true, label: true });
extensionActionBar.setFocusable(true);
// update focusable elements when the enablement of an action changes
this._register(Event.any(...actions.map(a => Event.filter(a.onDidChange, e => e.enabled !== undefined)))(() => {
extensionActionBar.setFocusable(false);
extensionActionBar.setFocusable(true);
}));
const otherExtensionContainers: IExtensionContainer[] = [];
const extensionStatusAction = this.instantiationService.createInstance(ExtensionStatusAction);
const extensionStatusWidget = this._register(this.instantiationService.createInstance(ExtensionStatusWidget, append(actionsAndStatusContainer, $('.status')), extensionStatusAction));
otherExtensionContainers.push(extensionStatusAction, new class extends ExtensionWidget {
render() {
actionsAndStatusContainer.classList.toggle('list-layout', this.extension?.state === ExtensionState.Installed);
}
}());
const recommendationWidget = this.instantiationService.createInstance(ExtensionRecommendationWidget, append(details, $('.recommendation')));
widgets.push(recommendationWidget);
this._register(Event.any(extensionStatusWidget.onDidRender, recommendationWidget.onDidRender)(() => {
if (this.dimension) {
this.layout(this.dimension);
}
}));
const extensionContainers: ExtensionContainers = this.instantiationService.createInstance(ExtensionContainers, [...actions, ...widgets, ...otherExtensionContainers]);
for (const disposable of [...actions, ...widgets, ...otherExtensionContainers, extensionContainers]) {
this._register(disposable);
}
this._register(Event.chain(extensionActionBar.onDidRun)
.map(({ error }) => error)
.filter(error => !!error)
.on(this.onError, this));
const body = append(root, $('.body'));
const navbar = new NavBar(body);
const content = append(body, $('.content'));
content.id = generateUuid(); // An id is needed for the webview parent flow to
this.template = {
builtin,
content,
description,
header,
icon,
iconContainer,
installCount,
name,
navbar,
preview,
publisher,
publisherDisplayName,
rating,
actionsAndStatusContainer,
extensionActionBar,
set extension(extension: IExtension) {
extensionContainers.extension = extension;
},
set gallery(gallery: IGalleryExtension | null) {
versionWidget.gallery = gallery;
preReleaseWidget.gallery = gallery;
},
set manifest(manifest: IExtensionManifest | null) {
installAction.manifest = manifest;
}
};
}
override async setInput(input: ExtensionsInput, options: IExtensionEditorOptions | undefined, context: IEditorOpenContext, token: CancellationToken): Promise<void> {
await super.setInput(input, options, context, token);
this.updatePreReleaseVersionContext();
if (this.template) {
await this.render(input.extension, this.template, !!options?.preserveFocus);
}
}
override setOptions(options: IExtensionEditorOptions | undefined): void {
const currentOptions: IExtensionEditorOptions | undefined = this.options;
super.setOptions(options);
this.updatePreReleaseVersionContext();
if (this.input && this.template && currentOptions?.showPreReleaseVersion !== options?.showPreReleaseVersion) {
this.render((this.input as ExtensionsInput).extension, this.template, !!options?.preserveFocus);
}
}
private updatePreReleaseVersionContext(): void {
let showPreReleaseVersion = (<IExtensionEditorOptions | undefined>this.options)?.showPreReleaseVersion;
if (isUndefined(showPreReleaseVersion)) {
showPreReleaseVersion = !!(<ExtensionsInput>this.input).extension.gallery?.properties.isPreReleaseVersion;
}
this.showPreReleaseVersionContextKey?.set(showPreReleaseVersion);
}
async openTab(tab: ExtensionEditorTab): Promise<void> {
if (!this.input || !this.template) {
return;
}
if (this.template.navbar.switch(tab)) {
return;
}
// Fallback to Readme tab if ExtensionPack tab does not exist
if (tab === ExtensionEditorTab.ExtensionPack) {
this.template.navbar.switch(ExtensionEditorTab.Readme);
}
}
private async getGalleryVersionToShow(extension: IExtension, preRelease?: boolean): Promise<IGalleryExtension | null> {
if (isUndefined(preRelease)) {
return null;
}
if (preRelease === extension.gallery?.properties.isPreReleaseVersion) {
return null;
}
if (preRelease && !extension.hasPreReleaseVersion) {
return null;
}
if (!preRelease && !extension.hasReleaseVersion) {
return null;
}
return (await this.extensionGalleryService.getExtensions([{ ...extension.identifier, preRelease, hasPreRelease: extension.hasPreReleaseVersion }], CancellationToken.None))[0] || null;
}
private async render(extension: IExtension, template: IExtensionEditorTemplate, preserveFocus: boolean): Promise<void> {
this.activeElement = null;
this.transientDisposables.clear();
const token = this.transientDisposables.add(new CancellationTokenSource()).token;
const gallery = await this.getGalleryVersionToShow(extension, (this.options as IExtensionEditorOptions)?.showPreReleaseVersion);
if (token.isCancellationRequested) {
return;
}
this.extensionReadme = new Cache(() => gallery ? this.extensionGalleryService.getReadme(gallery, token) : extension.getReadme(token));
this.extensionChangelog = new Cache(() => gallery ? this.extensionGalleryService.getChangelog(gallery, token) : extension.getChangelog(token));
this.extensionManifest = new Cache(() => gallery ? this.extensionGalleryService.getManifest(gallery, token) : extension.getManifest(token));
template.extension = extension;
template.gallery = gallery;
template.manifest = null;
this.transientDisposables.add(addDisposableListener(template.icon, 'error', () => template.icon.src = extension.iconUrlFallback, { once: true }));
template.icon.src = extension.iconUrl;
template.name.textContent = extension.displayName;
template.name.classList.toggle('clickable', !!extension.url);
template.name.classList.toggle('deprecated', !!extension.deprecationInfo);
template.preview.style.display = extension.preview ? 'inherit' : 'none';
template.builtin.style.display = extension.isBuiltin ? 'inherit' : 'none';
template.description.textContent = extension.description;
// subtitle
template.publisher.classList.toggle('clickable', !!extension.url);
template.publisherDisplayName.textContent = extension.publisherDisplayName;
template.installCount.parentElement?.classList.toggle('hide', !extension.url);
template.rating.parentElement?.classList.toggle('hide', !extension.url);
template.rating.classList.toggle('clickable', !!extension.url);
if (extension.url) {
this.transientDisposables.add(onClick(template.name, () => this.openerService.open(URI.parse(extension.url!))));
this.transientDisposables.add(onClick(template.rating, () => this.openerService.open(URI.parse(`${extension.url}&ssr=false#review-details`))));
this.transientDisposables.add(onClick(template.publisher, () => {
this.paneCompositeService.openPaneComposite(VIEWLET_ID, ViewContainerLocation.Sidebar, true)
.then(viewlet => viewlet?.getViewPaneContainer() as IExtensionsViewPaneContainer)
.then(viewlet => viewlet.search(`publisher:"${extension.publisherDisplayName}"`));
}));
}
const manifest = await this.extensionManifest.get().promise;
if (token.isCancellationRequested) {
return;
}
if (manifest) {
template.manifest = manifest;
}
this.renderNavbar(extension, manifest, template, preserveFocus);
// report telemetry
const extRecommendations = this.extensionRecommendationsService.getAllRecommendationsWithReason();
let recommendationsData = {};
if (extRecommendations[extension.identifier.id.toLowerCase()]) {
recommendationsData = { recommendationReason: extRecommendations[extension.identifier.id.toLowerCase()].reasonId };
}
/* __GDPR__
"extensionGallery:openExtension" : {
"owner": "sandy081",
"recommendationReason": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"${include}": [
"${GalleryExtensionTelemetryData}"
]
}
*/
this.telemetryService.publicLog('extensionGallery:openExtension', { ...extension.telemetryData, ...recommendationsData });
}
private renderNavbar(extension: IExtension, manifest: IExtensionManifest | null, template: IExtensionEditorTemplate, preserveFocus: boolean): void {
template.content.innerText = '';
template.navbar.clear();
if (this.currentIdentifier !== extension.identifier.id) {
this.initialScrollProgress.clear();
this.currentIdentifier = extension.identifier.id;
}
if (extension.hasReadme()) {
template.navbar.push(ExtensionEditorTab.Readme, localize('details', "Details"), localize('detailstooltip', "Extension details, rendered from the extension's 'README.md' file"));
}
if (manifest && manifest.contributes) {
template.navbar.push(ExtensionEditorTab.Contributions, localize('contributions', "Feature Contributions"), localize('contributionstooltip', "Lists contributions to VS Code by this extension"));
}
if (extension.hasChangelog()) {
template.navbar.push(ExtensionEditorTab.Changelog, localize('changelog', "Changelog"), localize('changelogtooltip', "Extension update history, rendered from the extension's 'CHANGELOG.md' file"));
}
if (extension.dependencies.length) {
template.navbar.push(ExtensionEditorTab.Dependencies, localize('dependencies', "Dependencies"), localize('dependenciestooltip', "Lists extensions this extension depends on"));
}
if (manifest && manifest.extensionPack?.length && !this.shallRenderAsExtensionPack(manifest)) {
template.navbar.push(ExtensionEditorTab.ExtensionPack, localize('extensionpack', "Extension Pack"), localize('extensionpacktooltip', "Lists extensions those will be installed together with this extension"));
}
const addRuntimeStatusSection = () => template.navbar.push(ExtensionEditorTab.RuntimeStatus, localize('runtimeStatus', "Runtime Status"), localize('runtimeStatus description', "Extension runtime status"));
if (this.extensionsWorkbenchService.getExtensionStatus(extension)) {
addRuntimeStatusSection();
} else {
const disposable = this.extensionService.onDidChangeExtensionsStatus(e => {
if (e.some(extensionIdentifier => areSameExtensions({ id: extensionIdentifier.value }, extension.identifier))) {
addRuntimeStatusSection();
disposable.dispose();
}
}, this, this.transientDisposables);
}
if (template.navbar.currentId) {
this.onNavbarChange(extension, { id: template.navbar.currentId, focus: !preserveFocus }, template);
}
template.navbar.onChange(e => this.onNavbarChange(extension, e, template), this, this.transientDisposables);
}
override clearInput(): void {
this.contentDisposables.clear();
this.transientDisposables.clear();
super.clearInput();
}
override focus(): void {
this.activeElement?.focus();
}
showFind(): void {
this.activeWebview?.showFind();
}
runFindAction(previous: boolean): void {
this.activeWebview?.runFindAction(previous);
}
public get activeWebview(): IWebview | undefined {
if (!this.activeElement || !(this.activeElement as IWebview).runFindAction) {
return undefined;
}
return this.activeElement as IWebview;
}
private onNavbarChange(extension: IExtension, { id, focus }: { id: string | null; focus: boolean }, template: IExtensionEditorTemplate): void {
this.contentDisposables.clear();
template.content.innerText = '';
this.activeElement = null;
if (id) {
const cts = new CancellationTokenSource();
this.contentDisposables.add(toDisposable(() => cts.dispose(true)));
this.open(id, extension, template, cts.token)
.then(activeElement => {
if (cts.token.isCancellationRequested) {
return;
}
this.activeElement = activeElement;
if (focus) {
this.focus();
}
});
}
}
private open(id: string, extension: IExtension, template: IExtensionEditorTemplate, token: CancellationToken): Promise<IActiveElement | null> {
switch (id) {
case ExtensionEditorTab.Readme: return this.openDetails(extension, template, token);
case ExtensionEditorTab.Contributions: return this.openContributions(template, token);
case ExtensionEditorTab.Changelog: return this.openChangelog(template, token);
case ExtensionEditorTab.Dependencies: return this.openExtensionDependencies(extension, template, token);
case ExtensionEditorTab.ExtensionPack: return this.openExtensionPack(extension, template, token);
case ExtensionEditorTab.RuntimeStatus: return this.openRuntimeStatus(extension, template, token);
}
return Promise.resolve(null);
}
private async openMarkdown(cacheResult: CacheResult<string>, noContentCopy: string, container: HTMLElement, webviewIndex: WebviewIndex, title: string, token: CancellationToken): Promise<IActiveElement | null> {
try {
const body = await this.renderMarkdown(cacheResult, container, token);
if (token.isCancellationRequested) {
return Promise.resolve(null);
}
const webview = this.contentDisposables.add(this.webviewService.createWebviewOverlay({
title,
options: {
enableFindWidget: true,
tryRestoreScrollPosition: true,
disableServiceWorker: true,
},
contentOptions: {},
extension: undefined,
}));
webview.initialScrollProgress = this.initialScrollProgress.get(webviewIndex) || 0;
webview.claim(this, this.scopedContextKeyService);
setParentFlowTo(webview.container, container);
webview.layoutWebviewOverElement(container);
webview.setHtml(body);
webview.claim(this, undefined);
this.contentDisposables.add(webview.onDidFocus(() => this.fireOnDidFocus()));
this.contentDisposables.add(webview.onDidScroll(() => this.initialScrollProgress.set(webviewIndex, webview.initialScrollProgress)));
const removeLayoutParticipant = arrays.insert(this.layoutParticipants, {
layout: () => {
webview.layoutWebviewOverElement(container);
}
});
this.contentDisposables.add(toDisposable(removeLayoutParticipant));
let isDisposed = false;
this.contentDisposables.add(toDisposable(() => { isDisposed = true; }));
this.contentDisposables.add(this.themeService.onDidColorThemeChange(async () => {
// Render again since syntax highlighting of code blocks may have changed
const body = await this.renderMarkdown(cacheResult, container);
if (!isDisposed) { // Make sure we weren't disposed of in the meantime
webview.setHtml(body);
}
}));
this.contentDisposables.add(webview.onDidClickLink(link => {
if (!link) {
return;
}
// Only allow links with specific schemes
if (matchesScheme(link, Schemas.http) || matchesScheme(link, Schemas.https) || matchesScheme(link, Schemas.mailto)) {
this.openerService.open(link);
}
if (matchesScheme(link, Schemas.command) && URI.parse(link).path === ShowCurrentReleaseNotesActionId) {
this.openerService.open(link, { allowCommands: true }); // TODO@sandy081 use commands service
}
}));
return webview;
} catch (e) {
const p = append(container, $('p.nocontent'));
p.textContent = noContentCopy;
return p;
}
}
private async renderMarkdown(cacheResult: CacheResult<string>, container: HTMLElement, token?: CancellationToken): Promise<string> {
const contents = await this.loadContents(() => cacheResult, container);
if (token?.isCancellationRequested) {
return '';
}
const content = await renderMarkdownDocument(contents, this.extensionService, this.languageService, true, false, token);
if (token?.isCancellationRequested) {
return '';
}
return this.renderBody(content);
}
private renderBody(body: string): string {
const nonce = generateUuid();
const colorMap = TokenizationRegistry.getColorMap();
const css = colorMap ? generateTokensCSSForColorMap(colorMap) : '';
return `<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src https: data:; media-src https:; script-src 'none'; style-src 'nonce-${nonce}';">
<style nonce="${nonce}">
${DEFAULT_MARKDOWN_STYLES}
/* prevent scroll-to-top button from blocking the body text */
body {
padding-bottom: 75px;
}
#scroll-to-top {
position: fixed;
width: 32px;
height: 32px;
right: 25px;
bottom: 25px;
background-color: var(--vscode-button-secondaryBackground);
border-color: var(--vscode-button-border);
border-radius: 50%;
cursor: pointer;
box-shadow: 1px 1px 1px rgba(0,0,0,.25);
outline: none;
display: flex;
justify-content: center;
align-items: center;
}
#scroll-to-top:hover {
background-color: var(--vscode-button-secondaryHoverBackground);
box-shadow: 2px 2px 2px rgba(0,0,0,.25);
}
body.vscode-high-contrast #scroll-to-top {
border-width: 2px;
border-style: solid;
box-shadow: none;
}
#scroll-to-top span.icon::before {
content: "";
display: block;
background: var(--vscode-button-foreground);
/* Chevron up icon */
webkit-mask-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDE5LjIuMCwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPgo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4IgoJIHZpZXdCb3g9IjAgMCAxNiAxNiIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgMTYgMTY7IiB4bWw6c3BhY2U9InByZXNlcnZlIj4KPHN0eWxlIHR5cGU9InRleHQvY3NzIj4KCS5zdDB7ZmlsbDojRkZGRkZGO30KCS5zdDF7ZmlsbDpub25lO30KPC9zdHlsZT4KPHRpdGxlPnVwY2hldnJvbjwvdGl0bGU+CjxwYXRoIGNsYXNzPSJzdDAiIGQ9Ik04LDUuMWwtNy4zLDcuM0wwLDExLjZsOC04bDgsOGwtMC43LDAuN0w4LDUuMXoiLz4KPHJlY3QgY2xhc3M9InN0MSIgd2lkdGg9IjE2IiBoZWlnaHQ9IjE2Ii8+Cjwvc3ZnPgo=');
-webkit-mask-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDE5LjIuMCwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPgo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4IgoJIHZpZXdCb3g9IjAgMCAxNiAxNiIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgMTYgMTY7IiB4bWw6c3BhY2U9InByZXNlcnZlIj4KPHN0eWxlIHR5cGU9InRleHQvY3NzIj4KCS5zdDB7ZmlsbDojRkZGRkZGO30KCS5zdDF7ZmlsbDpub25lO30KPC9zdHlsZT4KPHRpdGxlPnVwY2hldnJvbjwvdGl0bGU+CjxwYXRoIGNsYXNzPSJzdDAiIGQ9Ik04LDUuMWwtNy4zLDcuM0wwLDExLjZsOC04bDgsOGwtMC43LDAuN0w4LDUuMXoiLz4KPHJlY3QgY2xhc3M9InN0MSIgd2lkdGg9IjE2IiBoZWlnaHQ9IjE2Ii8+Cjwvc3ZnPgo=');
width: 16px;
height: 16px;
}
${css}
</style>
</head>
<body>
<a id="scroll-to-top" role="button" aria-label="scroll to top" href="#"><span class="icon"></span></a>
${body}
</body>
</html>`;
}
private async openDetails(extension: IExtension, template: IExtensionEditorTemplate, token: CancellationToken): Promise<IActiveElement | null> {
const details = append(template.content, $('.details'));
const readmeContainer = append(details, $('.readme-container'));
const additionalDetailsContainer = append(details, $('.additional-details-container'));
const layout = () => details.classList.toggle('narrow', this.dimension && this.dimension.width < 500);
layout();
this.contentDisposables.add(toDisposable(arrays.insert(this.layoutParticipants, { layout })));
let activeElement: IActiveElement | null = null;
const manifest = await this.extensionManifest!.get().promise;
if (manifest && manifest.extensionPack?.length && this.shallRenderAsExtensionPack(manifest)) {
activeElement = await this.openExtensionPackReadme(manifest, readmeContainer, token);
} else {
activeElement = await this.openMarkdown(this.extensionReadme!.get(), localize('noReadme', "No README available."), readmeContainer, WebviewIndex.Readme, localize('Readme title', "Readme"), token);
}
this.renderAdditionalDetails(additionalDetailsContainer, extension);
return activeElement;
}
private shallRenderAsExtensionPack(manifest: IExtensionManifest): boolean {
return !!(manifest.categories?.some(category => category.toLowerCase() === 'extension packs'));
}
private async openExtensionPackReadme(manifest: IExtensionManifest, container: HTMLElement, token: CancellationToken): Promise<IActiveElement | null> {
if (token.isCancellationRequested) {
return Promise.resolve(null);
}
const extensionPackReadme = append(container, $('div', { class: 'extension-pack-readme' }));
extensionPackReadme.style.margin = '0 auto';
extensionPackReadme.style.maxWidth = '882px';
const extensionPack = append(extensionPackReadme, $('div', { class: 'extension-pack' }));
if (manifest.extensionPack!.length <= 3) {
extensionPackReadme.classList.add('one-row');
} else if (manifest.extensionPack!.length <= 6) {
extensionPackReadme.classList.add('two-rows');
} else if (manifest.extensionPack!.length <= 9) {
extensionPackReadme.classList.add('three-rows');
} else {
extensionPackReadme.classList.add('more-rows');
}
const extensionPackHeader = append(extensionPack, $('div.header'));
extensionPackHeader.textContent = localize('extension pack', "Extension Pack ({0})", manifest.extensionPack!.length);
const extensionPackContent = append(extensionPack, $('div', { class: 'extension-pack-content' }));
extensionPackContent.setAttribute('tabindex', '0');
append(extensionPack, $('div.footer'));
const readmeContent = append(extensionPackReadme, $('div.readme-content'));
await Promise.all([
this.renderExtensionPack(manifest, extensionPackContent, token),
this.openMarkdown(this.extensionReadme!.get(), localize('noReadme', "No README available."), readmeContent, WebviewIndex.Readme, localize('Readme title', "Readme"), token),
]);
return { focus: () => extensionPackContent.focus() };
}
private renderAdditionalDetails(container: HTMLElement, extension: IExtension): void {
const content = $('div', { class: 'additional-details-content', tabindex: '0' });
const scrollableContent = new DomScrollableElement(content, {});
const layout = () => scrollableContent.scanDomNode();
const removeLayoutParticipant = arrays.insert(this.layoutParticipants, { layout });
this.contentDisposables.add(toDisposable(removeLayoutParticipant));
this.contentDisposables.add(scrollableContent);
this.renderCategories(content, extension);
this.renderExtensionResources(content, extension);
this.renderMoreInfo(content, extension);
append(container, scrollableContent.getDomNode());
scrollableContent.scanDomNode();
}
private renderCategories(container: HTMLElement, extension: IExtension): void {
if (extension.categories.length) {
const categoriesContainer = append(container, $('.categories-container.additional-details-element'));
append(categoriesContainer, $('.additional-details-title', undefined, localize('categories', "Categories")));
const categoriesElement = append(categoriesContainer, $('.categories'));
for (const category of extension.categories) {
this.transientDisposables.add(onClick(append(categoriesElement, $('span.category', { tabindex: '0' }, category)), () => {
this.paneCompositeService.openPaneComposite(VIEWLET_ID, ViewContainerLocation.Sidebar, true)
.then(viewlet => viewlet?.getViewPaneContainer() as IExtensionsViewPaneContainer)
.then(viewlet => viewlet.search(`@category:"${category}"`));
}));
}
}
}
private renderExtensionResources(container: HTMLElement, extension: IExtension): void {
const resources: [string, URI][] = [];
if (extension.url) {
resources.push([localize('Marketplace', "Marketplace"), URI.parse(extension.url)]);
}
if (extension.repository) {
try {
resources.push([localize('repository', "Repository"), URI.parse(extension.repository)]);
} catch (error) {/* Ignore */ }
}
if (extension.url && extension.licenseUrl) {
try {
resources.push([localize('license', "License"), URI.parse(extension.licenseUrl)]);
} catch (error) {/* Ignore */ }
}
if (extension.publisherUrl) {
resources.push([extension.publisherDisplayName, extension.publisherUrl]);
}
if (resources.length || extension.publisherSponsorLink) {
const extensionResourcesContainer = append(container, $('.resources-container.additional-details-element'));
append(extensionResourcesContainer, $('.additional-details-title', undefined, localize('resources', "Extension Resources")));
const resourcesElement = append(extensionResourcesContainer, $('.resources'));
for (const [label, uri] of resources) {
this.transientDisposables.add(onClick(append(resourcesElement, $('a.resource', { title: uri.toString(), tabindex: '0' }, label)), () => this.openerService.open(uri)));
}
}
}
private renderMoreInfo(container: HTMLElement, extension: IExtension): void {
const gallery = extension.gallery;
const moreInfoContainer = append(container, $('.more-info-container.additional-details-element'));
append(moreInfoContainer, $('.additional-details-title', undefined, localize('Marketplace Info', "More Info")));
const moreInfo = append(moreInfoContainer, $('.more-info'));
if (gallery) {
append(moreInfo,
$('.more-info-entry', undefined,
$('div', undefined, localize('published', "Published")),
$('div', undefined, new Date(gallery.releaseDate).toLocaleString(language, { hourCycle: 'h23' }))
),
$('.more-info-entry', undefined,
$('div', undefined, localize('last released', "Last released")),
$('div', undefined, new Date(gallery.lastUpdated).toLocaleString(language, { hourCycle: 'h23' }))
)
);
}
if (extension.local && extension.local.installedTimestamp) {
append(moreInfo,
$('.more-info-entry', undefined,
$('div', undefined, localize('last updated', "Last updated")),
$('div', undefined, new Date(extension.local.installedTimestamp).toLocaleString(language, { hourCycle: 'h23' }))
)
);
}
append(moreInfo,
$('.more-info-entry', undefined,
$('div', undefined, localize('id', "Identifier")),
$('code', undefined, extension.identifier.id)
));
}
private openChangelog(template: IExtensionEditorTemplate, token: CancellationToken): Promise<IActiveElement | null> {
return this.openMarkdown(this.extensionChangelog!.get(), localize('noChangelog', "No Changelog available."), template.content, WebviewIndex.Changelog, localize('Changelog title', "Changelog"), token);
}
private openContributions(template: IExtensionEditorTemplate, token: CancellationToken): Promise<IActiveElement | null> {
const content = $('div.subcontent.feature-contributions', { tabindex: '0' });
return this.loadContents(() => this.extensionManifest!.get(), template.content)
.then(manifest => {
if (token.isCancellationRequested) {
return null;
}
if (!manifest) {
return content;
}
const scrollableContent = new DomScrollableElement(content, {});
const layout = () => scrollableContent.scanDomNode();
const removeLayoutParticipant = arrays.insert(this.layoutParticipants, { layout });
this.contentDisposables.add(toDisposable(removeLayoutParticipant));
const renders = [
this.renderSettings(content, manifest, layout),
this.renderCommands(content, manifest, layout),
this.renderCodeActions(content, manifest, layout),
this.renderLanguages(content, manifest, layout),
this.renderColorThemes(content, manifest, layout),
this.renderIconThemes(content, manifest, layout),
this.renderProductIconThemes(content, manifest, layout),
this.renderColors(content, manifest, layout),
this.renderJSONValidation(content, manifest, layout),
this.renderDebuggers(content, manifest, layout),
this.renderViewContainers(content, manifest, layout),
this.renderViews(content, manifest, layout),
this.renderLocalizations(content, manifest, layout),
this.renderCustomEditors(content, manifest, layout),
this.renderNotebooks(content, manifest, layout),
this.renderNotebookRenderers(content, manifest, layout),
this.renderAuthentication(content, manifest, layout),
this.renderActivationEvents(content, manifest, layout),
];
scrollableContent.scanDomNode();
const isEmpty = !renders.some(x => x);
if (isEmpty) {
append(content, $('p.nocontent')).textContent = localize('noContributions', "No Contributions");
append(template.content, content);
} else {
append(template.content, scrollableContent.getDomNode());
this.contentDisposables.add(scrollableContent);
}
return content;
}, () => {
if (token.isCancellationRequested) {
return null;
}
append(content, $('p.nocontent')).textContent = localize('noContributions', "No Contributions");
append(template.content, content);
return content;
});
}
private openExtensionDependencies(extension: IExtension, template: IExtensionEditorTemplate, token: CancellationToken): Promise<IActiveElement | null> {
if (token.isCancellationRequested) {
return Promise.resolve(null);
}
if (arrays.isFalsyOrEmpty(extension.dependencies)) {
append(template.content, $('p.nocontent')).textContent = localize('noDependencies', "No Dependencies");
return Promise.resolve(template.content);
}
const content = $('div', { class: 'subcontent' });
const scrollableContent = new DomScrollableElement(content, {});
append(template.content, scrollableContent.getDomNode());
this.contentDisposables.add(scrollableContent);
const dependenciesTree = this.instantiationService.createInstance(ExtensionsTree,
new ExtensionData(extension, null, extension => extension.dependencies || [], this.extensionsWorkbenchService), content,
{
listBackground: editorBackground
});
const layout = () => {
scrollableContent.scanDomNode();
const scrollDimensions = scrollableContent.getScrollDimensions();
dependenciesTree.layout(scrollDimensions.height);
};
const removeLayoutParticipant = arrays.insert(this.layoutParticipants, { layout });
this.contentDisposables.add(toDisposable(removeLayoutParticipant));
this.contentDisposables.add(dependenciesTree);
scrollableContent.scanDomNode();
return Promise.resolve({ focus() { dependenciesTree.domFocus(); } });
}
private async openExtensionPack(extension: IExtension, template: IExtensionEditorTemplate, token: CancellationToken): Promise<IActiveElement | null> {
if (token.isCancellationRequested) {
return Promise.resolve(null);
}
const manifest = await this.loadContents(() => this.extensionManifest!.get(), template.content);
if (token.isCancellationRequested) {
return null;
}
if (!manifest) {
return null;
}
return this.renderExtensionPack(manifest, template.content, token);
}
private async openRuntimeStatus(extension: IExtension, template: IExtensionEditorTemplate, token: CancellationToken): Promise<IActiveElement | null> {
const content = $('div', { class: 'subcontent', tabindex: '0' });
const scrollableContent = new DomScrollableElement(content, {});
const layout = () => scrollableContent.scanDomNode();
const removeLayoutParticipant = arrays.insert(this.layoutParticipants, { layout });
this.contentDisposables.add(toDisposable(removeLayoutParticipant));
const updateContent = () => {
scrollableContent.scanDomNode();
reset(content, this.renderRuntimeStatus(extension, layout));
};
updateContent();
this.extensionService.onDidChangeExtensionsStatus(e => {
if (e.some(extensionIdentifier => areSameExtensions({ id: extensionIdentifier.value }, extension.identifier))) {
updateContent();
}
}, this, this.contentDisposables);
this.contentDisposables.add(scrollableContent);
append(template.content, scrollableContent.getDomNode());
return content;
}
private renderRuntimeStatus(extension: IExtension, onDetailsToggle: Function): HTMLElement {
const extensionStatus = this.extensionsWorkbenchService.getExtensionStatus(extension);
const element = $('.runtime-status');
if (extensionStatus?.activationTimes) {
const activationTime = extensionStatus.activationTimes.codeLoadingTime + extensionStatus.activationTimes.activateCallTime;
const activationElement = append(element, $('div.activation-details'));
const activationReasonElement = append(activationElement, $('div.activation-element-entry'));
append(activationReasonElement, $('span.activation-message-title', undefined, localize('activation reason', "Activation Event:")));
append(activationReasonElement, $('code', undefined, extensionStatus.activationTimes.activationReason.startup ? localize('startup', "Startup") : extensionStatus.activationTimes.activationReason.activationEvent));
const activationTimeElement = append(activationElement, $('div.activation-element-entry'));
append(activationTimeElement, $('span.activation-message-title', undefined, localize('activation time', "Activation Time:")));
append(activationTimeElement, $('code', undefined, `${activationTime}ms`));
if (ExtensionIdentifier.toKey(extensionStatus.activationTimes.activationReason.extensionId) !== ExtensionIdentifier.toKey(extension.identifier.id)) {
const activatedByElement = append(activationElement, $('div.activation-element-entry'));
append(activatedByElement, $('span.activation-message-title', undefined, localize('activatedBy', "Activated By:")));
append(activatedByElement, $('span', undefined, extensionStatus.activationTimes.activationReason.extensionId.value));
}
}
else if (extension.local && (extension.local.manifest.main || extension.local.manifest.browser)) {
append(element, $('div.activation-message', undefined, localize('not yet activated', "Not yet activated.")));
}
if (extensionStatus?.runtimeErrors.length) {
append(element, $('details', { open: true, ontoggle: onDetailsToggle },
$('summary', { tabindex: '0' }, localize('uncaught errors', "Uncaught Errors ({0})", extensionStatus.runtimeErrors.length)),
$('div', undefined,
...extensionStatus.runtimeErrors.map(error => $('div.message-entry', undefined,
$(`span${ThemeIcon.asCSSSelector(errorIcon)}`, undefined),
$('span', undefined, getErrorMessage(error)),
))
),
));
}
if (extensionStatus?.messages.length) {
append(element, $('details', { open: true, ontoggle: onDetailsToggle },
$('summary', { tabindex: '0' }, localize('messages', "Messages ({0})", extensionStatus?.messages.length)),
$('div', undefined,
...extensionStatus.messages.sort((a, b) => b.type - a.type)
.map(message => $('div.message-entry', undefined,
$(`span${ThemeIcon.asCSSSelector(message.type === Severity.Error ? errorIcon : message.type === Severity.Warning ? warningIcon : infoIcon)}`, undefined),
$('span', undefined, message.message)
))
),
));
}
if (element.children.length === 0) {
append(element, $('div.no-status-message')).textContent = localize('noStatus', "No status available.");
}
return element;
}
private async renderExtensionPack(manifest: IExtensionManifest, parent: HTMLElement, token: CancellationToken): Promise<IActiveElement | null> {
if (token.isCancellationRequested) {
return null;
}
const content = $('div', { class: 'subcontent' });
const scrollableContent = new DomScrollableElement(content, { useShadows: false });
append(parent, scrollableContent.getDomNode());
const extensionsGridView = this.instantiationService.createInstance(ExtensionsGridView, content, new Delegate());
const extensions: IExtension[] = await getExtensions(manifest.extensionPack!, this.extensionsWorkbenchService);
extensionsGridView.setExtensions(extensions);
scrollableContent.scanDomNode();
this.contentDisposables.add(scrollableContent);
this.contentDisposables.add(extensionsGridView);
this.contentDisposables.add(toDisposable(arrays.insert(this.layoutParticipants, { layout: () => scrollableContent.scanDomNode() })));
return content;
}
private renderSettings(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean {
const configuration = manifest.contributes?.configuration;
let properties: any = {};
if (Array.isArray(configuration)) {
configuration.forEach(config => {
properties = { ...properties, ...config.properties };
});
} else if (configuration) {
properties = configuration.properties;
}
let contrib = properties ? Object.keys(properties) : [];
// filter deprecated settings
contrib = contrib.filter(key => {
const config = properties[key];
return !config.deprecationMessage && !config.markdownDeprecationMessage;
});
if (!contrib.length) {
return false;
}
const details = $('details', { open: true, ontoggle: onDetailsToggle },
$('summary', { tabindex: '0' }, localize('settings', "Settings ({0})", contrib.length)),
$('table', undefined,
$('tr', undefined,
$('th', undefined, localize('setting name', "ID")),
$('th', undefined, localize('description', "Description")),
$('th', undefined, localize('default', "Default"))
),
...contrib.map(key => {
let description: (Node | string) = properties[key].description || '';
if (properties[key].markdownDescription) {
const { element, dispose } = renderMarkdown({ value: properties[key].markdownDescription }, { actionHandler: { callback: (content) => this.openerService.open(content).catch(onUnexpectedError), disposables: this.contentDisposables } });
description = element;
this.contentDisposables.add(toDisposable(dispose));
}
return $('tr', undefined,
$('td', undefined, $('code', undefined, key)),
$('td', undefined, description),
$('td', undefined, $('code', undefined, `${isUndefined(properties[key].default) ? getDefaultValue(properties[key].type) : properties[key].default}`)));
})
)
);
append(container, details);
return true;
}
private renderDebuggers(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean {
const contrib = manifest.contributes?.debuggers || [];
if (!contrib.length) {
return false;
}
const details = $('details', { open: true, ontoggle: onDetailsToggle },
$('summary', { tabindex: '0' }, localize('debuggers', "Debuggers ({0})", contrib.length)),
$('table', undefined,
$('tr', undefined,
$('th', undefined, localize('debugger name', "Name")),
$('th', undefined, localize('debugger type', "Type")),
),
...contrib.map(d => $('tr', undefined,
$('td', undefined, d.label!),
$('td', undefined, d.type)))
)
);
append(container, details);
return true;
}
private renderViewContainers(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean {
const contrib = manifest.contributes?.viewsContainers || {};
const viewContainers = Object.keys(contrib).reduce((result, location) => {
const viewContainersForLocation: IViewContainer[] = contrib[location];
result.push(...viewContainersForLocation.map(viewContainer => ({ ...viewContainer, location })));
return result;
}, [] as Array<{ id: string; title: string; location: string }>);
if (!viewContainers.length) {
return false;
}
const details = $('details', { open: true, ontoggle: onDetailsToggle },
$('summary', { tabindex: '0' }, localize('viewContainers', "View Containers ({0})", viewContainers.length)),
$('table', undefined,
$('tr', undefined, $('th', undefined, localize('view container id', "ID")), $('th', undefined, localize('view container title', "Title")), $('th', undefined, localize('view container location', "Where"))),
...viewContainers.map(viewContainer => $('tr', undefined, $('td', undefined, viewContainer.id), $('td', undefined, viewContainer.title), $('td', undefined, viewContainer.location)))
)
);
append(container, details);
return true;
}
private renderViews(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean {
const contrib = manifest.contributes?.views || {};
const views = Object.keys(contrib).reduce((result, location) => {
const viewsForLocation: IView[] = contrib[location];
result.push(...viewsForLocation.map(view => ({ ...view, location })));
return result;
}, [] as Array<{ id: string; name: string; location: string }>);
if (!views.length) {
return false;
}
const details = $('details', { open: true, ontoggle: onDetailsToggle },
$('summary', { tabindex: '0' }, localize('views', "Views ({0})", views.length)),
$('table', undefined,
$('tr', undefined, $('th', undefined, localize('view id', "ID")), $('th', undefined, localize('view name', "Name")), $('th', undefined, localize('view location', "Where"))),
...views.map(view => $('tr', undefined, $('td', undefined, view.id), $('td', undefined, view.name), $('td', undefined, view.location)))
)
);
append(container, details);
return true;
}
private renderLocalizations(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean {
const localizations = manifest.contributes?.localizations || [];
if (!localizations.length) {
return false;
}
const details = $('details', { open: true, ontoggle: onDetailsToggle },
$('summary', { tabindex: '0' }, localize('localizations', "Localizations ({0})", localizations.length)),
$('table', undefined,
$('tr', undefined, $('th', undefined, localize('localizations language id', "Language ID")), $('th', undefined, localize('localizations language name', "Language Name")), $('th', undefined, localize('localizations localized language name', "Language Name (Localized)"))),
...localizations.map(localization => $('tr', undefined, $('td', undefined, localization.languageId), $('td', undefined, localization.languageName || ''), $('td', undefined, localization.localizedLanguageName || '')))
)
);
append(container, details);
return true;
}
private renderCustomEditors(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean {
const webviewEditors = manifest.contributes?.customEditors || [];
if (!webviewEditors.length) {
return false;
}
const details = $('details', { open: true, ontoggle: onDetailsToggle },
$('summary', { tabindex: '0' }, localize('customEditors', "Custom Editors ({0})", webviewEditors.length)),
$('table', undefined,
$('tr', undefined,
$('th', undefined, localize('customEditors view type', "View Type")),
$('th', undefined, localize('customEditors priority', "Priority")),
$('th', undefined, localize('customEditors filenamePattern', "Filename Pattern"))),
...webviewEditors.map(webviewEditor =>
$('tr', undefined,
$('td', undefined, webviewEditor.viewType),
$('td', undefined, webviewEditor.priority),
$('td', undefined, arrays.coalesce(webviewEditor.selector.map(x => x.filenamePattern)).join(', '))))
)
);
append(container, details);
return true;
}
private renderCodeActions(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean {
const codeActions = manifest.contributes?.codeActions || [];
if (!codeActions.length) {
return false;
}
const flatActions = arrays.flatten(
codeActions.map(contribution =>
contribution.actions.map(action => ({ ...action, languages: contribution.languages }))));
const details = $('details', { open: true, ontoggle: onDetailsToggle },
$('summary', { tabindex: '0' }, localize('codeActions', "Code Actions ({0})", flatActions.length)),
$('table', undefined,
$('tr', undefined,
$('th', undefined, localize('codeActions.title', "Title")),
$('th', undefined, localize('codeActions.kind', "Kind")),
$('th', undefined, localize('codeActions.description', "Description")),
$('th', undefined, localize('codeActions.languages', "Languages"))),
...flatActions.map(action =>
$('tr', undefined,
$('td', undefined, action.title),
$('td', undefined, $('code', undefined, action.kind)),
$('td', undefined, action.description ?? ''),
$('td', undefined, ...action.languages.map(language => $('code', undefined, language)))))
)
);
append(container, details);
return true;
}
private renderAuthentication(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean {
const authentication = manifest.contributes?.authentication || [];
if (!authentication.length) {
return false;
}
const details = $('details', { open: true, ontoggle: onDetailsToggle },
$('summary', { tabindex: '0' }, localize('authentication', "Authentication ({0})", authentication.length)),
$('table', undefined,
$('tr', undefined,
$('th', undefined, localize('authentication.label', "Label")),
$('th', undefined, localize('authentication.id', "ID"))
),
...authentication.map(action =>
$('tr', undefined,
$('td', undefined, action.label),
$('td', undefined, action.id)
)
)
)
);
append(container, details);
return true;
}
private renderColorThemes(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean {
const contrib = manifest.contributes?.themes || [];
if (!contrib.length) {
return false;
}
const details = $('details', { open: true, ontoggle: onDetailsToggle },
$('summary', { tabindex: '0' }, localize('colorThemes', "Color Themes ({0})", contrib.length)),
$('ul', undefined, ...contrib.map(theme => $('li', undefined, theme.label)))
);
append(container, details);
return true;
}
private renderIconThemes(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean {
const contrib = manifest.contributes?.iconThemes || [];
if (!contrib.length) {
return false;
}
const details = $('details', { open: true, ontoggle: onDetailsToggle },
$('summary', { tabindex: '0' }, localize('iconThemes', "File Icon Themes ({0})", contrib.length)),
$('ul', undefined, ...contrib.map(theme => $('li', undefined, theme.label)))
);
append(container, details);
return true;
}
private renderProductIconThemes(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean {
const contrib = manifest.contributes?.productIconThemes || [];
if (!contrib.length) {
return false;
}
const details = $('details', { open: true, ontoggle: onDetailsToggle },
$('summary', { tabindex: '0' }, localize('productThemes', "Product Icon Themes ({0})", contrib.length)),
$('ul', undefined, ...contrib.map(theme => $('li', undefined, theme.label)))
);
append(container, details);
return true;
}
private renderColors(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean {
const colors = manifest.contributes?.colors || [];
if (!colors.length) {
return false;
}
function colorPreview(colorReference: string): Node[] {
const result: Node[] = [];
if (colorReference && colorReference[0] === '#') {
const color = Color.fromHex(colorReference);
if (color) {
result.push($('span', { class: 'colorBox', style: 'background-color: ' + Color.Format.CSS.format(color) }, ''));
}
}
result.push($('code', undefined, colorReference));
return result;
}
const details = $('details', { open: true, ontoggle: onDetailsToggle },
$('summary', { tabindex: '0' }, localize('colors', "Colors ({0})", colors.length)),
$('table', undefined,
$('tr', undefined,
$('th', undefined, localize('colorId', "ID")),
$('th', undefined, localize('description', "Description")),
$('th', undefined, localize('defaultDark', "Dark Default")),
$('th', undefined, localize('defaultLight', "Light Default")),
$('th', undefined, localize('defaultHC', "High Contrast Default"))
),
...colors.map(color => $('tr', undefined,
$('td', undefined, $('code', undefined, color.id)),
$('td', undefined, color.description),
$('td', undefined, ...colorPreview(color.defaults.dark)),
$('td', undefined, ...colorPreview(color.defaults.light)),
$('td', undefined, ...colorPreview(color.defaults.highContrast))
))
)
);
append(container, details);
return true;
}
private renderJSONValidation(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean {
const contrib = manifest.contributes?.jsonValidation || [];
if (!contrib.length) {
return false;
}
const details = $('details', { open: true, ontoggle: onDetailsToggle },
$('summary', { tabindex: '0' }, localize('JSON Validation', "JSON Validation ({0})", contrib.length)),
$('table', undefined,
$('tr', undefined,
$('th', undefined, localize('fileMatch', "File Match")),
$('th', undefined, localize('schema', "Schema"))
),
...contrib.map(v => $('tr', undefined,
$('td', undefined, $('code', undefined, Array.isArray(v.fileMatch) ? v.fileMatch.join(', ') : v.fileMatch)),
$('td', undefined, v.url)
))));
append(container, details);
return true;
}
private renderCommands(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean {
const rawCommands = manifest.contributes?.commands || [];
const commands = rawCommands.map(c => ({
id: c.command,
title: c.title,
keybindings: [] as ResolvedKeybinding[],
menus: [] as string[]
}));
const byId = arrays.index(commands, c => c.id);
const menus = manifest.contributes?.menus || {};
for (const context in menus) {
for (const menu of menus[context]) {
if (menu.command) {
let command = byId[menu.command];
if (command) {
command.menus.push(context);
} else {
command = { id: menu.command, title: '', keybindings: [], menus: [context] };
byId[command.id] = command;
commands.push(command);
}
}
}
}
const rawKeybindings = manifest.contributes?.keybindings ? (Array.isArray(manifest.contributes.keybindings) ? manifest.contributes.keybindings : [manifest.contributes.keybindings]) : [];
rawKeybindings.forEach(rawKeybinding => {
const keybinding = this.resolveKeybinding(rawKeybinding);
if (!keybinding) {
return;
}
let command = byId[rawKeybinding.command];
if (command) {
command.keybindings.push(keybinding);
} else {
command = { id: rawKeybinding.command, title: '', keybindings: [keybinding], menus: [] };
byId[command.id] = command;
commands.push(command);
}
});
if (!commands.length) {
return false;
}
const renderKeybinding = (keybinding: ResolvedKeybinding): HTMLElement => {
const element = $('');
const kbl = new KeybindingLabel(element, OS, defaultKeybindingLabelStyles);
kbl.set(keybinding);
return element;
};
const details = $('details', { open: true, ontoggle: onDetailsToggle },
$('summary', { tabindex: '0' }, localize('commands', "Commands ({0})", commands.length)),
$('table', undefined,
$('tr', undefined,
$('th', undefined, localize('command name', "ID")),
$('th', undefined, localize('command title', "Title")),
$('th', undefined, localize('keyboard shortcuts', "Keyboard Shortcuts")),
$('th', undefined, localize('menuContexts', "Menu Contexts"))
),
...commands.map(c => $('tr', undefined,
$('td', undefined, $('code', undefined, c.id)),
$('td', undefined, typeof c.title === 'string' ? c.title : c.title.value),
$('td', undefined, ...c.keybindings.map(keybinding => renderKeybinding(keybinding))),
$('td', undefined, ...c.menus.map(context => $('code', undefined, context)))
))
)
);
append(container, details);
return true;
}
private renderLanguages(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean {
const contributes = manifest.contributes;
const rawLanguages = contributes?.languages || [];
const languages = rawLanguages.map(l => ({
id: l.id,
name: (l.aliases || [])[0] || l.id,
extensions: l.extensions || [],
hasGrammar: false,
hasSnippets: false
}));
const byId = arrays.index(languages, l => l.id);
const grammars = contributes?.grammars || [];
grammars.forEach(grammar => {
let language = byId[grammar.language];
if (language) {
language.hasGrammar = true;
} else {
language = { id: grammar.language, name: grammar.language, extensions: [], hasGrammar: true, hasSnippets: false };
byId[language.id] = language;
languages.push(language);
}
});
const snippets = contributes?.snippets || [];
snippets.forEach(snippet => {
let language = byId[snippet.language];
if (language) {
language.hasSnippets = true;
} else {
language = { id: snippet.language, name: snippet.language, extensions: [], hasGrammar: false, hasSnippets: true };
byId[language.id] = language;
languages.push(language);
}
});
if (!languages.length) {
return false;
}
const details = $('details', { open: true, ontoggle: onDetailsToggle },
$('summary', { tabindex: '0' }, localize('languages', "Languages ({0})", languages.length)),
$('table', undefined,
$('tr', undefined,
$('th', undefined, localize('language id', "ID")),
$('th', undefined, localize('language name', "Name")),
$('th', undefined, localize('file extensions', "File Extensions")),
$('th', undefined, localize('grammar', "Grammar")),
$('th', undefined, localize('snippets', "Snippets"))
),
...languages.map(l => $('tr', undefined,
$('td', undefined, l.id),
$('td', undefined, l.name),
$('td', undefined, ...join(l.extensions.map(ext => $('code', undefined, ext)), ' ')),
$('td', undefined, document.createTextNode(l.hasGrammar ? '✔︎' : '\u2014')),
$('td', undefined, document.createTextNode(l.hasSnippets ? '✔︎' : '\u2014'))
))
)
);
append(container, details);
return true;
}
private renderActivationEvents(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean {
const activationEvents = manifest.activationEvents || [];
if (!activationEvents.length) {
return false;
}
const details = $('details', { open: true, ontoggle: onDetailsToggle },
$('summary', { tabindex: '0' }, localize('activation events', "Activation Events ({0})", activationEvents.length)),
$('ul', undefined, ...activationEvents.map(activationEvent => $('li', undefined, $('code', undefined, activationEvent))))
);
append(container, details);
return true;
}
private renderNotebooks(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean {
const contrib = manifest.contributes?.notebooks || [];
if (!contrib.length) {
return false;
}
const details = $('details', { open: true, ontoggle: onDetailsToggle },
$('summary', { tabindex: '0' }, localize('Notebooks', "Notebooks ({0})", contrib.length)),
$('table', undefined,
$('tr', undefined,
$('th', undefined, localize('Notebook id', "ID")),
$('th', undefined, localize('Notebook name', "Name")),
),
...contrib.map(d => $('tr', undefined,
$('td', undefined, d.type),
$('td', undefined, d.displayName)))
)
);
append(container, details);
return true;
}
private renderNotebookRenderers(container: HTMLElement, manifest: IExtensionManifest, onDetailsToggle: Function): boolean {
const contrib = manifest.contributes?.notebookRenderer || [];
if (!contrib.length) {
return false;
}
const details = $('details', { open: true, ontoggle: onDetailsToggle },
$('summary', { tabindex: '0' }, localize('NotebookRenderers', "Notebook Renderers ({0})", contrib.length)),
$('table', undefined,
$('tr', undefined,
$('th', undefined, localize('Notebook renderer name', "Name")),
$('th', undefined, localize('Notebook mimetypes', "Mimetypes")),
),
...contrib.map(d => $('tr', undefined,
$('td', undefined, d.displayName),
$('td', undefined, d.mimeTypes.join(','))))
)
);
append(container, details);
return true;
}
private resolveKeybinding(rawKeyBinding: IKeyBinding): ResolvedKeybinding | null {
let key: string | undefined;
switch (platform) {
case 'win32': key = rawKeyBinding.win; break;
case 'linux': key = rawKeyBinding.linux; break;
case 'darwin': key = rawKeyBinding.mac; break;
}
return this.keybindingService.resolveUserBinding(key || rawKeyBinding.key)[0];
}
private loadContents<T>(loadingTask: () => CacheResult<T>, container: HTMLElement): Promise<T> {
container.classList.add('loading');
const result = this.contentDisposables.add(loadingTask());
const onDone = () => container.classList.remove('loading');
result.promise.then(onDone, onDone);
return result.promise;
}
layout(dimension: Dimension): void {
this.dimension = dimension;
this.layoutParticipants.forEach(p => p.layout());
}
private onError(err: any): void {
if (isCancellationError(err)) {
return;
}
this.notificationService.error(err);
}
}
const contextKeyExpr = ContextKeyExpr.and(ContextKeyExpr.equals('activeEditor', ExtensionEditor.ID), EditorContextKeys.focus.toNegated());
registerAction2(class ShowExtensionEditorFindAction extends Action2 {
constructor() {
super({
id: 'editor.action.extensioneditor.showfind',
title: localize('find', "Find"),
keybinding: {
when: contextKeyExpr,
weight: KeybindingWeight.EditorContrib,
primary: KeyMod.CtrlCmd | KeyCode.KeyF,
}
});
}
run(accessor: ServicesAccessor): any {
const extensionEditor = getExtensionEditor(accessor);
extensionEditor?.showFind();
}
});
registerAction2(class StartExtensionEditorFindNextAction extends Action2 {
constructor() {
super({
id: 'editor.action.extensioneditor.findNext',
title: localize('find next', "Find Next"),
keybinding: {
when: ContextKeyExpr.and(
contextKeyExpr,
KEYBINDING_CONTEXT_WEBVIEW_FIND_WIDGET_FOCUSED),
primary: KeyCode.Enter,
weight: KeybindingWeight.EditorContrib
}
});
}
run(accessor: ServicesAccessor): any {
const extensionEditor = getExtensionEditor(accessor);
extensionEditor?.runFindAction(false);
}
});
registerAction2(class StartExtensionEditorFindPreviousAction extends Action2 {
constructor() {
super({
id: 'editor.action.extensioneditor.findPrevious',
title: localize('find previous', "Find Previous"),
keybinding: {
when: ContextKeyExpr.and(
contextKeyExpr,
KEYBINDING_CONTEXT_WEBVIEW_FIND_WIDGET_FOCUSED),
primary: KeyMod.Shift | KeyCode.Enter,
weight: KeybindingWeight.EditorContrib
}
});
}
run(accessor: ServicesAccessor): any {
const extensionEditor = getExtensionEditor(accessor);
extensionEditor?.runFindAction(true);
}
});
registerThemingParticipant((theme: IColorTheme, collector: ICssStyleCollector) => {
const link = theme.getColor(textLinkForeground);
if (link) {
collector.addRule(`.monaco-workbench .extension-editor .content .details .additional-details-container .resources-container a.resource { color: ${link}; }`);
collector.addRule(`.monaco-workbench .extension-editor .content .feature-contributions a { color: ${link}; }`);
}
const activeLink = theme.getColor(textLinkActiveForeground);
if (activeLink) {
collector.addRule(`.monaco-workbench .extension-editor .content .details .additional-details-container .resources-container a.resource:hover,
.monaco-workbench .extension-editor .content .details .additional-details-container .resources-container a.resource:active { color: ${activeLink}; }`);
collector.addRule(`.monaco-workbench .extension-editor .content .feature-contributions a:hover,
.monaco-workbench .extension-editor .content .feature-contributions a:active { color: ${activeLink}; }`);
}
const buttonHoverBackgroundColor = theme.getColor(buttonHoverBackground);
if (buttonHoverBackgroundColor) {
collector.addRule(`.monaco-workbench .extension-editor .content > .details > .additional-details-container .categories-container > .categories > .category:hover { background-color: ${buttonHoverBackgroundColor}; border-color: ${buttonHoverBackgroundColor}; }`);
collector.addRule(`.monaco-workbench .extension-editor .content > .details > .additional-details-container .tags-container > .tags > .tag:hover { background-color: ${buttonHoverBackgroundColor}; border-color: ${buttonHoverBackgroundColor}; }`);
}
const buttonForegroundColor = theme.getColor(buttonForeground);
if (buttonForegroundColor) {
collector.addRule(`.monaco-workbench .extension-editor .content > .details > .additional-details-container .categories-container > .categories > .category:hover { color: ${buttonForegroundColor}; }`);
collector.addRule(`.monaco-workbench .extension-editor .content > .details > .additional-details-container .tags-container > .tags > .tag:hover { color: ${buttonForegroundColor}; }`);
}
});
function getExtensionEditor(accessor: ServicesAccessor): ExtensionEditor | null {
const activeEditorPane = accessor.get(IEditorService).activeEditorPane;
if (activeEditorPane instanceof ExtensionEditor) {
return activeEditorPane;
}
return null;
}
| src/vs/workbench/contrib/extensions/browser/extensionEditor.ts | 0 | https://github.com/microsoft/vscode/commit/65123b465ad226eef0ed555216e447f0a4047851 | [
0.0002277914172736928,
0.00017068334273062646,
0.00016287535254377872,
0.00016964854148682207,
0.000006050826868886361
]
|
{
"id": 0,
"code_window": [
"// Type definitions for @koa/cors 2.2\n",
"// Project: https://github.com/koajs/cors\n",
"// Definitions by: Xavier Stouder <https://github.com/Xstoudi>\n",
"// Izayoi Ko <https://github.com/izayoiko>\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"// Type definitions for @koa/cors 3.0\n"
],
"file_path": "types/koa__cors/index.d.ts",
"type": "replace",
"edit_start_line_idx": 0
} | import Koa = require('koa');
import cors = require('@koa/cors');
const app = new Koa();
app.use(cors());
// Trying using cors() passing in a function ..
function testCorsFunction(ctx: Koa.Context) {
const requestOrigin = ctx.request.origin;
return requestOrigin;
}
app.use(cors({ origin: testCorsFunction }));
| types/koa__cors/koa__cors-tests.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/4cd3d1995545cb7377b0ee9005b0592681e34ecd | [
0.00017280587053392082,
0.00017130552441813052,
0.00016980519285425544,
0.00017130552441813052,
0.0000015003388398326933
]
|
{
"id": 0,
"code_window": [
"// Type definitions for @koa/cors 2.2\n",
"// Project: https://github.com/koajs/cors\n",
"// Definitions by: Xavier Stouder <https://github.com/Xstoudi>\n",
"// Izayoi Ko <https://github.com/izayoiko>\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"// Type definitions for @koa/cors 3.0\n"
],
"file_path": "types/koa__cors/index.d.ts",
"type": "replace",
"edit_start_line_idx": 0
} | {
"extends": "dtslint/dt.json"
} | types/react-big-calendar/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/4cd3d1995545cb7377b0ee9005b0592681e34ecd | [
0.00017330351693090051,
0.00017330351693090051,
0.00017330351693090051,
0.00017330351693090051,
0
]
|
{
"id": 0,
"code_window": [
"// Type definitions for @koa/cors 2.2\n",
"// Project: https://github.com/koajs/cors\n",
"// Definitions by: Xavier Stouder <https://github.com/Xstoudi>\n",
"// Izayoi Ko <https://github.com/izayoiko>\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"// Type definitions for @koa/cors 3.0\n"
],
"file_path": "types/koa__cors/index.d.ts",
"type": "replace",
"edit_start_line_idx": 0
} | // Type definitions for @ember/ordered-set 2.0
// Project: https://github.com/emberjs/ember-ordered-set
// Definitions by: Chris Krycho <https://github.com/chriskrycho>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.0
/**
* The `OrderedSet` class lets you store unique values of any type, whether
* primitive values or object references. It is mostly similar to the native
* `Set` class introduced in ES2015.
*/
export default class OrderedSet<T = unknown> {
constructor();
// Disable this to let users call like `OrderedSet.create<string>();`. This
// is a rare case where it's preferable, because it's *much* briefer than
// `let set: OrderedSet<string> = OrderedSet.create();`. If TS could infer
// from usage what the type would be, this wouldn't be required, but until
// it does, this is better than *not* allowing it.
// tslint:disable-next-line:no-unnecessary-generics
static create<T = unknown>(): OrderedSet<T>;
add(value: T): this;
clear(): void;
delete(value: T): boolean;
forEach(callbackfn: (this: undefined, value: T, value2: T, set: OrderedSet<T>) => void): void;
forEach<Ctx>(callbackfn: (this: Ctx, value: T, value2: T, set: OrderedSet<T>) => void, context: Ctx): void;
has(value: T): boolean;
isEmpty(): boolean;
toArray(): T[];
copy(): OrderedSet<T>;
}
| types/ember__ordered-set/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/4cd3d1995545cb7377b0ee9005b0592681e34ecd | [
0.00024312364985235035,
0.00018853976507671177,
0.00016529759159311652,
0.0001728689094306901,
0.00003167899194522761
]
|
{
"id": 0,
"code_window": [
"// Type definitions for @koa/cors 2.2\n",
"// Project: https://github.com/koajs/cors\n",
"// Definitions by: Xavier Stouder <https://github.com/Xstoudi>\n",
"// Izayoi Ko <https://github.com/izayoiko>\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"// Type definitions for @koa/cors 3.0\n"
],
"file_path": "types/koa__cors/index.d.ts",
"type": "replace",
"edit_start_line_idx": 0
} | {
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"npm-naming": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
}
| types/nodemailer-smtp-pool/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/4cd3d1995545cb7377b0ee9005b0592681e34ecd | [
0.00017504917923361063,
0.0001731727534206584,
0.00017196428962051868,
0.00017273800040129572,
0.0000010676518513719202
]
|
{
"id": 1,
"code_window": [
"declare function cors(options?: cors.Options): Koa.Middleware;\n",
"\n",
"declare namespace cors {\n",
" interface Options {\n",
" origin?: ((ctx: Koa.Context) => string) | string;\n",
" allowMethods?: string[] | string;\n",
" exposeHeaders?: string[] | string;\n",
" allowHeaders?: string[] | string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" origin?: ((ctx: Koa.Context) => string) | ((ctx: Koa.Context) => PromiseLike<string>) | string;\n"
],
"file_path": "types/koa__cors/index.d.ts",
"type": "replace",
"edit_start_line_idx": 17
} | import Koa = require('koa');
import cors = require('@koa/cors');
const app = new Koa();
app.use(cors());
// Trying using cors() passing in a function ..
function testCorsFunction(ctx: Koa.Context) {
const requestOrigin = ctx.request.origin;
return requestOrigin;
}
app.use(cors({ origin: testCorsFunction }));
| types/koa__cors/koa__cors-tests.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/4cd3d1995545cb7377b0ee9005b0592681e34ecd | [
0.9981722831726074,
0.9969323873519897,
0.9956925511360168,
0.9969323873519897,
0.001239866018295288
]
|
{
"id": 1,
"code_window": [
"declare function cors(options?: cors.Options): Koa.Middleware;\n",
"\n",
"declare namespace cors {\n",
" interface Options {\n",
" origin?: ((ctx: Koa.Context) => string) | string;\n",
" allowMethods?: string[] | string;\n",
" exposeHeaders?: string[] | string;\n",
" allowHeaders?: string[] | string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" origin?: ((ctx: Koa.Context) => string) | ((ctx: Koa.Context) => PromiseLike<string>) | string;\n"
],
"file_path": "types/koa__cors/index.d.ts",
"type": "replace",
"edit_start_line_idx": 17
} | { "extends": "dtslint/dt.json" }
| types/yazl/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/4cd3d1995545cb7377b0ee9005b0592681e34ecd | [
0.00017143973673228174,
0.00017143973673228174,
0.00017143973673228174,
0.00017143973673228174,
0
]
|
{
"id": 1,
"code_window": [
"declare function cors(options?: cors.Options): Koa.Middleware;\n",
"\n",
"declare namespace cors {\n",
" interface Options {\n",
" origin?: ((ctx: Koa.Context) => string) | string;\n",
" allowMethods?: string[] | string;\n",
" exposeHeaders?: string[] | string;\n",
" allowHeaders?: string[] | string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" origin?: ((ctx: Koa.Context) => string) | ((ctx: Koa.Context) => PromiseLike<string>) | string;\n"
],
"file_path": "types/koa__cors/index.d.ts",
"type": "replace",
"edit_start_line_idx": 17
} | {
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"npm-naming": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
}
| types/oidc-token-manager/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/4cd3d1995545cb7377b0ee9005b0592681e34ecd | [
0.00017397507326677442,
0.00017018178186845034,
0.00016715774836484343,
0.00016970757860690355,
0.0000021717189611081267
]
|
{
"id": 1,
"code_window": [
"declare function cors(options?: cors.Options): Koa.Middleware;\n",
"\n",
"declare namespace cors {\n",
" interface Options {\n",
" origin?: ((ctx: Koa.Context) => string) | string;\n",
" allowMethods?: string[] | string;\n",
" exposeHeaders?: string[] | string;\n",
" allowHeaders?: string[] | string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" origin?: ((ctx: Koa.Context) => string) | ((ctx: Koa.Context) => PromiseLike<string>) | string;\n"
],
"file_path": "types/koa__cors/index.d.ts",
"type": "replace",
"edit_start_line_idx": 17
} | // Type definitions for ref-napi 1.4
// Project: https://github.com/node-ffi-napi/ref-napi
// Definitions by: Keerthi Niranjan <https://github.com/keerthi16>, Kiran Niranjan <https://github.com/KiranNiranjan>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
export interface Type {
/** The size in bytes required to hold this datatype. */
size: number;
/** The current level of indirection of the buffer. */
indirection: number;
/** To invoke when `ref.get` is invoked on a buffer of this type. */
get(buffer: Buffer, offset: number): any;
/** To invoke when `ref.set` is invoked on a buffer of this type. */
set(buffer: Buffer, offset: number, value: any): void;
/** The name to use during debugging for this datatype. */
name?: string;
/** The alignment of this datatype when placed inside a struct. */
alignment?: number;
}
/** A Buffer that references the C NULL pointer. */
export declare var NULL: Buffer;
/** A pointer-sized buffer pointing to NULL. */
export declare var NULL_POINTER: Buffer;
/** Get the memory address of buffer. */
export declare function address(buffer: Buffer): number;
/** Allocate the memory with the given value written to it. */
export declare function alloc(type: Type, value?: any): Buffer;
/** Allocate the memory with the given value written to it. */
export declare function alloc(type: string, value?: any): Buffer;
/**
* Allocate the memory with the given string written to it with the given
* encoding (defaults to utf8). The buffer is 1 byte longer than the
* string itself, and is NULL terminated.
*/
export declare function allocCString(string: string, encoding?: string): Buffer;
/** Coerce a type.*/
export declare function coerceType(type: Type): Type;
/** Coerce a type. String are looked up from the ref.types object. */
export declare function coerceType(type: string): Type;
/**
* Get value after dereferencing buffer.
* That is, first it checks the indirection count of buffer's type, and
* if it's greater than 1 then it merely returns another Buffer, but with
* one level less indirection.
*/
export declare function deref(buffer: Buffer): any;
/** Create clone of the type, with decremented indirection level by 1. */
export declare function derefType(type: Type): Type;
/** Create clone of the type, with decremented indirection level by 1. */
export declare function derefType(type: string): Type;
/** Represents the native endianness of the processor ("LE" or "BE"). */
export declare var endianness: string;
/** Check the indirection level and return a dereferenced when necessary. */
export declare function get(buffer: Buffer, offset?: number, type?: Type): any;
/** Check the indirection level and return a dereferenced when necessary. */
export declare function get(buffer: Buffer, offset?: number, type?: string): any;
/** Get type of the buffer. Create a default type when none exists. */
export declare function getType(buffer: Buffer): Type;
/** Check the NULL. */
export declare function isNull(buffer: Buffer): boolean;
/** Read C string until the first NULL. */
export declare function readCString(buffer: Buffer, offset?: number): string;
/**
* Read a big-endian signed 64-bit int.
* If there is losing precision, then return a string, otherwise a number.
* @return {number|string}
*/
export declare function readInt64BE(buffer: Buffer, offset?: number): any;
/**
* Read a little-endian signed 64-bit int.
* If there is losing precision, then return a string, otherwise a number.
* @return {number|string}
*/
export declare function readInt64LE(buffer: Buffer, offset?: number): any;
/** Read a JS Object that has previously been written. */
export declare function readObject(buffer: Buffer, offset?: number): Object;
/** Read data from the pointer. */
export declare function readPointer(buffer: Buffer, offset?: number,
length?: number): Buffer;
/**
* Read a big-endian unsigned 64-bit int.
* If there is losing precision, then return a string, otherwise a number.
* @return {number|string}
*/
export declare function readUInt64BE(buffer: Buffer, offset?: number): any;
/**
* Read a little-endian unsigned 64-bit int.
* If there is losing precision, then return a string, otherwise a number.
* @return {number|string}
*/
export declare function readUInt64LE(buffer: Buffer, offset?: number): any;
/** Create pointer to buffer. */
export declare function ref(buffer: Buffer): Buffer;
/** Create clone of the type, with incremented indirection level by 1. */
export declare function refType(type: Type): Type;
/** Create clone of the type, with incremented indirection level by 1. */
export declare function refType(type: string): Type;
/**
* Create buffer with the specified size, with the same address as source.
* This function "attaches" source to the returned buffer to prevent it from
* being garbage collected.
*/
export declare function reinterpret(buffer: Buffer, size: number,
offset?: number): Buffer;
/**
* Scan past the boundary of the buffer's length until it finds size number
* of aligned NULL bytes.
*/
export declare function reinterpretUntilZeros(buffer: Buffer, size: number,
offset?: number): Buffer;
/** Write pointer if the indirection is 1, otherwise write value. */
export declare function set(buffer: Buffer, offset: number, value: any, type?: Type): void;
/** Write pointer if the indirection is 1, otherwise write value. */
export declare function set(buffer: Buffer, offset: number, value: any, type?: string): void;
/** Write the string as a NULL terminated. Default encoding is utf8. */
export declare function writeCString(buffer: Buffer, offset: number,
string: string, encoding?: string): void;
/** Write a big-endian signed 64-bit int. */
export declare function writeInt64BE(buffer: Buffer, offset: number, input: number): void;
/** Write a big-endian signed 64-bit int. */
export declare function writeInt64BE(buffer: Buffer, offset: number, input: string): void;
/** Write a little-endian signed 64-bit int. */
export declare function writeInt64LE(buffer: Buffer, offset: number, input: number): void;
/** Write a little-endian signed 64-bit int. */
export declare function writeInt64LE(buffer: Buffer, offset: number, input: string): void;
/**
* Write the JS Object. This function "attaches" object to buffer to prevent
* it from being garbage collected.
*/
export declare function writeObject(buffer: Buffer, offset: number, object: Object): void;
/**
* Write the memory address of pointer to buffer at the specified offset. This
* function "attaches" object to buffer to prevent it from being garbage collected.
*/
export declare function writePointer(buffer: Buffer, offset: number,
pointer: Buffer): void;
/** Write a little-endian unsigned 64-bit int. */
export declare function writeUInt64BE(buffer: Buffer, offset: number, input: number): void;
/** Write a little-endian unsigned 64-bit int. */
export declare function writeUInt64BE(buffer: Buffer, offset: number, input: string): void;
/**
* Attach object to buffer such.
* It prevents object from being garbage collected until buffer does.
*/
export declare function _attach(buffer: Buffer, object: Object): void;
/** Same as ref.reinterpret, except that this version does not attach buffer. */
export declare function _reinterpret(buffer: Buffer, size: number,
offset?: number): Buffer;
/** Same as ref.reinterpretUntilZeros, except that this version does not attach buffer. */
export declare function _reinterpretUntilZeros(buffer: Buffer, size: number,
offset?: number): Buffer;
/** Same as ref.writePointer, except that this version does not attach pointer. */
export declare function _writePointer(buffer: Buffer, offset: number,
pointer: Buffer): void;
/** Same as ref.writeObject, except that this version does not attach object. */
export declare function _writeObject(buffer: Buffer, offset: number, object: Object): void;
/** Default types. */
export declare var types: {
void: Type; int64: Type; ushort: Type;
int: Type; uint64: Type; float: Type;
uint: Type; long: Type; double: Type;
int8: Type; ulong: Type; Object: Type;
uint8: Type; longlong: Type; CString: Type;
int16: Type; ulonglong: Type; bool: Type;
uint16: Type; char: Type; byte: Type;
int32: Type; uchar: Type; size_t: Type;
uint32: Type; short: Type;
};
| types/ref-napi/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/4cd3d1995545cb7377b0ee9005b0592681e34ecd | [
0.000196389650227502,
0.00017165027384180576,
0.0001643016585148871,
0.00017123192083090544,
0.000007359441497101216
]
|
{
"id": 2,
"code_window": [
"import cors = require('@koa/cors');\n",
"\n",
"const app = new Koa();\n",
"app.use(cors());\n",
"\n",
"// Trying using cors() passing in a function ..\n",
"function testCorsFunction(ctx: Koa.Context) {\n",
" const requestOrigin = ctx.request.origin;\n",
" return requestOrigin;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// Trying using cors() passing in a function...\n"
],
"file_path": "types/koa__cors/koa__cors-tests.ts",
"type": "replace",
"edit_start_line_idx": 6
} | // Type definitions for @koa/cors 2.2
// Project: https://github.com/koajs/cors
// Definitions by: Xavier Stouder <https://github.com/Xstoudi>
// Izayoi Ko <https://github.com/izayoiko>
// Steve Hipwell <https://github.com/stevehipwell>
// Steven McDowall <https://github.com/sjmcdowall>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import * as Koa from 'koa';
export = cors;
declare function cors(options?: cors.Options): Koa.Middleware;
declare namespace cors {
interface Options {
origin?: ((ctx: Koa.Context) => string) | string;
allowMethods?: string[] | string;
exposeHeaders?: string[] | string;
allowHeaders?: string[] | string;
maxAge?: number | string;
credentials?: boolean;
keepHeadersOnError?: boolean;
}
}
| types/koa__cors/index.d.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/4cd3d1995545cb7377b0ee9005b0592681e34ecd | [
0.0036369492299854755,
0.0013483542716130614,
0.00017959783144760877,
0.00022851582616567612,
0.0016184041742235422
]
|
{
"id": 2,
"code_window": [
"import cors = require('@koa/cors');\n",
"\n",
"const app = new Koa();\n",
"app.use(cors());\n",
"\n",
"// Trying using cors() passing in a function ..\n",
"function testCorsFunction(ctx: Koa.Context) {\n",
" const requestOrigin = ctx.request.origin;\n",
" return requestOrigin;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// Trying using cors() passing in a function...\n"
],
"file_path": "types/koa__cors/koa__cors-tests.ts",
"type": "replace",
"edit_start_line_idx": 6
} | {
"extends": "dtslint/dt.json"
}
| types/xmldoc/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/4cd3d1995545cb7377b0ee9005b0592681e34ecd | [
0.0001786768261808902,
0.0001786768261808902,
0.0001786768261808902,
0.0001786768261808902,
0
]
|
{
"id": 2,
"code_window": [
"import cors = require('@koa/cors');\n",
"\n",
"const app = new Koa();\n",
"app.use(cors());\n",
"\n",
"// Trying using cors() passing in a function ..\n",
"function testCorsFunction(ctx: Koa.Context) {\n",
" const requestOrigin = ctx.request.origin;\n",
" return requestOrigin;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// Trying using cors() passing in a function...\n"
],
"file_path": "types/koa__cors/koa__cors-tests.ts",
"type": "replace",
"edit_start_line_idx": 6
} | {
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"shelljs-exec-proxy-tests.ts"
]
}
| types/shelljs-exec-proxy/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/4cd3d1995545cb7377b0ee9005b0592681e34ecd | [
0.00017809733981266618,
0.0001767591602401808,
0.00017509424651507288,
0.00017708587984088808,
0.0000012475853736759746
]
|
{
"id": 2,
"code_window": [
"import cors = require('@koa/cors');\n",
"\n",
"const app = new Koa();\n",
"app.use(cors());\n",
"\n",
"// Trying using cors() passing in a function ..\n",
"function testCorsFunction(ctx: Koa.Context) {\n",
" const requestOrigin = ctx.request.origin;\n",
" return requestOrigin;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// Trying using cors() passing in a function...\n"
],
"file_path": "types/koa__cors/koa__cors-tests.ts",
"type": "replace",
"edit_start_line_idx": 6
} | {
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false],
"ban-types": [false],
"await-promise": [true, "Request"]
}
}
| types/gapi.client.gamesconfiguration/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/4cd3d1995545cb7377b0ee9005b0592681e34ecd | [
0.00017815626051742584,
0.00017815626051742584,
0.00017815626051742584,
0.00017815626051742584,
0
]
|
{
"id": 3,
"code_window": [
" const requestOrigin = ctx.request.origin;\n",
" return requestOrigin;\n",
"}\n",
"\n",
"app.use(cors({ origin: testCorsFunction }));\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"// Trying using cors() passing in a function that returns a promise...\n",
"function testCorsPromiseFunction(ctx: Koa.Context) {\n",
" const requestOrigin = ctx.request.origin;\n",
" return Promise.resolve(requestOrigin);\n",
"}\n",
"\n",
"app.use(cors({ origin: testCorsPromiseFunction }));"
],
"file_path": "types/koa__cors/koa__cors-tests.ts",
"type": "add",
"edit_start_line_idx": 13
} | import Koa = require('koa');
import cors = require('@koa/cors');
const app = new Koa();
app.use(cors());
// Trying using cors() passing in a function ..
function testCorsFunction(ctx: Koa.Context) {
const requestOrigin = ctx.request.origin;
return requestOrigin;
}
app.use(cors({ origin: testCorsFunction }));
| types/koa__cors/koa__cors-tests.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/4cd3d1995545cb7377b0ee9005b0592681e34ecd | [
0.9967899918556213,
0.5136703848838806,
0.030550802126526833,
0.5136703848838806,
0.4831196069717407
]
|
{
"id": 3,
"code_window": [
" const requestOrigin = ctx.request.origin;\n",
" return requestOrigin;\n",
"}\n",
"\n",
"app.use(cors({ origin: testCorsFunction }));\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"// Trying using cors() passing in a function that returns a promise...\n",
"function testCorsPromiseFunction(ctx: Koa.Context) {\n",
" const requestOrigin = ctx.request.origin;\n",
" return Promise.resolve(requestOrigin);\n",
"}\n",
"\n",
"app.use(cors({ origin: testCorsPromiseFunction }));"
],
"file_path": "types/koa__cors/koa__cors-tests.ts",
"type": "add",
"edit_start_line_idx": 13
} | import { getProxyForUrl } from "proxy-from-env";
// $ExpectType string
getProxyForUrl("http://microsoft.github.io/TypeSearch/");
| types/proxy-from-env/proxy-from-env-tests.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/4cd3d1995545cb7377b0ee9005b0592681e34ecd | [
0.00016880847397260368,
0.00016880847397260368,
0.00016880847397260368,
0.00016880847397260368,
0
]
|
{
"id": 3,
"code_window": [
" const requestOrigin = ctx.request.origin;\n",
" return requestOrigin;\n",
"}\n",
"\n",
"app.use(cors({ origin: testCorsFunction }));\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"// Trying using cors() passing in a function that returns a promise...\n",
"function testCorsPromiseFunction(ctx: Koa.Context) {\n",
" const requestOrigin = ctx.request.origin;\n",
" return Promise.resolve(requestOrigin);\n",
"}\n",
"\n",
"app.use(cors({ origin: testCorsPromiseFunction }));"
],
"file_path": "types/koa__cors/koa__cors-tests.ts",
"type": "add",
"edit_start_line_idx": 13
} | {
"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",
"simple-oauth2-tests.ts"
]
} | types/simple-oauth2/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/4cd3d1995545cb7377b0ee9005b0592681e34ecd | [
0.00017138628754764795,
0.0001708028867142275,
0.00017014407785609365,
0.00017087830929085612,
5.099262239127711e-7
]
|
{
"id": 3,
"code_window": [
" const requestOrigin = ctx.request.origin;\n",
" return requestOrigin;\n",
"}\n",
"\n",
"app.use(cors({ origin: testCorsFunction }));\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"// Trying using cors() passing in a function that returns a promise...\n",
"function testCorsPromiseFunction(ctx: Koa.Context) {\n",
" const requestOrigin = ctx.request.origin;\n",
" return Promise.resolve(requestOrigin);\n",
"}\n",
"\n",
"app.use(cors({ origin: testCorsPromiseFunction }));"
],
"file_path": "types/koa__cors/koa__cors-tests.ts",
"type": "add",
"edit_start_line_idx": 13
} | // Type definitions for website-scraper v1.2.x
// Project: https://github.com/s0ph1e/node-website-scraper
// Definitions by: Christian Rackerseder <https://github.com/screendriver>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="request" />
import * as request from 'request';
declare namespace websiteScraper {
interface Url {
url: string;
filename: string;
}
interface SubDirectory {
directory: string;
extensions: string[];
}
interface Source {
selector: string;
attr?: string;
}
interface RequestOptions {
headers: request.Headers;
}
interface Options {
urls: (string | Url)[];
directory: string;
urlFilter?: (url: string) => boolean;
filenameGenerator?: string;
defaultFilename?: string;
prettifyUrls?: boolean;
sources?: Source[];
subdirectories?: SubDirectory[] | null;
request?: RequestOptions;
recursive?: boolean;
maxDepth?: number;
ignoreErrors?: boolean;
maxRecursiveDepth?: number;
requestConcurrency?: number;
plugins?: object[];
}
interface Resource {
url: string;
filename: string;
assets: Resource[];
}
interface Callback {
(error: any | null, result: Resource[] | null): void;
}
interface Scrape {
(options: Options, callback: Callback): void;
(options: Options): Promise<Resource[]>;
}
}
declare const websiteScraper: websiteScraper.Scrape;
export = websiteScraper;
| types/website-scraper/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/4cd3d1995545cb7377b0ee9005b0592681e34ecd | [
0.0008814511820673943,
0.00027408235473558307,
0.00016525379032827914,
0.00016908120596781373,
0.00024808841408230364
]
|
{
"id": 0,
"code_window": [
"\ttriggerScrollFromMouseWheelEvent(browserEvent: IMouseWheelEvent) {\n",
"\t\tthis.view.triggerScrollFromMouseWheelEvent(browserEvent);\n",
"\t}\n",
"\n",
"\n",
"\tupdateElementHeight2(element: ICellViewModel, size: number): void {\n",
"\t\tconst index = this._getViewIndexUpperBound(element);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tisElementAboveViewport(index: number) {\n",
"\t\tconst elementTop = this.view.elementTop(index);\n",
"\t\tconst elementBottom = elementTop + this.view.elementHeight(index);\n",
"\n",
"\t\treturn elementBottom < this.scrollTop;\n",
"\t}\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "add",
"edit_start_line_idx": 898
} | /*---------------------------------------------------------------------------------------------
* 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 { DisposableStore } from 'vs/base/common/lifecycle';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import { CellKind } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { NotebookOptions } from 'vs/workbench/contrib/notebook/common/notebookOptions';
import { createNotebookCellList, setupInstantiationService, withTestNotebook } from 'vs/workbench/contrib/notebook/test/browser/testNotebookEditor';
suite('NotebookCellList', () => {
let disposables: DisposableStore;
let instantiationService: TestInstantiationService;
let notebookDefaultOptions: NotebookOptions;
let topInsertToolbarHeight: number;
suiteSetup(() => {
disposables = new DisposableStore();
instantiationService = setupInstantiationService(disposables);
notebookDefaultOptions = new NotebookOptions(instantiationService.get(IConfigurationService));
topInsertToolbarHeight = notebookDefaultOptions.computeTopInsertToolbarHeight();
});
suiteTeardown(() => disposables.dispose());
test('revealElementsInView: reveal fully visible cell should not scroll', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// scroll a bit, scrollTop to bottom: 5, 215
cellList.scrollTop = 5;
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 5);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
// reveal cell 1, top 50, bottom 150, which is fully visible in the viewport
cellList.revealElementsInView({ start: 1, end: 2 });
assert.deepStrictEqual(cellList.scrollTop, 5);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
// reveal cell 2, top 150, bottom 200, which is fully visible in the viewport
cellList.revealElementsInView({ start: 2, end: 3 });
assert.deepStrictEqual(cellList.scrollTop, 5);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
// reveal cell 3, top 200, bottom 300, which is partially visible in the viewport
cellList.revealElementsInView({ start: 3, end: 4 });
assert.deepStrictEqual(cellList.scrollTop, 90);
});
});
test('revealElementsInView: reveal partially visible cell', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 0);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 210);
// reveal cell 3, top 200, bottom 300, which is partially visible in the viewport
cellList.revealElementsInView({ start: 3, end: 4 });
assert.deepStrictEqual(cellList.scrollTop, 90);
// scroll to 5
cellList.scrollTop = 5;
assert.deepStrictEqual(cellList.scrollTop, 5);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
// reveal cell 0, top 0, bottom 50
cellList.revealElementsInView({ start: 0, end: 1 });
assert.deepStrictEqual(cellList.scrollTop, 0);
});
});
test('revealElementsInView: reveal cell out of viewport', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
// without additionalscrollheight, the last 20 px will always be hidden due to `topInsertToolbarHeight`
cellList.updateOptions({ additionalScrollHeight: 100 });
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 0);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 210);
cellList.revealElementsInView({ start: 4, end: 5 });
assert.deepStrictEqual(cellList.scrollTop, 140);
// assert.deepStrictEqual(cellList.getViewScrollBottom(), 330);
});
});
test('updateElementHeight', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 0);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 210);
cellList.updateElementHeight(0, 60);
assert.deepStrictEqual(cellList.scrollTop, 0);
// scroll to 5
cellList.scrollTop = 5;
assert.deepStrictEqual(cellList.scrollTop, 5);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
cellList.updateElementHeight(0, 80);
assert.deepStrictEqual(cellList.scrollTop, 5);
});
});
test('updateElementHeight with anchor #121723', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 0);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 210);
// scroll to 5
cellList.scrollTop = 5;
assert.deepStrictEqual(cellList.scrollTop, 5);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
cellList.setFocus([1]);
cellList.updateElementHeight2(viewModel.cellAt(0)!, 100);
assert.deepStrictEqual(cellList.scrollHeight, 400);
// the first cell grows, but it's partially visible, so we won't push down the focused cell
assert.deepStrictEqual(cellList.scrollTop, 55);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 265);
// cellList.updateElementHeight2(viewModel.cellAt(0)!, 50);
// assert.deepStrictEqual(cellList.scrollTop, 5);
// assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
// focus won't be visible after cell 0 grow to 250, so let's try to keep the focused cell visible
// cellList.updateElementHeight2(viewModel.cellAt(0)!, 250);
// assert.deepStrictEqual(cellList.scrollTop, 250 + 100 - cellList.renderHeight);
// assert.deepStrictEqual(cellList.getViewScrollBottom(), 250 + 100 - cellList.renderHeight + 210);
});
});
test('updateElementHeight with anchor #121723: focus element out of viewport', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 0);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 210);
cellList.setFocus([4]);
cellList.updateElementHeight2(viewModel.cellAt(1)!, 130);
// the focus cell is not in the viewport, the scrolltop should not change at all
assert.deepStrictEqual(cellList.scrollTop, 0);
});
});
test('updateElementHeight of cells out of viewport should not trigger scroll #121140', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 0);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 210);
cellList.setFocus([1]);
cellList.scrollTop = 80;
assert.deepStrictEqual(cellList.scrollTop, 80);
cellList.updateElementHeight2(viewModel.cellAt(0)!, 30);
assert.deepStrictEqual(cellList.scrollTop, 60);
});
});
});
| src/vs/workbench/contrib/notebook/test/browser/notebookCellList.test.ts | 1 | https://github.com/microsoft/vscode/commit/d6b581f218bc689cda2d3a009635c2df01a81984 | [
0.9968135952949524,
0.15579327940940857,
0.0001636604283703491,
0.0001695844839559868,
0.36161425709724426
]
|
{
"id": 0,
"code_window": [
"\ttriggerScrollFromMouseWheelEvent(browserEvent: IMouseWheelEvent) {\n",
"\t\tthis.view.triggerScrollFromMouseWheelEvent(browserEvent);\n",
"\t}\n",
"\n",
"\n",
"\tupdateElementHeight2(element: ICellViewModel, size: number): void {\n",
"\t\tconst index = this._getViewIndexUpperBound(element);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tisElementAboveViewport(index: number) {\n",
"\t\tconst elementTop = this.view.elementTop(index);\n",
"\t\tconst elementBottom = elementTop + this.view.elementHeight(index);\n",
"\n",
"\t\treturn elementBottom < this.scrollTop;\n",
"\t}\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "add",
"edit_start_line_idx": 898
} | /*---------------------------------------------------------------------------------------------
* 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 * as _url from 'url';
import * as _cp from 'child_process';
import * as _http from 'http';
import * as _os from 'os';
import { cwd } from 'vs/base/common/process';
import { dirname, extname, resolve, join } from 'vs/base/common/path';
import { parseArgs, buildHelpMessage, buildVersionMessage, OPTIONS, OptionDescriptions, ErrorReporter } from 'vs/platform/environment/node/argv';
import { NativeParsedArgs } from 'vs/platform/environment/common/argv';
import { createWaitMarkerFile } from 'vs/platform/environment/node/wait';
import { PipeCommand } from 'vs/workbench/api/node/extHostCLIServer';
import { hasStdinWithoutTty, getStdinFilePath, readFromStdin } from 'vs/platform/environment/node/stdin';
/*
* Implements a standalone CLI app that opens VS Code from a remote terminal.
* - In integrated terminals for remote windows this connects to the remote server though a pipe.
* The pipe is passed in env VSCODE_IPC_HOOK_CLI.
* - In external terminals for WSL this calls VS Code on the Windows side.
* The VS Code desktop executable path is passed in env VSCODE_CLIENT_COMMAND.
*/
interface ProductDescription {
productName: string;
version: string;
commit: string;
executableName: string;
}
interface RemoteParsedArgs extends NativeParsedArgs { 'gitCredential'?: string; 'openExternal'?: boolean; }
const isSupportedForCmd = (optionId: keyof RemoteParsedArgs) => {
switch (optionId) {
case 'user-data-dir':
case 'extensions-dir':
case 'export-default-configuration':
case 'install-source':
case 'driver':
case 'extensions-download-dir':
case 'builtin-extensions-dir':
case 'telemetry':
return false;
default:
return true;
}
};
const isSupportedForPipe = (optionId: keyof RemoteParsedArgs) => {
switch (optionId) {
case 'version':
case 'help':
case 'folder-uri':
case 'file-uri':
case 'add':
case 'diff':
case 'wait':
case 'goto':
case 'reuse-window':
case 'new-window':
case 'status':
case 'install-extension':
case 'uninstall-extension':
case 'list-extensions':
case 'force':
case 'show-versions':
case 'category':
case 'verbose':
case 'remote':
return true;
default:
return false;
}
};
const cliPipe = process.env['VSCODE_IPC_HOOK_CLI'] as string;
const cliCommand = process.env['VSCODE_CLIENT_COMMAND'] as string;
const cliCommandCwd = process.env['VSCODE_CLIENT_COMMAND_CWD'] as string;
const cliRemoteAuthority = process.env['VSCODE_CLI_AUTHORITY'] as string;
const cliStdInFilePath = process.env['VSCODE_STDIN_FILE_PATH'] as string;
export function main(desc: ProductDescription, args: string[]): void {
if (!cliPipe && !cliCommand) {
console.log('Command is only available in WSL or inside a Visual Studio Code terminal.');
return;
}
// take the local options and remove the ones that don't apply
const options: OptionDescriptions<RemoteParsedArgs> = { ...OPTIONS };
const isSupported = cliCommand ? isSupportedForCmd : isSupportedForPipe;
for (const optionId in OPTIONS) {
const optId = <keyof RemoteParsedArgs>optionId;
if (!isSupported(optId)) {
delete options[optId];
}
}
if (cliPipe) {
options['openExternal'] = { type: 'boolean' };
}
const errorReporter : ErrorReporter = {
onMultipleValues: (id: string, usedValue: string) => {
console.error(`Option ${id} can only be defined once. Using value ${usedValue}.`);
},
onUnknownOption: (id: string) => {
console.error(`Ignoring option ${id}: not supported for ${desc.executableName}.`);
},
onDeprecatedOption: (deprecatedOption: string, actualOption: string) => {
console.warn(`Option '${deprecatedOption}' is deprecated, please use '${actualOption}' instead`);
}
};
const parsedArgs = parseArgs(args, options, errorReporter);
const mapFileUri = cliRemoteAuthority ? mapFileToRemoteUri : (uri: string) => uri;
const verbose = !!parsedArgs['verbose'];
if (parsedArgs.help) {
console.log(buildHelpMessage(desc.productName, desc.executableName, desc.version, options));
return;
}
if (parsedArgs.version) {
console.log(buildVersionMessage(desc.version, desc.commit));
return;
}
if (cliPipe) {
if (parsedArgs['openExternal']) {
openInBrowser(parsedArgs['_'], verbose);
return;
}
}
let remote: string | null | undefined = parsedArgs.remote;
if (remote === 'local' || remote === 'false' || remote === '') {
remote = null; // null represent a local window
}
const folderURIs = (parsedArgs['folder-uri'] || []).map(mapFileUri);
parsedArgs['folder-uri'] = folderURIs;
const fileURIs = (parsedArgs['file-uri'] || []).map(mapFileUri);
parsedArgs['file-uri'] = fileURIs;
const inputPaths = parsedArgs['_'];
let hasReadStdinArg = false;
for (let input of inputPaths) {
if (input === '-') {
hasReadStdinArg = true;
} else {
translatePath(input, mapFileUri, folderURIs, fileURIs);
}
}
parsedArgs['_'] = [];
if (hasReadStdinArg && fileURIs.length === 0 && folderURIs.length === 0 && hasStdinWithoutTty()) {
try {
let stdinFilePath = cliStdInFilePath;
if (!stdinFilePath) {
stdinFilePath = getStdinFilePath();
readFromStdin(stdinFilePath, verbose); // throws error if file can not be written
}
// Make sure to open tmp file
translatePath(stdinFilePath, mapFileUri, folderURIs, fileURIs);
// Enable --wait to get all data and ignore adding this to history
parsedArgs.wait = true;
parsedArgs['skip-add-to-recently-opened'] = true;
console.log(`Reading from stdin via: ${stdinFilePath}`);
} catch (e) {
console.log(`Failed to create file to read via stdin: ${e.toString()}`);
}
}
if (parsedArgs.extensionDevelopmentPath) {
parsedArgs.extensionDevelopmentPath = parsedArgs.extensionDevelopmentPath.map(p => mapFileUri(pathToURI(p).href));
}
if (parsedArgs.extensionTestsPath) {
parsedArgs.extensionTestsPath = mapFileUri(pathToURI(parsedArgs['extensionTestsPath']).href);
}
const crashReporterDirectory = parsedArgs['crash-reporter-directory'];
if (crashReporterDirectory !== undefined && !crashReporterDirectory.match(/^([a-zA-Z]:[\\\/])/)) {
console.log(`The crash reporter directory '${crashReporterDirectory}' must be an absolute Windows path (e.g. c:/crashes)`);
return;
}
if (cliCommand) {
if (parsedArgs['install-extension'] !== undefined || parsedArgs['uninstall-extension'] !== undefined || parsedArgs['list-extensions']) {
const cmdLine: string[] = [];
parsedArgs['install-extension']?.forEach(id => cmdLine.push('--install-extension', id));
parsedArgs['uninstall-extension']?.forEach(id => cmdLine.push('--uninstall-extension', id));
['list-extensions', 'force', 'show-versions', 'category'].forEach(opt => {
const value = parsedArgs[<keyof NativeParsedArgs>opt];
if (value !== undefined) {
cmdLine.push(`--${opt}=${value}`);
}
});
const cp = _cp.fork(join(__dirname, 'main.js'), cmdLine, { stdio: 'inherit' });
cp.on('error', err => console.log(err));
return;
}
let newCommandline: string[] = [];
for (let key in parsedArgs) {
let val = parsedArgs[key as keyof typeof parsedArgs];
if (typeof val === 'boolean') {
if (val) {
newCommandline.push('--' + key);
}
} else if (Array.isArray(val)) {
for (let entry of val) {
newCommandline.push(`--${key}=${entry.toString()}`);
}
} else if (val) {
newCommandline.push(`--${key}=${val.toString()}`);
}
}
if (remote !== null) {
newCommandline.push(`--remote=${remote || cliRemoteAuthority}`);
}
const ext = extname(cliCommand);
if (ext === '.bat' || ext === '.cmd') {
const processCwd = cliCommandCwd || cwd();
if (verbose) {
console.log(`Invoking: cmd.exe /C ${cliCommand} ${newCommandline.join(' ')} in ${processCwd}`);
}
_cp.spawn('cmd.exe', ['/C', cliCommand, ...newCommandline], {
stdio: 'inherit',
cwd: processCwd
});
} else {
const cliCwd = dirname(cliCommand);
const env = { ...process.env, ELECTRON_RUN_AS_NODE: '1' };
newCommandline.unshift('--ms-enable-electron-run-as-node');
newCommandline.unshift('resources/app/out/cli.js');
if (verbose) {
console.log(`Invoking: cd "${cliCwd}" && ELECTRON_RUN_AS_NODE=1 "${cliCommand}" "${newCommandline.join('" "')}"`);
}
_cp.spawn(cliCommand, newCommandline, { cwd: cliCwd, env, stdio: ['inherit'] });
}
} else {
if (parsedArgs.status) {
sendToPipe({
type: 'status'
}, verbose).then((res: string) => {
console.log(res);
});
return;
}
if (parsedArgs['install-extension'] !== undefined || parsedArgs['uninstall-extension'] !== undefined || parsedArgs['list-extensions']) {
sendToPipe({
type: 'extensionManagement',
list: parsedArgs['list-extensions'] ? { showVersions: parsedArgs['show-versions'], category: parsedArgs['category'] } : undefined,
install: asExtensionIdOrVSIX(parsedArgs['install-extension']),
uninstall: asExtensionIdOrVSIX(parsedArgs['uninstall-extension']),
force: parsedArgs['force']
}, verbose).then((res: string) => {
console.log(res);
});
return;
}
let waitMarkerFilePath: string | undefined = undefined;
if (parsedArgs['wait']) {
if (!fileURIs.length) {
console.log('At least one file must be provided to wait for.');
return;
}
waitMarkerFilePath = createWaitMarkerFile(verbose);
}
sendToPipe({
type: 'open',
fileURIs,
folderURIs,
diffMode: parsedArgs.diff,
addMode: parsedArgs.add,
gotoLineMode: parsedArgs.goto,
forceReuseWindow: parsedArgs['reuse-window'],
forceNewWindow: parsedArgs['new-window'],
waitMarkerFilePath,
remoteAuthority: remote
}, verbose);
if (waitMarkerFilePath) {
waitForFileDeleted(waitMarkerFilePath);
}
}
}
async function waitForFileDeleted(path: string) {
while (_fs.existsSync(path)) {
await new Promise(res => setTimeout(res, 1000));
}
}
function openInBrowser(args: string[], verbose: boolean) {
let uris: string[] = [];
for (let location of args) {
try {
if (/^(http|https|file):\/\//.test(location)) {
uris.push(_url.parse(location).href);
} else {
uris.push(pathToURI(location).href);
}
} catch (e) {
console.log(`Invalid url: ${location}`);
}
}
if (uris.length) {
sendToPipe({
type: 'openExternal',
uris
}, verbose);
}
}
function sendToPipe(args: PipeCommand, verbose: boolean): Promise<any> {
if (verbose) {
console.log(JSON.stringify(args, null, ' '));
}
return new Promise<string>(resolve => {
const message = JSON.stringify(args);
if (!cliPipe) {
console.log('Message ' + message);
resolve('');
return;
}
const opts: _http.RequestOptions = {
socketPath: cliPipe,
path: '/',
method: 'POST'
};
const req = _http.request(opts, res => {
const chunks: string[] = [];
res.setEncoding('utf8');
res.on('data', chunk => {
chunks.push(chunk);
});
res.on('error', () => fatal('Error in response'));
res.on('end', () => {
resolve(chunks.join(''));
});
});
req.on('error', () => fatal('Error in request'));
req.write(message);
req.end();
});
}
function asExtensionIdOrVSIX(inputs: string[] | undefined) {
return inputs?.map(input => /\.vsix$/i.test(input) ? pathToURI(input).href : input);
}
function fatal(err: any): void {
console.error('Unable to connect to VS Code server.');
console.error(err);
process.exit(1);
}
const preferredCwd = process.env.PWD || cwd(); // prefer process.env.PWD as it does not follow symlinks
function pathToURI(input: string): _url.URL {
input = input.trim();
input = resolve(preferredCwd, input);
return _url.pathToFileURL(input);
}
function translatePath(input: string, mapFileUri: (input: string) => string, folderURIS: string[], fileURIS: string[]) {
let url = pathToURI(input);
let mappedUri = mapFileUri(url.href);
try {
let stat = _fs.lstatSync(_fs.realpathSync(input));
if (stat.isFile()) {
fileURIS.push(mappedUri);
} else if (stat.isDirectory()) {
folderURIS.push(mappedUri);
} else if (input === '/dev/null') {
// handle /dev/null passed to us by external tools such as `git difftool`
fileURIS.push(mappedUri);
}
} catch (e) {
if (e.code === 'ENOENT') {
fileURIS.push(mappedUri);
} else {
console.log(`Problem accessing file ${input}. Ignoring file`, e);
}
}
}
function mapFileToRemoteUri(uri: string): string {
return uri.replace(/^file:\/\//, 'vscode-remote://' + cliRemoteAuthority);
}
let [, , productName, version, commit, executableName, ...remainingArgs] = process.argv;
main({ productName, version, commit, executableName }, remainingArgs);
| src/vs/server/remoteCli.ts | 0 | https://github.com/microsoft/vscode/commit/d6b581f218bc689cda2d3a009635c2df01a81984 | [
0.00017648142238613218,
0.00017237139400094748,
0.00016580273222643882,
0.0001733409590087831,
0.0000028589615794771817
]
|
{
"id": 0,
"code_window": [
"\ttriggerScrollFromMouseWheelEvent(browserEvent: IMouseWheelEvent) {\n",
"\t\tthis.view.triggerScrollFromMouseWheelEvent(browserEvent);\n",
"\t}\n",
"\n",
"\n",
"\tupdateElementHeight2(element: ICellViewModel, size: number): void {\n",
"\t\tconst index = this._getViewIndexUpperBound(element);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tisElementAboveViewport(index: number) {\n",
"\t\tconst elementTop = this.view.elementTop(index);\n",
"\t\tconst elementBottom = elementTop + this.view.elementHeight(index);\n",
"\n",
"\t\treturn elementBottom < this.scrollTop;\n",
"\t}\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "add",
"edit_start_line_idx": 898
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/**
* Extracted from json.ts to keep json nls free.
*/
import { localize } from 'vs/nls';
import { ParseErrorCode } from './json';
export function getParseErrorMessage(errorCode: ParseErrorCode): string {
switch (errorCode) {
case ParseErrorCode.InvalidSymbol: return localize('error.invalidSymbol', 'Invalid symbol');
case ParseErrorCode.InvalidNumberFormat: return localize('error.invalidNumberFormat', 'Invalid number format');
case ParseErrorCode.PropertyNameExpected: return localize('error.propertyNameExpected', 'Property name expected');
case ParseErrorCode.ValueExpected: return localize('error.valueExpected', 'Value expected');
case ParseErrorCode.ColonExpected: return localize('error.colonExpected', 'Colon expected');
case ParseErrorCode.CommaExpected: return localize('error.commaExpected', 'Comma expected');
case ParseErrorCode.CloseBraceExpected: return localize('error.closeBraceExpected', 'Closing brace expected');
case ParseErrorCode.CloseBracketExpected: return localize('error.closeBracketExpected', 'Closing bracket expected');
case ParseErrorCode.EndOfFileExpected: return localize('error.endOfFileExpected', 'End of file expected');
default:
return '';
}
}
| src/vs/base/common/jsonErrorMessages.ts | 0 | https://github.com/microsoft/vscode/commit/d6b581f218bc689cda2d3a009635c2df01a81984 | [
0.00017701498290989548,
0.00017373741138726473,
0.00016816859715618193,
0.00017602865409571677,
0.000003958281013183296
]
|
{
"id": 0,
"code_window": [
"\ttriggerScrollFromMouseWheelEvent(browserEvent: IMouseWheelEvent) {\n",
"\t\tthis.view.triggerScrollFromMouseWheelEvent(browserEvent);\n",
"\t}\n",
"\n",
"\n",
"\tupdateElementHeight2(element: ICellViewModel, size: number): void {\n",
"\t\tconst index = this._getViewIndexUpperBound(element);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tisElementAboveViewport(index: number) {\n",
"\t\tconst elementTop = this.view.elementTop(index);\n",
"\t\tconst elementBottom = elementTop + this.view.elementHeight(index);\n",
"\n",
"\t\treturn elementBottom < this.scrollTop;\n",
"\t}\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "add",
"edit_start_line_idx": 898
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./media/keybindings';
import * as nls from 'vs/nls';
import { OS } from 'vs/base/common/platform';
import { Disposable, toDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { Event, Emitter } from 'vs/base/common/event';
import { KeybindingLabel } from 'vs/base/browser/ui/keybindingLabel/keybindingLabel';
import { Widget } from 'vs/base/browser/ui/widget';
import { KeyCode } from 'vs/base/common/keyCodes';
import { ResolvedKeybinding } from 'vs/base/common/keybindings';
import * as dom from 'vs/base/browser/dom';
import { IKeyboardEvent, StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ICodeEditor, IOverlayWidget, IOverlayWidgetPosition } from 'vs/editor/browser/editorBrowser';
import { attachInputBoxStyler, attachKeybindingLabelStyler, attachStylerCallback } from 'vs/platform/theme/common/styler';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { editorWidgetBackground, editorWidgetForeground, widgetShadow } from 'vs/platform/theme/common/colorRegistry';
import { ScrollType } from 'vs/editor/common/editorCommon';
import { SearchWidget, SearchOptions } from 'vs/workbench/contrib/preferences/browser/preferencesWidgets';
import { withNullAsUndefined } from 'vs/base/common/types';
import { Promises, timeout } from 'vs/base/common/async';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
export interface KeybindingsSearchOptions extends SearchOptions {
recordEnter?: boolean;
quoteRecordedKeys?: boolean;
}
export class KeybindingsSearchWidget extends SearchWidget {
private _firstPart: ResolvedKeybinding | null;
private _chordPart: ResolvedKeybinding | null;
private _inputValue: string;
private readonly recordDisposables = this._register(new DisposableStore());
private _onKeybinding = this._register(new Emitter<[ResolvedKeybinding | null, ResolvedKeybinding | null]>());
readonly onKeybinding: Event<[ResolvedKeybinding | null, ResolvedKeybinding | null]> = this._onKeybinding.event;
private _onEnter = this._register(new Emitter<void>());
readonly onEnter: Event<void> = this._onEnter.event;
private _onEscape = this._register(new Emitter<void>());
readonly onEscape: Event<void> = this._onEscape.event;
private _onBlur = this._register(new Emitter<void>());
readonly onBlur: Event<void> = this._onBlur.event;
constructor(parent: HTMLElement, options: KeybindingsSearchOptions,
@IContextViewService contextViewService: IContextViewService,
@IInstantiationService instantiationService: IInstantiationService,
@IThemeService themeService: IThemeService,
@IContextKeyService contextKeyService: IContextKeyService,
@IKeybindingService keybindingService: IKeybindingService,
) {
super(parent, options, contextViewService, instantiationService, themeService, contextKeyService, keybindingService);
this._register(attachInputBoxStyler(this.inputBox, themeService));
this._register(toDisposable(() => this.stopRecordingKeys()));
this._firstPart = null;
this._chordPart = null;
this._inputValue = '';
this._reset();
}
override clear(): void {
this._reset();
super.clear();
}
startRecordingKeys(): void {
this.recordDisposables.add(dom.addDisposableListener(this.inputBox.inputElement, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => this._onKeyDown(new StandardKeyboardEvent(e))));
this.recordDisposables.add(dom.addDisposableListener(this.inputBox.inputElement, dom.EventType.BLUR, () => this._onBlur.fire()));
this.recordDisposables.add(dom.addDisposableListener(this.inputBox.inputElement, dom.EventType.INPUT, () => {
// Prevent other characters from showing up
this.setInputValue(this._inputValue);
}));
}
stopRecordingKeys(): void {
this._reset();
this.recordDisposables.clear();
}
setInputValue(value: string): void {
this._inputValue = value;
this.inputBox.value = this._inputValue;
}
private _reset() {
this._firstPart = null;
this._chordPart = null;
}
private _onKeyDown(keyboardEvent: IKeyboardEvent): void {
keyboardEvent.preventDefault();
keyboardEvent.stopPropagation();
const options = this.options as KeybindingsSearchOptions;
if (!options.recordEnter && keyboardEvent.equals(KeyCode.Enter)) {
this._onEnter.fire();
return;
}
if (keyboardEvent.equals(KeyCode.Escape)) {
this._onEscape.fire();
return;
}
this.printKeybinding(keyboardEvent);
}
private printKeybinding(keyboardEvent: IKeyboardEvent): void {
const keybinding = this.keybindingService.resolveKeyboardEvent(keyboardEvent);
const info = `code: ${keyboardEvent.browserEvent.code}, keyCode: ${keyboardEvent.browserEvent.keyCode}, key: ${keyboardEvent.browserEvent.key} => UI: ${keybinding.getAriaLabel()}, user settings: ${keybinding.getUserSettingsLabel()}, dispatch: ${keybinding.getDispatchParts()[0]}`;
const options = this.options as KeybindingsSearchOptions;
const hasFirstPart = (this._firstPart && this._firstPart.getDispatchParts()[0] !== null);
const hasChordPart = (this._chordPart && this._chordPart.getDispatchParts()[0] !== null);
if (hasFirstPart && hasChordPart) {
// Reset
this._firstPart = keybinding;
this._chordPart = null;
} else if (!hasFirstPart) {
this._firstPart = keybinding;
} else {
this._chordPart = keybinding;
}
let value = '';
if (this._firstPart) {
value = (this._firstPart.getUserSettingsLabel() || '');
}
if (this._chordPart) {
value = value + ' ' + this._chordPart.getUserSettingsLabel();
}
this.setInputValue(options.quoteRecordedKeys ? `"${value}"` : value);
this.inputBox.inputElement.title = info;
this._onKeybinding.fire([this._firstPart, this._chordPart]);
}
}
export class DefineKeybindingWidget extends Widget {
private static readonly WIDTH = 400;
private static readonly HEIGHT = 110;
private _domNode: FastDomNode<HTMLElement>;
private _keybindingInputWidget: KeybindingsSearchWidget;
private _outputNode: HTMLElement;
private _showExistingKeybindingsNode: HTMLElement;
private _firstPart: ResolvedKeybinding | null = null;
private _chordPart: ResolvedKeybinding | null = null;
private _isVisible: boolean = false;
private _onHide = this._register(new Emitter<void>());
private _onDidChange = this._register(new Emitter<string>());
onDidChange: Event<string> = this._onDidChange.event;
private _onShowExistingKeybindings = this._register(new Emitter<string | null>());
readonly onShowExistingKeybidings: Event<string | null> = this._onShowExistingKeybindings.event;
private disposables = this._register(new DisposableStore());
private keybindingLabelStylers = this.disposables.add(new DisposableStore());
constructor(
parent: HTMLElement | null,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IThemeService private readonly themeService: IThemeService
) {
super();
this._domNode = createFastDomNode(document.createElement('div'));
this._domNode.setDisplay('none');
this._domNode.setClassName('defineKeybindingWidget');
this._domNode.setWidth(DefineKeybindingWidget.WIDTH);
this._domNode.setHeight(DefineKeybindingWidget.HEIGHT);
const message = nls.localize('defineKeybinding.initial', "Press desired key combination and then press ENTER.");
dom.append(this._domNode.domNode, dom.$('.message', undefined, message));
this._register(attachStylerCallback(this.themeService, { editorWidgetBackground, editorWidgetForeground, widgetShadow }, colors => {
if (colors.editorWidgetBackground) {
this._domNode.domNode.style.backgroundColor = colors.editorWidgetBackground.toString();
} else {
this._domNode.domNode.style.backgroundColor = '';
}
if (colors.editorWidgetForeground) {
this._domNode.domNode.style.color = colors.editorWidgetForeground.toString();
} else {
this._domNode.domNode.style.color = '';
}
if (colors.widgetShadow) {
this._domNode.domNode.style.boxShadow = `0 2px 8px ${colors.widgetShadow}`;
} else {
this._domNode.domNode.style.boxShadow = '';
}
}));
this._keybindingInputWidget = this._register(this.instantiationService.createInstance(KeybindingsSearchWidget, this._domNode.domNode, { ariaLabel: message, history: [] }));
this._keybindingInputWidget.startRecordingKeys();
this._register(this._keybindingInputWidget.onKeybinding(keybinding => this.onKeybinding(keybinding)));
this._register(this._keybindingInputWidget.onEnter(() => this.hide()));
this._register(this._keybindingInputWidget.onEscape(() => this.onCancel()));
this._register(this._keybindingInputWidget.onBlur(() => this.onCancel()));
this._outputNode = dom.append(this._domNode.domNode, dom.$('.output'));
this._showExistingKeybindingsNode = dom.append(this._domNode.domNode, dom.$('.existing'));
if (parent) {
dom.append(parent, this._domNode.domNode);
}
}
get domNode(): HTMLElement {
return this._domNode.domNode;
}
define(): Promise<string | null> {
this._keybindingInputWidget.clear();
return Promises.withAsyncBody<string | null>(async (c) => {
if (!this._isVisible) {
this._isVisible = true;
this._domNode.setDisplay('block');
this._firstPart = null;
this._chordPart = null;
this._keybindingInputWidget.setInputValue('');
dom.clearNode(this._outputNode);
dom.clearNode(this._showExistingKeybindingsNode);
// Input is not getting focus without timeout in safari
// https://github.com/microsoft/vscode/issues/108817
await timeout(0);
this._keybindingInputWidget.focus();
}
const disposable = this._onHide.event(() => {
c(this.getUserSettingsLabel());
disposable.dispose();
});
});
}
layout(layout: dom.Dimension): void {
const top = Math.round((layout.height - DefineKeybindingWidget.HEIGHT) / 2);
this._domNode.setTop(top);
const left = Math.round((layout.width - DefineKeybindingWidget.WIDTH) / 2);
this._domNode.setLeft(left);
}
printExisting(numberOfExisting: number): void {
if (numberOfExisting > 0) {
const existingElement = dom.$('span.existingText');
const text = numberOfExisting === 1 ? nls.localize('defineKeybinding.oneExists', "1 existing command has this keybinding", numberOfExisting) : nls.localize('defineKeybinding.existing', "{0} existing commands have this keybinding", numberOfExisting);
dom.append(existingElement, document.createTextNode(text));
this._showExistingKeybindingsNode.appendChild(existingElement);
existingElement.onmousedown = (e) => { e.preventDefault(); };
existingElement.onmouseup = (e) => { e.preventDefault(); };
existingElement.onclick = () => { this._onShowExistingKeybindings.fire(this.getUserSettingsLabel()); };
}
}
private onKeybinding(keybinding: [ResolvedKeybinding | null, ResolvedKeybinding | null]): void {
const [firstPart, chordPart] = keybinding;
this._firstPart = firstPart;
this._chordPart = chordPart;
dom.clearNode(this._outputNode);
dom.clearNode(this._showExistingKeybindingsNode);
this.keybindingLabelStylers.clear();
const firstLabel = new KeybindingLabel(this._outputNode, OS);
firstLabel.set(withNullAsUndefined(this._firstPart));
this.keybindingLabelStylers.add(attachKeybindingLabelStyler(firstLabel, this.themeService));
if (this._chordPart) {
this._outputNode.appendChild(document.createTextNode(nls.localize('defineKeybinding.chordsTo', "chord to")));
const chordLabel = new KeybindingLabel(this._outputNode, OS);
chordLabel.set(this._chordPart);
this.keybindingLabelStylers.add(attachKeybindingLabelStyler(chordLabel, this.themeService));
}
const label = this.getUserSettingsLabel();
if (label) {
this._onDidChange.fire(label);
}
}
private getUserSettingsLabel(): string | null {
let label: string | null = null;
if (this._firstPart) {
label = this._firstPart.getUserSettingsLabel();
if (this._chordPart) {
label = label + ' ' + this._chordPart.getUserSettingsLabel();
}
}
return label;
}
private onCancel(): void {
this._firstPart = null;
this._chordPart = null;
this.hide();
}
private hide(): void {
this._domNode.setDisplay('none');
this._isVisible = false;
this._onHide.fire();
}
}
export class DefineKeybindingOverlayWidget extends Disposable implements IOverlayWidget {
private static readonly ID = 'editor.contrib.defineKeybindingWidget';
private readonly _widget: DefineKeybindingWidget;
constructor(private _editor: ICodeEditor,
@IInstantiationService instantiationService: IInstantiationService
) {
super();
this._widget = instantiationService.createInstance(DefineKeybindingWidget, null);
this._editor.addOverlayWidget(this);
}
getId(): string {
return DefineKeybindingOverlayWidget.ID;
}
getDomNode(): HTMLElement {
return this._widget.domNode;
}
getPosition(): IOverlayWidgetPosition {
return {
preference: null
};
}
override dispose(): void {
this._editor.removeOverlayWidget(this);
super.dispose();
}
start(): Promise<string | null> {
if (this._editor.hasModel()) {
this._editor.revealPositionInCenterIfOutsideViewport(this._editor.getPosition(), ScrollType.Smooth);
}
const layoutInfo = this._editor.getLayoutInfo();
this._widget.layout(new dom.Dimension(layoutInfo.width, layoutInfo.height));
return this._widget.define();
}
}
| src/vs/workbench/contrib/preferences/browser/keybindingWidgets.ts | 0 | https://github.com/microsoft/vscode/commit/d6b581f218bc689cda2d3a009635c2df01a81984 | [
0.00017423255485482514,
0.00016983068780973554,
0.00016546002007089555,
0.00016967214469332248,
0.0000022621366042585578
]
|
{
"id": 1,
"code_window": [
"\t\t\treturn;\n",
"\t\t}\n",
"\n",
"\t\tif (index < this.firstVisibleIndex) {\n",
"\t\t\t// update element above viewport\n",
"\t\t\tconst oldHeight = this.elementHeight(element);\n",
"\t\t\tconst delta = oldHeight - size;\n",
"\t\t\t// const date = new Date();\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tif (this.isElementAboveViewport(index)) {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 905
} | /*---------------------------------------------------------------------------------------------
* 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 { DisposableStore } from 'vs/base/common/lifecycle';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import { CellKind } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { NotebookOptions } from 'vs/workbench/contrib/notebook/common/notebookOptions';
import { createNotebookCellList, setupInstantiationService, withTestNotebook } from 'vs/workbench/contrib/notebook/test/browser/testNotebookEditor';
suite('NotebookCellList', () => {
let disposables: DisposableStore;
let instantiationService: TestInstantiationService;
let notebookDefaultOptions: NotebookOptions;
let topInsertToolbarHeight: number;
suiteSetup(() => {
disposables = new DisposableStore();
instantiationService = setupInstantiationService(disposables);
notebookDefaultOptions = new NotebookOptions(instantiationService.get(IConfigurationService));
topInsertToolbarHeight = notebookDefaultOptions.computeTopInsertToolbarHeight();
});
suiteTeardown(() => disposables.dispose());
test('revealElementsInView: reveal fully visible cell should not scroll', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// scroll a bit, scrollTop to bottom: 5, 215
cellList.scrollTop = 5;
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 5);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
// reveal cell 1, top 50, bottom 150, which is fully visible in the viewport
cellList.revealElementsInView({ start: 1, end: 2 });
assert.deepStrictEqual(cellList.scrollTop, 5);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
// reveal cell 2, top 150, bottom 200, which is fully visible in the viewport
cellList.revealElementsInView({ start: 2, end: 3 });
assert.deepStrictEqual(cellList.scrollTop, 5);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
// reveal cell 3, top 200, bottom 300, which is partially visible in the viewport
cellList.revealElementsInView({ start: 3, end: 4 });
assert.deepStrictEqual(cellList.scrollTop, 90);
});
});
test('revealElementsInView: reveal partially visible cell', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 0);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 210);
// reveal cell 3, top 200, bottom 300, which is partially visible in the viewport
cellList.revealElementsInView({ start: 3, end: 4 });
assert.deepStrictEqual(cellList.scrollTop, 90);
// scroll to 5
cellList.scrollTop = 5;
assert.deepStrictEqual(cellList.scrollTop, 5);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
// reveal cell 0, top 0, bottom 50
cellList.revealElementsInView({ start: 0, end: 1 });
assert.deepStrictEqual(cellList.scrollTop, 0);
});
});
test('revealElementsInView: reveal cell out of viewport', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
// without additionalscrollheight, the last 20 px will always be hidden due to `topInsertToolbarHeight`
cellList.updateOptions({ additionalScrollHeight: 100 });
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 0);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 210);
cellList.revealElementsInView({ start: 4, end: 5 });
assert.deepStrictEqual(cellList.scrollTop, 140);
// assert.deepStrictEqual(cellList.getViewScrollBottom(), 330);
});
});
test('updateElementHeight', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 0);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 210);
cellList.updateElementHeight(0, 60);
assert.deepStrictEqual(cellList.scrollTop, 0);
// scroll to 5
cellList.scrollTop = 5;
assert.deepStrictEqual(cellList.scrollTop, 5);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
cellList.updateElementHeight(0, 80);
assert.deepStrictEqual(cellList.scrollTop, 5);
});
});
test('updateElementHeight with anchor #121723', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 0);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 210);
// scroll to 5
cellList.scrollTop = 5;
assert.deepStrictEqual(cellList.scrollTop, 5);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
cellList.setFocus([1]);
cellList.updateElementHeight2(viewModel.cellAt(0)!, 100);
assert.deepStrictEqual(cellList.scrollHeight, 400);
// the first cell grows, but it's partially visible, so we won't push down the focused cell
assert.deepStrictEqual(cellList.scrollTop, 55);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 265);
// cellList.updateElementHeight2(viewModel.cellAt(0)!, 50);
// assert.deepStrictEqual(cellList.scrollTop, 5);
// assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
// focus won't be visible after cell 0 grow to 250, so let's try to keep the focused cell visible
// cellList.updateElementHeight2(viewModel.cellAt(0)!, 250);
// assert.deepStrictEqual(cellList.scrollTop, 250 + 100 - cellList.renderHeight);
// assert.deepStrictEqual(cellList.getViewScrollBottom(), 250 + 100 - cellList.renderHeight + 210);
});
});
test('updateElementHeight with anchor #121723: focus element out of viewport', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 0);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 210);
cellList.setFocus([4]);
cellList.updateElementHeight2(viewModel.cellAt(1)!, 130);
// the focus cell is not in the viewport, the scrolltop should not change at all
assert.deepStrictEqual(cellList.scrollTop, 0);
});
});
test('updateElementHeight of cells out of viewport should not trigger scroll #121140', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 0);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 210);
cellList.setFocus([1]);
cellList.scrollTop = 80;
assert.deepStrictEqual(cellList.scrollTop, 80);
cellList.updateElementHeight2(viewModel.cellAt(0)!, 30);
assert.deepStrictEqual(cellList.scrollTop, 60);
});
});
});
| src/vs/workbench/contrib/notebook/test/browser/notebookCellList.test.ts | 1 | https://github.com/microsoft/vscode/commit/d6b581f218bc689cda2d3a009635c2df01a81984 | [
0.00017646458582021296,
0.00017025842680595815,
0.00016484931984450668,
0.000171078514540568,
0.0000033044159408746054
]
|
{
"id": 1,
"code_window": [
"\t\t\treturn;\n",
"\t\t}\n",
"\n",
"\t\tif (index < this.firstVisibleIndex) {\n",
"\t\t\t// update element above viewport\n",
"\t\t\tconst oldHeight = this.elementHeight(element);\n",
"\t\t\tconst delta = oldHeight - size;\n",
"\t\t\t// const date = new Date();\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tif (this.isElementAboveViewport(index)) {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 905
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { localize } from 'vs/nls';
import { GettingStartedInputSerializer, GettingStartedPage, inWelcomeContext } from 'vs/workbench/contrib/welcome/gettingStarted/browser/gettingStarted';
import { Registry } from 'vs/platform/registry/common/platform';
import { EditorExtensions, IEditorFactoryRegistry } from 'vs/workbench/common/editor';
import { MenuId, registerAction2, Action2 } from 'vs/platform/actions/common/actions';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IEditorService, SIDE_GROUP } from 'vs/workbench/services/editor/common/editorService';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { KeyCode } from 'vs/base/common/keyCodes';
import { EditorPaneDescriptor, IEditorPaneRegistry } from 'vs/workbench/browser/editor';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { IWalkthroughsService } from 'vs/workbench/contrib/welcome/gettingStarted/browser/gettingStartedService';
import { GettingStartedInput } from 'vs/workbench/contrib/welcome/gettingStarted/browser/gettingStartedInput';
import { Extensions as WorkbenchExtensions, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions';
import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry';
import { workbenchConfigurationNodeBase } from 'vs/workbench/common/configuration';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { EditorResolution } from 'vs/platform/editor/common/editor';
import { CommandsRegistry, ICommandService } from 'vs/platform/commands/common/commands';
import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';
import { IWorkbenchAssignmentService } from 'vs/workbench/services/assignment/common/assignmentService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { isLinux, isMacintosh, isWindows, OperatingSystem as OS } from 'vs/base/common/platform';
import { IExtensionManagementServerService } from 'vs/workbench/services/extensionManagement/common/extensionManagement';
export * as icons from 'vs/workbench/contrib/welcome/gettingStarted/browser/gettingStartedIcons';
registerAction2(class extends Action2 {
constructor() {
super({
id: 'workbench.action.openWalkthrough',
title: localize('miGetStarted', "Get Started"),
category: localize('help', "Help"),
f1: true,
menu: {
id: MenuId.MenubarHelpMenu,
group: '1_welcome',
order: 1,
}
});
}
public run(accessor: ServicesAccessor, walkthroughID: string | { category: string, step: string } | undefined, toSide: boolean | undefined) {
const editorGroupsService = accessor.get(IEditorGroupsService);
const instantiationService = accessor.get(IInstantiationService);
const editorService = accessor.get(IEditorService);
if (walkthroughID) {
const selectedCategory = typeof walkthroughID === 'string' ? walkthroughID : walkthroughID.category;
const selectedStep = typeof walkthroughID === 'string' ? undefined : walkthroughID.step;
// Try first to select the walkthrough on an active welcome page with no selected walkthrough
for (const group of editorGroupsService.groups) {
if (group.activeEditor instanceof GettingStartedInput) {
if (!group.activeEditor.selectedCategory) {
(group.activeEditorPane as GettingStartedPage).makeCategoryVisibleWhenAvailable(selectedCategory, selectedStep);
return;
}
}
}
// Otherwise, try to find a welcome input somewhere with no selected walkthrough, and open it to this one.
const result = editorService.findEditors({ typeId: GettingStartedInput.ID, editorId: undefined, resource: GettingStartedInput.RESOURCE });
for (const { editor, groupId } of result) {
if (editor instanceof GettingStartedInput) {
if (!editor.selectedCategory) {
editor.selectedCategory = selectedCategory;
editor.selectedStep = selectedStep;
editorService.openEditor(editor, { revealIfOpened: true, override: EditorResolution.DISABLED }, groupId);
return;
}
}
}
// Otherwise, just make a new one.
editorService.openEditor(instantiationService.createInstance(GettingStartedInput, { selectedCategory: selectedCategory, selectedStep: selectedStep }), {}, toSide ? SIDE_GROUP : undefined);
} else {
editorService.openEditor(new GettingStartedInput({}), {});
}
}
});
Registry.as<IEditorFactoryRegistry>(EditorExtensions.EditorFactory).registerEditorSerializer(GettingStartedInput.ID, GettingStartedInputSerializer);
Registry.as<IEditorPaneRegistry>(EditorExtensions.EditorPane).registerEditorPane(
EditorPaneDescriptor.create(
GettingStartedPage,
GettingStartedPage.ID,
localize('getStarted', "Get Started")
),
[
new SyncDescriptor(GettingStartedInput)
]
);
const category = localize('getStarted', "Get Started");
registerAction2(class extends Action2 {
constructor() {
super({
id: 'welcome.goBack',
title: localize('welcome.goBack', "Go Back"),
category,
keybinding: {
weight: KeybindingWeight.EditorContrib,
primary: KeyCode.Escape,
when: inWelcomeContext
},
precondition: ContextKeyExpr.equals('activeEditor', 'gettingStartedPage'),
f1: true
});
}
run(accessor: ServicesAccessor) {
const editorService = accessor.get(IEditorService);
const editorPane = editorService.activeEditorPane;
if (editorPane instanceof GettingStartedPage) {
editorPane.escape();
}
}
});
CommandsRegistry.registerCommand({
id: 'walkthroughs.selectStep',
handler: (accessor, stepID: string) => {
const editorService = accessor.get(IEditorService);
const editorPane = editorService.activeEditorPane;
if (editorPane instanceof GettingStartedPage) {
editorPane.selectStepLoose(stepID);
} else {
console.error('Cannot run walkthroughs.selectStep outside of walkthrough context');
}
}
});
registerAction2(class extends Action2 {
constructor() {
super({
id: 'welcome.markStepComplete',
title: localize('welcome.markStepComplete', "Mark Step Complete"),
category,
});
}
run(accessor: ServicesAccessor, arg: string) {
if (!arg) { return; }
const gettingStartedService = accessor.get(IWalkthroughsService);
gettingStartedService.progressStep(arg);
}
});
registerAction2(class extends Action2 {
constructor() {
super({
id: 'welcome.markStepIncomplete',
title: localize('welcome.markStepInomplete', "Mark Step Incomplete"),
category,
});
}
run(accessor: ServicesAccessor, arg: string) {
if (!arg) { return; }
const gettingStartedService = accessor.get(IWalkthroughsService);
gettingStartedService.deprogressStep(arg);
}
});
registerAction2(class extends Action2 {
constructor() {
super({
id: 'welcome.showAllWalkthroughs',
title: localize('welcome.showAllWalkthroughs', "Open Walkthrough..."),
category,
f1: true,
});
}
async run(accessor: ServicesAccessor) {
const commandService = accessor.get(ICommandService);
const contextService = accessor.get(IContextKeyService);
const quickInputService = accessor.get(IQuickInputService);
const gettingStartedService = accessor.get(IWalkthroughsService);
const categories = gettingStartedService.getWalkthroughs();
const selection = await quickInputService.pick(categories
.filter(c => contextService.contextMatchesRules(c.when))
.map(x => ({
id: x.id,
label: x.title,
detail: x.description,
description: x.source,
})), { canPickMany: false, matchOnDescription: true, matchOnDetail: true, title: localize('pickWalkthroughs', "Open Walkthrough...") });
if (selection) {
commandService.executeCommand('workbench.action.openWalkthrough', selection.id);
}
}
});
const prefersReducedMotionConfig = {
...workbenchConfigurationNodeBase,
'properties': {
'workbench.welcomePage.preferReducedMotion': {
scope: ConfigurationScope.APPLICATION,
type: 'boolean',
default: true,
description: localize('workbench.welcomePage.preferReducedMotion', "When enabled, reduce motion in welcome page.")
}
}
} as const;
const prefersStandardMotionConfig = {
...workbenchConfigurationNodeBase,
'properties': {
'workbench.welcomePage.preferReducedMotion': {
scope: ConfigurationScope.APPLICATION,
type: 'boolean',
default: false,
description: localize('workbench.welcomePage.preferReducedMotion', "When enabled, reduce motion in welcome page.")
}
}
} as const;
class WorkbenchConfigurationContribution {
constructor(
@IInstantiationService _instantiationService: IInstantiationService,
@IConfigurationService _configurationService: IConfigurationService,
@IWorkbenchAssignmentService _experimentSevice: IWorkbenchAssignmentService,
) {
this.registerConfigs(_experimentSevice);
}
private async registerConfigs(_experimentSevice: IWorkbenchAssignmentService) {
const preferReduced = await _experimentSevice.getTreatment('welcomePage.preferReducedMotion').catch(e => false);
if (preferReduced) {
configurationRegistry.updateConfigurations({ add: [prefersReducedMotionConfig], remove: [prefersStandardMotionConfig] });
}
else {
configurationRegistry.updateConfigurations({ add: [prefersStandardMotionConfig], remove: [prefersReducedMotionConfig] });
}
}
}
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench)
.registerWorkbenchContribution(WorkbenchConfigurationContribution, LifecyclePhase.Restored);
export const WorkspacePlatform = new RawContextKey<'mac' | 'linux' | 'windows' | 'webworker' | undefined>('workspacePlatform', undefined, localize('workspacePlatform', "The platform of the current workspace, which in remote or serverless contexts may be different from the platform of the UI"));
class WorkspacePlatformContribution {
constructor(
@IExtensionManagementServerService private readonly extensionManagementServerService: IExtensionManagementServerService,
@IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService,
@IContextKeyService private readonly contextService: IContextKeyService,
) {
this.remoteAgentService.getEnvironment().then(env => {
const remoteOS = env?.os;
const remotePlatform = remoteOS === OS.Macintosh ? 'mac'
: remoteOS === OS.Windows ? 'windows'
: remoteOS === OS.Linux ? 'linux'
: undefined;
if (remotePlatform) {
WorkspacePlatform.bindTo(this.contextService).set(remotePlatform);
} else if (this.extensionManagementServerService.localExtensionManagementServer) {
if (isMacintosh) {
WorkspacePlatform.bindTo(this.contextService).set('mac');
} else if (isLinux) {
WorkspacePlatform.bindTo(this.contextService).set('linux');
} else if (isWindows) {
WorkspacePlatform.bindTo(this.contextService).set('windows');
}
} else if (this.extensionManagementServerService.webExtensionManagementServer) {
WorkspacePlatform.bindTo(this.contextService).set('webworker');
} else {
console.error('Error: Unable to detect workspace platform');
}
});
}
}
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench)
.registerWorkbenchContribution(WorkspacePlatformContribution, LifecyclePhase.Restored);
const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration);
configurationRegistry.registerConfiguration({
...workbenchConfigurationNodeBase,
properties: {
'workbench.welcomePage.walkthroughs.openOnInstall': {
scope: ConfigurationScope.MACHINE,
type: 'boolean',
default: true,
description: localize('workbench.welcomePage.walkthroughs.openOnInstall', "When enabled, an extension's walkthrough will open upon install of the extension.")
}
}
});
| src/vs/workbench/contrib/welcome/gettingStarted/browser/gettingStarted.contribution.ts | 0 | https://github.com/microsoft/vscode/commit/d6b581f218bc689cda2d3a009635c2df01a81984 | [
0.00019281014101579785,
0.0001727839990053326,
0.00016674162179697305,
0.00017254063277505338,
0.000004404521860124078
]
|
{
"id": 1,
"code_window": [
"\t\t\treturn;\n",
"\t\t}\n",
"\n",
"\t\tif (index < this.firstVisibleIndex) {\n",
"\t\t\t// update element above viewport\n",
"\t\t\tconst oldHeight = this.elementHeight(element);\n",
"\t\t\tconst delta = oldHeight - size;\n",
"\t\t\t// const date = new Date();\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tif (this.isElementAboveViewport(index)) {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 905
} | /*---------------------------------------------------------------------------------------------
* 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 { URI } from 'vs/base/common/uri';
import { CodeEditorStateFlag, EditorState } from 'vs/editor/browser/core/editorState';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { Position } from 'vs/editor/common/core/position';
import { Selection } from 'vs/editor/common/core/selection';
import { ITextModel } from 'vs/editor/common/model';
interface IStubEditorState {
model?: { uri?: URI, version?: number };
position?: Position;
selection?: Selection;
scroll?: { left?: number, top?: number };
}
suite('Editor Core - Editor State', () => {
const allFlags = (
CodeEditorStateFlag.Value
| CodeEditorStateFlag.Selection
| CodeEditorStateFlag.Position
| CodeEditorStateFlag.Scroll
);
test('empty editor state should be valid', () => {
let result = validate({}, {});
assert.strictEqual(result, true);
});
test('different model URIs should be invalid', () => {
let result = validate(
{ model: { uri: URI.parse('http://test1') } },
{ model: { uri: URI.parse('http://test2') } }
);
assert.strictEqual(result, false);
});
test('different model versions should be invalid', () => {
let result = validate(
{ model: { version: 1 } },
{ model: { version: 2 } }
);
assert.strictEqual(result, false);
});
test('different positions should be invalid', () => {
let result = validate(
{ position: new Position(1, 2) },
{ position: new Position(2, 3) }
);
assert.strictEqual(result, false);
});
test('different selections should be invalid', () => {
let result = validate(
{ selection: new Selection(1, 2, 3, 4) },
{ selection: new Selection(5, 2, 3, 4) }
);
assert.strictEqual(result, false);
});
test('different scroll positions should be invalid', () => {
let result = validate(
{ scroll: { left: 1, top: 2 } },
{ scroll: { left: 3, top: 2 } }
);
assert.strictEqual(result, false);
});
function validate(source: IStubEditorState, target: IStubEditorState) {
let sourceEditor = createEditor(source),
targetEditor = createEditor(target);
let result = new EditorState(sourceEditor, allFlags).validate(targetEditor);
return result;
}
function createEditor({ model, position, selection, scroll }: IStubEditorState = {}): ICodeEditor {
let mappedModel = model ? { uri: model.uri ? model.uri : URI.parse('http://dummy.org'), getVersionId: () => model.version } : null;
return {
getModel: (): ITextModel => <any>mappedModel,
getPosition: (): Position | undefined => position,
getSelection: (): Selection | undefined => selection,
getScrollLeft: (): number | undefined => scroll && scroll.left,
getScrollTop: (): number | undefined => scroll && scroll.top
} as ICodeEditor;
}
});
| src/vs/editor/test/browser/core/editorState.test.ts | 0 | https://github.com/microsoft/vscode/commit/d6b581f218bc689cda2d3a009635c2df01a81984 | [
0.00017688859952613711,
0.00017478453810326755,
0.0001702221343293786,
0.00017472867330070585,
0.0000017937442180482321
]
|
{
"id": 1,
"code_window": [
"\t\t\treturn;\n",
"\t\t}\n",
"\n",
"\t\tif (index < this.firstVisibleIndex) {\n",
"\t\t\t// update element above viewport\n",
"\t\t\tconst oldHeight = this.elementHeight(element);\n",
"\t\t\tconst delta = oldHeight - size;\n",
"\t\t\t// const date = new Date();\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tif (this.isElementAboveViewport(index)) {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 905
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Increase max listeners for event emitters
require('events').EventEmitter.defaultMaxListeners = 100;
const gulp = require('gulp');
const path = require('path');
const nodeUtil = require('util');
const es = require('event-stream');
const filter = require('gulp-filter');
const util = require('./lib/util');
const task = require('./lib/task');
const watcher = require('./lib/watch');
const createReporter = require('./lib/reporter').createReporter;
const glob = require('glob');
const root = path.dirname(__dirname);
const commit = util.getVersion(root);
const plumber = require('gulp-plumber');
const ext = require('./lib/extensions');
const extensionsPath = path.join(path.dirname(__dirname), 'extensions');
// To save 250ms for each gulp startup, we are caching the result here
// const compilations = glob.sync('**/tsconfig.json', {
// cwd: extensionsPath,
// ignore: ['**/out/**', '**/node_modules/**']
// });
const compilations = [
'configuration-editing/build/tsconfig.json',
'configuration-editing/tsconfig.json',
'css-language-features/client/tsconfig.json',
'css-language-features/server/tsconfig.json',
'debug-auto-launch/tsconfig.json',
'debug-server-ready/tsconfig.json',
'emmet/tsconfig.json',
'extension-editing/tsconfig.json',
'git/tsconfig.json',
'git-base/tsconfig.json',
'github-authentication/tsconfig.json',
'github/tsconfig.json',
'grunt/tsconfig.json',
'gulp/tsconfig.json',
'html-language-features/client/tsconfig.json',
'html-language-features/server/tsconfig.json',
'image-preview/tsconfig.json',
'ipynb/tsconfig.json',
'jake/tsconfig.json',
'json-language-features/client/tsconfig.json',
'json-language-features/server/tsconfig.json',
'markdown-language-features/preview-src/tsconfig.json',
'markdown-language-features/tsconfig.json',
'markdown-math/tsconfig.json',
'merge-conflict/tsconfig.json',
'microsoft-authentication/tsconfig.json',
'npm/tsconfig.json',
'php-language-features/tsconfig.json',
'search-result/tsconfig.json',
'simple-browser/tsconfig.json',
'typescript-language-features/test-workspace/tsconfig.json',
'typescript-language-features/tsconfig.json',
'vscode-api-tests/tsconfig.json',
'vscode-colorize-tests/tsconfig.json',
'vscode-custom-editor-tests/tsconfig.json',
'vscode-notebook-tests/tsconfig.json',
'vscode-test-resolver/tsconfig.json'
];
const getBaseUrl = out => `https://ticino.blob.core.windows.net/sourcemaps/${commit}/${out}`;
const tasks = compilations.map(function (tsconfigFile) {
const absolutePath = path.join(extensionsPath, tsconfigFile);
const relativeDirname = path.dirname(tsconfigFile);
const overrideOptions = {};
overrideOptions.sourceMap = true;
const name = relativeDirname.replace(/\//g, '-');
const root = path.join('extensions', relativeDirname);
const srcBase = path.join(root, 'src');
const src = path.join(srcBase, '**');
const srcOpts = { cwd: path.dirname(__dirname), base: srcBase };
const out = path.join(root, 'out');
const baseUrl = getBaseUrl(out);
let headerId, headerOut;
let index = relativeDirname.indexOf('/');
if (index < 0) {
headerId = 'vscode.' + relativeDirname;
headerOut = 'out';
} else {
headerId = 'vscode.' + relativeDirname.substr(0, index);
headerOut = relativeDirname.substr(index + 1) + '/out';
}
function createPipeline(build, emitError) {
const nlsDev = require('vscode-nls-dev');
const tsb = require('gulp-tsb');
const sourcemaps = require('gulp-sourcemaps');
const reporter = createReporter('extensions');
overrideOptions.inlineSources = Boolean(build);
overrideOptions.base = path.dirname(absolutePath);
const compilation = tsb.create(absolutePath, overrideOptions, false, err => reporter(err.toString()));
const pipeline = function () {
const input = es.through();
const tsFilter = filter(['**/*.ts', '!**/lib/lib*.d.ts', '!**/node_modules/**'], { restore: true });
const output = input
.pipe(plumber({
errorHandler: function (err) {
if (err && !err.__reporter__) {
reporter(err);
}
}
}))
.pipe(tsFilter)
.pipe(util.loadSourcemaps())
.pipe(compilation())
.pipe(build ? nlsDev.rewriteLocalizeCalls() : es.through())
.pipe(build ? util.stripSourceMappingURL() : es.through())
.pipe(sourcemaps.write('.', {
sourceMappingURL: !build ? null : f => `${baseUrl}/${f.relative}.map`,
addComment: !!build,
includeContent: !!build,
sourceRoot: '../src'
}))
.pipe(tsFilter.restore)
.pipe(build ? nlsDev.bundleMetaDataFiles(headerId, headerOut) : es.through())
// Filter out *.nls.json file. We needed them only to bundle meta data file.
.pipe(filter(['**', '!**/*.nls.json']))
.pipe(reporter.end(emitError));
return es.duplex(input, output);
};
// add src-stream for project files
pipeline.tsProjectSrc = () => {
return compilation.src(srcOpts);
};
return pipeline;
}
const cleanTask = task.define(`clean-extension-${name}`, util.rimraf(out));
const compileTask = task.define(`compile-extension:${name}`, task.series(cleanTask, () => {
const pipeline = createPipeline(false, true);
const nonts = gulp.src(src, srcOpts).pipe(filter(['**', '!**/*.ts']));
const input = es.merge(nonts, pipeline.tsProjectSrc());
return input
.pipe(pipeline())
.pipe(gulp.dest(out));
}));
const watchTask = task.define(`watch-extension:${name}`, task.series(cleanTask, () => {
const pipeline = createPipeline(false);
const nonts = gulp.src(src, srcOpts).pipe(filter(['**', '!**/*.ts']));
const input = es.merge(nonts, pipeline.tsProjectSrc());
const watchInput = watcher(src, { ...srcOpts, ...{ readDelay: 200 } });
return watchInput
.pipe(util.incremental(pipeline, input))
.pipe(gulp.dest(out));
}));
const compileBuildTask = task.define(`compile-build-extension-${name}`, task.series(cleanTask, () => {
const pipeline = createPipeline(true, true);
const nonts = gulp.src(src, srcOpts).pipe(filter(['**', '!**/*.ts']));
const input = es.merge(nonts, pipeline.tsProjectSrc());
return input
.pipe(pipeline())
.pipe(gulp.dest(out));
}));
// Tasks
gulp.task(compileTask);
gulp.task(watchTask);
return { compileTask, watchTask, compileBuildTask };
});
const compileExtensionsTask = task.define('compile-extensions', task.parallel(...tasks.map(t => t.compileTask)));
gulp.task(compileExtensionsTask);
exports.compileExtensionsTask = compileExtensionsTask;
const watchExtensionsTask = task.define('watch-extensions', task.parallel(...tasks.map(t => t.watchTask)));
gulp.task(watchExtensionsTask);
exports.watchExtensionsTask = watchExtensionsTask;
const compileExtensionsBuildLegacyTask = task.define('compile-extensions-build-legacy', task.parallel(...tasks.map(t => t.compileBuildTask)));
gulp.task(compileExtensionsBuildLegacyTask);
//#region Extension media
const compileExtensionMediaTask = task.define('compile-extension-media', () => ext.buildExtensionMedia(false));
gulp.task(compileExtensionMediaTask);
exports.compileExtensionMediaTask = compileExtensionMediaTask;
const watchExtensionMedia = task.define('watch-extension-media', () => ext.buildExtensionMedia(true));
gulp.task(watchExtensionMedia);
exports.watchExtensionMedia = watchExtensionMedia;
const compileExtensionMediaBuildTask = task.define('compile-extension-media-build', () => ext.buildExtensionMedia(false, '.build/extensions'));
gulp.task(compileExtensionMediaBuildTask);
exports.compileExtensionMediaBuildTask = compileExtensionMediaBuildTask;
//#endregion
//#region Azure Pipelines
const cleanExtensionsBuildTask = task.define('clean-extensions-build', util.rimraf('.build/extensions'));
const compileExtensionsBuildTask = task.define('compile-extensions-build', task.series(
cleanExtensionsBuildTask,
task.define('bundle-extensions-build', () => ext.packageLocalExtensionsStream(false).pipe(gulp.dest('.build'))),
task.define('bundle-marketplace-extensions-build', () => ext.packageMarketplaceExtensionsStream(false).pipe(gulp.dest('.build'))),
));
gulp.task(compileExtensionsBuildTask);
gulp.task(task.define('extensions-ci', task.series(compileExtensionsBuildTask, compileExtensionMediaBuildTask)));
exports.compileExtensionsBuildTask = compileExtensionsBuildTask;
//#endregion
const compileWebExtensionsTask = task.define('compile-web', () => buildWebExtensions(false));
gulp.task(compileWebExtensionsTask);
exports.compileWebExtensionsTask = compileWebExtensionsTask;
const watchWebExtensionsTask = task.define('watch-web', () => buildWebExtensions(true));
gulp.task(watchWebExtensionsTask);
exports.watchWebExtensionsTask = watchWebExtensionsTask;
async function buildWebExtensions(isWatch) {
const webpackConfigLocations = await nodeUtil.promisify(glob)(
path.join(extensionsPath, '**', 'extension-browser.webpack.config.js'),
{ ignore: ['**/node_modules'] }
);
return ext.webpackExtensions('packaging web extension', isWatch, webpackConfigLocations.map(configPath => ({ configPath })));
}
| build/gulpfile.extensions.js | 0 | https://github.com/microsoft/vscode/commit/d6b581f218bc689cda2d3a009635c2df01a81984 | [
0.0009187116520479321,
0.00020304869394749403,
0.0001686952164163813,
0.00017350309644825757,
0.00014610648213420063
]
|
{
"id": 2,
"code_window": [
"\n",
"\t\t\t\t// the first cell grows, but it's partially visible, so we won't push down the focused cell\n",
"\t\t\t\tassert.deepStrictEqual(cellList.scrollTop, 55);\n",
"\t\t\t\tassert.deepStrictEqual(cellList.getViewScrollBottom(), 265);\n",
"\n",
"\t\t\t\t// cellList.updateElementHeight2(viewModel.cellAt(0)!, 50);\n",
"\t\t\t\t// assert.deepStrictEqual(cellList.scrollTop, 5);\n",
"\t\t\t\t// assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);\n",
"\n",
"\t\t\t\t// focus won't be visible after cell 0 grow to 250, so let's try to keep the focused cell visible\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tcellList.updateElementHeight2(viewModel.cellAt(0)!, 50);\n",
"\t\t\t\tassert.deepStrictEqual(cellList.scrollTop, 5);\n",
"\t\t\t\tassert.deepStrictEqual(cellList.getViewScrollBottom(), 215);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/test/browser/notebookCellList.test.ts",
"type": "replace",
"edit_start_line_idx": 236
} | /*---------------------------------------------------------------------------------------------
* 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 { IMouseWheelEvent } from 'vs/base/browser/mouseEvent';
import { IListRenderer, IListVirtualDelegate, ListError } from 'vs/base/browser/ui/list/list';
import { IListStyles, IStyleController } from 'vs/base/browser/ui/list/listWidget';
import { Emitter, Event } from 'vs/base/common/event';
import { DisposableStore, IDisposable, MutableDisposable } from 'vs/base/common/lifecycle';
import { isMacintosh } from 'vs/base/common/platform';
import { ScrollEvent } from 'vs/base/common/scrollable';
import { Range } from 'vs/editor/common/core/range';
import { TrackedRangeStickiness } from 'vs/editor/common/model';
import { PrefixSumComputer } from 'vs/editor/common/viewModel/prefixSumComputer';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IListService, IWorkbenchListOptions, WorkbenchList } from 'vs/platform/list/browser/listService';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { CellRevealPosition, CellRevealType, CursorAtBoundary, getVisibleCells, ICellViewModel, CellEditState, CellFocusMode, NOTEBOOK_CELL_LIST_FOCUSED, ICellOutputViewModel } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { CellViewModel, NotebookViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModel';
import { diff, NOTEBOOK_EDITOR_CURSOR_BOUNDARY, CellKind, SelectionStateType } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { ICellRange, cellRangesToIndexes, reduceCellRanges, cellRangesEqual } from 'vs/workbench/contrib/notebook/common/notebookRange';
import { clamp } from 'vs/base/common/numbers';
import { ISplice } from 'vs/base/common/sequence';
import { ViewContext } from 'vs/workbench/contrib/notebook/browser/viewModel/viewContext';
import { BaseCellRenderTemplate, INotebookCellList } from 'vs/workbench/contrib/notebook/browser/view/notebookRenderingCommon';
import { FastDomNode } from 'vs/base/browser/fastDomNode';
export interface IFocusNextPreviousDelegate {
onFocusNext(applyFocusNext: () => void): void;
onFocusPrevious(applyFocusPrevious: () => void): void;
}
export interface INotebookCellListOptions extends IWorkbenchListOptions<CellViewModel> {
focusNextPreviousDelegate: IFocusNextPreviousDelegate;
}
export const NOTEBOOK_WEBVIEW_BOUNDARY = 5000;
function validateWebviewBoundary(element: HTMLElement) {
const webviewTop = 0 - (parseInt(element.style.top, 10) || 0);
return webviewTop >= 0 && webviewTop <= NOTEBOOK_WEBVIEW_BOUNDARY * 2;
}
export class NotebookCellList extends WorkbenchList<CellViewModel> implements IDisposable, IStyleController, INotebookCellList {
get onWillScroll(): Event<ScrollEvent> { return this.view.onWillScroll; }
get rowsContainer(): HTMLElement {
return this.view.containerDomNode;
}
private _previousFocusedElements: CellViewModel[] = [];
private readonly _localDisposableStore = new DisposableStore();
private readonly _viewModelStore = new DisposableStore();
private styleElement?: HTMLStyleElement;
private readonly _onDidRemoveOutputs = this._localDisposableStore.add(new Emitter<readonly ICellOutputViewModel[]>());
readonly onDidRemoveOutputs = this._onDidRemoveOutputs.event;
private readonly _onDidHideOutputs = this._localDisposableStore.add(new Emitter<readonly ICellOutputViewModel[]>());
readonly onDidHideOutputs = this._onDidHideOutputs.event;
private readonly _onDidRemoveCellsFromView = this._localDisposableStore.add(new Emitter<readonly ICellViewModel[]>());
readonly onDidRemoveCellsFromView = this._onDidRemoveCellsFromView.event;
private _viewModel: NotebookViewModel | null = null;
get viewModel(): NotebookViewModel | null {
return this._viewModel;
}
private _hiddenRangeIds: string[] = [];
private hiddenRangesPrefixSum: PrefixSumComputer | null = null;
private readonly _onDidChangeVisibleRanges = this._localDisposableStore.add(new Emitter<void>());
onDidChangeVisibleRanges: Event<void> = this._onDidChangeVisibleRanges.event;
private _visibleRanges: ICellRange[] = [];
get visibleRanges() {
return this._visibleRanges;
}
set visibleRanges(ranges: ICellRange[]) {
if (cellRangesEqual(this._visibleRanges, ranges)) {
return;
}
this._visibleRanges = ranges;
this._onDidChangeVisibleRanges.fire();
}
private _isDisposed = false;
get isDisposed() {
return this._isDisposed;
}
private _isInLayout: boolean = false;
private readonly _focusNextPreviousDelegate: IFocusNextPreviousDelegate;
private readonly _viewContext: ViewContext;
private _webviewElement: FastDomNode<HTMLElement> | null = null;
get webviewElement() {
return this._webviewElement;
}
constructor(
private listUser: string,
parentContainer: HTMLElement,
container: HTMLElement,
viewContext: ViewContext,
delegate: IListVirtualDelegate<CellViewModel>,
renderers: IListRenderer<CellViewModel, BaseCellRenderTemplate>[],
contextKeyService: IContextKeyService,
options: INotebookCellListOptions,
@IListService listService: IListService,
@IThemeService themeService: IThemeService,
@IConfigurationService configurationService: IConfigurationService,
@IKeybindingService keybindingService: IKeybindingService
) {
super(listUser, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService);
NOTEBOOK_CELL_LIST_FOCUSED.bindTo(this.contextKeyService).set(true);
this._viewContext = viewContext;
this._focusNextPreviousDelegate = options.focusNextPreviousDelegate;
this._previousFocusedElements = this.getFocusedElements();
this._localDisposableStore.add(this.onDidChangeFocus((e) => {
this._previousFocusedElements.forEach(element => {
if (e.elements.indexOf(element) < 0) {
element.onDeselect();
}
});
this._previousFocusedElements = e.elements;
if (document.activeElement && document.activeElement.classList.contains('webview')) {
super.domFocus();
}
}));
const notebookEditorCursorAtBoundaryContext = NOTEBOOK_EDITOR_CURSOR_BOUNDARY.bindTo(contextKeyService);
notebookEditorCursorAtBoundaryContext.set('none');
const cursorSelectionListener = this._localDisposableStore.add(new MutableDisposable());
const textEditorAttachListener = this._localDisposableStore.add(new MutableDisposable());
const recomputeContext = (element: CellViewModel) => {
switch (element.cursorAtBoundary()) {
case CursorAtBoundary.Both:
notebookEditorCursorAtBoundaryContext.set('both');
break;
case CursorAtBoundary.Top:
notebookEditorCursorAtBoundaryContext.set('top');
break;
case CursorAtBoundary.Bottom:
notebookEditorCursorAtBoundaryContext.set('bottom');
break;
default:
notebookEditorCursorAtBoundaryContext.set('none');
break;
}
return;
};
// Cursor Boundary context
this._localDisposableStore.add(this.onDidChangeFocus((e) => {
if (e.elements.length) {
// we only validate the first focused element
const focusedElement = e.elements[0];
cursorSelectionListener.value = focusedElement.onDidChangeState((e) => {
if (e.selectionChanged) {
recomputeContext(focusedElement);
}
});
textEditorAttachListener.value = focusedElement.onDidChangeEditorAttachState(() => {
if (focusedElement.editorAttached) {
recomputeContext(focusedElement);
}
});
recomputeContext(focusedElement);
return;
}
// reset context
notebookEditorCursorAtBoundaryContext.set('none');
}));
this._localDisposableStore.add(this.view.onMouseDblClick(() => {
const focus = this.getFocusedElements()[0];
if (focus && focus.cellKind === CellKind.Markup && !focus.isInputCollapsed && !this._viewModel?.options.isReadOnly) {
// scroll the cell into view if out of viewport
this.revealElementInView(focus);
focus.updateEditState(CellEditState.Editing, 'dbclick');
focus.focusMode = CellFocusMode.Editor;
}
}));
// update visibleRanges
const updateVisibleRanges = () => {
if (!this.view.length) {
return;
}
const top = this.getViewScrollTop();
const bottom = this.getViewScrollBottom();
if (top >= bottom) {
return;
}
const topViewIndex = clamp(this.view.indexAt(top), 0, this.view.length - 1);
const topElement = this.view.element(topViewIndex);
const topModelIndex = this._viewModel!.getCellIndex(topElement);
const bottomViewIndex = clamp(this.view.indexAt(bottom), 0, this.view.length - 1);
const bottomElement = this.view.element(bottomViewIndex);
const bottomModelIndex = this._viewModel!.getCellIndex(bottomElement);
if (bottomModelIndex - topModelIndex === bottomViewIndex - topViewIndex) {
this.visibleRanges = [{ start: topModelIndex, end: bottomModelIndex }];
} else {
this.visibleRanges = this._getVisibleRangesFromIndex(topViewIndex, topModelIndex, bottomViewIndex, bottomModelIndex);
}
};
this._localDisposableStore.add(this.view.onDidChangeContentHeight(() => {
if (this._isInLayout) {
DOM.scheduleAtNextAnimationFrame(() => {
updateVisibleRanges();
});
}
updateVisibleRanges();
}));
this._localDisposableStore.add(this.view.onDidScroll(() => {
if (this._isInLayout) {
DOM.scheduleAtNextAnimationFrame(() => {
updateVisibleRanges();
});
}
updateVisibleRanges();
}));
}
attachWebview(element: HTMLElement) {
element.style.top = `-${NOTEBOOK_WEBVIEW_BOUNDARY}px`;
this.rowsContainer.insertAdjacentElement('afterbegin', element);
this._webviewElement = new FastDomNode<HTMLElement>(element);
}
elementAt(position: number): ICellViewModel | undefined {
if (!this.view.length) {
return undefined;
}
const idx = this.view.indexAt(position);
const clamped = clamp(idx, 0, this.view.length - 1);
return this.element(clamped);
}
elementHeight(element: ICellViewModel): number {
const index = this._getViewIndexUpperBound(element);
if (index === undefined || index < 0 || index >= this.length) {
this._getViewIndexUpperBound(element);
throw new ListError(this.listUser, `Invalid index ${index}`);
}
return this.view.elementHeight(index);
}
detachViewModel() {
this._viewModelStore.clear();
this._viewModel = null;
this.hiddenRangesPrefixSum = null;
}
attachViewModel(model: NotebookViewModel) {
this._viewModel = model;
this._viewModelStore.add(model.onDidChangeViewCells((e) => {
if (this._isDisposed) {
return;
}
const currentRanges = this._hiddenRangeIds.map(id => this._viewModel!.getTrackedRange(id)).filter(range => range !== null) as ICellRange[];
const newVisibleViewCells: CellViewModel[] = getVisibleCells(this._viewModel!.viewCells as CellViewModel[], currentRanges);
const oldVisibleViewCells: CellViewModel[] = [];
const oldViewCellMapping = new Set<string>();
for (let i = 0; i < this.length; i++) {
oldVisibleViewCells.push(this.element(i));
oldViewCellMapping.add(this.element(i).uri.toString());
}
const viewDiffs = diff<CellViewModel>(oldVisibleViewCells, newVisibleViewCells, a => {
return oldViewCellMapping.has(a.uri.toString());
});
if (e.synchronous) {
this._updateElementsInWebview(viewDiffs);
} else {
this._viewModelStore.add(DOM.scheduleAtNextAnimationFrame(() => {
if (this._isDisposed) {
return;
}
this._updateElementsInWebview(viewDiffs);
}));
}
}));
this._viewModelStore.add(model.onDidChangeSelection((e) => {
if (e === 'view') {
return;
}
// convert model selections to view selections
const viewSelections = cellRangesToIndexes(model.getSelections()).map(index => model.cellAt(index)).filter(cell => !!cell).map(cell => this._getViewIndexUpperBound(cell!));
this.setSelection(viewSelections, undefined, true);
const primary = cellRangesToIndexes([model.getFocus()]).map(index => model.cellAt(index)).filter(cell => !!cell).map(cell => this._getViewIndexUpperBound(cell!));
if (primary.length) {
this.setFocus(primary, undefined, true);
}
}));
const hiddenRanges = model.getHiddenRanges();
this.setHiddenAreas(hiddenRanges, false);
const newRanges = reduceCellRanges(hiddenRanges);
const viewCells = model.viewCells.slice(0) as CellViewModel[];
newRanges.reverse().forEach(range => {
const removedCells = viewCells.splice(range.start, range.end - range.start + 1);
this._onDidRemoveCellsFromView.fire(removedCells);
});
this.splice2(0, 0, viewCells);
}
private _updateElementsInWebview(viewDiffs: ISplice<CellViewModel>[]) {
viewDiffs.reverse().forEach((diff) => {
const hiddenOutputs: ICellOutputViewModel[] = [];
const deletedOutputs: ICellOutputViewModel[] = [];
const removedMarkdownCells: ICellViewModel[] = [];
for (let i = diff.start; i < diff.start + diff.deleteCount; i++) {
const cell = this.element(i);
if (cell.cellKind === CellKind.Code) {
if (this._viewModel!.hasCell(cell)) {
hiddenOutputs.push(...cell?.outputsViewModels);
} else {
deletedOutputs.push(...cell?.outputsViewModels);
}
} else {
removedMarkdownCells.push(cell);
}
}
this.splice2(diff.start, diff.deleteCount, diff.toInsert);
this._onDidHideOutputs.fire(hiddenOutputs);
this._onDidRemoveOutputs.fire(deletedOutputs);
this._onDidRemoveCellsFromView.fire(removedMarkdownCells);
});
}
clear() {
super.splice(0, this.length);
}
setHiddenAreas(_ranges: ICellRange[], triggerViewUpdate: boolean): boolean {
if (!this._viewModel) {
return false;
}
const newRanges = reduceCellRanges(_ranges);
// delete old tracking ranges
const oldRanges = this._hiddenRangeIds.map(id => this._viewModel!.getTrackedRange(id)).filter(range => range !== null) as ICellRange[];
if (newRanges.length === oldRanges.length) {
let hasDifference = false;
for (let i = 0; i < newRanges.length; i++) {
if (!(newRanges[i].start === oldRanges[i].start && newRanges[i].end === oldRanges[i].end)) {
hasDifference = true;
break;
}
}
if (!hasDifference) {
// they call 'setHiddenAreas' for a reason, even if the ranges are still the same, it's possible that the hiddenRangeSum is not update to date
this._updateHiddenRangePrefixSum(newRanges);
return false;
}
}
this._hiddenRangeIds.forEach(id => this._viewModel!.setTrackedRange(id, null, TrackedRangeStickiness.GrowsOnlyWhenTypingAfter));
const hiddenAreaIds = newRanges.map(range => this._viewModel!.setTrackedRange(null, range, TrackedRangeStickiness.GrowsOnlyWhenTypingAfter)).filter(id => id !== null) as string[];
this._hiddenRangeIds = hiddenAreaIds;
// set hidden ranges prefix sum
this._updateHiddenRangePrefixSum(newRanges);
if (triggerViewUpdate) {
this.updateHiddenAreasInView(oldRanges, newRanges);
}
return true;
}
private _updateHiddenRangePrefixSum(newRanges: ICellRange[]) {
let start = 0;
let index = 0;
const ret: number[] = [];
while (index < newRanges.length) {
for (let j = start; j < newRanges[index].start - 1; j++) {
ret.push(1);
}
ret.push(newRanges[index].end - newRanges[index].start + 1 + 1);
start = newRanges[index].end + 1;
index++;
}
for (let i = start; i < this._viewModel!.length; i++) {
ret.push(1);
}
const values = new Uint32Array(ret.length);
for (let i = 0; i < ret.length; i++) {
values[i] = ret[i];
}
this.hiddenRangesPrefixSum = new PrefixSumComputer(values);
}
/**
* oldRanges and newRanges are all reduced and sorted.
*/
updateHiddenAreasInView(oldRanges: ICellRange[], newRanges: ICellRange[]) {
const oldViewCellEntries: CellViewModel[] = getVisibleCells(this._viewModel!.viewCells as CellViewModel[], oldRanges);
const oldViewCellMapping = new Set<string>();
oldViewCellEntries.forEach(cell => {
oldViewCellMapping.add(cell.uri.toString());
});
const newViewCellEntries: CellViewModel[] = getVisibleCells(this._viewModel!.viewCells as CellViewModel[], newRanges);
const viewDiffs = diff<CellViewModel>(oldViewCellEntries, newViewCellEntries, a => {
return oldViewCellMapping.has(a.uri.toString());
});
this._updateElementsInWebview(viewDiffs);
}
splice2(start: number, deleteCount: number, elements: CellViewModel[] = []): void {
// we need to convert start and delete count based on hidden ranges
if (start < 0 || start > this.view.length) {
return;
}
const focusInside = DOM.isAncestor(document.activeElement, this.rowsContainer);
super.splice(start, deleteCount, elements);
if (focusInside) {
this.domFocus();
}
const selectionsLeft = [];
this.getSelectedElements().forEach(el => {
if (this._viewModel!.hasCell(el)) {
selectionsLeft.push(el.handle);
}
});
if (!selectionsLeft.length && this._viewModel!.viewCells.length) {
// after splice, the selected cells are deleted
this._viewModel!.updateSelectionsState({ kind: SelectionStateType.Index, focus: { start: 0, end: 1 }, selections: [{ start: 0, end: 1 }] });
}
}
getModelIndex(cell: CellViewModel): number | undefined {
const viewIndex = this.indexOf(cell);
return this.getModelIndex2(viewIndex);
}
getModelIndex2(viewIndex: number): number | undefined {
if (!this.hiddenRangesPrefixSum) {
return viewIndex;
}
const modelIndex = this.hiddenRangesPrefixSum.getPrefixSum(viewIndex - 1);
return modelIndex;
}
getViewIndex(cell: ICellViewModel) {
const modelIndex = this._viewModel!.getCellIndex(cell);
return this.getViewIndex2(modelIndex);
}
getViewIndex2(modelIndex: number): number | undefined {
if (!this.hiddenRangesPrefixSum) {
return modelIndex;
}
const viewIndexInfo = this.hiddenRangesPrefixSum.getIndexOf(modelIndex);
if (viewIndexInfo.remainder !== 0) {
if (modelIndex >= this.hiddenRangesPrefixSum.getTotalSum()) {
// it's already after the last hidden range
return modelIndex - (this.hiddenRangesPrefixSum.getTotalSum() - this.hiddenRangesPrefixSum.getCount());
}
return undefined;
} else {
return viewIndexInfo.index;
}
}
private _getVisibleRangesFromIndex(topViewIndex: number, topModelIndex: number, bottomViewIndex: number, bottomModelIndex: number) {
let stack: number[] = [];
const ranges: ICellRange[] = [];
// there are hidden ranges
let index = topViewIndex;
let modelIndex = topModelIndex;
while (index <= bottomViewIndex) {
const accu = this.hiddenRangesPrefixSum!.getPrefixSum(index);
if (accu === modelIndex + 1) {
// no hidden area after it
if (stack.length) {
if (stack[stack.length - 1] === modelIndex - 1) {
ranges.push({ start: stack[stack.length - 1], end: modelIndex });
} else {
ranges.push({ start: stack[stack.length - 1], end: stack[stack.length - 1] });
}
}
stack.push(modelIndex);
index++;
modelIndex++;
} else {
// there are hidden ranges after it
if (stack.length) {
if (stack[stack.length - 1] === modelIndex - 1) {
ranges.push({ start: stack[stack.length - 1], end: modelIndex });
} else {
ranges.push({ start: stack[stack.length - 1], end: stack[stack.length - 1] });
}
}
stack.push(modelIndex);
index++;
modelIndex = accu;
}
}
if (stack.length) {
ranges.push({ start: stack[stack.length - 1], end: stack[stack.length - 1] });
}
return reduceCellRanges(ranges);
}
getVisibleRangesPlusViewportBelow() {
if (this.view.length <= 0) {
return [];
}
const bottom = clamp(this.getViewScrollBottom() + this.renderHeight, 0, this.scrollHeight);
const topViewIndex = this.firstVisibleIndex;
const topElement = this.view.element(topViewIndex);
const topModelIndex = this._viewModel!.getCellIndex(topElement);
const bottomViewIndex = clamp(this.view.indexAt(bottom), 0, this.view.length - 1);
const bottomElement = this.view.element(bottomViewIndex);
const bottomModelIndex = this._viewModel!.getCellIndex(bottomElement);
if (bottomModelIndex - topModelIndex === bottomViewIndex - topViewIndex) {
return [{ start: topModelIndex, end: bottomModelIndex }];
} else {
return this._getVisibleRangesFromIndex(topViewIndex, topModelIndex, bottomViewIndex, bottomModelIndex);
}
}
private _getViewIndexUpperBound(cell: ICellViewModel): number {
if (!this._viewModel) {
return -1;
}
const modelIndex = this._viewModel.getCellIndex(cell);
if (!this.hiddenRangesPrefixSum) {
return modelIndex;
}
const viewIndexInfo = this.hiddenRangesPrefixSum.getIndexOf(modelIndex);
if (viewIndexInfo.remainder !== 0) {
if (modelIndex >= this.hiddenRangesPrefixSum.getTotalSum()) {
return modelIndex - (this.hiddenRangesPrefixSum.getTotalSum() - this.hiddenRangesPrefixSum.getCount());
}
}
return viewIndexInfo.index;
}
private _getViewIndexUpperBound2(modelIndex: number) {
if (!this.hiddenRangesPrefixSum) {
return modelIndex;
}
const viewIndexInfo = this.hiddenRangesPrefixSum.getIndexOf(modelIndex);
if (viewIndexInfo.remainder !== 0) {
if (modelIndex >= this.hiddenRangesPrefixSum.getTotalSum()) {
return modelIndex - (this.hiddenRangesPrefixSum.getTotalSum() - this.hiddenRangesPrefixSum.getCount());
}
}
return viewIndexInfo.index;
}
focusElement(cell: ICellViewModel) {
const index = this._getViewIndexUpperBound(cell);
if (index >= 0 && this._viewModel) {
// update view model first, which will update both `focus` and `selection` in a single transaction
const focusedElementHandle = this.element(index).handle;
this._viewModel.updateSelectionsState({
kind: SelectionStateType.Handle,
primary: focusedElementHandle,
selections: [focusedElementHandle]
}, 'view');
// update the view as previous model update will not trigger event
this.setFocus([index], undefined, false);
}
}
selectElements(elements: ICellViewModel[]) {
const indices = elements.map(cell => this._getViewIndexUpperBound(cell)).filter(index => index >= 0);
this.setSelection(indices);
}
override focusNext(n: number | undefined, loop: boolean | undefined, browserEvent?: UIEvent, filter?: (element: CellViewModel) => boolean): void {
this._focusNextPreviousDelegate.onFocusNext(() => {
super.focusNext(n, loop, browserEvent, filter);
});
}
override focusPrevious(n: number | undefined, loop: boolean | undefined, browserEvent?: UIEvent, filter?: (element: CellViewModel) => boolean): void {
this._focusNextPreviousDelegate.onFocusPrevious(() => {
super.focusPrevious(n, loop, browserEvent, filter);
});
}
override setFocus(indexes: number[], browserEvent?: UIEvent, ignoreTextModelUpdate?: boolean): void {
if (ignoreTextModelUpdate) {
super.setFocus(indexes, browserEvent);
return;
}
if (!indexes.length) {
if (this._viewModel) {
this._viewModel.updateSelectionsState({
kind: SelectionStateType.Handle,
primary: null,
selections: []
}, 'view');
}
} else {
if (this._viewModel) {
const focusedElementHandle = this.element(indexes[0]).handle;
this._viewModel.updateSelectionsState({
kind: SelectionStateType.Handle,
primary: focusedElementHandle,
selections: this.getSelection().map(selection => this.element(selection).handle)
}, 'view');
}
}
super.setFocus(indexes, browserEvent);
}
override setSelection(indexes: number[], browserEvent?: UIEvent | undefined, ignoreTextModelUpdate?: boolean) {
if (ignoreTextModelUpdate) {
super.setSelection(indexes, browserEvent);
return;
}
if (!indexes.length) {
if (this._viewModel) {
this._viewModel.updateSelectionsState({
kind: SelectionStateType.Handle,
primary: this.getFocusedElements()[0]?.handle ?? null,
selections: []
}, 'view');
}
} else {
if (this._viewModel) {
this._viewModel.updateSelectionsState({
kind: SelectionStateType.Handle,
primary: this.getFocusedElements()[0]?.handle ?? null,
selections: indexes.map(index => this.element(index)).map(cell => cell.handle)
}, 'view');
}
}
super.setSelection(indexes, browserEvent);
}
/**
* The range will be revealed with as little scrolling as possible.
*/
revealElementsInView(range: ICellRange) {
const startIndex = this._getViewIndexUpperBound2(range.start);
if (startIndex < 0) {
return;
}
const endIndex = this._getViewIndexUpperBound2(range.end - 1);
const scrollTop = this.getViewScrollTop();
const wrapperBottom = this.getViewScrollBottom();
const elementTop = this.view.elementTop(startIndex);
if (elementTop >= scrollTop
&& elementTop < wrapperBottom) {
// start element is visible
// check end
const endElementTop = this.view.elementTop(endIndex);
const endElementHeight = this.view.elementHeight(endIndex);
if (endElementTop + endElementHeight <= wrapperBottom) {
// fully visible
return;
}
if (endElementTop >= wrapperBottom) {
return this._revealInternal(endIndex, false, CellRevealPosition.Bottom);
}
if (endElementTop < wrapperBottom) {
// end element partially visible
if (endElementTop + endElementHeight - wrapperBottom < elementTop - scrollTop) {
// there is enough space to just scroll up a little bit to make the end element visible
return this.view.setScrollTop(scrollTop + endElementTop + endElementHeight - wrapperBottom);
} else {
// don't even try it
return this._revealInternal(startIndex, false, CellRevealPosition.Top);
}
}
}
this._revealInView(startIndex);
}
isScrolledToBottom() {
if (this.length === 0) {
return true;
}
const last = this.length - 1;
const bottom = this.view.elementHeight(last) + this.view.elementTop(last);
const wrapperBottom = this.getViewScrollTop() + this.view.renderHeight;
if (bottom <= wrapperBottom) {
return true;
}
return false;
}
scrollToBottom() {
const scrollHeight = this.view.scrollHeight;
const scrollTop = this.getViewScrollTop();
const wrapperBottom = this.getViewScrollBottom();
const topInsertToolbarHeight = this._viewContext.notebookOptions.computeTopInsertToolbarHeight(this.viewModel?.viewType);
this.view.setScrollTop(scrollHeight - (wrapperBottom - scrollTop) - topInsertToolbarHeight);
}
revealElementInView(cell: ICellViewModel) {
const index = this._getViewIndexUpperBound(cell);
if (index >= 0) {
this._revealInView(index);
}
}
revealElementInViewAtTop(cell: ICellViewModel) {
const index = this._getViewIndexUpperBound(cell);
if (index >= 0) {
this._revealInternal(index, false, CellRevealPosition.Top);
}
}
revealElementInCenterIfOutsideViewport(cell: ICellViewModel) {
const index = this._getViewIndexUpperBound(cell);
if (index >= 0) {
this._revealInCenterIfOutsideViewport(index);
}
}
revealElementInCenter(cell: ICellViewModel) {
const index = this._getViewIndexUpperBound(cell);
if (index >= 0) {
this._revealInCenter(index);
}
}
async revealElementInCenterIfOutsideViewportAsync(cell: ICellViewModel): Promise<void> {
const index = this._getViewIndexUpperBound(cell);
if (index >= 0) {
return this._revealInCenterIfOutsideViewportAsync(index);
}
}
async revealElementLineInViewAsync(cell: ICellViewModel, line: number): Promise<void> {
const index = this._getViewIndexUpperBound(cell);
if (index >= 0) {
return this._revealLineInViewAsync(index, line);
}
}
async revealElementLineInCenterAsync(cell: ICellViewModel, line: number): Promise<void> {
const index = this._getViewIndexUpperBound(cell);
if (index >= 0) {
return this._revealLineInCenterAsync(index, line);
}
}
async revealElementLineInCenterIfOutsideViewportAsync(cell: ICellViewModel, line: number): Promise<void> {
const index = this._getViewIndexUpperBound(cell);
if (index >= 0) {
return this._revealLineInCenterIfOutsideViewportAsync(index, line);
}
}
async revealElementRangeInViewAsync(cell: ICellViewModel, range: Range): Promise<void> {
const index = this._getViewIndexUpperBound(cell);
if (index >= 0) {
return this._revealRangeInView(index, range);
}
}
async revealElementRangeInCenterAsync(cell: ICellViewModel, range: Range): Promise<void> {
const index = this._getViewIndexUpperBound(cell);
if (index >= 0) {
return this._revealRangeInCenterAsync(index, range);
}
}
async revealElementRangeInCenterIfOutsideViewportAsync(cell: ICellViewModel, range: Range): Promise<void> {
const index = this._getViewIndexUpperBound(cell);
if (index >= 0) {
return this._revealRangeInCenterIfOutsideViewportAsync(index, range);
}
}
domElementOfElement(element: ICellViewModel): HTMLElement | null {
const index = this._getViewIndexUpperBound(element);
if (index >= 0) {
return this.view.domElement(index);
}
return null;
}
focusView() {
this.view.domNode.focus();
}
getAbsoluteTopOfElement(element: ICellViewModel): number {
const index = this._getViewIndexUpperBound(element);
if (index === undefined || index < 0 || index >= this.length) {
this._getViewIndexUpperBound(element);
throw new ListError(this.listUser, `Invalid index ${index}`);
}
return this.view.elementTop(index);
}
triggerScrollFromMouseWheelEvent(browserEvent: IMouseWheelEvent) {
this.view.triggerScrollFromMouseWheelEvent(browserEvent);
}
updateElementHeight2(element: ICellViewModel, size: number): void {
const index = this._getViewIndexUpperBound(element);
if (index === undefined || index < 0 || index >= this.length) {
return;
}
if (index < this.firstVisibleIndex) {
// update element above viewport
const oldHeight = this.elementHeight(element);
const delta = oldHeight - size;
// const date = new Date();
if (this._webviewElement) {
Event.once(this.view.onWillScroll)(() => {
const webviewTop = parseInt(this._webviewElement!.domNode.style.top, 10);
if (validateWebviewBoundary(this._webviewElement!.domNode)) {
this._webviewElement!.setTop(webviewTop - delta);
} else {
// When the webview top boundary is below the list view scrollable element top boundary, then we can't insert a markdown cell at the top
// or when its bottom boundary is above the list view bottom boundary, then we can't insert a markdown cell at the end
// thus we have to revert the webview element position to initial state `-NOTEBOOK_WEBVIEW_BOUNDARY`.
// this will trigger one visual flicker (as we need to update element offsets in the webview)
// but as long as NOTEBOOK_WEBVIEW_BOUNDARY is large enough, it will happen less often
this._webviewElement!.setTop(-NOTEBOOK_WEBVIEW_BOUNDARY);
}
});
}
this.view.updateElementHeight(index, size, null);
return;
}
const focused = this.getFocus();
if (!focused.length) {
this.view.updateElementHeight(index, size, null);
return;
}
const focus = focused[0];
if (focus <= index) {
this.view.updateElementHeight(index, size, focus);
return;
}
// the `element` is in the viewport, it's very often that the height update is triggerred by user interaction (collapse, run cell)
// then we should make sure that the `element`'s visual view position doesn't change.
if (this.view.elementTop(index) >= this.view.scrollTop) {
this.view.updateElementHeight(index, size, index);
return;
}
this.view.updateElementHeight(index, size, focus);
}
// override
override domFocus() {
const focused = this.getFocusedElements()[0];
const focusedDomElement = focused && this.domElementOfElement(focused);
if (document.activeElement && focusedDomElement && focusedDomElement.contains(document.activeElement)) {
// for example, when focus goes into monaco editor, if we refocus the list view, the editor will lose focus.
return;
}
if (!isMacintosh && document.activeElement && isContextMenuFocused()) {
return;
}
super.domFocus();
}
focusContainer() {
super.domFocus();
}
getViewScrollTop() {
return this.view.getScrollTop();
}
getViewScrollBottom() {
const topInsertToolbarHeight = this._viewContext.notebookOptions.computeTopInsertToolbarHeight(this.viewModel?.viewType);
return this.getViewScrollTop() + this.view.renderHeight - topInsertToolbarHeight;
}
private _revealRange(viewIndex: number, range: Range, revealType: CellRevealType, newlyCreated: boolean, alignToBottom: boolean) {
const element = this.view.element(viewIndex);
const scrollTop = this.getViewScrollTop();
const wrapperBottom = this.getViewScrollBottom();
const positionOffset = element.getPositionScrollTopOffset(range.startLineNumber, range.startColumn);
const elementTop = this.view.elementTop(viewIndex);
const positionTop = elementTop + positionOffset;
// TODO@rebornix 30 ---> line height * 1.5
if (positionTop < scrollTop) {
this.view.setScrollTop(positionTop - 30);
} else if (positionTop > wrapperBottom) {
this.view.setScrollTop(scrollTop + positionTop - wrapperBottom + 30);
} else if (newlyCreated) {
// newly scrolled into view
if (alignToBottom) {
// align to the bottom
this.view.setScrollTop(scrollTop + positionTop - wrapperBottom + 30);
} else {
// align to to top
this.view.setScrollTop(positionTop - 30);
}
}
if (revealType === CellRevealType.Range) {
element.revealRangeInCenter(range);
}
}
// List items have real dynamic heights, which means after we set `scrollTop` based on the `elementTop(index)`, the element at `index` might still be removed from the view once all relayouting tasks are done.
// For example, we scroll item 10 into the view upwards, in the first round, items 7, 8, 9, 10 are all in the viewport. Then item 7 and 8 resize themselves to be larger and finally item 10 is removed from the view.
// To ensure that item 10 is always there, we need to scroll item 10 to the top edge of the viewport.
private async _revealRangeInternalAsync(viewIndex: number, range: Range, revealType: CellRevealType): Promise<void> {
const scrollTop = this.getViewScrollTop();
const wrapperBottom = this.getViewScrollBottom();
const elementTop = this.view.elementTop(viewIndex);
const element = this.view.element(viewIndex);
if (element.editorAttached) {
this._revealRange(viewIndex, range, revealType, false, false);
} else {
const elementHeight = this.view.elementHeight(viewIndex);
let upwards = false;
if (elementTop + elementHeight < scrollTop) {
// scroll downwards
this.view.setScrollTop(elementTop);
upwards = false;
} else if (elementTop > wrapperBottom) {
// scroll upwards
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
upwards = true;
}
const editorAttachedPromise = new Promise<void>((resolve, reject) => {
element.onDidChangeEditorAttachState(() => {
element.editorAttached ? resolve() : reject();
});
});
return editorAttachedPromise.then(() => {
this._revealRange(viewIndex, range, revealType, true, upwards);
});
}
}
private async _revealLineInViewAsync(viewIndex: number, line: number): Promise<void> {
return this._revealRangeInternalAsync(viewIndex, new Range(line, 1, line, 1), CellRevealType.Line);
}
private async _revealRangeInView(viewIndex: number, range: Range): Promise<void> {
return this._revealRangeInternalAsync(viewIndex, range, CellRevealType.Range);
}
private async _revealRangeInCenterInternalAsync(viewIndex: number, range: Range, revealType: CellRevealType): Promise<void> {
const reveal = (viewIndex: number, range: Range, revealType: CellRevealType) => {
const element = this.view.element(viewIndex);
const positionOffset = element.getPositionScrollTopOffset(range.startLineNumber, range.startColumn);
const positionOffsetInView = this.view.elementTop(viewIndex) + positionOffset;
this.view.setScrollTop(positionOffsetInView - this.view.renderHeight / 2);
if (revealType === CellRevealType.Range) {
element.revealRangeInCenter(range);
}
};
const elementTop = this.view.elementTop(viewIndex);
const viewItemOffset = elementTop;
this.view.setScrollTop(viewItemOffset - this.view.renderHeight / 2);
const element = this.view.element(viewIndex);
if (!element.editorAttached) {
return getEditorAttachedPromise(element).then(() => reveal(viewIndex, range, revealType));
} else {
reveal(viewIndex, range, revealType);
}
}
private async _revealLineInCenterAsync(viewIndex: number, line: number): Promise<void> {
return this._revealRangeInCenterInternalAsync(viewIndex, new Range(line, 1, line, 1), CellRevealType.Line);
}
private _revealRangeInCenterAsync(viewIndex: number, range: Range): Promise<void> {
return this._revealRangeInCenterInternalAsync(viewIndex, range, CellRevealType.Range);
}
private async _revealRangeInCenterIfOutsideViewportInternalAsync(viewIndex: number, range: Range, revealType: CellRevealType): Promise<void> {
const reveal = (viewIndex: number, range: Range, revealType: CellRevealType) => {
const element = this.view.element(viewIndex);
const positionOffset = element.getPositionScrollTopOffset(range.startLineNumber, range.startColumn);
const positionOffsetInView = this.view.elementTop(viewIndex) + positionOffset;
this.view.setScrollTop(positionOffsetInView - this.view.renderHeight / 2);
if (revealType === CellRevealType.Range) {
element.revealRangeInCenter(range);
}
};
const scrollTop = this.getViewScrollTop();
const wrapperBottom = this.getViewScrollBottom();
const elementTop = this.view.elementTop(viewIndex);
const viewItemOffset = elementTop;
const element = this.view.element(viewIndex);
const positionOffset = viewItemOffset + element.getPositionScrollTopOffset(range.startLineNumber, range.startColumn);
if (positionOffset < scrollTop || positionOffset > wrapperBottom) {
// let it render
this.view.setScrollTop(positionOffset - this.view.renderHeight / 2);
// after rendering, it might be pushed down due to markdown cell dynamic height
const newPositionOffset = this.view.elementTop(viewIndex) + element.getPositionScrollTopOffset(range.startLineNumber, range.startColumn);
this.view.setScrollTop(newPositionOffset - this.view.renderHeight / 2);
// reveal editor
if (!element.editorAttached) {
return getEditorAttachedPromise(element).then(() => reveal(viewIndex, range, revealType));
} else {
// for example markdown
}
} else {
if (element.editorAttached) {
element.revealRangeInCenter(range);
} else {
// for example, markdown cell in preview mode
return getEditorAttachedPromise(element).then(() => reveal(viewIndex, range, revealType));
}
}
}
private async _revealInCenterIfOutsideViewportAsync(viewIndex: number): Promise<void> {
this._revealInternal(viewIndex, true, CellRevealPosition.Center);
const element = this.view.element(viewIndex);
// wait for the editor to be created only if the cell is in editing mode (meaning it has an editor and will focus the editor)
if (element.getEditState() === CellEditState.Editing && !element.editorAttached) {
return getEditorAttachedPromise(element);
}
return;
}
private async _revealLineInCenterIfOutsideViewportAsync(viewIndex: number, line: number): Promise<void> {
return this._revealRangeInCenterIfOutsideViewportInternalAsync(viewIndex, new Range(line, 1, line, 1), CellRevealType.Line);
}
private async _revealRangeInCenterIfOutsideViewportAsync(viewIndex: number, range: Range): Promise<void> {
return this._revealRangeInCenterIfOutsideViewportInternalAsync(viewIndex, range, CellRevealType.Range);
}
private _revealInternal(viewIndex: number, ignoreIfInsideViewport: boolean, revealPosition: CellRevealPosition) {
if (viewIndex >= this.view.length) {
return;
}
const scrollTop = this.getViewScrollTop();
const wrapperBottom = this.getViewScrollBottom();
const elementTop = this.view.elementTop(viewIndex);
const elementBottom = this.view.elementHeight(viewIndex) + elementTop;
if (ignoreIfInsideViewport
&& elementTop >= scrollTop
&& elementTop < wrapperBottom) {
if (revealPosition === CellRevealPosition.Center
&& elementBottom > wrapperBottom
&& elementTop > (scrollTop + wrapperBottom) / 2) {
// the element is partially visible and it's below the center of the viewport
} else {
return;
}
}
switch (revealPosition) {
case CellRevealPosition.Top:
this.view.setScrollTop(elementTop);
this.view.setScrollTop(this.view.elementTop(viewIndex));
break;
case CellRevealPosition.Center:
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
this.view.setScrollTop(this.view.elementTop(viewIndex) - this.view.renderHeight / 2);
break;
case CellRevealPosition.Bottom:
this.view.setScrollTop(this.scrollTop + (elementBottom - wrapperBottom));
this.view.setScrollTop(this.scrollTop + (this.view.elementTop(viewIndex) + this.view.elementHeight(viewIndex) - this.getViewScrollBottom()));
break;
default:
break;
}
}
private _revealInView(viewIndex: number) {
const firstIndex = this.view.firstVisibleIndex;
if (viewIndex < firstIndex) {
this._revealInternal(viewIndex, true, CellRevealPosition.Top);
} else {
this._revealInternal(viewIndex, true, CellRevealPosition.Bottom);
}
}
private _revealInCenter(viewIndex: number) {
this._revealInternal(viewIndex, false, CellRevealPosition.Center);
}
private _revealInCenterIfOutsideViewport(viewIndex: number) {
this._revealInternal(viewIndex, true, CellRevealPosition.Center);
}
setCellSelection(cell: ICellViewModel, range: Range) {
const element = cell as CellViewModel;
if (element.editorAttached) {
element.setSelection(range);
} else {
getEditorAttachedPromise(element).then(() => { element.setSelection(range); });
}
}
override style(styles: IListStyles) {
const selectorSuffix = this.view.domId;
if (!this.styleElement) {
this.styleElement = DOM.createStyleSheet(this.view.domNode);
}
const suffix = selectorSuffix && `.${selectorSuffix}`;
const content: string[] = [];
if (styles.listBackground) {
if (styles.listBackground.isOpaque()) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows { background: ${styles.listBackground}; }`);
} else if (!isMacintosh) { // subpixel AA doesn't exist in macOS
console.warn(`List with id '${selectorSuffix}' was styled with a non-opaque background color. This will break sub-pixel antialiasing.`);
}
}
if (styles.listFocusBackground) {
content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { background-color: ${styles.listFocusBackground}; }`);
content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused:hover { background-color: ${styles.listFocusBackground}; }`); // overwrite :hover style in this case!
}
if (styles.listFocusForeground) {
content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`);
}
if (styles.listActiveSelectionBackground) {
content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { background-color: ${styles.listActiveSelectionBackground}; }`);
content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected:hover { background-color: ${styles.listActiveSelectionBackground}; }`); // overwrite :hover style in this case!
}
if (styles.listActiveSelectionForeground) {
content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { color: ${styles.listActiveSelectionForeground}; }`);
}
if (styles.listFocusAndSelectionBackground) {
content.push(`
.monaco-drag-image,
.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected.focused { background-color: ${styles.listFocusAndSelectionBackground}; }
`);
}
if (styles.listFocusAndSelectionForeground) {
content.push(`
.monaco-drag-image,
.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected.focused { color: ${styles.listFocusAndSelectionForeground}; }
`);
}
if (styles.listInactiveFocusBackground) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { background-color: ${styles.listInactiveFocusBackground}; }`);
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused:hover { background-color: ${styles.listInactiveFocusBackground}; }`); // overwrite :hover style in this case!
}
if (styles.listInactiveSelectionBackground) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { background-color: ${styles.listInactiveSelectionBackground}; }`);
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected:hover { background-color: ${styles.listInactiveSelectionBackground}; }`); // overwrite :hover style in this case!
}
if (styles.listInactiveSelectionForeground) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { color: ${styles.listInactiveSelectionForeground}; }`);
}
if (styles.listHoverBackground) {
content.push(`.monaco-list${suffix}:not(.drop-target) > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover:not(.selected):not(.focused) { background-color: ${styles.listHoverBackground}; }`);
}
if (styles.listHoverForeground) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover:not(.selected):not(.focused) { color: ${styles.listHoverForeground}; }`);
}
if (styles.listSelectionOutline) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; outline-offset: -1px; }`);
}
if (styles.listFocusOutline) {
content.push(`
.monaco-drag-image,
.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; }
`);
}
if (styles.listInactiveFocusOutline) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { outline: 1px dotted ${styles.listInactiveFocusOutline}; outline-offset: -1px; }`);
}
if (styles.listHoverOutline) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover { outline: 1px dashed ${styles.listHoverOutline}; outline-offset: -1px; }`);
}
if (styles.listDropBackground) {
content.push(`
.monaco-list${suffix}.drop-target,
.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows.drop-target,
.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-row.drop-target { background-color: ${styles.listDropBackground} !important; color: inherit !important; }
`);
}
if (styles.listFilterWidgetBackground) {
content.push(`.monaco-list-type-filter { background-color: ${styles.listFilterWidgetBackground} }`);
}
if (styles.listFilterWidgetOutline) {
content.push(`.monaco-list-type-filter { border: 1px solid ${styles.listFilterWidgetOutline}; }`);
}
if (styles.listFilterWidgetNoMatchesOutline) {
content.push(`.monaco-list-type-filter.no-matches { border: 1px solid ${styles.listFilterWidgetNoMatchesOutline}; }`);
}
if (styles.listMatchesShadow) {
content.push(`.monaco-list-type-filter { box-shadow: 1px 1px 1px ${styles.listMatchesShadow}; }`);
}
const newStyles = content.join('\n');
if (newStyles !== this.styleElement.textContent) {
this.styleElement.textContent = newStyles;
}
}
getRenderHeight() {
return this.view.renderHeight;
}
override layout(height?: number, width?: number): void {
this._isInLayout = true;
super.layout(height, width);
if (this.renderHeight === 0) {
this.view.domNode.style.visibility = 'hidden';
} else {
this.view.domNode.style.visibility = 'initial';
}
this._isInLayout = false;
}
override dispose() {
this._isDisposed = true;
this._viewModelStore.dispose();
this._localDisposableStore.dispose();
super.dispose();
// un-ref
this._previousFocusedElements = [];
this._viewModel = null;
this._hiddenRangeIds = [];
this.hiddenRangesPrefixSum = null;
this._visibleRanges = [];
}
}
function getEditorAttachedPromise(element: CellViewModel) {
return new Promise<void>((resolve, reject) => {
Event.once(element.onDidChangeEditorAttachState)(() => element.editorAttached ? resolve() : reject());
});
}
function isContextMenuFocused() {
return !!DOM.findParentWithClass(<HTMLElement>document.activeElement, 'context-view');
}
| src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts | 1 | https://github.com/microsoft/vscode/commit/d6b581f218bc689cda2d3a009635c2df01a81984 | [
0.009426827542483807,
0.00040437784628011286,
0.00016229599714279175,
0.0001686562318354845,
0.001048979815095663
]
|
{
"id": 2,
"code_window": [
"\n",
"\t\t\t\t// the first cell grows, but it's partially visible, so we won't push down the focused cell\n",
"\t\t\t\tassert.deepStrictEqual(cellList.scrollTop, 55);\n",
"\t\t\t\tassert.deepStrictEqual(cellList.getViewScrollBottom(), 265);\n",
"\n",
"\t\t\t\t// cellList.updateElementHeight2(viewModel.cellAt(0)!, 50);\n",
"\t\t\t\t// assert.deepStrictEqual(cellList.scrollTop, 5);\n",
"\t\t\t\t// assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);\n",
"\n",
"\t\t\t\t// focus won't be visible after cell 0 grow to 250, so let's try to keep the focused cell visible\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tcellList.updateElementHeight2(viewModel.cellAt(0)!, 50);\n",
"\t\t\t\tassert.deepStrictEqual(cellList.scrollTop, 5);\n",
"\t\t\t\tassert.deepStrictEqual(cellList.getViewScrollBottom(), 215);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/test/browser/notebookCellList.test.ts",
"type": "replace",
"edit_start_line_idx": 236
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export interface NewWorkerMessage {
type: '_newWorker';
id: string;
port: any /* MessagePort */;
url: string;
options: any /* WorkerOptions */ | undefined;
}
export interface TerminateWorkerMessage {
type: '_terminateWorker';
id: string;
}
| src/vs/workbench/services/extensions/common/polyfillNestedWorker.protocol.ts | 0 | https://github.com/microsoft/vscode/commit/d6b581f218bc689cda2d3a009635c2df01a81984 | [
0.0001747318310663104,
0.00017282161570619792,
0.00017091140034608543,
0.00017282161570619792,
0.0000019102153601124883
]
|
{
"id": 2,
"code_window": [
"\n",
"\t\t\t\t// the first cell grows, but it's partially visible, so we won't push down the focused cell\n",
"\t\t\t\tassert.deepStrictEqual(cellList.scrollTop, 55);\n",
"\t\t\t\tassert.deepStrictEqual(cellList.getViewScrollBottom(), 265);\n",
"\n",
"\t\t\t\t// cellList.updateElementHeight2(viewModel.cellAt(0)!, 50);\n",
"\t\t\t\t// assert.deepStrictEqual(cellList.scrollTop, 5);\n",
"\t\t\t\t// assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);\n",
"\n",
"\t\t\t\t// focus won't be visible after cell 0 grow to 250, so let's try to keep the focused cell visible\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tcellList.updateElementHeight2(viewModel.cellAt(0)!, 50);\n",
"\t\t\t\tassert.deepStrictEqual(cellList.scrollTop, 5);\n",
"\t\t\t\tassert.deepStrictEqual(cellList.getViewScrollBottom(), 215);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/test/browser/notebookCellList.test.ts",
"type": "replace",
"edit_start_line_idx": 236
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as Types from 'vs/base/common/types';
import * as resources from 'vs/base/common/resources';
import { IJSONSchemaMap } from 'vs/base/common/jsonSchema';
import * as Objects from 'vs/base/common/objects';
import { UriComponents, URI } from 'vs/base/common/uri';
import { ProblemMatcher } from 'vs/workbench/contrib/tasks/common/problemMatcher';
import { IWorkspaceFolder, IWorkspace } from 'vs/platform/workspace/common/workspace';
import { RawContextKey, ContextKeyExpression } from 'vs/platform/contextkey/common/contextkey';
import { TaskDefinitionRegistry } from 'vs/workbench/contrib/tasks/common/taskDefinitionRegistry';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
import { USER_TASKS_GROUP_KEY } from 'vs/workbench/contrib/tasks/common/taskService';
export const TASK_RUNNING_STATE = new RawContextKey<boolean>('taskRunning', false, nls.localize('tasks.taskRunningContext', "Whether a task is currently running."));
export const TASKS_CATEGORY = { value: nls.localize('tasksCategory', "Tasks"), original: 'Tasks' };
export enum ShellQuoting {
/**
* Use character escaping.
*/
Escape = 1,
/**
* Use strong quoting
*/
Strong = 2,
/**
* Use weak quoting.
*/
Weak = 3,
}
export const CUSTOMIZED_TASK_TYPE = '$customized';
export namespace ShellQuoting {
export function from(this: void, value: string): ShellQuoting {
if (!value) {
return ShellQuoting.Strong;
}
switch (value.toLowerCase()) {
case 'escape':
return ShellQuoting.Escape;
case 'strong':
return ShellQuoting.Strong;
case 'weak':
return ShellQuoting.Weak;
default:
return ShellQuoting.Strong;
}
}
}
export interface ShellQuotingOptions {
/**
* The character used to do character escaping.
*/
escape?: string | {
escapeChar: string;
charsToEscape: string;
};
/**
* The character used for string quoting.
*/
strong?: string;
/**
* The character used for weak quoting.
*/
weak?: string;
}
export interface ShellConfiguration {
/**
* The shell executable.
*/
executable?: string;
/**
* The arguments to be passed to the shell executable.
*/
args?: string[];
/**
* Which kind of quotes the shell supports.
*/
quoting?: ShellQuotingOptions;
}
export interface CommandOptions {
/**
* The shell to use if the task is a shell command.
*/
shell?: ShellConfiguration;
/**
* The current working directory of the executed program or shell.
* If omitted VSCode's current workspace root is used.
*/
cwd?: string;
/**
* The environment of the executed program or shell. If omitted
* the parent process' environment is used.
*/
env?: { [key: string]: string; };
}
export namespace CommandOptions {
export const defaults: CommandOptions = { cwd: '${workspaceFolder}' };
}
export enum RevealKind {
/**
* Always brings the terminal to front if the task is executed.
*/
Always = 1,
/**
* Only brings the terminal to front if a problem is detected executing the task
* e.g. the task couldn't be started,
* the task ended with an exit code other than zero,
* or the problem matcher found an error.
*/
Silent = 2,
/**
* The terminal never comes to front when the task is executed.
*/
Never = 3
}
export namespace RevealKind {
export function fromString(this: void, value: string): RevealKind {
switch (value.toLowerCase()) {
case 'always':
return RevealKind.Always;
case 'silent':
return RevealKind.Silent;
case 'never':
return RevealKind.Never;
default:
return RevealKind.Always;
}
}
}
export enum RevealProblemKind {
/**
* Never reveals the problems panel when this task is executed.
*/
Never = 1,
/**
* Only reveals the problems panel if a problem is found.
*/
OnProblem = 2,
/**
* Never reveals the problems panel when this task is executed.
*/
Always = 3
}
export namespace RevealProblemKind {
export function fromString(this: void, value: string): RevealProblemKind {
switch (value.toLowerCase()) {
case 'always':
return RevealProblemKind.Always;
case 'never':
return RevealProblemKind.Never;
case 'onproblem':
return RevealProblemKind.OnProblem;
default:
return RevealProblemKind.OnProblem;
}
}
}
export enum PanelKind {
/**
* Shares a panel with other tasks. This is the default.
*/
Shared = 1,
/**
* Uses a dedicated panel for this tasks. The panel is not
* shared with other tasks.
*/
Dedicated = 2,
/**
* Creates a new panel whenever this task is executed.
*/
New = 3
}
export namespace PanelKind {
export function fromString(value: string): PanelKind {
switch (value.toLowerCase()) {
case 'shared':
return PanelKind.Shared;
case 'dedicated':
return PanelKind.Dedicated;
case 'new':
return PanelKind.New;
default:
return PanelKind.Shared;
}
}
}
export interface PresentationOptions {
/**
* Controls whether the task output is reveal in the user interface.
* Defaults to `RevealKind.Always`.
*/
reveal: RevealKind;
/**
* Controls whether the problems pane is revealed when running this task or not.
* Defaults to `RevealProblemKind.Never`.
*/
revealProblems: RevealProblemKind;
/**
* Controls whether the command associated with the task is echoed
* in the user interface.
*/
echo: boolean;
/**
* Controls whether the panel showing the task output is taking focus.
*/
focus: boolean;
/**
* Controls if the task panel is used for this task only (dedicated),
* shared between tasks (shared) or if a new panel is created on
* every task execution (new). Defaults to `TaskInstanceKind.Shared`
*/
panel: PanelKind;
/**
* Controls whether to show the "Terminal will be reused by tasks, press any key to close it" message.
*/
showReuseMessage: boolean;
/**
* Controls whether to clear the terminal before executing the task.
*/
clear: boolean;
/**
* Controls whether the task is executed in a specific terminal group using split panes.
*/
group?: string;
/**
* Controls whether the terminal that the task runs in is closed when the task completes.
*/
close?: boolean;
}
export namespace PresentationOptions {
export const defaults: PresentationOptions = {
echo: true, reveal: RevealKind.Always, revealProblems: RevealProblemKind.Never, focus: false, panel: PanelKind.Shared, showReuseMessage: true, clear: false
};
}
export enum RuntimeType {
Shell = 1,
Process = 2,
CustomExecution = 3
}
export namespace RuntimeType {
export function fromString(value: string): RuntimeType {
switch (value.toLowerCase()) {
case 'shell':
return RuntimeType.Shell;
case 'process':
return RuntimeType.Process;
case 'customExecution':
return RuntimeType.CustomExecution;
default:
return RuntimeType.Process;
}
}
export function toString(value: RuntimeType): string {
switch (value) {
case RuntimeType.Shell: return 'shell';
case RuntimeType.Process: return 'process';
case RuntimeType.CustomExecution: return 'customExecution';
default: return 'process';
}
}
}
export interface QuotedString {
value: string;
quoting: ShellQuoting;
}
export type CommandString = string | QuotedString;
export namespace CommandString {
export function value(value: CommandString): string {
if (Types.isString(value)) {
return value;
} else {
return value.value;
}
}
}
export interface CommandConfiguration {
/**
* The task type
*/
runtime?: RuntimeType;
/**
* The command to execute
*/
name?: CommandString;
/**
* Additional command options.
*/
options?: CommandOptions;
/**
* Command arguments.
*/
args?: CommandString[];
/**
* The task selector if needed.
*/
taskSelector?: string;
/**
* Whether to suppress the task name when merging global args
*
*/
suppressTaskName?: boolean;
/**
* Describes how the task is presented in the UI.
*/
presentation?: PresentationOptions;
}
export namespace TaskGroup {
export const Clean: TaskGroup = { _id: 'clean', isDefault: false };
export const Build: TaskGroup = { _id: 'build', isDefault: false };
export const Rebuild: TaskGroup = { _id: 'rebuild', isDefault: false };
export const Test: TaskGroup = { _id: 'test', isDefault: false };
export function is(value: any): value is string {
return value === Clean._id || value === Build._id || value === Rebuild._id || value === Test._id;
}
export function from(value: string | TaskGroup | undefined): TaskGroup | undefined {
if (value === undefined) {
return undefined;
} else if (Types.isString(value)) {
if (is(value)) {
return { _id: value, isDefault: false };
}
return undefined;
} else {
return value;
}
}
}
export interface TaskGroup {
_id: string;
isDefault?: boolean;
}
export const enum TaskScope {
Global = 1,
Workspace = 2,
Folder = 3
}
export namespace TaskSourceKind {
export const Workspace: 'workspace' = 'workspace';
export const Extension: 'extension' = 'extension';
export const InMemory: 'inMemory' = 'inMemory';
export const WorkspaceFile: 'workspaceFile' = 'workspaceFile';
export const User: 'user' = 'user';
export function toConfigurationTarget(kind: string): ConfigurationTarget {
switch (kind) {
case TaskSourceKind.User: return ConfigurationTarget.USER;
case TaskSourceKind.WorkspaceFile: return ConfigurationTarget.WORKSPACE;
default: return ConfigurationTarget.WORKSPACE_FOLDER;
}
}
}
export interface TaskSourceConfigElement {
workspaceFolder?: IWorkspaceFolder;
workspace?: IWorkspace;
file: string;
index: number;
element: any;
}
interface BaseTaskSource {
readonly kind: string;
readonly label: string;
}
export interface WorkspaceTaskSource extends BaseTaskSource {
readonly kind: 'workspace';
readonly config: TaskSourceConfigElement;
readonly customizes?: KeyedTaskIdentifier;
}
export interface ExtensionTaskSource extends BaseTaskSource {
readonly kind: 'extension';
readonly extension?: string;
readonly scope: TaskScope;
readonly workspaceFolder: IWorkspaceFolder | undefined;
}
export interface ExtensionTaskSourceTransfer {
__workspaceFolder: UriComponents;
__definition: { type: string;[name: string]: any };
}
export interface InMemoryTaskSource extends BaseTaskSource {
readonly kind: 'inMemory';
}
export interface UserTaskSource extends BaseTaskSource {
readonly kind: 'user';
readonly config: TaskSourceConfigElement;
readonly customizes?: KeyedTaskIdentifier;
}
export interface WorkspaceFileTaskSource extends BaseTaskSource {
readonly kind: 'workspaceFile';
readonly config: TaskSourceConfigElement;
readonly customizes?: KeyedTaskIdentifier;
}
export type TaskSource = WorkspaceTaskSource | ExtensionTaskSource | InMemoryTaskSource | UserTaskSource | WorkspaceFileTaskSource;
export type FileBasedTaskSource = WorkspaceTaskSource | UserTaskSource | WorkspaceFileTaskSource;
export interface TaskIdentifier {
type: string;
[name: string]: any;
}
export interface KeyedTaskIdentifier extends TaskIdentifier {
_key: string;
}
export interface TaskDependency {
uri: URI | string;
task: string | KeyedTaskIdentifier | undefined;
}
export const enum DependsOrder {
parallel = 'parallel',
sequence = 'sequence'
}
export interface ConfigurationProperties {
/**
* The task's name
*/
name?: string;
/**
* The task's name
*/
identifier?: string;
/**
* The task's group;
*/
group?: string | TaskGroup;
/**
* The presentation options
*/
presentation?: PresentationOptions;
/**
* The command options;
*/
options?: CommandOptions;
/**
* Whether the task is a background task or not.
*/
isBackground?: boolean;
/**
* Whether the task should prompt on close for confirmation if running.
*/
promptOnClose?: boolean;
/**
* The other tasks this task depends on.
*/
dependsOn?: TaskDependency[];
/**
* The order the dependsOn tasks should be executed in.
*/
dependsOrder?: DependsOrder;
/**
* A description of the task.
*/
detail?: string;
/**
* The problem watchers to use for this task
*/
problemMatchers?: Array<string | ProblemMatcher>;
}
export enum RunOnOptions {
default = 1,
folderOpen = 2
}
export interface RunOptions {
reevaluateOnRerun?: boolean;
runOn?: RunOnOptions;
instanceLimit?: number;
}
export namespace RunOptions {
export const defaults: RunOptions = { reevaluateOnRerun: true, runOn: RunOnOptions.default, instanceLimit: 1 };
}
export abstract class CommonTask {
/**
* The task's internal id
*/
readonly _id: string;
/**
* The cached label.
*/
_label: string = '';
type?: string;
runOptions: RunOptions;
configurationProperties: ConfigurationProperties;
_source: BaseTaskSource;
private _taskLoadMessages: string[] | undefined;
protected constructor(id: string, label: string | undefined, type: string | undefined, runOptions: RunOptions,
configurationProperties: ConfigurationProperties, source: BaseTaskSource) {
this._id = id;
if (label) {
this._label = label;
}
if (type) {
this.type = type;
}
this.runOptions = runOptions;
this.configurationProperties = configurationProperties;
this._source = source;
}
public getDefinition(useSource?: boolean): KeyedTaskIdentifier | undefined {
return undefined;
}
public getMapKey(): string {
return this._id;
}
public getRecentlyUsedKey(): string | undefined {
return undefined;
}
protected abstract getFolderId(): string | undefined;
public getCommonTaskId(): string {
interface RecentTaskKey {
folder: string | undefined;
id: string;
}
const key: RecentTaskKey = { folder: this.getFolderId(), id: this._id };
return JSON.stringify(key);
}
public clone(): Task {
return this.fromObject(Object.assign({}, <any>this));
}
protected abstract fromObject(object: any): Task;
public getWorkspaceFolder(): IWorkspaceFolder | undefined {
return undefined;
}
public getWorkspaceFileName(): string | undefined {
return undefined;
}
public getTelemetryKind(): string {
return 'unknown';
}
public matches(key: string | KeyedTaskIdentifier | undefined, compareId: boolean = false): boolean {
if (key === undefined) {
return false;
}
if (Types.isString(key)) {
return key === this._label || key === this.configurationProperties.identifier || (compareId && key === this._id);
}
let identifier = this.getDefinition(true);
return identifier !== undefined && identifier._key === key._key;
}
public getQualifiedLabel(): string {
let workspaceFolder = this.getWorkspaceFolder();
if (workspaceFolder) {
return `${this._label} (${workspaceFolder.name})`;
} else {
return this._label;
}
}
public getTaskExecution(): TaskExecution {
let result: TaskExecution = {
id: this._id,
task: <any>this
};
return result;
}
public addTaskLoadMessages(messages: string[] | undefined) {
if (this._taskLoadMessages === undefined) {
this._taskLoadMessages = [];
}
if (messages) {
this._taskLoadMessages = this._taskLoadMessages.concat(messages);
}
}
get taskLoadMessages(): string[] | undefined {
return this._taskLoadMessages;
}
}
export class CustomTask extends CommonTask {
override type!: '$customized'; // CUSTOMIZED_TASK_TYPE
instance: number | undefined;
/**
* Indicated the source of the task (e.g. tasks.json or extension)
*/
override _source: FileBasedTaskSource;
hasDefinedMatchers: boolean;
/**
* The command configuration
*/
command: CommandConfiguration = {};
public constructor(id: string, source: FileBasedTaskSource, label: string, type: string, command: CommandConfiguration | undefined,
hasDefinedMatchers: boolean, runOptions: RunOptions, configurationProperties: ConfigurationProperties) {
super(id, label, undefined, runOptions, configurationProperties, source);
this._source = source;
this.hasDefinedMatchers = hasDefinedMatchers;
if (command) {
this.command = command;
}
}
public override clone(): CustomTask {
return new CustomTask(this._id, this._source, this._label, this.type, this.command, this.hasDefinedMatchers, this.runOptions, this.configurationProperties);
}
public customizes(): KeyedTaskIdentifier | undefined {
if (this._source && this._source.customizes) {
return this._source.customizes;
}
return undefined;
}
public override getDefinition(useSource: boolean = false): KeyedTaskIdentifier {
if (useSource && this._source.customizes !== undefined) {
return this._source.customizes;
} else {
let type: string;
const commandRuntime = this.command ? this.command.runtime : undefined;
switch (commandRuntime) {
case RuntimeType.Shell:
type = 'shell';
break;
case RuntimeType.Process:
type = 'process';
break;
case RuntimeType.CustomExecution:
type = 'customExecution';
break;
case undefined:
type = '$composite';
break;
default:
throw new Error('Unexpected task runtime');
}
let result: KeyedTaskIdentifier = {
type,
_key: this._id,
id: this._id
};
return result;
}
}
public static is(value: any): value is CustomTask {
return value instanceof CustomTask;
}
public override getMapKey(): string {
let workspaceFolder = this._source.config.workspaceFolder;
return workspaceFolder ? `${workspaceFolder.uri.toString()}|${this._id}|${this.instance}` : `${this._id}|${this.instance}`;
}
protected getFolderId(): string | undefined {
return this._source.kind === TaskSourceKind.User ? USER_TASKS_GROUP_KEY : this._source.config.workspaceFolder?.uri.toString();
}
public override getCommonTaskId(): string {
return this._source.customizes ? super.getCommonTaskId() : (this.getRecentlyUsedKey() ?? super.getCommonTaskId());
}
public override getRecentlyUsedKey(): string | undefined {
interface CustomKey {
type: string;
folder: string;
id: string;
}
let workspaceFolder = this.getFolderId();
if (!workspaceFolder) {
return undefined;
}
let id: string = this.configurationProperties.identifier!;
if (this._source.kind !== TaskSourceKind.Workspace) {
id += this._source.kind;
}
let key: CustomKey = { type: CUSTOMIZED_TASK_TYPE, folder: workspaceFolder, id };
return JSON.stringify(key);
}
public override getWorkspaceFolder(): IWorkspaceFolder | undefined {
return this._source.config.workspaceFolder;
}
public override getWorkspaceFileName(): string | undefined {
return (this._source.config.workspace && this._source.config.workspace.configuration) ? resources.basename(this._source.config.workspace.configuration) : undefined;
}
public override getTelemetryKind(): string {
if (this._source.customizes) {
return 'workspace>extension';
} else {
return 'workspace';
}
}
protected fromObject(object: CustomTask): CustomTask {
return new CustomTask(object._id, object._source, object._label, object.type, object.command, object.hasDefinedMatchers, object.runOptions, object.configurationProperties);
}
}
export class ConfiguringTask extends CommonTask {
/**
* Indicated the source of the task (e.g. tasks.json or extension)
*/
override _source: FileBasedTaskSource;
configures: KeyedTaskIdentifier;
public constructor(id: string, source: FileBasedTaskSource, label: string | undefined, type: string | undefined,
configures: KeyedTaskIdentifier, runOptions: RunOptions, configurationProperties: ConfigurationProperties) {
super(id, label, type, runOptions, configurationProperties, source);
this._source = source;
this.configures = configures;
}
public static is(value: any): value is ConfiguringTask {
return value instanceof ConfiguringTask;
}
protected fromObject(object: any): Task {
return object;
}
public override getDefinition(): KeyedTaskIdentifier {
return this.configures;
}
public override getWorkspaceFileName(): string | undefined {
return (this._source.config.workspace && this._source.config.workspace.configuration) ? resources.basename(this._source.config.workspace.configuration) : undefined;
}
public override getWorkspaceFolder(): IWorkspaceFolder | undefined {
return this._source.config.workspaceFolder;
}
protected getFolderId(): string | undefined {
return this._source.kind === TaskSourceKind.User ? USER_TASKS_GROUP_KEY : this._source.config.workspaceFolder?.uri.toString();
}
public override getRecentlyUsedKey(): string | undefined {
interface CustomKey {
type: string;
folder: string;
id: string;
}
let workspaceFolder = this.getFolderId();
if (!workspaceFolder) {
return undefined;
}
let id: string = this.configurationProperties.identifier!;
if (this._source.kind !== TaskSourceKind.Workspace) {
id += this._source.kind;
}
let key: CustomKey = { type: CUSTOMIZED_TASK_TYPE, folder: workspaceFolder, id };
return JSON.stringify(key);
}
}
export class ContributedTask extends CommonTask {
/**
* Indicated the source of the task (e.g. tasks.json or extension)
* Set in the super constructor
*/
override _source!: ExtensionTaskSource;
instance: number | undefined;
defines: KeyedTaskIdentifier;
hasDefinedMatchers: boolean;
/**
* The command configuration
*/
command: CommandConfiguration;
public constructor(id: string, source: ExtensionTaskSource, label: string, type: string | undefined, defines: KeyedTaskIdentifier,
command: CommandConfiguration, hasDefinedMatchers: boolean, runOptions: RunOptions,
configurationProperties: ConfigurationProperties) {
super(id, label, type, runOptions, configurationProperties, source);
this.defines = defines;
this.hasDefinedMatchers = hasDefinedMatchers;
this.command = command;
}
public override clone(): ContributedTask {
return new ContributedTask(this._id, this._source, this._label, this.type, this.defines, this.command, this.hasDefinedMatchers, this.runOptions, this.configurationProperties);
}
public override getDefinition(): KeyedTaskIdentifier {
return this.defines;
}
public static is(value: any): value is ContributedTask {
return value instanceof ContributedTask;
}
public override getMapKey(): string {
let workspaceFolder = this._source.workspaceFolder;
return workspaceFolder
? `${this._source.scope.toString()}|${workspaceFolder.uri.toString()}|${this._id}|${this.instance}`
: `${this._source.scope.toString()}|${this._id}|${this.instance}`;
}
protected getFolderId(): string | undefined {
if (this._source.scope === TaskScope.Folder && this._source.workspaceFolder) {
return this._source.workspaceFolder.uri.toString();
}
return undefined;
}
public override getRecentlyUsedKey(): string | undefined {
interface ContributedKey {
type: string;
scope: number;
folder?: string;
id: string;
}
let key: ContributedKey = { type: 'contributed', scope: this._source.scope, id: this._id };
key.folder = this.getFolderId();
return JSON.stringify(key);
}
public override getWorkspaceFolder(): IWorkspaceFolder | undefined {
return this._source.workspaceFolder;
}
public override getTelemetryKind(): string {
return 'extension';
}
protected fromObject(object: ContributedTask): ContributedTask {
return new ContributedTask(object._id, object._source, object._label, object.type, object.defines, object.command, object.hasDefinedMatchers, object.runOptions, object.configurationProperties);
}
}
export class InMemoryTask extends CommonTask {
/**
* Indicated the source of the task (e.g. tasks.json or extension)
*/
override _source: InMemoryTaskSource;
instance: number | undefined;
override type!: 'inMemory';
public constructor(id: string, source: InMemoryTaskSource, label: string, type: string,
runOptions: RunOptions, configurationProperties: ConfigurationProperties) {
super(id, label, type, runOptions, configurationProperties, source);
this._source = source;
}
public override clone(): InMemoryTask {
return new InMemoryTask(this._id, this._source, this._label, this.type, this.runOptions, this.configurationProperties);
}
public static is(value: any): value is InMemoryTask {
return value instanceof InMemoryTask;
}
public override getTelemetryKind(): string {
return 'composite';
}
public override getMapKey(): string {
return `${this._id}|${this.instance}`;
}
protected getFolderId(): undefined {
return undefined;
}
protected fromObject(object: InMemoryTask): InMemoryTask {
return new InMemoryTask(object._id, object._source, object._label, object.type, object.runOptions, object.configurationProperties);
}
}
export type Task = CustomTask | ContributedTask | InMemoryTask;
export interface TaskExecution {
id: string;
task: Task;
}
export enum ExecutionEngine {
Process = 1,
Terminal = 2
}
export namespace ExecutionEngine {
export const _default: ExecutionEngine = ExecutionEngine.Terminal;
}
export const enum JsonSchemaVersion {
V0_1_0 = 1,
V2_0_0 = 2
}
export interface TaskSet {
tasks: Task[];
extension?: IExtensionDescription;
}
export interface TaskDefinition {
extensionId: string;
taskType: string;
required: string[];
properties: IJSONSchemaMap;
when?: ContextKeyExpression;
}
export class TaskSorter {
private _order: Map<string, number> = new Map();
constructor(workspaceFolders: IWorkspaceFolder[]) {
for (let i = 0; i < workspaceFolders.length; i++) {
this._order.set(workspaceFolders[i].uri.toString(), i);
}
}
public compare(a: Task | ConfiguringTask, b: Task | ConfiguringTask): number {
let aw = a.getWorkspaceFolder();
let bw = b.getWorkspaceFolder();
if (aw && bw) {
let ai = this._order.get(aw.uri.toString());
ai = ai === undefined ? 0 : ai + 1;
let bi = this._order.get(bw.uri.toString());
bi = bi === undefined ? 0 : bi + 1;
if (ai === bi) {
return a._label.localeCompare(b._label);
} else {
return ai - bi;
}
} else if (!aw && bw) {
return -1;
} else if (aw && !bw) {
return +1;
} else {
return 0;
}
}
}
export const enum TaskEventKind {
DependsOnStarted = 'dependsOnStarted',
AcquiredInput = 'acquiredInput',
Start = 'start',
ProcessStarted = 'processStarted',
Active = 'active',
Inactive = 'inactive',
Changed = 'changed',
Terminated = 'terminated',
ProcessEnded = 'processEnded',
End = 'end'
}
export const enum TaskRunType {
SingleRun = 'singleRun',
Background = 'background'
}
export interface TaskEvent {
kind: TaskEventKind;
taskId?: string;
taskName?: string;
runType?: TaskRunType;
group?: string | TaskGroup;
processId?: number;
exitCode?: number;
terminalId?: number;
__task?: Task;
resolvedVariables?: Map<string, string>;
}
export const enum TaskRunSource {
System,
User,
FolderOpen,
ConfigurationChange
}
export namespace TaskEvent {
export function create(kind: TaskEventKind.ProcessStarted | TaskEventKind.ProcessEnded, task: Task, processIdOrExitCode?: number): TaskEvent;
export function create(kind: TaskEventKind.Start, task: Task, terminalId?: number, resolvedVariables?: Map<string, string>): TaskEvent;
export function create(kind: TaskEventKind.AcquiredInput | TaskEventKind.DependsOnStarted | TaskEventKind.Start | TaskEventKind.Active | TaskEventKind.Inactive | TaskEventKind.Terminated | TaskEventKind.End, task: Task): TaskEvent;
export function create(kind: TaskEventKind.Changed): TaskEvent;
export function create(kind: TaskEventKind, task?: Task, processIdOrExitCodeOrTerminalId?: number, resolvedVariables?: Map<string, string>): TaskEvent {
if (task) {
let result: TaskEvent = {
kind: kind,
taskId: task._id,
taskName: task.configurationProperties.name,
runType: task.configurationProperties.isBackground ? TaskRunType.Background : TaskRunType.SingleRun,
group: task.configurationProperties.group,
processId: undefined as number | undefined,
exitCode: undefined as number | undefined,
terminalId: undefined as number | undefined,
__task: task,
};
if (kind === TaskEventKind.Start) {
result.terminalId = processIdOrExitCodeOrTerminalId;
result.resolvedVariables = resolvedVariables;
} else if (kind === TaskEventKind.ProcessStarted) {
result.processId = processIdOrExitCodeOrTerminalId;
} else if (kind === TaskEventKind.ProcessEnded) {
result.exitCode = processIdOrExitCodeOrTerminalId;
}
return Object.freeze(result);
} else {
return Object.freeze({ kind: TaskEventKind.Changed });
}
}
}
export namespace KeyedTaskIdentifier {
function sortedStringify(literal: any): string {
const keys = Object.keys(literal).sort();
let result: string = '';
for (const key of keys) {
let stringified = literal[key];
if (stringified instanceof Object) {
stringified = sortedStringify(stringified);
} else if (typeof stringified === 'string') {
stringified = stringified.replace(/,/g, ',,');
}
result += key + ',' + stringified + ',';
}
return result;
}
export function create(value: TaskIdentifier): KeyedTaskIdentifier {
const resultKey = sortedStringify(value);
let result = { _key: resultKey, type: value.taskType };
Object.assign(result, value);
return result;
}
}
export namespace TaskDefinition {
export function createTaskIdentifier(external: TaskIdentifier, reporter: { error(message: string): void; }): KeyedTaskIdentifier | undefined {
let definition = TaskDefinitionRegistry.get(external.type);
if (definition === undefined) {
// We have no task definition so we can't sanitize the literal. Take it as is
let copy = Objects.deepClone(external);
delete copy._key;
return KeyedTaskIdentifier.create(copy);
}
let literal: { type: string;[name: string]: any } = Object.create(null);
literal.type = definition.taskType;
let required: Set<string> = new Set();
definition.required.forEach(element => required.add(element));
let properties = definition.properties;
for (let property of Object.keys(properties)) {
let value = external[property];
if (value !== undefined && value !== null) {
literal[property] = value;
} else if (required.has(property)) {
let schema = properties[property];
if (schema.default !== undefined) {
literal[property] = Objects.deepClone(schema.default);
} else {
switch (schema.type) {
case 'boolean':
literal[property] = false;
break;
case 'number':
case 'integer':
literal[property] = 0;
break;
case 'string':
literal[property] = '';
break;
default:
reporter.error(nls.localize(
'TaskDefinition.missingRequiredProperty',
'Error: the task identifier \'{0}\' is missing the required property \'{1}\'. The task identifier will be ignored.', JSON.stringify(external, undefined, 0), property
));
return undefined;
}
}
}
}
return KeyedTaskIdentifier.create(literal);
}
}
| src/vs/workbench/contrib/tasks/common/tasks.ts | 0 | https://github.com/microsoft/vscode/commit/d6b581f218bc689cda2d3a009635c2df01a81984 | [
0.0001775972341420129,
0.00017248225049115717,
0.0001657243410591036,
0.00017277027654927224,
0.0000021265827854222152
]
|
{
"id": 2,
"code_window": [
"\n",
"\t\t\t\t// the first cell grows, but it's partially visible, so we won't push down the focused cell\n",
"\t\t\t\tassert.deepStrictEqual(cellList.scrollTop, 55);\n",
"\t\t\t\tassert.deepStrictEqual(cellList.getViewScrollBottom(), 265);\n",
"\n",
"\t\t\t\t// cellList.updateElementHeight2(viewModel.cellAt(0)!, 50);\n",
"\t\t\t\t// assert.deepStrictEqual(cellList.scrollTop, 5);\n",
"\t\t\t\t// assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);\n",
"\n",
"\t\t\t\t// focus won't be visible after cell 0 grow to 250, so let's try to keep the focused cell visible\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tcellList.updateElementHeight2(viewModel.cellAt(0)!, 50);\n",
"\t\t\t\tassert.deepStrictEqual(cellList.scrollTop, 5);\n",
"\t\t\t\tassert.deepStrictEqual(cellList.getViewScrollBottom(), 215);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/test/browser/notebookCellList.test.ts",
"type": "replace",
"edit_start_line_idx": 236
} | /*---------------------------------------------------------------------------------------------
* 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';
export class DebugCompoundRoot {
private stopped = false;
private stopEmitter = new Emitter<void>();
onDidSessionStop = this.stopEmitter.event;
sessionStopped(): void {
if (!this.stopped) { // avoid sending extranous terminate events
this.stopped = true;
this.stopEmitter.fire();
}
}
}
| src/vs/workbench/contrib/debug/common/debugCompoundRoot.ts | 0 | https://github.com/microsoft/vscode/commit/d6b581f218bc689cda2d3a009635c2df01a81984 | [
0.00017516322259325534,
0.00017077430675271899,
0.00016681206761859357,
0.00017034764459822327,
0.0000034226677598780952
]
|
{
"id": 3,
"code_window": [
"\n",
"\t\t\t\t// focus won't be visible after cell 0 grow to 250, so let's try to keep the focused cell visible\n",
"\t\t\t\t// cellList.updateElementHeight2(viewModel.cellAt(0)!, 250);\n",
"\t\t\t\t// assert.deepStrictEqual(cellList.scrollTop, 250 + 100 - cellList.renderHeight);\n",
"\t\t\t\t// assert.deepStrictEqual(cellList.getViewScrollBottom(), 250 + 100 - cellList.renderHeight + 210);\n",
"\t\t\t});\n",
"\t});\n",
"\n",
"\ttest('updateElementHeight with anchor #121723: focus element out of viewport', async function () {\n",
"\t\tawait withTestNotebook(\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tcellList.updateElementHeight2(viewModel.cellAt(0)!, 250);\n",
"\t\t\t\tassert.deepStrictEqual(cellList.scrollTop, 250 + 100 - cellList.renderHeight);\n",
"\t\t\t\tassert.deepStrictEqual(cellList.getViewScrollBottom(), 250 + 100 - cellList.renderHeight + 210);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/test/browser/notebookCellList.test.ts",
"type": "replace",
"edit_start_line_idx": 241
} | /*---------------------------------------------------------------------------------------------
* 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 { DisposableStore } from 'vs/base/common/lifecycle';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import { CellKind } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { NotebookOptions } from 'vs/workbench/contrib/notebook/common/notebookOptions';
import { createNotebookCellList, setupInstantiationService, withTestNotebook } from 'vs/workbench/contrib/notebook/test/browser/testNotebookEditor';
suite('NotebookCellList', () => {
let disposables: DisposableStore;
let instantiationService: TestInstantiationService;
let notebookDefaultOptions: NotebookOptions;
let topInsertToolbarHeight: number;
suiteSetup(() => {
disposables = new DisposableStore();
instantiationService = setupInstantiationService(disposables);
notebookDefaultOptions = new NotebookOptions(instantiationService.get(IConfigurationService));
topInsertToolbarHeight = notebookDefaultOptions.computeTopInsertToolbarHeight();
});
suiteTeardown(() => disposables.dispose());
test('revealElementsInView: reveal fully visible cell should not scroll', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// scroll a bit, scrollTop to bottom: 5, 215
cellList.scrollTop = 5;
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 5);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
// reveal cell 1, top 50, bottom 150, which is fully visible in the viewport
cellList.revealElementsInView({ start: 1, end: 2 });
assert.deepStrictEqual(cellList.scrollTop, 5);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
// reveal cell 2, top 150, bottom 200, which is fully visible in the viewport
cellList.revealElementsInView({ start: 2, end: 3 });
assert.deepStrictEqual(cellList.scrollTop, 5);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
// reveal cell 3, top 200, bottom 300, which is partially visible in the viewport
cellList.revealElementsInView({ start: 3, end: 4 });
assert.deepStrictEqual(cellList.scrollTop, 90);
});
});
test('revealElementsInView: reveal partially visible cell', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 0);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 210);
// reveal cell 3, top 200, bottom 300, which is partially visible in the viewport
cellList.revealElementsInView({ start: 3, end: 4 });
assert.deepStrictEqual(cellList.scrollTop, 90);
// scroll to 5
cellList.scrollTop = 5;
assert.deepStrictEqual(cellList.scrollTop, 5);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
// reveal cell 0, top 0, bottom 50
cellList.revealElementsInView({ start: 0, end: 1 });
assert.deepStrictEqual(cellList.scrollTop, 0);
});
});
test('revealElementsInView: reveal cell out of viewport', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
// without additionalscrollheight, the last 20 px will always be hidden due to `topInsertToolbarHeight`
cellList.updateOptions({ additionalScrollHeight: 100 });
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 0);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 210);
cellList.revealElementsInView({ start: 4, end: 5 });
assert.deepStrictEqual(cellList.scrollTop, 140);
// assert.deepStrictEqual(cellList.getViewScrollBottom(), 330);
});
});
test('updateElementHeight', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 0);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 210);
cellList.updateElementHeight(0, 60);
assert.deepStrictEqual(cellList.scrollTop, 0);
// scroll to 5
cellList.scrollTop = 5;
assert.deepStrictEqual(cellList.scrollTop, 5);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
cellList.updateElementHeight(0, 80);
assert.deepStrictEqual(cellList.scrollTop, 5);
});
});
test('updateElementHeight with anchor #121723', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 0);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 210);
// scroll to 5
cellList.scrollTop = 5;
assert.deepStrictEqual(cellList.scrollTop, 5);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
cellList.setFocus([1]);
cellList.updateElementHeight2(viewModel.cellAt(0)!, 100);
assert.deepStrictEqual(cellList.scrollHeight, 400);
// the first cell grows, but it's partially visible, so we won't push down the focused cell
assert.deepStrictEqual(cellList.scrollTop, 55);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 265);
// cellList.updateElementHeight2(viewModel.cellAt(0)!, 50);
// assert.deepStrictEqual(cellList.scrollTop, 5);
// assert.deepStrictEqual(cellList.getViewScrollBottom(), 215);
// focus won't be visible after cell 0 grow to 250, so let's try to keep the focused cell visible
// cellList.updateElementHeight2(viewModel.cellAt(0)!, 250);
// assert.deepStrictEqual(cellList.scrollTop, 250 + 100 - cellList.renderHeight);
// assert.deepStrictEqual(cellList.getViewScrollBottom(), 250 + 100 - cellList.renderHeight + 210);
});
});
test('updateElementHeight with anchor #121723: focus element out of viewport', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 0);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 210);
cellList.setFocus([4]);
cellList.updateElementHeight2(viewModel.cellAt(1)!, 130);
// the focus cell is not in the viewport, the scrolltop should not change at all
assert.deepStrictEqual(cellList.scrollTop, 0);
});
});
test('updateElementHeight of cells out of viewport should not trigger scroll #121140', async function () {
await withTestNotebook(
[
['# header a', 'markdown', CellKind.Markup, [], {}],
['var b = 1;', 'javascript', CellKind.Code, [], {}],
['# header b', 'markdown', CellKind.Markup, [], {}],
['var b = 2;', 'javascript', CellKind.Code, [], {}],
['# header c', 'markdown', CellKind.Markup, [], {}]
],
async (editor, viewModel) => {
viewModel.restoreEditorViewState({
editingCells: [false, false, false, false, false],
editorViewStates: [null, null, null, null, null],
cellTotalHeights: [50, 100, 50, 100, 50],
collapsedInputCells: {},
collapsedOutputCells: {},
});
const cellList = createNotebookCellList(instantiationService);
cellList.attachViewModel(viewModel);
// render height 210, it can render 3 full cells and 1 partial cell
cellList.layout(210 + topInsertToolbarHeight, 100);
// init scrollTop and scrollBottom
assert.deepStrictEqual(cellList.scrollTop, 0);
assert.deepStrictEqual(cellList.getViewScrollBottom(), 210);
cellList.setFocus([1]);
cellList.scrollTop = 80;
assert.deepStrictEqual(cellList.scrollTop, 80);
cellList.updateElementHeight2(viewModel.cellAt(0)!, 30);
assert.deepStrictEqual(cellList.scrollTop, 60);
});
});
});
| src/vs/workbench/contrib/notebook/test/browser/notebookCellList.test.ts | 1 | https://github.com/microsoft/vscode/commit/d6b581f218bc689cda2d3a009635c2df01a81984 | [
0.9976497292518616,
0.03275720030069351,
0.000160397554282099,
0.0015917947748675942,
0.17330685257911682
]
|
{
"id": 3,
"code_window": [
"\n",
"\t\t\t\t// focus won't be visible after cell 0 grow to 250, so let's try to keep the focused cell visible\n",
"\t\t\t\t// cellList.updateElementHeight2(viewModel.cellAt(0)!, 250);\n",
"\t\t\t\t// assert.deepStrictEqual(cellList.scrollTop, 250 + 100 - cellList.renderHeight);\n",
"\t\t\t\t// assert.deepStrictEqual(cellList.getViewScrollBottom(), 250 + 100 - cellList.renderHeight + 210);\n",
"\t\t\t});\n",
"\t});\n",
"\n",
"\ttest('updateElementHeight with anchor #121723: focus element out of viewport', async function () {\n",
"\t\tawait withTestNotebook(\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tcellList.updateElementHeight2(viewModel.cellAt(0)!, 250);\n",
"\t\t\t\tassert.deepStrictEqual(cellList.scrollTop, 250 + 100 - cellList.renderHeight);\n",
"\t\t\t\tassert.deepStrictEqual(cellList.getViewScrollBottom(), 250 + 100 - cellList.renderHeight + 210);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/test/browser/notebookCellList.test.ts",
"type": "replace",
"edit_start_line_idx": 241
} | 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/d6b581f218bc689cda2d3a009635c2df01a81984 | [
0.00017091383051592857,
0.00017091383051592857,
0.00017091383051592857,
0.00017091383051592857,
0
]
|
{
"id": 3,
"code_window": [
"\n",
"\t\t\t\t// focus won't be visible after cell 0 grow to 250, so let's try to keep the focused cell visible\n",
"\t\t\t\t// cellList.updateElementHeight2(viewModel.cellAt(0)!, 250);\n",
"\t\t\t\t// assert.deepStrictEqual(cellList.scrollTop, 250 + 100 - cellList.renderHeight);\n",
"\t\t\t\t// assert.deepStrictEqual(cellList.getViewScrollBottom(), 250 + 100 - cellList.renderHeight + 210);\n",
"\t\t\t});\n",
"\t});\n",
"\n",
"\ttest('updateElementHeight with anchor #121723: focus element out of viewport', async function () {\n",
"\t\tawait withTestNotebook(\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tcellList.updateElementHeight2(viewModel.cellAt(0)!, 250);\n",
"\t\t\t\tassert.deepStrictEqual(cellList.scrollTop, 250 + 100 - cellList.renderHeight);\n",
"\t\t\t\tassert.deepStrictEqual(cellList.getViewScrollBottom(), 250 + 100 - cellList.renderHeight + 210);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/test/browser/notebookCellList.test.ts",
"type": "replace",
"edit_start_line_idx": 241
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { Schemas } from 'vs/base/common/network';
import { URI } from 'vs/base/common/uri';
import * as pfs from 'vs/base/node/pfs';
import { ILogService } from 'vs/platform/log/common/log';
import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { ExtHostSearch, reviveQuery } from 'vs/workbench/api/common/extHostSearch';
import { IURITransformerService } from 'vs/workbench/api/common/extHostUriTransformerService';
import { IFileQuery, IRawFileQuery, ISearchCompleteStats, ISerializedSearchProgressItem, isSerializedFileMatch, ITextQuery } from 'vs/workbench/services/search/common/search';
import { TextSearchManager } from 'vs/workbench/services/search/common/textSearchManager';
import { SearchService } from 'vs/workbench/services/search/node/rawSearchService';
import { RipgrepSearchProvider } from 'vs/workbench/services/search/node/ripgrepSearchProvider';
import { OutputChannel } from 'vs/workbench/services/search/node/ripgrepSearchUtils';
import { NativeTextSearchManager } from 'vs/workbench/services/search/node/textSearchManager';
import type * as vscode from 'vscode';
export class NativeExtHostSearch extends ExtHostSearch {
protected _pfs: typeof pfs = pfs; // allow extending for tests
private _internalFileSearchHandle: number = -1;
private _internalFileSearchProvider: SearchService | null = null;
private _registeredEHSearchProvider = false;
constructor(
@IExtHostRpcService extHostRpc: IExtHostRpcService,
@IExtHostInitDataService initData: IExtHostInitDataService,
@IURITransformerService _uriTransformer: IURITransformerService,
@ILogService _logService: ILogService,
) {
super(extHostRpc, _uriTransformer, _logService);
const outputChannel = new OutputChannel('RipgrepSearchUD', this._logService);
this.registerTextSearchProvider(Schemas.userData, new RipgrepSearchProvider(outputChannel));
if (initData.remote.isRemote && initData.remote.authority) {
this._registerEHSearchProviders();
}
}
override $enableExtensionHostSearch(): void {
this._registerEHSearchProviders();
}
private _registerEHSearchProviders(): void {
if (this._registeredEHSearchProvider) {
return;
}
this._registeredEHSearchProvider = true;
const outputChannel = new OutputChannel('RipgrepSearchEH', this._logService);
this.registerTextSearchProvider(Schemas.file, new RipgrepSearchProvider(outputChannel));
this.registerInternalFileSearchProvider(Schemas.file, new SearchService('fileSearchProvider'));
}
private registerInternalFileSearchProvider(scheme: string, provider: SearchService): IDisposable {
const handle = this._handlePool++;
this._internalFileSearchProvider = provider;
this._internalFileSearchHandle = handle;
this._proxy.$registerFileSearchProvider(handle, this._transformScheme(scheme));
return toDisposable(() => {
this._internalFileSearchProvider = null;
this._proxy.$unregisterProvider(handle);
});
}
override $provideFileSearchResults(handle: number, session: number, rawQuery: IRawFileQuery, token: vscode.CancellationToken): Promise<ISearchCompleteStats> {
const query = reviveQuery(rawQuery);
if (handle === this._internalFileSearchHandle) {
return this.doInternalFileSearch(handle, session, query, token);
}
return super.$provideFileSearchResults(handle, session, rawQuery, token);
}
private doInternalFileSearch(handle: number, session: number, rawQuery: IFileQuery, token: vscode.CancellationToken): Promise<ISearchCompleteStats> {
const onResult = (ev: ISerializedSearchProgressItem) => {
if (isSerializedFileMatch(ev)) {
ev = [ev];
}
if (Array.isArray(ev)) {
this._proxy.$handleFileMatch(handle, session, ev.map(m => URI.file(m.path)));
return;
}
if (ev.message) {
this._logService.debug('ExtHostSearch', ev.message);
}
};
if (!this._internalFileSearchProvider) {
throw new Error('No internal file search handler');
}
return <Promise<ISearchCompleteStats>>this._internalFileSearchProvider.doFileSearch(rawQuery, onResult, token);
}
override $clearCache(cacheKey: string): Promise<void> {
if (this._internalFileSearchProvider) {
this._internalFileSearchProvider.clearCache(cacheKey);
}
return super.$clearCache(cacheKey);
}
protected override createTextSearchManager(query: ITextQuery, provider: vscode.TextSearchProvider): TextSearchManager {
return new NativeTextSearchManager(query, provider, undefined, 'textSearchProvider');
}
}
| src/vs/workbench/api/node/extHostSearch.ts | 0 | https://github.com/microsoft/vscode/commit/d6b581f218bc689cda2d3a009635c2df01a81984 | [
0.00017800887871999294,
0.00017387991829309613,
0.0001707673945929855,
0.0001737774582579732,
0.000001820449597289553
]
|
{
"id": 3,
"code_window": [
"\n",
"\t\t\t\t// focus won't be visible after cell 0 grow to 250, so let's try to keep the focused cell visible\n",
"\t\t\t\t// cellList.updateElementHeight2(viewModel.cellAt(0)!, 250);\n",
"\t\t\t\t// assert.deepStrictEqual(cellList.scrollTop, 250 + 100 - cellList.renderHeight);\n",
"\t\t\t\t// assert.deepStrictEqual(cellList.getViewScrollBottom(), 250 + 100 - cellList.renderHeight + 210);\n",
"\t\t\t});\n",
"\t});\n",
"\n",
"\ttest('updateElementHeight with anchor #121723: focus element out of viewport', async function () {\n",
"\t\tawait withTestNotebook(\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tcellList.updateElementHeight2(viewModel.cellAt(0)!, 250);\n",
"\t\t\t\tassert.deepStrictEqual(cellList.scrollTop, 250 + 100 - cellList.renderHeight);\n",
"\t\t\t\tassert.deepStrictEqual(cellList.getViewScrollBottom(), 250 + 100 - cellList.renderHeight + 210);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/test/browser/notebookCellList.test.ts",
"type": "replace",
"edit_start_line_idx": 241
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { Registry } from 'vs/platform/registry/common/platform';
import { Extensions as JSONExtensions, IJSONContributionRegistry } from 'vs/platform/jsonschemas/common/jsonContributionRegistry';
import { IJSONSchema } from 'vs/base/common/jsonSchema';
import { workbenchColorsSchemaId } from 'vs/platform/theme/common/colorRegistry';
import { tokenStylingSchemaId } from 'vs/platform/theme/common/tokenClassificationRegistry';
let textMateScopes = [
'comment',
'comment.block',
'comment.block.documentation',
'comment.line',
'constant',
'constant.character',
'constant.character.escape',
'constant.numeric',
'constant.numeric.integer',
'constant.numeric.float',
'constant.numeric.hex',
'constant.numeric.octal',
'constant.other',
'constant.regexp',
'constant.rgb-value',
'emphasis',
'entity',
'entity.name',
'entity.name.class',
'entity.name.function',
'entity.name.method',
'entity.name.section',
'entity.name.selector',
'entity.name.tag',
'entity.name.type',
'entity.other',
'entity.other.attribute-name',
'entity.other.inherited-class',
'invalid',
'invalid.deprecated',
'invalid.illegal',
'keyword',
'keyword.control',
'keyword.operator',
'keyword.operator.new',
'keyword.operator.assignment',
'keyword.operator.arithmetic',
'keyword.operator.logical',
'keyword.other',
'markup',
'markup.bold',
'markup.changed',
'markup.deleted',
'markup.heading',
'markup.inline.raw',
'markup.inserted',
'markup.italic',
'markup.list',
'markup.list.numbered',
'markup.list.unnumbered',
'markup.other',
'markup.quote',
'markup.raw',
'markup.underline',
'markup.underline.link',
'meta',
'meta.block',
'meta.cast',
'meta.class',
'meta.function',
'meta.function-call',
'meta.preprocessor',
'meta.return-type',
'meta.selector',
'meta.tag',
'meta.type.annotation',
'meta.type',
'punctuation.definition.string.begin',
'punctuation.definition.string.end',
'punctuation.separator',
'punctuation.separator.continuation',
'punctuation.terminator',
'storage',
'storage.modifier',
'storage.type',
'string',
'string.interpolated',
'string.other',
'string.quoted',
'string.quoted.double',
'string.quoted.other',
'string.quoted.single',
'string.quoted.triple',
'string.regexp',
'string.unquoted',
'strong',
'support',
'support.class',
'support.constant',
'support.function',
'support.other',
'support.type',
'support.type.property-name',
'support.variable',
'variable',
'variable.language',
'variable.name',
'variable.other',
'variable.other.readwrite',
'variable.parameter'
];
export const textmateColorsSchemaId = 'vscode://schemas/textmate-colors';
export const textmateColorSettingsSchemaId = `${textmateColorsSchemaId}#/definitions/settings`;
export const textmateColorGroupSchemaId = `${textmateColorsSchemaId}#/definitions/colorGroup`;
const textmateColorSchema: IJSONSchema = {
type: 'array',
definitions: {
colorGroup: {
default: '#FF0000',
anyOf: [
{
type: 'string',
format: 'color-hex'
},
{
$ref: '#/definitions/settings'
}
]
},
settings: {
type: 'object',
description: nls.localize('schema.token.settings', 'Colors and styles for the token.'),
properties: {
foreground: {
type: 'string',
description: nls.localize('schema.token.foreground', 'Foreground color for the token.'),
format: 'color-hex',
default: '#ff0000'
},
background: {
type: 'string',
deprecationMessage: nls.localize('schema.token.background.warning', 'Token background colors are currently not supported.')
},
fontStyle: {
type: 'string',
description: nls.localize('schema.token.fontStyle', 'Font style of the rule: \'italic\', \'bold\' or \'underline\' or a combination. The empty string unsets inherited settings.'),
pattern: '^(\\s*\\b(italic|bold|underline))*\\s*$',
patternErrorMessage: nls.localize('schema.fontStyle.error', 'Font style must be \'italic\', \'bold\' or \'underline\' or a combination or the empty string.'),
defaultSnippets: [{ label: nls.localize('schema.token.fontStyle.none', 'None (clear inherited style)'), bodyText: '""' }, { body: 'italic' }, { body: 'bold' }, { body: 'underline' }, { body: 'italic bold' }, { body: 'italic underline' }, { body: 'bold underline' }, { body: 'italic bold underline' }]
}
},
additionalProperties: false,
defaultSnippets: [{ body: { foreground: '${1:#FF0000}', fontStyle: '${2:bold}' } }]
}
},
items: {
type: 'object',
defaultSnippets: [{ body: { scope: '${1:keyword.operator}', settings: { foreground: '${2:#FF0000}' } } }],
properties: {
name: {
type: 'string',
description: nls.localize('schema.properties.name', 'Description of the rule.')
},
scope: {
description: nls.localize('schema.properties.scope', 'Scope selector against which this rule matches.'),
anyOf: [
{
enum: textMateScopes
},
{
type: 'string'
},
{
type: 'array',
items: {
enum: textMateScopes
}
},
{
type: 'array',
items: {
type: 'string'
}
}
]
},
settings: {
$ref: '#/definitions/settings'
}
},
required: [
'settings', 'scope'
],
additionalProperties: false
}
};
export const colorThemeSchemaId = 'vscode://schemas/color-theme';
const colorThemeSchema: IJSONSchema = {
type: 'object',
allowComments: true,
allowTrailingCommas: true,
properties: {
colors: {
description: nls.localize('schema.workbenchColors', 'Colors in the workbench'),
$ref: workbenchColorsSchemaId,
additionalProperties: false
},
tokenColors: {
anyOf: [{
type: 'string',
description: nls.localize('schema.tokenColors.path', 'Path to a tmTheme file (relative to the current file).')
},
{
description: nls.localize('schema.colors', 'Colors for syntax highlighting'),
$ref: textmateColorsSchemaId
}
]
},
semanticHighlighting: {
type: 'boolean',
description: nls.localize('schema.supportsSemanticHighlighting', 'Whether semantic highlighting should be enabled for this theme.')
},
semanticTokenColors: {
type: 'object',
description: nls.localize('schema.semanticTokenColors', 'Colors for semantic tokens'),
$ref: tokenStylingSchemaId
}
}
};
export function registerColorThemeSchemas() {
let schemaRegistry = Registry.as<IJSONContributionRegistry>(JSONExtensions.JSONContribution);
schemaRegistry.registerSchema(colorThemeSchemaId, colorThemeSchema);
schemaRegistry.registerSchema(textmateColorsSchemaId, textmateColorSchema);
}
| src/vs/workbench/services/themes/common/colorThemeSchema.ts | 0 | https://github.com/microsoft/vscode/commit/d6b581f218bc689cda2d3a009635c2df01a81984 | [
0.0001770070375641808,
0.0001733069511828944,
0.0001672449434408918,
0.0001734782854327932,
0.0000020888485323666828
]
|
{
"id": 0,
"code_window": [
" @HostBinding() href: string;\n",
" @HostBinding('class.router-link-active') isActive: boolean = false;\n",
"\n",
" constructor(@Optional() private _routeSegment: RouteSegment, private _router: Router) {\n",
" // because auxiliary links take existing primary and auxiliary routes into account,\n",
" // we need to update the link whenever params or other routes change.\n",
" this._subscription =\n",
" ObservableWrapper.subscribe(_router.changes, (_) => { this._updateTargetUrlAndHref(); });\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" constructor(private _routeSegment: RouteSegment, private _router: Router) {\n"
],
"file_path": "modules/@angular/router/src/directives/router_link.ts",
"type": "replace",
"edit_start_line_idx": 61
} | import {
AsyncTestCompleter,
beforeEach,
ddescribe,
xdescribe,
describe,
expect,
iit,
inject,
beforeEachProviders,
it,
xit
} from '@angular/core/testing/testing_internal';
import {recognize} from '../src/recognize';
import {Routes, Route} from '@angular/router';
import {provide, Component, ComponentResolver} from '@angular/core';
import {UrlSegment, RouteTree, UrlTree} from '../src/segments';
import {DefaultRouterUrlSerializer} from '../src/router_url_serializer';
import {DEFAULT_OUTLET_NAME} from '../src/constants';
export function main() {
ddescribe('recognize', () => {
it('should handle position args',
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree("b/paramB/c/paramC/d"))
.then(r => {
let a = r.root;
expect(stringifyUrl(a.urlSegments)).toEqual([""]);
expect(a.type).toBe(ComponentA);
let b = r.firstChild(r.root);
expect(stringifyUrl(b.urlSegments)).toEqual(["b", "paramB"]);
expect(b.type).toBe(ComponentB);
let c = r.firstChild(r.firstChild(r.root));
expect(stringifyUrl(c.urlSegments)).toEqual(["c", "paramC"]);
expect(c.type).toBe(ComponentC);
let d = r.firstChild(r.firstChild(r.firstChild(r.root)));
expect(stringifyUrl(d.urlSegments)).toEqual(["d"]);
expect(d.type).toBe(ComponentD);
async.done();
});
}));
it('should support empty routes',
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree("f"))
.then(r => {
let a = r.root;
expect(stringifyUrl(a.urlSegments)).toEqual([""]);
expect(a.type).toBe(ComponentA);
let f = r.firstChild(r.root);
expect(stringifyUrl(f.urlSegments)).toEqual(["f"]);
expect(f.type).toBe(ComponentF);
let d = r.firstChild(r.firstChild(r.root));
expect(stringifyUrl(d.urlSegments)).toEqual([]);
expect(d.type).toBe(ComponentD);
async.done();
});
}));
it('should handle aux routes',
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree("b/paramB(/d//right:d)"))
.then(r => {
let c = r.children(r.root);
expect(stringifyUrl(c[0].urlSegments)).toEqual(["b", "paramB"]);
expect(c[0].outlet).toEqual(DEFAULT_OUTLET_NAME);
expect(c[0].type).toBe(ComponentB);
expect(stringifyUrl(c[1].urlSegments)).toEqual(["d"]);
expect(c[1].outlet).toEqual("aux");
expect(c[1].type).toBe(ComponentD);
expect(stringifyUrl(c[2].urlSegments)).toEqual(["d"]);
expect(c[2].outlet).toEqual("right");
expect(c[2].type).toBe(ComponentD);
async.done();
});
}));
it("should error when two segments with the same outlet name",
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree("b/paramB(right:d//right:e)"))
.catch(e => {
expect(e.message).toEqual(
"Two segments cannot have the same outlet name: 'right:d' and 'right:e'.");
async.done();
});
}));
it('should handle nested aux routes',
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree("b/paramB(/d(right:e))"))
.then(r => {
let c = r.children(r.root);
expect(stringifyUrl(c[0].urlSegments)).toEqual(["b", "paramB"]);
expect(c[0].outlet).toEqual(DEFAULT_OUTLET_NAME);
expect(c[0].type).toBe(ComponentB);
expect(stringifyUrl(c[1].urlSegments)).toEqual(["d"]);
expect(c[1].outlet).toEqual("aux");
expect(c[1].type).toBe(ComponentD);
expect(stringifyUrl(c[2].urlSegments)).toEqual(["e"]);
expect(c[2].outlet).toEqual("right");
expect(c[2].type).toBe(ComponentE);
async.done();
});
}));
it('should handle non top-level aux routes',
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree('b/paramB/d(e)'))
.then(r => {
let c = r.children(r.firstChild(r.root));
expect(stringifyUrl(c[0].urlSegments)).toEqual(["d"]);
expect(c[0].outlet).toEqual(DEFAULT_OUTLET_NAME);
expect(c[0].type).toBe(ComponentD);
expect(stringifyUrl(c[1].urlSegments)).toEqual(["e"]);
expect(c[1].outlet).toEqual("aux");
expect(c[1].type).toBe(ComponentE);
async.done();
});
}));
it('should handle matrix parameters',
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree("b/paramB;b1=1;b2=2(/d;d1=1;d2=2)"))
.then(r => {
let c = r.children(r.root);
expect(c[0].parameters).toEqual({'b': 'paramB', 'b1': '1', 'b2': '2'});
expect(c[1].parameters).toEqual({'d1': '1', 'd2': '2'});
async.done();
});
}));
it('should match a wildcard',
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentG, tree("a;aa=1/b;bb=2"))
.then(r => {
let c = r.children(r.root);
expect(c.length).toEqual(1);
expect(stringifyUrl(c[0].urlSegments)).toEqual([]);
expect(c[0].parameters).toEqual(null);
async.done();
});
}));
it('should error when no matching routes',
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree("invalid"))
.catch(e => {
expect(e.message).toContain("Cannot match any routes");
async.done();
});
}));
it('should handle no matching routes (too short)',
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree("b"))
.catch(e => {
expect(e.message).toContain("Cannot match any routes");
async.done();
});
}));
it("should error when a component doesn't have @Routes",
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree("d/invalid"))
.catch(e => {
expect(e.message)
.toEqual("Component 'ComponentD' does not have route configuration");
async.done();
});
}));
});
}
function tree(url: string): UrlTree {
return new DefaultRouterUrlSerializer().parse(url);
}
function stringifyUrl(segments: UrlSegment[]): string[] {
return segments.map(s => s.segment);
}
@Component({selector: 'd', template: 't'})
class ComponentD {
}
@Component({selector: 'e', template: 't'})
class ComponentE {
}
@Component({selector: 'f', template: 't'})
@Routes([new Route({path: "/", component: ComponentD})])
class ComponentF {
}
@Component({selector: 'c', template: 't'})
@Routes([new Route({path: "d", component: ComponentD})])
class ComponentC {
}
@Component({selector: 'b', template: 't'})
@Routes([
new Route({path: "d", component: ComponentD}),
new Route({path: "e", component: ComponentE}),
new Route({path: "c/:c", component: ComponentC})
])
class ComponentB {
}
@Component({selector: 'g', template: 't'})
@Routes(
[new Route({path: "d", component: ComponentD}), new Route({path: "*", component: ComponentE})])
class ComponentG {
}
@Component({selector: 'a', template: 't'})
@Routes([
new Route({path: "b/:b", component: ComponentB}),
new Route({path: "d", component: ComponentD}),
new Route({path: "e", component: ComponentE}),
new Route({path: "f", component: ComponentF})
])
class ComponentA {
}
| modules/@angular/router/test/recognize_spec.ts | 1 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.00023109912581276149,
0.0001718965795589611,
0.0001640529080759734,
0.00016914409934543073,
0.000012510658962128218
]
|
{
"id": 0,
"code_window": [
" @HostBinding() href: string;\n",
" @HostBinding('class.router-link-active') isActive: boolean = false;\n",
"\n",
" constructor(@Optional() private _routeSegment: RouteSegment, private _router: Router) {\n",
" // because auxiliary links take existing primary and auxiliary routes into account,\n",
" // we need to update the link whenever params or other routes change.\n",
" this._subscription =\n",
" ObservableWrapper.subscribe(_router.changes, (_) => { this._updateTargetUrlAndHref(); });\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" constructor(private _routeSegment: RouteSegment, private _router: Router) {\n"
],
"file_path": "modules/@angular/router/src/directives/router_link.ts",
"type": "replace",
"edit_start_line_idx": 61
} | {{greeting}} | modules_dart/transform/test/transform/inliner_for_test/split_url_expression_files/template.html | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.00017214885156136006,
0.00017214885156136006,
0.00017214885156136006,
0.00017214885156136006,
0
]
|
{
"id": 0,
"code_window": [
" @HostBinding() href: string;\n",
" @HostBinding('class.router-link-active') isActive: boolean = false;\n",
"\n",
" constructor(@Optional() private _routeSegment: RouteSegment, private _router: Router) {\n",
" // because auxiliary links take existing primary and auxiliary routes into account,\n",
" // we need to update the link whenever params or other routes change.\n",
" this._subscription =\n",
" ObservableWrapper.subscribe(_router.changes, (_) => { this._updateTargetUrlAndHref(); });\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" constructor(private _routeSegment: RouteSegment, private _router: Router) {\n"
],
"file_path": "modules/@angular/router/src/directives/router_link.ts",
"type": "replace",
"edit_start_line_idx": 61
} | import {Type} from '@angular/core';
import {NgControlName} from './directives/ng_control_name';
import {NgFormControl} from './directives/ng_form_control';
import {NgModel} from './directives/ng_model';
import {NgControlGroup} from './directives/ng_control_group';
import {NgFormModel} from './directives/ng_form_model';
import {NgForm} from './directives/ng_form';
import {DefaultValueAccessor} from './directives/default_value_accessor';
import {CheckboxControlValueAccessor} from './directives/checkbox_value_accessor';
import {NumberValueAccessor} from './directives/number_value_accessor';
import {RadioControlValueAccessor} from './directives/radio_control_value_accessor';
import {NgControlStatus} from './directives/ng_control_status';
import {
SelectControlValueAccessor,
NgSelectOption
} from './directives/select_control_value_accessor';
import {
RequiredValidator,
MinLengthValidator,
MaxLengthValidator,
PatternValidator
} from './directives/validators';
export {NgControlName} from './directives/ng_control_name';
export {NgFormControl} from './directives/ng_form_control';
export {NgModel} from './directives/ng_model';
export {NgControlGroup} from './directives/ng_control_group';
export {NgFormModel} from './directives/ng_form_model';
export {NgForm} from './directives/ng_form';
export {DefaultValueAccessor} from './directives/default_value_accessor';
export {CheckboxControlValueAccessor} from './directives/checkbox_value_accessor';
export {
RadioControlValueAccessor,
RadioButtonState
} from './directives/radio_control_value_accessor';
export {NumberValueAccessor} from './directives/number_value_accessor';
export {NgControlStatus} from './directives/ng_control_status';
export {
SelectControlValueAccessor,
NgSelectOption
} from './directives/select_control_value_accessor';
export {
RequiredValidator,
MinLengthValidator,
MaxLengthValidator,
PatternValidator
} from './directives/validators';
export {NgControl} from './directives/ng_control';
export {ControlValueAccessor} from './directives/control_value_accessor';
/**
*
* A list of all the form directives used as part of a `@Component` annotation.
*
* This is a shorthand for importing them each individually.
*
* ### Example
*
* ```typescript
* @Component({
* selector: 'my-app',
* directives: [FORM_DIRECTIVES]
* })
* class MyApp {}
* ```
*/
export const FORM_DIRECTIVES: Type[] = /*@ts2dart_const*/[
NgControlName,
NgControlGroup,
NgFormControl,
NgModel,
NgFormModel,
NgForm,
NgSelectOption,
DefaultValueAccessor,
NumberValueAccessor,
CheckboxControlValueAccessor,
SelectControlValueAccessor,
RadioControlValueAccessor,
NgControlStatus,
RequiredValidator,
MinLengthValidator,
MaxLengthValidator,
PatternValidator
];
| modules/@angular/common/src/forms/directives.ts | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.0001767850772012025,
0.00017255073180422187,
0.0001642814459046349,
0.0001739891740726307,
0.000003993829977844143
]
|
{
"id": 0,
"code_window": [
" @HostBinding() href: string;\n",
" @HostBinding('class.router-link-active') isActive: boolean = false;\n",
"\n",
" constructor(@Optional() private _routeSegment: RouteSegment, private _router: Router) {\n",
" // because auxiliary links take existing primary and auxiliary routes into account,\n",
" // we need to update the link whenever params or other routes change.\n",
" this._subscription =\n",
" ObservableWrapper.subscribe(_router.changes, (_) => { this._updateTargetUrlAndHref(); });\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" constructor(private _routeSegment: RouteSegment, private _router: Router) {\n"
],
"file_path": "modules/@angular/router/src/directives/router_link.ts",
"type": "replace",
"edit_start_line_idx": 61
} | /// This file contains tests that make sense only in Dart
library angular2.test.facade.async_dart_spec;
import 'dart:async';
import 'package:angular2/testing_internal.dart';
import 'package:angular2/src/facade/async.dart';
class MockException implements Error {
var message;
var stackTrace;
}
class NonError {
var message;
}
void functionThatThrows() {
try {
throw new MockException();
} catch (e, stack) {
// If we lose the stack trace the message will no longer match
// the first line in the stack
e.message = stack.toString().split('\n')[0];
e.stackTrace = stack;
rethrow;
}
}
void functionThatThrowsNonError() {
try {
throw new NonError();
} catch (e, stack) {
// If we lose the stack trace the message will no longer match
// the first line in the stack
e.message = stack.toString().split('\n')[0];
rethrow;
}
}
void expectFunctionThatThrowsWithStackTrace(
Future future, AsyncTestCompleter async) {
PromiseWrapper.catchError(future, (err, StackTrace stack) {
expect(stack.toString().split('\n')[0]).toEqual(err.message);
async.done();
});
}
main() {
describe('async facade', () {
describe('Completer', () {
it(
'should preserve Error stack traces',
inject([AsyncTestCompleter], (async) {
var c = PromiseWrapper.completer();
expectFunctionThatThrowsWithStackTrace(c.promise, async);
try {
functionThatThrows();
} catch (e) {
c.reject(e, null);
}
}));
it(
'should preserve error stack traces for non-Errors',
inject([AsyncTestCompleter], (async) {
var c = PromiseWrapper.completer();
expectFunctionThatThrowsWithStackTrace(c.promise, async);
try {
functionThatThrowsNonError();
} catch (e, s) {
c.reject(e, s);
}
}));
});
describe('PromiseWrapper', () {
describe('reject', () {
it(
'should preserve Error stack traces',
inject([AsyncTestCompleter], (async) {
try {
functionThatThrows();
} catch (e) {
var rejectedFuture = PromiseWrapper.reject(e, null);
expectFunctionThatThrowsWithStackTrace(rejectedFuture, async);
}
}));
it(
'should preserve stack traces for non-Errors',
inject([AsyncTestCompleter], (async) {
try {
functionThatThrowsNonError();
} catch (e, s) {
var rejectedFuture = PromiseWrapper.reject(e, s);
expectFunctionThatThrowsWithStackTrace(rejectedFuture, async);
}
}));
});
});
});
}
| modules/@angular/facade/test/async_dart_spec.dart | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.00017487534205429256,
0.0001715930993668735,
0.000169066057424061,
0.00017139314149972051,
0.0000020329664494056487
]
|
{
"id": 1,
"code_window": [
"import {BaseException} from '@angular/core';\n",
"import {ComponentResolver} from '@angular/core';\n",
"import {DEFAULT_OUTLET_NAME} from './constants';\n",
"import {reflector} from '@angular/core';\n",
"\n",
"// TODO: vsavkin: recognize should take the old tree and merge it\n",
"export function recognize(componentResolver: ComponentResolver, rootComponent: Type,\n",
" url: UrlTree): Promise<RouteTree> {\n",
" let matched = new _MatchResult(rootComponent, [url.root], {}, rootNode(url).children, []);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "modules/@angular/router/src/recognize.ts",
"type": "replace",
"edit_start_line_idx": 10
} | import {SpyLocation} from '@angular/common/testing';
import {Location} from '@angular/common';
import {Router, RouterOutletMap} from '../src/router';
import {RouterUrlSerializer, DefaultRouterUrlSerializer} from '../src/router_url_serializer';
import {Component, ComponentResolver} from '@angular/core';
@Component({selector: 'fake-app-root-comp', template: `<span></span>`})
class FakeAppRootCmp {
}
function routerFactory(componentResolver: ComponentResolver, urlSerializer: RouterUrlSerializer,
routerOutletMap: RouterOutletMap, location: Location): Router {
return new Router(null, FakeAppRootCmp, componentResolver, urlSerializer, routerOutletMap,
location);
}
export const ROUTER_FAKE_PROVIDERS: any[] = /*@ts2dart_const*/ [
RouterOutletMap,
/* @ts2dart_Provider */ {provide: Location, useClass: SpyLocation},
/* @ts2dart_Provider */ {provide: RouterUrlSerializer, useClass: DefaultRouterUrlSerializer},
/* @ts2dart_Provider */ {
provide: Router,
useFactory: routerFactory,
deps: /*@ts2dart_const*/
[ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location]
},
];
| modules/@angular/router/testing/router_testing_providers.ts | 1 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.0003591479326132685,
0.00024397960805799812,
0.00016836175927892327,
0.00020442911772988737,
0.00008275675645563751
]
|
{
"id": 1,
"code_window": [
"import {BaseException} from '@angular/core';\n",
"import {ComponentResolver} from '@angular/core';\n",
"import {DEFAULT_OUTLET_NAME} from './constants';\n",
"import {reflector} from '@angular/core';\n",
"\n",
"// TODO: vsavkin: recognize should take the old tree and merge it\n",
"export function recognize(componentResolver: ComponentResolver, rootComponent: Type,\n",
" url: UrlTree): Promise<RouteTree> {\n",
" let matched = new _MatchResult(rootComponent, [url.root], {}, rootNode(url).children, []);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "modules/@angular/router/src/recognize.ts",
"type": "replace",
"edit_start_line_idx": 10
} | {{greeting}} | modules_dart/transform/test/transform/inliner_for_test/split_url_expression_files/template.html | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.00016743899323046207,
0.00016743899323046207,
0.00016743899323046207,
0.00016743899323046207,
0
]
|
{
"id": 1,
"code_window": [
"import {BaseException} from '@angular/core';\n",
"import {ComponentResolver} from '@angular/core';\n",
"import {DEFAULT_OUTLET_NAME} from './constants';\n",
"import {reflector} from '@angular/core';\n",
"\n",
"// TODO: vsavkin: recognize should take the old tree and merge it\n",
"export function recognize(componentResolver: ComponentResolver, rootComponent: Type,\n",
" url: UrlTree): Promise<RouteTree> {\n",
" let matched = new _MatchResult(rootComponent, [url.root], {}, rootNode(url).children, []);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "modules/@angular/router/src/recognize.ts",
"type": "replace",
"edit_start_line_idx": 10
} | import {StringWrapper} from '../../src/facade/lang';
var CAMEL_CASE_REGEXP = /([A-Z])/g;
var DASH_CASE_REGEXP = /-([a-z])/g;
export function camelCaseToDashCase(input: string): string {
return StringWrapper.replaceAllMapped(input, CAMEL_CASE_REGEXP,
(m) => { return '-' + m[1].toLowerCase(); });
}
export function dashCaseToCamelCase(input: string): string {
return StringWrapper.replaceAllMapped(input, DASH_CASE_REGEXP,
(m) => { return m[1].toUpperCase(); });
}
| modules/@angular/platform-browser/src/dom/util.ts | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.0001674509549047798,
0.0001670281053520739,
0.00016660527035128325,
0.0001670281053520739,
4.228422767482698e-7
]
|
{
"id": 1,
"code_window": [
"import {BaseException} from '@angular/core';\n",
"import {ComponentResolver} from '@angular/core';\n",
"import {DEFAULT_OUTLET_NAME} from './constants';\n",
"import {reflector} from '@angular/core';\n",
"\n",
"// TODO: vsavkin: recognize should take the old tree and merge it\n",
"export function recognize(componentResolver: ComponentResolver, rootComponent: Type,\n",
" url: UrlTree): Promise<RouteTree> {\n",
" let matched = new _MatchResult(rootComponent, [url.root], {}, rootNode(url).children, []);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "modules/@angular/router/src/recognize.ts",
"type": "replace",
"edit_start_line_idx": 10
} | <div>
<h2 class="page-title">Inbox</h2>
<ol class="inbox-list">
<li *ngFor="#item of items" class="inbox-item-record">
<a id="item-{{ item.id }}"
[routerLink]="['/detail', item.id]">{{ item.subject }}</a>
</li>
</ol>
</div> | modules/playground/src/alt_routing/app/inbox.html | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.00017249127267859876,
0.0001694976817816496,
0.00016650410543661565,
0.0001694976817816496,
0.000002993583620991558
]
|
{
"id": 2,
"code_window": [
"import {OpaqueToken, ComponentResolver} from '@angular/core';\n",
"import {LocationStrategy, PathLocationStrategy, Location} from '@angular/common';\n",
"import {Router, RouterOutletMap} from './router';\n",
"import {RouterUrlSerializer, DefaultRouterUrlSerializer} from './router_url_serializer';\n",
"import {ApplicationRef} from '@angular/core';\n",
"import {BaseException} from '@angular/core';\n",
"\n",
"/**\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {RouteSegment} from './segments';\n"
],
"file_path": "modules/@angular/router/src/router_providers_common.ts",
"type": "add",
"edit_start_line_idx": 3
} | import {SpyLocation} from '@angular/common/testing';
import {Location} from '@angular/common';
import {Router, RouterOutletMap} from '../src/router';
import {RouterUrlSerializer, DefaultRouterUrlSerializer} from '../src/router_url_serializer';
import {Component, ComponentResolver} from '@angular/core';
@Component({selector: 'fake-app-root-comp', template: `<span></span>`})
class FakeAppRootCmp {
}
function routerFactory(componentResolver: ComponentResolver, urlSerializer: RouterUrlSerializer,
routerOutletMap: RouterOutletMap, location: Location): Router {
return new Router(null, FakeAppRootCmp, componentResolver, urlSerializer, routerOutletMap,
location);
}
export const ROUTER_FAKE_PROVIDERS: any[] = /*@ts2dart_const*/ [
RouterOutletMap,
/* @ts2dart_Provider */ {provide: Location, useClass: SpyLocation},
/* @ts2dart_Provider */ {provide: RouterUrlSerializer, useClass: DefaultRouterUrlSerializer},
/* @ts2dart_Provider */ {
provide: Router,
useFactory: routerFactory,
deps: /*@ts2dart_const*/
[ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location]
},
];
| modules/@angular/router/testing/router_testing_providers.ts | 1 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.002266306197270751,
0.0013519111089408398,
0.00020647226483561099,
0.0015829546609893441,
0.0008566465112380683
]
|
{
"id": 2,
"code_window": [
"import {OpaqueToken, ComponentResolver} from '@angular/core';\n",
"import {LocationStrategy, PathLocationStrategy, Location} from '@angular/common';\n",
"import {Router, RouterOutletMap} from './router';\n",
"import {RouterUrlSerializer, DefaultRouterUrlSerializer} from './router_url_serializer';\n",
"import {ApplicationRef} from '@angular/core';\n",
"import {BaseException} from '@angular/core';\n",
"\n",
"/**\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {RouteSegment} from './segments';\n"
],
"file_path": "modules/@angular/router/src/router_providers_common.ts",
"type": "add",
"edit_start_line_idx": 3
} | // Verify we don't try to extract metadata for .d.ts files
export declare var a: string;
| modules/@angular/compiler_cli/integrationtest/src/dep.d.ts | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.00017226247291546315,
0.00017226247291546315,
0.00017226247291546315,
0.00017226247291546315,
0
]
|
{
"id": 2,
"code_window": [
"import {OpaqueToken, ComponentResolver} from '@angular/core';\n",
"import {LocationStrategy, PathLocationStrategy, Location} from '@angular/common';\n",
"import {Router, RouterOutletMap} from './router';\n",
"import {RouterUrlSerializer, DefaultRouterUrlSerializer} from './router_url_serializer';\n",
"import {ApplicationRef} from '@angular/core';\n",
"import {BaseException} from '@angular/core';\n",
"\n",
"/**\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {RouteSegment} from './segments';\n"
],
"file_path": "modules/@angular/router/src/router_providers_common.ts",
"type": "add",
"edit_start_line_idx": 3
} | import {
isPresent,
isBlank,
normalizeBool,
RegExpWrapper,
} from '../src/facade/lang';
// see http://www.w3.org/TR/html51/syntax.html#named-character-references
// see https://html.spec.whatwg.org/multipage/entities.json
// This list is not exhaustive to keep the compiler footprint low.
// The `{` / `ƫ` syntax should be used when the named character reference does not exist.
export const NAMED_ENTITIES = /*@ts2dart_const*/ {
'Aacute': '\u00C1',
'aacute': '\u00E1',
'Acirc': '\u00C2',
'acirc': '\u00E2',
'acute': '\u00B4',
'AElig': '\u00C6',
'aelig': '\u00E6',
'Agrave': '\u00C0',
'agrave': '\u00E0',
'alefsym': '\u2135',
'Alpha': '\u0391',
'alpha': '\u03B1',
'amp': '&',
'and': '\u2227',
'ang': '\u2220',
'apos': '\u0027',
'Aring': '\u00C5',
'aring': '\u00E5',
'asymp': '\u2248',
'Atilde': '\u00C3',
'atilde': '\u00E3',
'Auml': '\u00C4',
'auml': '\u00E4',
'bdquo': '\u201E',
'Beta': '\u0392',
'beta': '\u03B2',
'brvbar': '\u00A6',
'bull': '\u2022',
'cap': '\u2229',
'Ccedil': '\u00C7',
'ccedil': '\u00E7',
'cedil': '\u00B8',
'cent': '\u00A2',
'Chi': '\u03A7',
'chi': '\u03C7',
'circ': '\u02C6',
'clubs': '\u2663',
'cong': '\u2245',
'copy': '\u00A9',
'crarr': '\u21B5',
'cup': '\u222A',
'curren': '\u00A4',
'dagger': '\u2020',
'Dagger': '\u2021',
'darr': '\u2193',
'dArr': '\u21D3',
'deg': '\u00B0',
'Delta': '\u0394',
'delta': '\u03B4',
'diams': '\u2666',
'divide': '\u00F7',
'Eacute': '\u00C9',
'eacute': '\u00E9',
'Ecirc': '\u00CA',
'ecirc': '\u00EA',
'Egrave': '\u00C8',
'egrave': '\u00E8',
'empty': '\u2205',
'emsp': '\u2003',
'ensp': '\u2002',
'Epsilon': '\u0395',
'epsilon': '\u03B5',
'equiv': '\u2261',
'Eta': '\u0397',
'eta': '\u03B7',
'ETH': '\u00D0',
'eth': '\u00F0',
'Euml': '\u00CB',
'euml': '\u00EB',
'euro': '\u20AC',
'exist': '\u2203',
'fnof': '\u0192',
'forall': '\u2200',
'frac12': '\u00BD',
'frac14': '\u00BC',
'frac34': '\u00BE',
'frasl': '\u2044',
'Gamma': '\u0393',
'gamma': '\u03B3',
'ge': '\u2265',
'gt': '>',
'harr': '\u2194',
'hArr': '\u21D4',
'hearts': '\u2665',
'hellip': '\u2026',
'Iacute': '\u00CD',
'iacute': '\u00ED',
'Icirc': '\u00CE',
'icirc': '\u00EE',
'iexcl': '\u00A1',
'Igrave': '\u00CC',
'igrave': '\u00EC',
'image': '\u2111',
'infin': '\u221E',
'int': '\u222B',
'Iota': '\u0399',
'iota': '\u03B9',
'iquest': '\u00BF',
'isin': '\u2208',
'Iuml': '\u00CF',
'iuml': '\u00EF',
'Kappa': '\u039A',
'kappa': '\u03BA',
'Lambda': '\u039B',
'lambda': '\u03BB',
'lang': '\u27E8',
'laquo': '\u00AB',
'larr': '\u2190',
'lArr': '\u21D0',
'lceil': '\u2308',
'ldquo': '\u201C',
'le': '\u2264',
'lfloor': '\u230A',
'lowast': '\u2217',
'loz': '\u25CA',
'lrm': '\u200E',
'lsaquo': '\u2039',
'lsquo': '\u2018',
'lt': '<',
'macr': '\u00AF',
'mdash': '\u2014',
'micro': '\u00B5',
'middot': '\u00B7',
'minus': '\u2212',
'Mu': '\u039C',
'mu': '\u03BC',
'nabla': '\u2207',
'nbsp': '\u00A0',
'ndash': '\u2013',
'ne': '\u2260',
'ni': '\u220B',
'not': '\u00AC',
'notin': '\u2209',
'nsub': '\u2284',
'Ntilde': '\u00D1',
'ntilde': '\u00F1',
'Nu': '\u039D',
'nu': '\u03BD',
'Oacute': '\u00D3',
'oacute': '\u00F3',
'Ocirc': '\u00D4',
'ocirc': '\u00F4',
'OElig': '\u0152',
'oelig': '\u0153',
'Ograve': '\u00D2',
'ograve': '\u00F2',
'oline': '\u203E',
'Omega': '\u03A9',
'omega': '\u03C9',
'Omicron': '\u039F',
'omicron': '\u03BF',
'oplus': '\u2295',
'or': '\u2228',
'ordf': '\u00AA',
'ordm': '\u00BA',
'Oslash': '\u00D8',
'oslash': '\u00F8',
'Otilde': '\u00D5',
'otilde': '\u00F5',
'otimes': '\u2297',
'Ouml': '\u00D6',
'ouml': '\u00F6',
'para': '\u00B6',
'permil': '\u2030',
'perp': '\u22A5',
'Phi': '\u03A6',
'phi': '\u03C6',
'Pi': '\u03A0',
'pi': '\u03C0',
'piv': '\u03D6',
'plusmn': '\u00B1',
'pound': '\u00A3',
'prime': '\u2032',
'Prime': '\u2033',
'prod': '\u220F',
'prop': '\u221D',
'Psi': '\u03A8',
'psi': '\u03C8',
'quot': '\u0022',
'radic': '\u221A',
'rang': '\u27E9',
'raquo': '\u00BB',
'rarr': '\u2192',
'rArr': '\u21D2',
'rceil': '\u2309',
'rdquo': '\u201D',
'real': '\u211C',
'reg': '\u00AE',
'rfloor': '\u230B',
'Rho': '\u03A1',
'rho': '\u03C1',
'rlm': '\u200F',
'rsaquo': '\u203A',
'rsquo': '\u2019',
'sbquo': '\u201A',
'Scaron': '\u0160',
'scaron': '\u0161',
'sdot': '\u22C5',
'sect': '\u00A7',
'shy': '\u00AD',
'Sigma': '\u03A3',
'sigma': '\u03C3',
'sigmaf': '\u03C2',
'sim': '\u223C',
'spades': '\u2660',
'sub': '\u2282',
'sube': '\u2286',
'sum': '\u2211',
'sup': '\u2283',
'sup1': '\u00B9',
'sup2': '\u00B2',
'sup3': '\u00B3',
'supe': '\u2287',
'szlig': '\u00DF',
'Tau': '\u03A4',
'tau': '\u03C4',
'there4': '\u2234',
'Theta': '\u0398',
'theta': '\u03B8',
'thetasym': '\u03D1',
'thinsp': '\u2009',
'THORN': '\u00DE',
'thorn': '\u00FE',
'tilde': '\u02DC',
'times': '\u00D7',
'trade': '\u2122',
'Uacute': '\u00DA',
'uacute': '\u00FA',
'uarr': '\u2191',
'uArr': '\u21D1',
'Ucirc': '\u00DB',
'ucirc': '\u00FB',
'Ugrave': '\u00D9',
'ugrave': '\u00F9',
'uml': '\u00A8',
'upsih': '\u03D2',
'Upsilon': '\u03A5',
'upsilon': '\u03C5',
'Uuml': '\u00DC',
'uuml': '\u00FC',
'weierp': '\u2118',
'Xi': '\u039E',
'xi': '\u03BE',
'Yacute': '\u00DD',
'yacute': '\u00FD',
'yen': '\u00A5',
'yuml': '\u00FF',
'Yuml': '\u0178',
'Zeta': '\u0396',
'zeta': '\u03B6',
'zwj': '\u200D',
'zwnj': '\u200C',
};
export enum HtmlTagContentType {
RAW_TEXT,
ESCAPABLE_RAW_TEXT,
PARSABLE_DATA
}
export class HtmlTagDefinition {
private closedByChildren: {[key: string]: boolean} = {};
public closedByParent: boolean = false;
public requiredParents: {[key: string]: boolean};
public parentToAdd: string;
public implicitNamespacePrefix: string;
public contentType: HtmlTagContentType;
public isVoid: boolean;
public ignoreFirstLf: boolean;
constructor({closedByChildren, requiredParents, implicitNamespacePrefix, contentType,
closedByParent, isVoid, ignoreFirstLf}: {
closedByChildren?: string[],
closedByParent?: boolean,
requiredParents?: string[],
implicitNamespacePrefix?: string,
contentType?: HtmlTagContentType,
isVoid?: boolean,
ignoreFirstLf?: boolean
} = {}) {
if (isPresent(closedByChildren) && closedByChildren.length > 0) {
closedByChildren.forEach(tagName => this.closedByChildren[tagName] = true);
}
this.isVoid = normalizeBool(isVoid);
this.closedByParent = normalizeBool(closedByParent) || this.isVoid;
if (isPresent(requiredParents) && requiredParents.length > 0) {
this.requiredParents = {};
this.parentToAdd = requiredParents[0];
requiredParents.forEach(tagName => this.requiredParents[tagName] = true);
}
this.implicitNamespacePrefix = implicitNamespacePrefix;
this.contentType = isPresent(contentType) ? contentType : HtmlTagContentType.PARSABLE_DATA;
this.ignoreFirstLf = normalizeBool(ignoreFirstLf);
}
requireExtraParent(currentParent: string): boolean {
if (isBlank(this.requiredParents)) {
return false;
}
if (isBlank(currentParent)) {
return true;
}
let lcParent = currentParent.toLowerCase();
return this.requiredParents[lcParent] != true && lcParent != 'template';
}
isClosedByChild(name: string): boolean {
return this.isVoid || normalizeBool(this.closedByChildren[name.toLowerCase()]);
}
}
// see http://www.w3.org/TR/html51/syntax.html#optional-tags
// This implementation does not fully conform to the HTML5 spec.
var TAG_DEFINITIONS: {[key: string]: HtmlTagDefinition} = {
'base': new HtmlTagDefinition({isVoid: true}),
'meta': new HtmlTagDefinition({isVoid: true}),
'area': new HtmlTagDefinition({isVoid: true}),
'embed': new HtmlTagDefinition({isVoid: true}),
'link': new HtmlTagDefinition({isVoid: true}),
'img': new HtmlTagDefinition({isVoid: true}),
'input': new HtmlTagDefinition({isVoid: true}),
'param': new HtmlTagDefinition({isVoid: true}),
'hr': new HtmlTagDefinition({isVoid: true}),
'br': new HtmlTagDefinition({isVoid: true}),
'source': new HtmlTagDefinition({isVoid: true}),
'track': new HtmlTagDefinition({isVoid: true}),
'wbr': new HtmlTagDefinition({isVoid: true}),
'p': new HtmlTagDefinition({
closedByChildren: [
'address',
'article',
'aside',
'blockquote',
'div',
'dl',
'fieldset',
'footer',
'form',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'header',
'hgroup',
'hr',
'main',
'nav',
'ol',
'p',
'pre',
'section',
'table',
'ul'
],
closedByParent: true
}),
'thead': new HtmlTagDefinition({closedByChildren: ['tbody', 'tfoot']}),
'tbody': new HtmlTagDefinition({closedByChildren: ['tbody', 'tfoot'], closedByParent: true}),
'tfoot': new HtmlTagDefinition({closedByChildren: ['tbody'], closedByParent: true}),
'tr': new HtmlTagDefinition({
closedByChildren: ['tr'],
requiredParents: ['tbody', 'tfoot', 'thead'],
closedByParent: true
}),
'td': new HtmlTagDefinition({closedByChildren: ['td', 'th'], closedByParent: true}),
'th': new HtmlTagDefinition({closedByChildren: ['td', 'th'], closedByParent: true}),
'col': new HtmlTagDefinition({requiredParents: ['colgroup'], isVoid: true}),
'svg': new HtmlTagDefinition({implicitNamespacePrefix: 'svg'}),
'math': new HtmlTagDefinition({implicitNamespacePrefix: 'math'}),
'li': new HtmlTagDefinition({closedByChildren: ['li'], closedByParent: true}),
'dt': new HtmlTagDefinition({closedByChildren: ['dt', 'dd']}),
'dd': new HtmlTagDefinition({closedByChildren: ['dt', 'dd'], closedByParent: true}),
'rb': new HtmlTagDefinition({closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true}),
'rt': new HtmlTagDefinition({closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true}),
'rtc': new HtmlTagDefinition({closedByChildren: ['rb', 'rtc', 'rp'], closedByParent: true}),
'rp': new HtmlTagDefinition({closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true}),
'optgroup': new HtmlTagDefinition({closedByChildren: ['optgroup'], closedByParent: true}),
'option': new HtmlTagDefinition({closedByChildren: ['option', 'optgroup'], closedByParent: true}),
'pre': new HtmlTagDefinition({ignoreFirstLf: true}),
'listing': new HtmlTagDefinition({ignoreFirstLf: true}),
'style': new HtmlTagDefinition({contentType: HtmlTagContentType.RAW_TEXT}),
'script': new HtmlTagDefinition({contentType: HtmlTagContentType.RAW_TEXT}),
'title': new HtmlTagDefinition({contentType: HtmlTagContentType.ESCAPABLE_RAW_TEXT}),
'textarea': new HtmlTagDefinition(
{contentType: HtmlTagContentType.ESCAPABLE_RAW_TEXT, ignoreFirstLf: true}),
};
var DEFAULT_TAG_DEFINITION = new HtmlTagDefinition();
export function getHtmlTagDefinition(tagName: string): HtmlTagDefinition {
var result = TAG_DEFINITIONS[tagName.toLowerCase()];
return isPresent(result) ? result : DEFAULT_TAG_DEFINITION;
}
var NS_PREFIX_RE = /^@([^:]+):(.+)/g;
export function splitNsName(elementName: string): string[] {
if (elementName[0] != '@') {
return [null, elementName];
}
let match = RegExpWrapper.firstMatch(NS_PREFIX_RE, elementName);
return [match[1], match[2]];
}
export function getNsPrefix(elementName: string): string {
return splitNsName(elementName)[0];
}
export function mergeNsAndName(prefix: string, localName: string): string {
return isPresent(prefix) ? `@${prefix}:${localName}` : localName;
}
| modules/@angular/compiler/src/html_tags.ts | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.0001780231250450015,
0.00017521236441098154,
0.00016630132449790835,
0.00017595986719243228,
0.0000026006914595200215
]
|
{
"id": 2,
"code_window": [
"import {OpaqueToken, ComponentResolver} from '@angular/core';\n",
"import {LocationStrategy, PathLocationStrategy, Location} from '@angular/common';\n",
"import {Router, RouterOutletMap} from './router';\n",
"import {RouterUrlSerializer, DefaultRouterUrlSerializer} from './router_url_serializer';\n",
"import {ApplicationRef} from '@angular/core';\n",
"import {BaseException} from '@angular/core';\n",
"\n",
"/**\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {RouteSegment} from './segments';\n"
],
"file_path": "modules/@angular/router/src/router_providers_common.ts",
"type": "add",
"edit_start_line_idx": 3
} | import {
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xit,
} from '@angular/core/testing/testing_internal';
import {Component, Directive} from '@angular/core';
import {reflector} from '@angular/core/src/reflection/reflection';
export function main() {
describe('es5 decorators', () => {
it('should declare directive class', () => {
var MyDirective = Directive({}).Class({constructor: function() { this.works = true; }});
expect(new MyDirective().works).toEqual(true);
});
it('should declare Component class', () => {
var MyComponent =
Component({}).View({}).View({}).Class({constructor: function() { this.works = true; }});
expect(new MyComponent().works).toEqual(true);
});
it('should create type in ES5', () => {
function MyComponent(){};
var as;
(<any>MyComponent).annotations = as = Component({}).View({});
expect(reflector.annotations(MyComponent)).toEqual(as.annotations);
});
});
}
| modules/@angular/core/test/metadata/decorators_spec.ts | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.00017359445337206125,
0.00017073894559871405,
0.00016834716370794922,
0.00017050706082955003,
0.0000022061446998122847
]
|
{
"id": 3,
"code_window": [
" deps: /*@ts2dart_const*/\n",
" [ApplicationRef, ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location],\n",
" },\n",
"];\n",
"\n",
"function routerFactory(app: ApplicationRef, componentResolver: ComponentResolver,\n",
" urlSerializer: RouterUrlSerializer, routerOutletMap: RouterOutletMap,\n",
" location: Location): Router {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" /*@ts2dart_Provider*/ {provide: RouteSegment, useFactory: (r) => r.routeTree.root, deps: [Router]}\n"
],
"file_path": "modules/@angular/router/src/router_providers_common.ts",
"type": "add",
"edit_start_line_idx": 20
} | import {OpaqueToken, ComponentResolver} from '@angular/core';
import {LocationStrategy, PathLocationStrategy, Location} from '@angular/common';
import {Router, RouterOutletMap} from './router';
import {RouterUrlSerializer, DefaultRouterUrlSerializer} from './router_url_serializer';
import {ApplicationRef} from '@angular/core';
import {BaseException} from '@angular/core';
/**
* The Platform agnostic ROUTER PROVIDERS
*/
export const ROUTER_PROVIDERS_COMMON: any[] = /*@ts2dart_const*/[
RouterOutletMap,
/*@ts2dart_Provider*/ {provide: RouterUrlSerializer, useClass: DefaultRouterUrlSerializer},
/*@ts2dart_Provider*/ {provide: LocationStrategy, useClass: PathLocationStrategy}, Location,
/*@ts2dart_Provider*/ {
provide: Router,
useFactory: routerFactory,
deps: /*@ts2dart_const*/
[ApplicationRef, ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location],
},
];
function routerFactory(app: ApplicationRef, componentResolver: ComponentResolver,
urlSerializer: RouterUrlSerializer, routerOutletMap: RouterOutletMap,
location: Location): Router {
if (app.componentTypes.length == 0) {
throw new BaseException("Bootstrap at least one component before injecting Router.");
}
// TODO: vsavkin this should not be null
let router = new Router(null, app.componentTypes[0], componentResolver, urlSerializer,
routerOutletMap, location);
app.registerDisposeListener(() => router.dispose());
return router;
}
| modules/@angular/router/src/router_providers_common.ts | 1 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.9992730021476746,
0.7156394720077515,
0.012956713326275349,
0.9251641035079956,
0.4094308018684387
]
|
{
"id": 3,
"code_window": [
" deps: /*@ts2dart_const*/\n",
" [ApplicationRef, ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location],\n",
" },\n",
"];\n",
"\n",
"function routerFactory(app: ApplicationRef, componentResolver: ComponentResolver,\n",
" urlSerializer: RouterUrlSerializer, routerOutletMap: RouterOutletMap,\n",
" location: Location): Router {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" /*@ts2dart_Provider*/ {provide: RouteSegment, useFactory: (r) => r.routeTree.root, deps: [Router]}\n"
],
"file_path": "modules/@angular/router/src/router_providers_common.ts",
"type": "add",
"edit_start_line_idx": 20
} | import {XHR} from '@angular/compiler';
import {BaseException} from '../../src/facade/exceptions';
import {global} from '../../src/facade/lang';
import {PromiseWrapper} from '../../src/facade/promise';
/**
* An implementation of XHR that uses a template cache to avoid doing an actual
* XHR.
*
* The template cache needs to be built and loaded into window.$templateCache
* via a separate mechanism.
*/
export class CachedXHR extends XHR {
private _cache: {[url: string]: string};
constructor() {
super();
this._cache = (<any>global).$templateCache;
if (this._cache == null) {
throw new BaseException('CachedXHR: Template cache was not found in $templateCache.');
}
}
get(url: string): Promise<string> {
if (this._cache.hasOwnProperty(url)) {
return PromiseWrapper.resolve(this._cache[url]);
} else {
return PromiseWrapper.reject('CachedXHR: Did not find cached template for ' + url, null);
}
}
}
| modules/@angular/platform-browser-dynamic/src/xhr/xhr_cache.ts | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.00017038648365996778,
0.00016735601820982993,
0.00016238857642747462,
0.00016832449182402343,
0.000003087940058321692
]
|
{
"id": 3,
"code_window": [
" deps: /*@ts2dart_const*/\n",
" [ApplicationRef, ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location],\n",
" },\n",
"];\n",
"\n",
"function routerFactory(app: ApplicationRef, componentResolver: ComponentResolver,\n",
" urlSerializer: RouterUrlSerializer, routerOutletMap: RouterOutletMap,\n",
" location: Location): Router {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" /*@ts2dart_Provider*/ {provide: RouteSegment, useFactory: (r) => r.routeTree.root, deps: [Router]}\n"
],
"file_path": "modules/@angular/router/src/router_providers_common.ts",
"type": "add",
"edit_start_line_idx": 20
} | import {LifecycleHooks} from '../../core_private';
import * as o from '../output/output_ast';
import {DetectChangesVars, ChangeDetectorStateEnum} from './constants';
import {CompileDirectiveMetadata, CompilePipeMetadata} from '../compile_metadata';
import {DirectiveAst} from '../template_ast';
import {CompileElement} from './compile_element';
import {CompileView} from './compile_view';
var STATE_IS_NEVER_CHECKED =
o.THIS_EXPR.prop('cdState').identical(ChangeDetectorStateEnum.NeverChecked);
var NOT_THROW_ON_CHANGES = o.not(DetectChangesVars.throwOnChange);
export function bindDirectiveDetectChangesLifecycleCallbacks(
directiveAst: DirectiveAst, directiveInstance: o.Expression, compileElement: CompileElement) {
var view = compileElement.view;
var detectChangesInInputsMethod = view.detectChangesInInputsMethod;
var lifecycleHooks = directiveAst.directive.lifecycleHooks;
if (lifecycleHooks.indexOf(LifecycleHooks.OnChanges) !== -1 && directiveAst.inputs.length > 0) {
detectChangesInInputsMethod.addStmt(new o.IfStmt(
DetectChangesVars.changes.notIdentical(o.NULL_EXPR),
[directiveInstance.callMethod('ngOnChanges', [DetectChangesVars.changes]).toStmt()]));
}
if (lifecycleHooks.indexOf(LifecycleHooks.OnInit) !== -1) {
detectChangesInInputsMethod.addStmt(
new o.IfStmt(STATE_IS_NEVER_CHECKED.and(NOT_THROW_ON_CHANGES),
[directiveInstance.callMethod('ngOnInit', []).toStmt()]));
}
if (lifecycleHooks.indexOf(LifecycleHooks.DoCheck) !== -1) {
detectChangesInInputsMethod.addStmt(new o.IfStmt(
NOT_THROW_ON_CHANGES, [directiveInstance.callMethod('ngDoCheck', []).toStmt()]));
}
}
export function bindDirectiveAfterContentLifecycleCallbacks(directiveMeta: CompileDirectiveMetadata,
directiveInstance: o.Expression,
compileElement: CompileElement) {
var view = compileElement.view;
var lifecycleHooks = directiveMeta.lifecycleHooks;
var afterContentLifecycleCallbacksMethod = view.afterContentLifecycleCallbacksMethod;
afterContentLifecycleCallbacksMethod.resetDebugInfo(compileElement.nodeIndex,
compileElement.sourceAst);
if (lifecycleHooks.indexOf(LifecycleHooks.AfterContentInit) !== -1) {
afterContentLifecycleCallbacksMethod.addStmt(new o.IfStmt(
STATE_IS_NEVER_CHECKED, [directiveInstance.callMethod('ngAfterContentInit', []).toStmt()]));
}
if (lifecycleHooks.indexOf(LifecycleHooks.AfterContentChecked) !== -1) {
afterContentLifecycleCallbacksMethod.addStmt(
directiveInstance.callMethod('ngAfterContentChecked', []).toStmt());
}
}
export function bindDirectiveAfterViewLifecycleCallbacks(directiveMeta: CompileDirectiveMetadata,
directiveInstance: o.Expression,
compileElement: CompileElement) {
var view = compileElement.view;
var lifecycleHooks = directiveMeta.lifecycleHooks;
var afterViewLifecycleCallbacksMethod = view.afterViewLifecycleCallbacksMethod;
afterViewLifecycleCallbacksMethod.resetDebugInfo(compileElement.nodeIndex,
compileElement.sourceAst);
if (lifecycleHooks.indexOf(LifecycleHooks.AfterViewInit) !== -1) {
afterViewLifecycleCallbacksMethod.addStmt(new o.IfStmt(
STATE_IS_NEVER_CHECKED, [directiveInstance.callMethod('ngAfterViewInit', []).toStmt()]));
}
if (lifecycleHooks.indexOf(LifecycleHooks.AfterViewChecked) !== -1) {
afterViewLifecycleCallbacksMethod.addStmt(
directiveInstance.callMethod('ngAfterViewChecked', []).toStmt());
}
}
export function bindDirectiveDestroyLifecycleCallbacks(directiveMeta: CompileDirectiveMetadata,
directiveInstance: o.Expression,
compileElement: CompileElement) {
var onDestroyMethod = compileElement.view.destroyMethod;
onDestroyMethod.resetDebugInfo(compileElement.nodeIndex, compileElement.sourceAst);
if (directiveMeta.lifecycleHooks.indexOf(LifecycleHooks.OnDestroy) !== -1) {
onDestroyMethod.addStmt(directiveInstance.callMethod('ngOnDestroy', []).toStmt());
}
}
export function bindPipeDestroyLifecycleCallbacks(pipeMeta: CompilePipeMetadata,
pipeInstance: o.Expression, view: CompileView) {
var onDestroyMethod = view.destroyMethod;
if (pipeMeta.lifecycleHooks.indexOf(LifecycleHooks.OnDestroy) !== -1) {
onDestroyMethod.addStmt(pipeInstance.callMethod('ngOnDestroy', []).toStmt());
}
}
| modules/@angular/compiler/src/view_compiler/lifecycle_binder.ts | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.0009222539374604821,
0.00042061402928084135,
0.0001719370629871264,
0.00031066793599165976,
0.0002597309066914022
]
|
{
"id": 3,
"code_window": [
" deps: /*@ts2dart_const*/\n",
" [ApplicationRef, ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location],\n",
" },\n",
"];\n",
"\n",
"function routerFactory(app: ApplicationRef, componentResolver: ComponentResolver,\n",
" urlSerializer: RouterUrlSerializer, routerOutletMap: RouterOutletMap,\n",
" location: Location): Router {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" /*@ts2dart_Provider*/ {provide: RouteSegment, useFactory: (r) => r.routeTree.root, deps: [Router]}\n"
],
"file_path": "modules/@angular/router/src/router_providers_common.ts",
"type": "add",
"edit_start_line_idx": 20
} | modules/@angular/examples/animate/ts/.gitkeep | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.00023473554756492376,
0.00023473554756492376,
0.00023473554756492376,
0.00023473554756492376,
0
]
|
|
{
"id": 4,
"code_window": [
" provide(RouterUrlSerializer, {useClass: DefaultRouterUrlSerializer}),\n",
" RouterOutletMap,\n",
" provide(Location, {useClass: SpyLocation}),\n",
" provide(Router,\n",
" {\n",
" useFactory: (resolver, urlParser, outletMap, location) => new Router(\n",
" \"RootComponent\", RootCmp, resolver, urlParser, outletMap, location),\n",
" deps: [ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location]\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" provide(RouteSegment, {useFactory: (r) => r.routeTree.root, deps: [Router]}),\n"
],
"file_path": "modules/@angular/router/test/integration_spec.ts",
"type": "add",
"edit_start_line_idx": 41
} | import {SpyLocation} from '@angular/common/testing';
import {Location} from '@angular/common';
import {Router, RouterOutletMap} from '../src/router';
import {RouterUrlSerializer, DefaultRouterUrlSerializer} from '../src/router_url_serializer';
import {Component, ComponentResolver} from '@angular/core';
@Component({selector: 'fake-app-root-comp', template: `<span></span>`})
class FakeAppRootCmp {
}
function routerFactory(componentResolver: ComponentResolver, urlSerializer: RouterUrlSerializer,
routerOutletMap: RouterOutletMap, location: Location): Router {
return new Router(null, FakeAppRootCmp, componentResolver, urlSerializer, routerOutletMap,
location);
}
export const ROUTER_FAKE_PROVIDERS: any[] = /*@ts2dart_const*/ [
RouterOutletMap,
/* @ts2dart_Provider */ {provide: Location, useClass: SpyLocation},
/* @ts2dart_Provider */ {provide: RouterUrlSerializer, useClass: DefaultRouterUrlSerializer},
/* @ts2dart_Provider */ {
provide: Router,
useFactory: routerFactory,
deps: /*@ts2dart_const*/
[ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location]
},
];
| modules/@angular/router/testing/router_testing_providers.ts | 1 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.049760255962610245,
0.017642678692936897,
0.00045151219819672406,
0.0027162691112607718,
0.02272936888039112
]
|
{
"id": 4,
"code_window": [
" provide(RouterUrlSerializer, {useClass: DefaultRouterUrlSerializer}),\n",
" RouterOutletMap,\n",
" provide(Location, {useClass: SpyLocation}),\n",
" provide(Router,\n",
" {\n",
" useFactory: (resolver, urlParser, outletMap, location) => new Router(\n",
" \"RootComponent\", RootCmp, resolver, urlParser, outletMap, location),\n",
" deps: [ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location]\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" provide(RouteSegment, {useFactory: (r) => r.routeTree.root, deps: [Router]}),\n"
],
"file_path": "modules/@angular/router/test/integration_spec.ts",
"type": "add",
"edit_start_line_idx": 41
} | library angular2.transform.template_compiler.compile_data_creator;
import 'dart:async';
import 'dart:convert';
import 'package:angular2/src/compiler/compile_metadata.dart';
import 'package:angular2/src/compiler/offline_compiler.dart';
import 'package:angular2/src/transform/common/asset_reader.dart';
import 'package:angular2/src/transform/common/logging.dart';
import 'package:angular2/src/transform/common/model/ng_deps_model.pb.dart';
import 'package:angular2/src/transform/common/model/reflection_info_model.pb.dart';
import 'package:angular2/src/transform/common/names.dart';
import 'package:angular2/src/transform/common/ng_meta.dart';
import 'package:angular2/src/transform/common/url_resolver.dart';
import 'package:barback/barback.dart';
/// Creates [NormalizedComponentWithViewDirectives] objects for all `View`
/// `Directive`s defined in `assetId`.
///
/// The returned value wraps the [NgDepsModel] at `assetId` as well as these
/// created objects.
///
/// `platformDirectives` is an optional [List] containing names of [Directive]s
/// which should be available to all [View]s in this app.
///
/// `platformPipes` is an optional [List] containing names of [Pipe]s which
/// should be available to all [View]s in this app.
Future<CompileDataResults> createCompileData(
AssetReader reader,
AssetId assetId,
List<String> platformDirectives,
List<String> platformPipes) async {
return logElapsedAsync(() async {
final creator = await _CompileDataCreator.create(
reader, assetId, platformDirectives, platformPipes);
return creator != null ? creator.createCompileData() : null;
}, operationName: 'createCompileData', assetId: assetId);
}
class CompileDataResults {
final NgMeta ngMeta;
final Map<ReflectionInfoModel, NormalizedComponentWithViewDirectives>
viewDefinitions;
CompileDataResults._(this.ngMeta, this.viewDefinitions);
}
/// Creates [ViewDefinition] objects for all `View` `Directive`s defined in
/// `entryPoint`.
class _CompileDataCreator {
final AssetReader reader;
final AssetId entryPoint;
final NgMeta ngMeta;
final List<String> platformDirectives;
final List<String> platformPipes;
_CompileDataCreator(this.reader, this.entryPoint, this.ngMeta,
this.platformDirectives, this.platformPipes);
static Future<_CompileDataCreator> create(AssetReader reader, AssetId assetId,
List<String> platformDirectives, List<String> platformPipes) async {
if (!(await reader.hasInput(assetId))) return null;
final json = await reader.readAsString(assetId);
if (json == null || json.isEmpty) return null;
final ngMeta = new NgMeta.fromJson(JSON.decode(json));
return new _CompileDataCreator(
reader, assetId, ngMeta, platformDirectives, platformPipes);
}
NgDepsModel get ngDeps => ngMeta.ngDeps;
Future<CompileDataResults> createCompileData() async {
var hasTemplate = ngDeps != null &&
ngDeps.reflectables != null &&
ngDeps.reflectables.any((reflectable) {
if (ngMeta.identifiers.containsKey(reflectable.name)) {
final metadata = ngMeta.identifiers[reflectable.name];
return metadata is CompileDirectiveMetadata;
}
return false;
});
if (!hasTemplate) return new CompileDataResults._(ngMeta, const {});
final compileData =
<ReflectionInfoModel, NormalizedComponentWithViewDirectives>{};
final platformDirectives =
await _readPlatformTypes(this.platformDirectives, 'directives');
final platformPipes = await _readPlatformTypes(this.platformPipes, 'pipes');
final ngMetaMap = await _extractNgMeta();
for (var reflectable in ngDeps.reflectables) {
if (ngMeta.identifiers.containsKey(reflectable.name)) {
final compileDirectiveMetadata = ngMeta.identifiers[reflectable.name];
if (compileDirectiveMetadata is CompileDirectiveMetadata &&
compileDirectiveMetadata.template != null) {
final compileDatum = new NormalizedComponentWithViewDirectives(
compileDirectiveMetadata,
<CompileDirectiveMetadata>[],
<CompilePipeMetadata>[]);
compileDatum.directives.addAll(platformDirectives);
compileDatum.directives
.addAll(_resolveTypeMetadata(ngMetaMap, reflectable.directives));
compileDatum.pipes.addAll(platformPipes);
compileDatum.pipes
.addAll(_resolveTypeMetadata(ngMetaMap, reflectable.pipes));
compileData[reflectable] = compileDatum;
}
}
}
return new CompileDataResults._(ngMeta, compileData);
}
List<dynamic> _resolveTypeMetadata(
Map<String, NgMeta> ngMetaMap, List<PrefixedType> prefixedTypes) {
var resolvedMetadata = [];
for (var dep in prefixedTypes) {
if (!ngMetaMap.containsKey(dep.prefix)) {
log.error(
'Missing prefix "${dep.prefix}" '
'needed by "${dep}" from metadata map,',
asset: entryPoint);
return null;
}
final depNgMeta = ngMetaMap[dep.prefix];
if (depNgMeta.aliases.containsKey(dep.name)) {
resolvedMetadata.addAll(depNgMeta.flatten(dep.name));
} else if (depNgMeta.identifiers.containsKey(dep.name)) {
resolvedMetadata.add(depNgMeta.identifiers[dep.name]);
} else {
log.error(
'Could not find Directive/Pipe entry for $dep. '
'Please be aware that Dart transformers have limited support for '
'reusable, pre-defined lists of Directives/Pipes (aka '
'"directive/pipe aliases"). See https://goo.gl/d8XPt0 for details.',
asset: entryPoint);
}
}
return resolvedMetadata;
}
Future<List<dynamic>> _readPlatformTypes(
List<String> inputPlatformTypes, String configOption) async {
if (inputPlatformTypes == null) return const [];
final res = [];
for (var pd in inputPlatformTypes) {
final parts = pd.split("#");
if (parts.length != 2) {
log.warning(
'The platform ${configOption} configuration option '
'must be in the following format: "URI#TOKEN"',
asset: entryPoint);
return const [];
}
res.addAll(await _readPlatformTypesFromUri(parts[0], parts[1]));
}
return res;
}
Future<List<dynamic>> _readPlatformTypesFromUri(
String uri, String token) async {
final metaAssetId = fromUri(toMetaExtension(uri));
try {
var jsonString = await reader.readAsString(metaAssetId);
if (jsonString != null && jsonString.isNotEmpty) {
var newMetadata = new NgMeta.fromJson(JSON.decode(jsonString));
if (newMetadata.aliases.containsKey(token)) {
return newMetadata.flatten(token);
} else if (newMetadata.identifiers.containsKey(token)) {
return [newMetadata.identifiers[token]];
} else {
log.warning('Could not resolve platform type ${token} in ${uri}',
asset: metaAssetId);
}
}
} catch (ex, stackTrace) {
log.warning('Failed to decode: $ex, $stackTrace', asset: metaAssetId);
}
return [];
}
/// Creates a map from import prefix to the asset: uris of all `.dart`
/// libraries visible from `entryPoint`, excluding `dart:` and generated files
/// it imports. Unprefixed imports have the empty string as their key.
/// `entryPoint` is included in the map with no prefix.
Map<String, Iterable<String>> _createPrefixToImportsMap() {
final baseUri = toAssetUri(entryPoint);
final map = <String, Set<String>>{'': new Set<String>()..add(baseUri)};
if (ngDeps == null || ngDeps.imports == null || ngDeps.imports.isEmpty) {
return map;
}
final resolver = createOfflineCompileUrlResolver();
ngMeta.ngDeps.imports
.where((model) => !isDartCoreUri(model.uri))
.forEach((model) {
var prefix = model.prefix == null ? '' : model.prefix;
map
.putIfAbsent(prefix, () => new Set<String>())
.add(resolver.resolve(baseUri, model.uri));
});
return map;
}
/// Reads the `.ng_meta.json` files associated with all of `entryPoint`'s
/// imports and creates a map of prefix (or blank) to the
/// associated [NgMeta] object.
///
/// For example, if in `entryPoint` we have:
///
/// ```
/// import 'component.dart' as prefix;
/// ```
///
/// and in 'component.dart' we have:
///
/// ```
/// @Component(...)
/// class MyComponent {...}
/// ```
///
/// This method will look for `component.ng_meta.json`to contain the
/// serialized [NgMeta] for `MyComponent` and any other
/// `Directive`s declared in `component.dart`. We use this information to
/// build a map:
///
/// ```
/// {
/// "prefix": [NgMeta with CompileDirectiveMetadata for MyComponent],
/// ...<any other entries>...
/// }
/// ```
Future<Map<String, NgMeta>> _extractNgMeta() async {
var prefixToImports = _createPrefixToImportsMap();
final retVal = <String, NgMeta>{};
for (var prefix in prefixToImports.keys) {
var ngMeta = retVal[prefix] = new NgMeta.empty();
for (var importAssetUri in prefixToImports[prefix]) {
var metaAssetId = fromUri(toMetaExtension(importAssetUri));
if (await reader.hasInput(metaAssetId)) {
try {
var jsonString = await reader.readAsString(metaAssetId);
if (jsonString != null && jsonString.isNotEmpty) {
var newMetadata = new NgMeta.fromJson(JSON.decode(jsonString));
ngMeta.addAll(newMetadata);
}
} catch (ex, stackTrace) {
log.warning('Failed to decode: $ex, $stackTrace',
asset: metaAssetId);
}
}
}
}
return retVal;
}
}
| modules_dart/transform/lib/src/transform/template_compiler/compile_data_creator.dart | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.00017919344827532768,
0.0001740279549267143,
0.00016503932420164347,
0.0001743696630001068,
0.0000035669279441208346
]
|
{
"id": 4,
"code_window": [
" provide(RouterUrlSerializer, {useClass: DefaultRouterUrlSerializer}),\n",
" RouterOutletMap,\n",
" provide(Location, {useClass: SpyLocation}),\n",
" provide(Router,\n",
" {\n",
" useFactory: (resolver, urlParser, outletMap, location) => new Router(\n",
" \"RootComponent\", RootCmp, resolver, urlParser, outletMap, location),\n",
" deps: [ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location]\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" provide(RouteSegment, {useFactory: (r) => r.routeTree.root, deps: [Router]}),\n"
],
"file_path": "modules/@angular/router/test/integration_spec.ts",
"type": "add",
"edit_start_line_idx": 41
} | // tree benchmark in React
import {getIntParameter, bindAction} from '@angular/testing/src/benchmark_util';
import * as React from './react.min';
var TreeComponent = React.createClass({
displayName: 'TreeComponent',
render: function() {
var treeNode = this.props.treeNode;
var left = null;
if (treeNode.left) {
left = React.createElement(
"span", {}, [React.createElement(TreeComponent, {treeNode: treeNode.left}, "")])
}
var right = null;
if (treeNode.right) {
right = React.createElement(
"span", {}, [React.createElement(TreeComponent, {treeNode: treeNode.right}, "")])
}
var span = React.createElement("span", {}, [" " + treeNode.value, left, right]);
return (React.createElement("tree", {}, [span]));
}
});
export function main() {
var count = 0;
var maxDepth = getIntParameter('depth');
bindAction('#destroyDom', destroyDom);
bindAction('#createDom', createDom);
var empty = new TreeNode(0, null, null);
var rootComponent = React.render(React.createElement(TreeComponent, {treeNode: empty}, ""),
document.getElementById('rootTree'));
function destroyDom() { rootComponent.setProps({treeNode: empty}); }
function createDom() {
var values = count++ % 2 == 0 ? ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '*'] :
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', '-'];
rootComponent.setProps({treeNode: buildTree(maxDepth, values, 0)});
}
}
class TreeNode {
value: string;
left: TreeNode;
right: TreeNode;
constructor(value, left, right) {
this.value = value;
this.left = left;
this.right = right;
}
}
function buildTree(maxDepth, values, curDepth) {
if (maxDepth === curDepth) return new TreeNode('', null, null);
return new TreeNode(values[curDepth], buildTree(maxDepth, values, curDepth + 1),
buildTree(maxDepth, values, curDepth + 1));
}
| modules/benchmarks_external/src/tree/react/index.ts | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.00017664421466179192,
0.00017301857587881386,
0.00016456427692901343,
0.00017470451712142676,
0.0000036916214867233066
]
|
{
"id": 4,
"code_window": [
" provide(RouterUrlSerializer, {useClass: DefaultRouterUrlSerializer}),\n",
" RouterOutletMap,\n",
" provide(Location, {useClass: SpyLocation}),\n",
" provide(Router,\n",
" {\n",
" useFactory: (resolver, urlParser, outletMap, location) => new Router(\n",
" \"RootComponent\", RootCmp, resolver, urlParser, outletMap, location),\n",
" deps: [ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location]\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" provide(RouteSegment, {useFactory: (r) => r.routeTree.root, deps: [Router]}),\n"
],
"file_path": "modules/@angular/router/test/integration_spec.ts",
"type": "add",
"edit_start_line_idx": 41
} | library angular2.test.core.compiler.directive_lifecycle_spec;
import 'package:angular2/testing_internal.dart';
import 'package:angular2/src/compiler/directive_lifecycle_reflector.dart';
import 'package:angular2/src/core/metadata/lifecycle_hooks.dart';
main() {
describe('Create DirectiveMetadata', () {
describe('lifecycle', () {
describe("ngOnChanges", () {
it("should be true when the directive has the ngOnChanges method", () {
expect(hasLifecycleHook(
LifecycleHooks.OnChanges, DirectiveImplementingOnChanges))
.toBe(true);
});
it("should be false otherwise", () {
expect(hasLifecycleHook(LifecycleHooks.OnChanges, DirectiveNoHooks))
.toBe(false);
});
});
describe("ngOnDestroy", () {
it("should be true when the directive has the ngOnDestroy method", () {
expect(hasLifecycleHook(
LifecycleHooks.OnDestroy, DirectiveImplementingOnDestroy))
.toBe(true);
});
it("should be false otherwise", () {
expect(hasLifecycleHook(LifecycleHooks.OnDestroy, DirectiveNoHooks))
.toBe(false);
});
});
describe("ngOnInit", () {
it("should be true when the directive has the ngOnInit method", () {
expect(hasLifecycleHook(
LifecycleHooks.OnInit, DirectiveImplementingOnInit)).toBe(true);
});
it("should be false otherwise", () {
expect(hasLifecycleHook(LifecycleHooks.OnInit, DirectiveNoHooks))
.toBe(false);
});
});
describe("ngDoCheck", () {
it("should be true when the directive has the ngDoCheck method", () {
expect(hasLifecycleHook(
LifecycleHooks.DoCheck, DirectiveImplementingOnCheck)).toBe(true);
});
it("should be false otherwise", () {
expect(hasLifecycleHook(LifecycleHooks.DoCheck, DirectiveNoHooks))
.toBe(false);
});
});
describe("ngAfterContentInit", () {
it("should be true when the directive has the ngAfterContentInit method",
() {
expect(hasLifecycleHook(LifecycleHooks.AfterContentInit,
DirectiveImplementingAfterContentInit)).toBe(true);
});
it("should be false otherwise", () {
expect(hasLifecycleHook(
LifecycleHooks.AfterContentInit, DirectiveNoHooks)).toBe(false);
});
});
describe("ngAfterContentChecked", () {
it("should be true when the directive has the ngAfterContentChecked method",
() {
expect(hasLifecycleHook(LifecycleHooks.AfterContentChecked,
DirectiveImplementingAfterContentChecked)).toBe(true);
});
it("should be false otherwise", () {
expect(hasLifecycleHook(
LifecycleHooks.AfterContentChecked, DirectiveNoHooks))
.toBe(false);
});
});
describe("ngAfterViewInit", () {
it("should be true when the directive has the ngAfterViewInit method",
() {
expect(hasLifecycleHook(LifecycleHooks.AfterViewInit,
DirectiveImplementingAfterViewInit)).toBe(true);
});
it("should be false otherwise", () {
expect(hasLifecycleHook(
LifecycleHooks.AfterViewInit, DirectiveNoHooks)).toBe(false);
});
});
describe("ngAfterViewChecked", () {
it("should be true when the directive has the ngAfterViewChecked method",
() {
expect(hasLifecycleHook(LifecycleHooks.AfterViewChecked,
DirectiveImplementingAfterViewChecked)).toBe(true);
});
it("should be false otherwise", () {
expect(hasLifecycleHook(
LifecycleHooks.AfterViewChecked, DirectiveNoHooks)).toBe(false);
});
});
});
});
}
class DirectiveNoHooks {}
class DirectiveImplementingOnChanges implements OnChanges {
ngOnChanges(_) {}
}
class DirectiveImplementingOnCheck implements DoCheck {
ngDoCheck() {}
}
class DirectiveImplementingOnInit implements OnInit {
ngOnInit() {}
}
class DirectiveImplementingOnDestroy implements OnDestroy {
ngOnDestroy() {}
}
class DirectiveImplementingAfterContentInit implements AfterContentInit {
ngAfterContentInit() {}
}
class DirectiveImplementingAfterContentChecked implements AfterContentChecked {
ngAfterContentChecked() {}
}
class DirectiveImplementingAfterViewInit implements AfterViewInit {
ngAfterViewInit() {}
}
class DirectiveImplementingAfterViewChecked implements AfterViewChecked {
ngAfterViewChecked() {}
}
| modules/@angular/compiler/test/directive_lifecycle_spec.dart | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.00018086502677761018,
0.0001756630081217736,
0.00016698775289114565,
0.00017611058137845248,
0.000003494988050078973
]
|
{
"id": 5,
"code_window": [
" router.navigateByUrl('/team/22/link(simple2)');\n",
" advance(fixture);\n",
"\n",
" expect(getDOM().getAttribute(native, \"href\")).toEqual(\"/team/33/simple(aux:simple2)\");\n",
" })));\n",
" }\n",
" });\n",
"}\n",
"\n",
"function advance(fixture: ComponentFixture<any>): void {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" it(\"should support top-level link\",\n",
" fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {\n",
" let fixture = tcb.createFakeAsync(LinkCmp);\n",
" advance(fixture);\n",
" expect(fixture.debugElement.nativeElement).toHaveText('link');\n",
" })));\n"
],
"file_path": "modules/@angular/router/test/integration_spec.ts",
"type": "add",
"edit_start_line_idx": 226
} | import {
AsyncTestCompleter,
beforeEach,
ddescribe,
xdescribe,
describe,
expect,
iit,
inject,
beforeEachProviders,
it,
xit
} from '@angular/core/testing/testing_internal';
import {recognize} from '../src/recognize';
import {Routes, Route} from '@angular/router';
import {provide, Component, ComponentResolver} from '@angular/core';
import {UrlSegment, RouteTree, UrlTree} from '../src/segments';
import {DefaultRouterUrlSerializer} from '../src/router_url_serializer';
import {DEFAULT_OUTLET_NAME} from '../src/constants';
export function main() {
ddescribe('recognize', () => {
it('should handle position args',
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree("b/paramB/c/paramC/d"))
.then(r => {
let a = r.root;
expect(stringifyUrl(a.urlSegments)).toEqual([""]);
expect(a.type).toBe(ComponentA);
let b = r.firstChild(r.root);
expect(stringifyUrl(b.urlSegments)).toEqual(["b", "paramB"]);
expect(b.type).toBe(ComponentB);
let c = r.firstChild(r.firstChild(r.root));
expect(stringifyUrl(c.urlSegments)).toEqual(["c", "paramC"]);
expect(c.type).toBe(ComponentC);
let d = r.firstChild(r.firstChild(r.firstChild(r.root)));
expect(stringifyUrl(d.urlSegments)).toEqual(["d"]);
expect(d.type).toBe(ComponentD);
async.done();
});
}));
it('should support empty routes',
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree("f"))
.then(r => {
let a = r.root;
expect(stringifyUrl(a.urlSegments)).toEqual([""]);
expect(a.type).toBe(ComponentA);
let f = r.firstChild(r.root);
expect(stringifyUrl(f.urlSegments)).toEqual(["f"]);
expect(f.type).toBe(ComponentF);
let d = r.firstChild(r.firstChild(r.root));
expect(stringifyUrl(d.urlSegments)).toEqual([]);
expect(d.type).toBe(ComponentD);
async.done();
});
}));
it('should handle aux routes',
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree("b/paramB(/d//right:d)"))
.then(r => {
let c = r.children(r.root);
expect(stringifyUrl(c[0].urlSegments)).toEqual(["b", "paramB"]);
expect(c[0].outlet).toEqual(DEFAULT_OUTLET_NAME);
expect(c[0].type).toBe(ComponentB);
expect(stringifyUrl(c[1].urlSegments)).toEqual(["d"]);
expect(c[1].outlet).toEqual("aux");
expect(c[1].type).toBe(ComponentD);
expect(stringifyUrl(c[2].urlSegments)).toEqual(["d"]);
expect(c[2].outlet).toEqual("right");
expect(c[2].type).toBe(ComponentD);
async.done();
});
}));
it("should error when two segments with the same outlet name",
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree("b/paramB(right:d//right:e)"))
.catch(e => {
expect(e.message).toEqual(
"Two segments cannot have the same outlet name: 'right:d' and 'right:e'.");
async.done();
});
}));
it('should handle nested aux routes',
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree("b/paramB(/d(right:e))"))
.then(r => {
let c = r.children(r.root);
expect(stringifyUrl(c[0].urlSegments)).toEqual(["b", "paramB"]);
expect(c[0].outlet).toEqual(DEFAULT_OUTLET_NAME);
expect(c[0].type).toBe(ComponentB);
expect(stringifyUrl(c[1].urlSegments)).toEqual(["d"]);
expect(c[1].outlet).toEqual("aux");
expect(c[1].type).toBe(ComponentD);
expect(stringifyUrl(c[2].urlSegments)).toEqual(["e"]);
expect(c[2].outlet).toEqual("right");
expect(c[2].type).toBe(ComponentE);
async.done();
});
}));
it('should handle non top-level aux routes',
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree('b/paramB/d(e)'))
.then(r => {
let c = r.children(r.firstChild(r.root));
expect(stringifyUrl(c[0].urlSegments)).toEqual(["d"]);
expect(c[0].outlet).toEqual(DEFAULT_OUTLET_NAME);
expect(c[0].type).toBe(ComponentD);
expect(stringifyUrl(c[1].urlSegments)).toEqual(["e"]);
expect(c[1].outlet).toEqual("aux");
expect(c[1].type).toBe(ComponentE);
async.done();
});
}));
it('should handle matrix parameters',
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree("b/paramB;b1=1;b2=2(/d;d1=1;d2=2)"))
.then(r => {
let c = r.children(r.root);
expect(c[0].parameters).toEqual({'b': 'paramB', 'b1': '1', 'b2': '2'});
expect(c[1].parameters).toEqual({'d1': '1', 'd2': '2'});
async.done();
});
}));
it('should match a wildcard',
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentG, tree("a;aa=1/b;bb=2"))
.then(r => {
let c = r.children(r.root);
expect(c.length).toEqual(1);
expect(stringifyUrl(c[0].urlSegments)).toEqual([]);
expect(c[0].parameters).toEqual(null);
async.done();
});
}));
it('should error when no matching routes',
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree("invalid"))
.catch(e => {
expect(e.message).toContain("Cannot match any routes");
async.done();
});
}));
it('should handle no matching routes (too short)',
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree("b"))
.catch(e => {
expect(e.message).toContain("Cannot match any routes");
async.done();
});
}));
it("should error when a component doesn't have @Routes",
inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {
recognize(resolver, ComponentA, tree("d/invalid"))
.catch(e => {
expect(e.message)
.toEqual("Component 'ComponentD' does not have route configuration");
async.done();
});
}));
});
}
function tree(url: string): UrlTree {
return new DefaultRouterUrlSerializer().parse(url);
}
function stringifyUrl(segments: UrlSegment[]): string[] {
return segments.map(s => s.segment);
}
@Component({selector: 'd', template: 't'})
class ComponentD {
}
@Component({selector: 'e', template: 't'})
class ComponentE {
}
@Component({selector: 'f', template: 't'})
@Routes([new Route({path: "/", component: ComponentD})])
class ComponentF {
}
@Component({selector: 'c', template: 't'})
@Routes([new Route({path: "d", component: ComponentD})])
class ComponentC {
}
@Component({selector: 'b', template: 't'})
@Routes([
new Route({path: "d", component: ComponentD}),
new Route({path: "e", component: ComponentE}),
new Route({path: "c/:c", component: ComponentC})
])
class ComponentB {
}
@Component({selector: 'g', template: 't'})
@Routes(
[new Route({path: "d", component: ComponentD}), new Route({path: "*", component: ComponentE})])
class ComponentG {
}
@Component({selector: 'a', template: 't'})
@Routes([
new Route({path: "b/:b", component: ComponentB}),
new Route({path: "d", component: ComponentD}),
new Route({path: "e", component: ComponentE}),
new Route({path: "f", component: ComponentF})
])
class ComponentA {
}
| modules/@angular/router/test/recognize_spec.ts | 1 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.004367241635918617,
0.0004248538753017783,
0.0001641494600335136,
0.0001718798594083637,
0.0008534306543879211
]
|
{
"id": 5,
"code_window": [
" router.navigateByUrl('/team/22/link(simple2)');\n",
" advance(fixture);\n",
"\n",
" expect(getDOM().getAttribute(native, \"href\")).toEqual(\"/team/33/simple(aux:simple2)\");\n",
" })));\n",
" }\n",
" });\n",
"}\n",
"\n",
"function advance(fixture: ComponentFixture<any>): void {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" it(\"should support top-level link\",\n",
" fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {\n",
" let fixture = tcb.createFakeAsync(LinkCmp);\n",
" advance(fixture);\n",
" expect(fixture.debugElement.nativeElement).toHaveText('link');\n",
" })));\n"
],
"file_path": "modules/@angular/router/test/integration_spec.ts",
"type": "add",
"edit_start_line_idx": 226
} | syntax = "proto2";
package angular2.src.transform.common.model.proto;
message ParameterModel {
optional string type_name = 1;
optional string type_args = 2;
repeated string metadata = 3;
optional string param_name = 4;
}
| modules_dart/transform/lib/src/transform/common/model/parameter_model.proto | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.0001742754247970879,
0.00017391731671523303,
0.00017355920863337815,
0.00017391731671523303,
3.5810808185487986e-7
]
|
{
"id": 5,
"code_window": [
" router.navigateByUrl('/team/22/link(simple2)');\n",
" advance(fixture);\n",
"\n",
" expect(getDOM().getAttribute(native, \"href\")).toEqual(\"/team/33/simple(aux:simple2)\");\n",
" })));\n",
" }\n",
" });\n",
"}\n",
"\n",
"function advance(fixture: ComponentFixture<any>): void {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" it(\"should support top-level link\",\n",
" fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {\n",
" let fixture = tcb.createFakeAsync(LinkCmp);\n",
" advance(fixture);\n",
" expect(fixture.debugElement.nativeElement).toHaveText('link');\n",
" })));\n"
],
"file_path": "modules/@angular/router/test/integration_spec.ts",
"type": "add",
"edit_start_line_idx": 226
} | import {Type} from '../../src/facade/lang';
/**
* Defines template and style encapsulation options available for Component's {@link View}.
*
* See {@link ViewMetadata#encapsulation}.
*/
export enum ViewEncapsulation {
/**
* Emulate `Native` scoping of styles by adding an attribute containing surrogate id to the Host
* Element and pre-processing the style rules provided via
* {@link ViewMetadata#styles} or {@link ViewMetadata#stylesUrls}, and adding the new Host Element
* attribute to all selectors.
*
* This is the default option.
*/
Emulated,
/**
* Use the native encapsulation mechanism of the renderer.
*
* For the DOM this means using [Shadow DOM](https://w3c.github.io/webcomponents/spec/shadow/) and
* creating a ShadowRoot for Component's Host Element.
*/
Native,
/**
* Don't provide any template or style encapsulation.
*/
None
}
export var VIEW_ENCAPSULATION_VALUES =
[ViewEncapsulation.Emulated, ViewEncapsulation.Native, ViewEncapsulation.None];
/**
* Metadata properties available for configuring Views.
*
* Each Angular component requires a single `@Component` and at least one `@View` annotation. The
* `@View` annotation specifies the HTML template to use, and lists the directives that are active
* within the template.
*
* When a component is instantiated, the template is loaded into the component's shadow root, and
* the expressions and statements in the template are evaluated against the component.
*
* For details on the `@Component` annotation, see {@link ComponentMetadata}.
*
* ### Example
*
* ```
* @Component({
* selector: 'greet',
* template: 'Hello {{name}}!',
* directives: [GreetUser, Bold]
* })
* class Greet {
* name: string;
*
* constructor() {
* this.name = 'World';
* }
* }
* ```
* @ts2dart_const
*/
export class ViewMetadata {
/**
* Specifies a template URL for an Angular component.
*
* NOTE: Only one of `templateUrl` or `template` can be defined per View.
*
* <!-- TODO: what's the url relative to? -->
*/
templateUrl: string;
/**
* Specifies an inline template for an Angular component.
*
* NOTE: Only one of `templateUrl` or `template` can be defined per View.
*/
template: string;
/**
* Specifies stylesheet URLs for an Angular component.
*
* <!-- TODO: what's the url relative to? -->
*/
styleUrls: string[];
/**
* Specifies an inline stylesheet for an Angular component.
*/
styles: string[];
/**
* Specifies a list of directives that can be used within a template.
*
* Directives must be listed explicitly to provide proper component encapsulation.
*
* ### Example
*
* ```javascript
* @Component({
* selector: 'my-component',
* directives: [NgFor]
* template: '
* <ul>
* <li *ngFor="let item of items">{{item}}</li>
* </ul>'
* })
* class MyComponent {
* }
* ```
*/
directives: Array<Type | any[]>;
pipes: Array<Type | any[]>;
/**
* Specify how the template and the styles should be encapsulated.
* The default is {@link ViewEncapsulation#Emulated `ViewEncapsulation.Emulated`} if the view
* has styles,
* otherwise {@link ViewEncapsulation#None `ViewEncapsulation.None`}.
*/
encapsulation: ViewEncapsulation;
constructor({templateUrl, template, directives, pipes, encapsulation, styles, styleUrls}: {
templateUrl?: string,
template?: string,
directives?: Array<Type | any[]>,
pipes?: Array<Type | any[]>,
encapsulation?: ViewEncapsulation,
styles?: string[],
styleUrls?: string[],
} = {}) {
this.templateUrl = templateUrl;
this.template = template;
this.styleUrls = styleUrls;
this.styles = styles;
this.directives = directives;
this.pipes = pipes;
this.encapsulation = encapsulation;
}
}
| modules/@angular/core/src/metadata/view.ts | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.00023624346067663282,
0.00017214956460520625,
0.00016275362577289343,
0.0001674266968620941,
0.000017504771676613018
]
|
{
"id": 5,
"code_window": [
" router.navigateByUrl('/team/22/link(simple2)');\n",
" advance(fixture);\n",
"\n",
" expect(getDOM().getAttribute(native, \"href\")).toEqual(\"/team/33/simple(aux:simple2)\");\n",
" })));\n",
" }\n",
" });\n",
"}\n",
"\n",
"function advance(fixture: ComponentFixture<any>): void {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" it(\"should support top-level link\",\n",
" fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {\n",
" let fixture = tcb.createFakeAsync(LinkCmp);\n",
" advance(fixture);\n",
" expect(fixture.debugElement.nativeElement).toHaveText('link');\n",
" })));\n"
],
"file_path": "modules/@angular/router/test/integration_spec.ts",
"type": "add",
"edit_start_line_idx": 226
} | library angular2.test.transform.directive_processor.pipe_files.pipes;
import 'package:angular2/angular2.dart' show Pipe;
@Pipe(name: 'nameOnly')
class NameOnlyPipe {}
@Pipe(name: 'nameAndPure', pure: true)
class NameAndPurePipe {}
| modules_dart/transform/test/transform/directive_processor/pipe_files/pipes.dart | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.0001755745615810156,
0.0001755745615810156,
0.0001755745615810156,
0.0001755745615810156,
0
]
|
{
"id": 6,
"code_window": [
"import {UrlSegment, RouteTree, UrlTree} from '../src/segments';\n",
"import {DefaultRouterUrlSerializer} from '../src/router_url_serializer';\n",
"import {DEFAULT_OUTLET_NAME} from '../src/constants';\n",
"\n",
"export function main() {\n",
" ddescribe('recognize', () => {\n",
" it('should handle position args',\n",
" inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {\n",
" recognize(resolver, ComponentA, tree(\"b/paramB/c/paramC/d\"))\n",
" .then(r => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" describe('recognize', () => {\n"
],
"file_path": "modules/@angular/router/test/recognize_spec.ts",
"type": "replace",
"edit_start_line_idx": 22
} | import {
AsyncTestCompleter,
beforeEach,
ddescribe,
xdescribe,
describe,
expect,
iit,
inject,
beforeEachProviders,
it,
xit
} from '@angular/core/testing/testing_internal';
import {fakeAsync, tick} from '@angular/core/testing';
import {ComponentFixture, TestComponentBuilder} from '@angular/compiler/testing';
import {provide, Component, ComponentResolver} from '@angular/core';
import {PromiseWrapper} from '../src/facade/async';
import {
Router,
RouterOutletMap,
RouteSegment,
Route,
ROUTER_DIRECTIVES,
Routes,
RouterUrlSerializer,
DefaultRouterUrlSerializer,
OnActivate,
CanDeactivate
} from '@angular/router';
import {SpyLocation} from '@angular/common/testing';
import {Location} from '@angular/common';
import {getDOM} from '../platform_browser_private';
export function main() {
describe('navigation', () => {
beforeEachProviders(() => [
provide(RouterUrlSerializer, {useClass: DefaultRouterUrlSerializer}),
RouterOutletMap,
provide(Location, {useClass: SpyLocation}),
provide(Router,
{
useFactory: (resolver, urlParser, outletMap, location) => new Router(
"RootComponent", RootCmp, resolver, urlParser, outletMap, location),
deps: [ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location]
})
]);
it('should update location when navigating',
fakeAsync(inject([Router, TestComponentBuilder, Location], (router, tcb, location) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
expect(location.path()).toEqual('/team/22/user/victor');
router.navigateByUrl('/team/33/simple');
advance(fixture);
expect(location.path()).toEqual('/team/33/simple');
})));
it('should navigate when locations changes',
fakeAsync(inject([Router, TestComponentBuilder, Location], (router, tcb, location) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
location.simulateHashChange("/team/22/user/fedor");
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('team 22 { hello fedor, aux: }');
})));
it('should support nested routes',
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('team 22 { hello victor, aux: }');
})));
it('should support aux routes',
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor(/simple)');
advance(fixture);
expect(fixture.debugElement.nativeElement)
.toHaveText('team 22 { hello victor, aux: simple }');
})));
it('should deactivate outlets', fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor(/simple)');
advance(fixture);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('team 22 { hello victor, aux: }');
})));
it('should deactivate nested outlets',
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor(/simple)');
advance(fixture);
router.navigateByUrl('/');
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('');
})));
it('should update nested routes when url changes',
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
let team1 = fixture.debugElement.children[1].componentInstance;
router.navigateByUrl('/team/22/user/fedor');
advance(fixture);
let team2 = fixture.debugElement.children[1].componentInstance;
expect(team1).toBe(team2);
expect(fixture.debugElement.nativeElement).toHaveText('team 22 { hello fedor, aux: }');
})));
it('should not deactivate the route if can deactivate returns false',
fakeAsync(inject([Router, TestComponentBuilder, Location], (router, tcb, location) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/cannotDeactivate');
advance(fixture);
router.navigateByUrl('/team/22/user/fedor');
advance(fixture);
expect(fixture.debugElement.nativeElement)
.toHaveText('team 22 { cannotDeactivate, aux: }');
expect(location.path()).toEqual('/team/22/cannotDeactivate');
})));
if (getDOM().supportsDOMEvents()) {
it("should support absolute router links",
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
advance(fixture);
router.navigateByUrl('/team/22/link');
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('team 22 { link, aux: }');
let native = getDOM().querySelector(fixture.debugElement.nativeElement, "a");
expect(getDOM().getAttribute(native, "href")).toEqual("/team/33/simple");
getDOM().dispatchEvent(native, getDOM().createMouseEvent('click'));
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('team 33 { simple, aux: }');
})));
it("should support relative router links",
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
advance(fixture);
router.navigateByUrl('/team/22/relativelink');
advance(fixture);
expect(fixture.debugElement.nativeElement)
.toHaveText('team 22 { relativelink { }, aux: }');
let native = getDOM().querySelector(fixture.debugElement.nativeElement, "a");
expect(getDOM().getAttribute(native, "href")).toEqual("/team/22/relativelink/simple");
getDOM().dispatchEvent(native, getDOM().createMouseEvent('click'));
advance(fixture);
expect(fixture.debugElement.nativeElement)
.toHaveText('team 22 { relativelink { simple }, aux: }');
})));
it("should set the router-link-active class",
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
advance(fixture);
router.navigateByUrl('/team/22/relativelink');
advance(fixture);
expect(fixture.debugElement.nativeElement)
.toHaveText('team 22 { relativelink { }, aux: }');
let link = getDOM().querySelector(fixture.debugElement.nativeElement, "a");
expect(getDOM().hasClass(link, "router-link-active")).toEqual(false);
getDOM().dispatchEvent(link, getDOM().createMouseEvent('click'));
advance(fixture);
expect(getDOM().hasClass(link, "router-link-active")).toEqual(true);
})));
it("should update router links when router changes",
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
advance(fixture);
router.navigateByUrl('/team/22/link(simple)');
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('team 22 { link, aux: simple }');
let native = getDOM().querySelector(fixture.debugElement.nativeElement, "a");
expect(getDOM().getAttribute(native, "href")).toEqual("/team/33/simple(aux:simple)");
router.navigateByUrl('/team/22/link(simple2)');
advance(fixture);
expect(getDOM().getAttribute(native, "href")).toEqual("/team/33/simple(aux:simple2)");
})));
}
});
}
function advance(fixture: ComponentFixture<any>): void {
tick();
fixture.detectChanges();
}
function compileRoot(tcb: TestComponentBuilder): Promise<ComponentFixture<any>> {
return tcb.createAsync(RootCmp);
}
@Component({selector: 'user-cmp', template: `hello {{user}}`})
class UserCmp implements OnActivate {
user: string;
routerOnActivate(s: RouteSegment, a?, b?, c?) { this.user = s.getParam('name'); }
}
@Component({selector: 'cannot-deactivate', template: `cannotDeactivate`})
class CanDeactivateCmp implements CanDeactivate {
routerCanDeactivate(a?, b?): Promise<boolean> { return PromiseWrapper.resolve(false); }
}
@Component({selector: 'simple-cmp', template: `simple`})
class SimpleCmp {
}
@Component({selector: 'simple2-cmp', template: `simple2`})
class Simple2Cmp {
}
@Component({
selector: 'link-cmp',
template: `<a [routerLink]="['/team', '33', 'simple']">link</a>`,
directives: ROUTER_DIRECTIVES
})
class LinkCmp {
}
@Component({
selector: 'link-cmp',
template: `<a [routerLink]="['./simple']">relativelink</a> { <router-outlet></router-outlet> }`,
directives: ROUTER_DIRECTIVES
})
@Routes([new Route({path: 'simple', component: SimpleCmp})])
class RelativeLinkCmp {
}
@Component({
selector: 'team-cmp',
template: `team {{id}} { <router-outlet></router-outlet>, aux: <router-outlet name="aux"></router-outlet> }`,
directives: [ROUTER_DIRECTIVES]
})
@Routes([
new Route({path: 'user/:name', component: UserCmp}),
new Route({path: 'simple', component: SimpleCmp}),
new Route({path: 'simple2', component: Simple2Cmp}),
new Route({path: 'link', component: LinkCmp}),
new Route({path: 'relativelink', component: RelativeLinkCmp}),
new Route({path: 'cannotDeactivate', component: CanDeactivateCmp})
])
class TeamCmp implements OnActivate {
id: string;
routerOnActivate(s: RouteSegment, a?, b?, c?) { this.id = s.getParam('id'); }
}
@Component({
selector: 'root-cmp',
template: `<router-outlet></router-outlet>`,
directives: [ROUTER_DIRECTIVES]
})
@Routes([new Route({path: 'team/:id', component: TeamCmp})])
class RootCmp {
}
| modules/@angular/router/test/integration_spec.ts | 1 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.0012988544767722487,
0.0002717438037507236,
0.00016034036525525153,
0.00017528384341858327,
0.000259863561950624
]
|
{
"id": 6,
"code_window": [
"import {UrlSegment, RouteTree, UrlTree} from '../src/segments';\n",
"import {DefaultRouterUrlSerializer} from '../src/router_url_serializer';\n",
"import {DEFAULT_OUTLET_NAME} from '../src/constants';\n",
"\n",
"export function main() {\n",
" ddescribe('recognize', () => {\n",
" it('should handle position args',\n",
" inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {\n",
" recognize(resolver, ComponentA, tree(\"b/paramB/c/paramC/d\"))\n",
" .then(r => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" describe('recognize', () => {\n"
],
"file_path": "modules/@angular/router/test/recognize_spec.ts",
"type": "replace",
"edit_start_line_idx": 22
} | library benchmarks_external.e2e_test.naive_infinite_scroll_perf;
main() {}
| modules/benchmarks_external/e2e_test/naive_infinite_scroll_perf.dart | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.9619760513305664,
0.9619760513305664,
0.9619760513305664,
0.9619760513305664,
0
]
|
{
"id": 6,
"code_window": [
"import {UrlSegment, RouteTree, UrlTree} from '../src/segments';\n",
"import {DefaultRouterUrlSerializer} from '../src/router_url_serializer';\n",
"import {DEFAULT_OUTLET_NAME} from '../src/constants';\n",
"\n",
"export function main() {\n",
" ddescribe('recognize', () => {\n",
" it('should handle position args',\n",
" inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {\n",
" recognize(resolver, ComponentA, tree(\"b/paramB/c/paramC/d\"))\n",
" .then(r => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" describe('recognize', () => {\n"
],
"file_path": "modules/@angular/router/test/recognize_spec.ts",
"type": "replace",
"edit_start_line_idx": 22
} | # Components
* Different kinds of injections and visibility
* Shadow DOM usage
* | modules/@angular/docs/core/05_component_directive.md | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.00016481081547681242,
0.00016481081547681242,
0.00016481081547681242,
0.00016481081547681242,
0
]
|
{
"id": 6,
"code_window": [
"import {UrlSegment, RouteTree, UrlTree} from '../src/segments';\n",
"import {DefaultRouterUrlSerializer} from '../src/router_url_serializer';\n",
"import {DEFAULT_OUTLET_NAME} from '../src/constants';\n",
"\n",
"export function main() {\n",
" ddescribe('recognize', () => {\n",
" it('should handle position args',\n",
" inject([AsyncTestCompleter, ComponentResolver], (async, resolver) => {\n",
" recognize(resolver, ComponentA, tree(\"b/paramB/c/paramC/d\"))\n",
" .then(r => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" describe('recognize', () => {\n"
],
"file_path": "modules/@angular/router/test/recognize_spec.ts",
"type": "replace",
"edit_start_line_idx": 22
} | library reflection.reflection_capabilities;
import 'dart:mirrors';
import 'package:angular2/src/core/metadata/lifecycle_hooks.dart';
import 'package:angular2/src/facade/lang.dart';
import 'platform_reflection_capabilities.dart';
import 'types.dart';
import '../linker/template_ref.dart';
var DOT_REGEX = new RegExp('\\.');
class ReflectionCapabilities implements PlatformReflectionCapabilities {
Map<Symbol, Type> parameterizedTypeMapping = new Map<Symbol, Type>();
ReflectionCapabilities([metadataReader]) {
// In Dart, there is no way of getting from a parameterized Type to
// the underlying non parameterized type.
// So we need to have a separate Map for the types that are generic
// and used in our DI...
parameterizedTypeMapping[reflectType(TemplateRef).qualifiedName] = TemplateRef;
}
_typeFromMirror(TypeMirror typeMirror) {
var result = parameterizedTypeMapping[typeMirror.qualifiedName];
if (result == null && typeMirror.hasReflectedType && typeMirror.reflectedType != dynamic) {
result = typeMirror.reflectedType;
}
return result;
}
bool isReflectionEnabled() {
return true;
}
Function factory(Type type) {
ClassMirror classMirror = reflectType(type);
MethodMirror ctor = classMirror.declarations[classMirror.simpleName];
Function create = classMirror.newInstance;
Symbol name = ctor.constructorName;
int length = ctor.parameters.length;
switch (length) {
case 0:
return () => create(name, []).reflectee;
case 1:
return (a1) => create(name, [a1]).reflectee;
case 2:
return (a1, a2) => create(name, [a1, a2]).reflectee;
case 3:
return (a1, a2, a3) => create(name, [a1, a2, a3]).reflectee;
case 4:
return (a1, a2, a3, a4) => create(name, [a1, a2, a3, a4]).reflectee;
case 5:
return (a1, a2, a3, a4, a5) =>
create(name, [a1, a2, a3, a4, a5]).reflectee;
case 6:
return (a1, a2, a3, a4, a5, a6) =>
create(name, [a1, a2, a3, a4, a5, a6]).reflectee;
case 7:
return (a1, a2, a3, a4, a5, a6, a7) =>
create(name, [a1, a2, a3, a4, a5, a6, a7]).reflectee;
case 8:
return (a1, a2, a3, a4, a5, a6, a7, a8) =>
create(name, [a1, a2, a3, a4, a5, a6, a7, a8]).reflectee;
case 9:
return (a1, a2, a3, a4, a5, a6, a7, a8, a9) =>
create(name, [a1, a2, a3, a4, a5, a6, a7, a8, a9]).reflectee;
case 10:
return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) =>
create(name, [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10]).reflectee;
case 11:
return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) =>
create(name, [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11])
.reflectee;
case 12:
return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) =>
create(name, [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12])
.reflectee;
case 13:
return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13) =>
create(name, [
a1,
a2,
a3,
a4,
a5,
a6,
a7,
a8,
a9,
a10,
a11,
a12,
a13
]).reflectee;
case 14:
return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14) =>
create(name, [
a1,
a2,
a3,
a4,
a5,
a6,
a7,
a8,
a9,
a10,
a11,
a12,
a13,
a14
]).reflectee;
case 15:
return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14,
a15) =>
create(name, [
a1,
a2,
a3,
a4,
a5,
a6,
a7,
a8,
a9,
a10,
a11,
a12,
a13,
a14,
a15
]).reflectee;
case 16:
return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14,
a15, a16) =>
create(name, [
a1,
a2,
a3,
a4,
a5,
a6,
a7,
a8,
a9,
a10,
a11,
a12,
a13,
a14,
a15,
a16
]).reflectee;
case 17:
return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14,
a15, a16, a17) =>
create(name, [
a1,
a2,
a3,
a4,
a5,
a6,
a7,
a8,
a9,
a10,
a11,
a12,
a13,
a14,
a15,
a16,
a17
]).reflectee;
case 18:
return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14,
a15, a16, a17, a18) =>
create(name, [
a1,
a2,
a3,
a4,
a5,
a6,
a7,
a8,
a9,
a10,
a11,
a12,
a13,
a14,
a15,
a16,
a17,
a18
]).reflectee;
case 19:
return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14,
a15, a16, a17, a18, a19) =>
create(name, [
a1,
a2,
a3,
a4,
a5,
a6,
a7,
a8,
a9,
a10,
a11,
a12,
a13,
a14,
a15,
a16,
a17,
a18,
a19
]).reflectee;
case 20:
return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14,
a15, a16, a17, a18, a19, a20) =>
create(name, [
a1,
a2,
a3,
a4,
a5,
a6,
a7,
a8,
a9,
a10,
a11,
a12,
a13,
a14,
a15,
a16,
a17,
a18,
a19,
a20
]).reflectee;
}
throw "Cannot create a factory for '${stringify(type)}' because its constructor has more than 20 arguments";
}
List<List> parameters(typeOrFunc) {
final parameters = typeOrFunc is Type
? _constructorParameters(typeOrFunc)
: _functionParameters(typeOrFunc);
return parameters.map(_convertParameter).toList();
}
List _convertParameter(ParameterMirror p) {
var t = p.type;
var type = _typeFromMirror(t);
var res = type != null ? [type] : [];
res.addAll(p.metadata.map((m) => m.reflectee));
return res;
}
List annotations(typeOrFunc) {
final meta = typeOrFunc is Type
? _constructorMetadata(typeOrFunc)
: _functionMetadata(typeOrFunc);
return meta.map((m) => m.reflectee).toList();
}
Map propMetadata(typeOrFunc) {
final res = {};
reflectClass(typeOrFunc).declarations.forEach((k, v) {
var name = _normalizeName(MirrorSystem.getName(k));
if (res[name] == null) res[name] = [];
res[name].addAll(v.metadata.map((fm) => fm.reflectee));
});
return res;
}
String _normalizeName(String name) {
return name.endsWith("=") ? name.substring(0, name.length - 1) : name;
}
bool hasLifecycleHook(dynamic type, Type lcInterface, String lcProperty) {
if (type is! Type) return false;
return this.interfaces(type).contains(lcInterface);
}
List interfaces(type) {
final clazz = reflectType(type);
_assertDeclaresLifecycleHooks(clazz);
return _interfacesFromMirror(clazz);
}
List _interfacesFromMirror(classMirror) {
return classMirror.superinterfaces.map((si) => si.reflectedType).toList()
..addAll(classMirror.superclass == null
? []
: _interfacesFromMirror(classMirror.superclass));
}
GetterFn getter(String name) {
var symbol = new Symbol(name);
return (receiver) => reflect(receiver).getField(symbol).reflectee;
}
SetterFn setter(String name) {
var symbol = new Symbol(name);
return (receiver, value) =>
reflect(receiver).setField(symbol, value).reflectee;
}
MethodFn method(String name) {
var symbol = new Symbol(name);
return (receiver, posArgs) =>
reflect(receiver).invoke(symbol, posArgs).reflectee;
}
List _functionParameters(Function func) {
var closureMirror = reflect(func);
return closureMirror.function.parameters;
}
List _constructorParameters(Type type) {
ClassMirror classMirror = reflectType(type);
MethodMirror ctor = classMirror.declarations[classMirror.simpleName];
return ctor.parameters;
}
List _functionMetadata(Function func) {
var closureMirror = reflect(func);
return closureMirror.function.metadata;
}
List _constructorMetadata(Type type) {
ClassMirror classMirror = reflectType(type);
return classMirror.metadata;
}
String importUri(dynamic type) {
// StaticSymbol
if (type is Map && type['filePath'] != null) {
return type['filePath'];
}
// Runtime type
return '${(reflectClass(type).owner as LibraryMirror).uri}';
}
}
final _lifecycleHookMirrors = <ClassMirror>[
reflectType(AfterContentChecked),
reflectType(AfterContentInit),
reflectType(AfterViewChecked),
reflectType(AfterViewInit),
reflectType(DoCheck),
reflectType(OnChanges),
reflectType(OnDestroy),
reflectType(OnInit),
];
/// Checks whether [clazz] implements lifecycle ifaces without declaring them.
///
/// Due to Dart implementation details, lifecycle hooks are only called when a
/// class explicitly declares that it implements the associated interface.
/// See https://goo.gl/b07Kii for details.
void _assertDeclaresLifecycleHooks(ClassMirror clazz) {
final missingDeclarations = <ClassMirror>[];
for (var iface in _lifecycleHookMirrors) {
if (!_checkDeclares(clazz, iface: iface) &&
_checkImplements(clazz, iface: iface)) {
missingDeclarations.add(iface);
}
}
if (missingDeclarations.isNotEmpty) {
throw new MissingInterfaceError(clazz, missingDeclarations);
}
}
/// Returns whether [clazz] declares that it implements [iface].
///
/// Returns `false` if [clazz] implements [iface] but does not declare it.
/// Returns `false` if [clazz]'s superclass declares that it
/// implements [iface].
bool _checkDeclares(ClassMirror clazz, {ClassMirror iface: null}) {
if (iface == null) {
throw new ArgumentError.notNull('iface');
}
return clazz.superinterfaces.contains(iface);
}
/// Returns whether [clazz] implements [iface].
///
/// Returns `true` if [clazz] implements [iface] and does not declare it.
/// Returns `true` if [clazz]'s superclass implements [iface].
///
/// This is an approximation of a JavaScript feature check:
/// ```js
/// var matches = true;
/// for (var prop in iface) {
/// if (iface.hasOwnProperty(prop)) {
/// matches = matches && clazz.hasOwnProperty(prop);
/// }
/// }
/// return matches;
/// ```
bool _checkImplements(ClassMirror clazz, {ClassMirror iface: null}) {
if (iface == null) {
throw new ArgumentError.notNull('iface');
}
var matches = true;
iface.declarations.forEach((symbol, declarationMirror) {
if (!matches) return;
if (declarationMirror.isConstructor || declarationMirror.isPrivate) return;
matches = clazz.declarations.keys.contains(symbol);
});
if (!matches && clazz.superclass != null) {
matches = _checkImplements(clazz.superclass, iface: iface);
}
if (!matches && clazz.mixin != clazz) {
matches = _checkImplements(clazz.mixin, iface: iface);
}
return matches;
}
/// Error thrown when a class implements a lifecycle iface it does not declare.
class MissingInterfaceError extends Error {
final ClassMirror clazz;
final List<ClassMirror> missingDeclarations;
MissingInterfaceError(this.clazz, this.missingDeclarations);
@override
String toString() {
final buf = new StringBuffer();
buf.write('${clazz.simpleName} implements ');
if (missingDeclarations.length == 1) {
buf.write('an interface but does not declare it: ');
} else {
buf.write('interfaces but does not declare them: ');
}
buf.write(
missingDeclarations.map((d) => d.simpleName.toString()).join(', '));
buf.write('. See https://goo.gl/b07Kii for more info.');
return buf.toString();
}
}
| modules/@angular/core/src/reflection/reflection_capabilities.dart | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.00038917045458219945,
0.00017830841534305364,
0.0001630814076634124,
0.0001750029477989301,
0.00003163634755765088
]
|
{
"id": 7,
"code_window": [
"import {SpyLocation} from '@angular/common/testing';\n",
"import {Location} from '@angular/common';\n",
"import {Router, RouterOutletMap} from '../src/router';\n",
"import {RouterUrlSerializer, DefaultRouterUrlSerializer} from '../src/router_url_serializer';\n",
"import {Component, ComponentResolver} from '@angular/core';\n",
"\n",
"@Component({selector: 'fake-app-root-comp', template: `<span></span>`})\n",
"class FakeAppRootCmp {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {RouteSegment} from '../src/segments';\n"
],
"file_path": "modules/@angular/router/testing/router_testing_providers.ts",
"type": "add",
"edit_start_line_idx": 3
} | import {
AsyncTestCompleter,
beforeEach,
ddescribe,
xdescribe,
describe,
expect,
iit,
inject,
beforeEachProviders,
it,
xit
} from '@angular/core/testing/testing_internal';
import {fakeAsync, tick} from '@angular/core/testing';
import {ComponentFixture, TestComponentBuilder} from '@angular/compiler/testing';
import {provide, Component, ComponentResolver} from '@angular/core';
import {PromiseWrapper} from '../src/facade/async';
import {
Router,
RouterOutletMap,
RouteSegment,
Route,
ROUTER_DIRECTIVES,
Routes,
RouterUrlSerializer,
DefaultRouterUrlSerializer,
OnActivate,
CanDeactivate
} from '@angular/router';
import {SpyLocation} from '@angular/common/testing';
import {Location} from '@angular/common';
import {getDOM} from '../platform_browser_private';
export function main() {
describe('navigation', () => {
beforeEachProviders(() => [
provide(RouterUrlSerializer, {useClass: DefaultRouterUrlSerializer}),
RouterOutletMap,
provide(Location, {useClass: SpyLocation}),
provide(Router,
{
useFactory: (resolver, urlParser, outletMap, location) => new Router(
"RootComponent", RootCmp, resolver, urlParser, outletMap, location),
deps: [ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location]
})
]);
it('should update location when navigating',
fakeAsync(inject([Router, TestComponentBuilder, Location], (router, tcb, location) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
expect(location.path()).toEqual('/team/22/user/victor');
router.navigateByUrl('/team/33/simple');
advance(fixture);
expect(location.path()).toEqual('/team/33/simple');
})));
it('should navigate when locations changes',
fakeAsync(inject([Router, TestComponentBuilder, Location], (router, tcb, location) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
location.simulateHashChange("/team/22/user/fedor");
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('team 22 { hello fedor, aux: }');
})));
it('should support nested routes',
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('team 22 { hello victor, aux: }');
})));
it('should support aux routes',
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor(/simple)');
advance(fixture);
expect(fixture.debugElement.nativeElement)
.toHaveText('team 22 { hello victor, aux: simple }');
})));
it('should deactivate outlets', fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor(/simple)');
advance(fixture);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('team 22 { hello victor, aux: }');
})));
it('should deactivate nested outlets',
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor(/simple)');
advance(fixture);
router.navigateByUrl('/');
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('');
})));
it('should update nested routes when url changes',
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
let team1 = fixture.debugElement.children[1].componentInstance;
router.navigateByUrl('/team/22/user/fedor');
advance(fixture);
let team2 = fixture.debugElement.children[1].componentInstance;
expect(team1).toBe(team2);
expect(fixture.debugElement.nativeElement).toHaveText('team 22 { hello fedor, aux: }');
})));
it('should not deactivate the route if can deactivate returns false',
fakeAsync(inject([Router, TestComponentBuilder, Location], (router, tcb, location) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/cannotDeactivate');
advance(fixture);
router.navigateByUrl('/team/22/user/fedor');
advance(fixture);
expect(fixture.debugElement.nativeElement)
.toHaveText('team 22 { cannotDeactivate, aux: }');
expect(location.path()).toEqual('/team/22/cannotDeactivate');
})));
if (getDOM().supportsDOMEvents()) {
it("should support absolute router links",
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
advance(fixture);
router.navigateByUrl('/team/22/link');
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('team 22 { link, aux: }');
let native = getDOM().querySelector(fixture.debugElement.nativeElement, "a");
expect(getDOM().getAttribute(native, "href")).toEqual("/team/33/simple");
getDOM().dispatchEvent(native, getDOM().createMouseEvent('click'));
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('team 33 { simple, aux: }');
})));
it("should support relative router links",
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
advance(fixture);
router.navigateByUrl('/team/22/relativelink');
advance(fixture);
expect(fixture.debugElement.nativeElement)
.toHaveText('team 22 { relativelink { }, aux: }');
let native = getDOM().querySelector(fixture.debugElement.nativeElement, "a");
expect(getDOM().getAttribute(native, "href")).toEqual("/team/22/relativelink/simple");
getDOM().dispatchEvent(native, getDOM().createMouseEvent('click'));
advance(fixture);
expect(fixture.debugElement.nativeElement)
.toHaveText('team 22 { relativelink { simple }, aux: }');
})));
it("should set the router-link-active class",
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
advance(fixture);
router.navigateByUrl('/team/22/relativelink');
advance(fixture);
expect(fixture.debugElement.nativeElement)
.toHaveText('team 22 { relativelink { }, aux: }');
let link = getDOM().querySelector(fixture.debugElement.nativeElement, "a");
expect(getDOM().hasClass(link, "router-link-active")).toEqual(false);
getDOM().dispatchEvent(link, getDOM().createMouseEvent('click'));
advance(fixture);
expect(getDOM().hasClass(link, "router-link-active")).toEqual(true);
})));
it("should update router links when router changes",
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
advance(fixture);
router.navigateByUrl('/team/22/link(simple)');
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('team 22 { link, aux: simple }');
let native = getDOM().querySelector(fixture.debugElement.nativeElement, "a");
expect(getDOM().getAttribute(native, "href")).toEqual("/team/33/simple(aux:simple)");
router.navigateByUrl('/team/22/link(simple2)');
advance(fixture);
expect(getDOM().getAttribute(native, "href")).toEqual("/team/33/simple(aux:simple2)");
})));
}
});
}
function advance(fixture: ComponentFixture<any>): void {
tick();
fixture.detectChanges();
}
function compileRoot(tcb: TestComponentBuilder): Promise<ComponentFixture<any>> {
return tcb.createAsync(RootCmp);
}
@Component({selector: 'user-cmp', template: `hello {{user}}`})
class UserCmp implements OnActivate {
user: string;
routerOnActivate(s: RouteSegment, a?, b?, c?) { this.user = s.getParam('name'); }
}
@Component({selector: 'cannot-deactivate', template: `cannotDeactivate`})
class CanDeactivateCmp implements CanDeactivate {
routerCanDeactivate(a?, b?): Promise<boolean> { return PromiseWrapper.resolve(false); }
}
@Component({selector: 'simple-cmp', template: `simple`})
class SimpleCmp {
}
@Component({selector: 'simple2-cmp', template: `simple2`})
class Simple2Cmp {
}
@Component({
selector: 'link-cmp',
template: `<a [routerLink]="['/team', '33', 'simple']">link</a>`,
directives: ROUTER_DIRECTIVES
})
class LinkCmp {
}
@Component({
selector: 'link-cmp',
template: `<a [routerLink]="['./simple']">relativelink</a> { <router-outlet></router-outlet> }`,
directives: ROUTER_DIRECTIVES
})
@Routes([new Route({path: 'simple', component: SimpleCmp})])
class RelativeLinkCmp {
}
@Component({
selector: 'team-cmp',
template: `team {{id}} { <router-outlet></router-outlet>, aux: <router-outlet name="aux"></router-outlet> }`,
directives: [ROUTER_DIRECTIVES]
})
@Routes([
new Route({path: 'user/:name', component: UserCmp}),
new Route({path: 'simple', component: SimpleCmp}),
new Route({path: 'simple2', component: Simple2Cmp}),
new Route({path: 'link', component: LinkCmp}),
new Route({path: 'relativelink', component: RelativeLinkCmp}),
new Route({path: 'cannotDeactivate', component: CanDeactivateCmp})
])
class TeamCmp implements OnActivate {
id: string;
routerOnActivate(s: RouteSegment, a?, b?, c?) { this.id = s.getParam('id'); }
}
@Component({
selector: 'root-cmp',
template: `<router-outlet></router-outlet>`,
directives: [ROUTER_DIRECTIVES]
})
@Routes([new Route({path: 'team/:id', component: TeamCmp})])
class RootCmp {
}
| modules/@angular/router/test/integration_spec.ts | 1 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.04122917354106903,
0.0035002732183784246,
0.00016556985792703927,
0.00046579548506997526,
0.008849674835801125
]
|
{
"id": 7,
"code_window": [
"import {SpyLocation} from '@angular/common/testing';\n",
"import {Location} from '@angular/common';\n",
"import {Router, RouterOutletMap} from '../src/router';\n",
"import {RouterUrlSerializer, DefaultRouterUrlSerializer} from '../src/router_url_serializer';\n",
"import {Component, ComponentResolver} from '@angular/core';\n",
"\n",
"@Component({selector: 'fake-app-root-comp', template: `<span></span>`})\n",
"class FakeAppRootCmp {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {RouteSegment} from '../src/segments';\n"
],
"file_path": "modules/@angular/router/testing/router_testing_providers.ts",
"type": "add",
"edit_start_line_idx": 3
} | $SCRIPTS$
System.config({
baseURL: '/',
defaultJSExtensions: true
});
System.import("playground/src/web_workers/todo/background_index")
.then(
function(m) {
try {
m.main();
} catch (e) {
console.error(e);
}
},
function(error) { console.error("error loading background", error); });
| modules/playground/src/web_workers/todo/loader.js | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.0001726209302432835,
0.0001713460951577872,
0.00017007124552037567,
0.0001713460951577872,
0.0000012748423614539206
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.