hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 8,
"code_window": [
"\t}\n",
"\n",
"\tprivate refreshTree(event?: IChangeEvent): TPromise<any> {\n",
"\t\tif (!event) {\n",
"\t\t\treturn this.tree.refresh(this.viewModel.searchResult);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tif (!event || event.added || event.removed) {\n"
],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 331
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"workingFilesViewerAriaLabel": "{0}, fichiers de travail"
} | i18n/fra/src/vs/workbench/parts/files/browser/views/workingFilesViewer.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.0001774418487912044,
0.0001774418487912044,
0.0001774418487912044,
0.0001774418487912044,
0
] |
{
"id": 8,
"code_window": [
"\t}\n",
"\n",
"\tprivate refreshTree(event?: IChangeEvent): TPromise<any> {\n",
"\t\tif (!event) {\n",
"\t\t\treturn this.tree.refresh(this.viewModel.searchResult);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tif (!event || event.added || event.removed) {\n"
],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 331
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"help": "Hilfe",
"interactivePlayground": "Interaktiver Playground",
"walkThrough.editor.label": "Interaktiver Playground"
} | i18n/deu/src/vs/workbench/parts/welcome/walkThrough/electron-browser/walkThrough.contribution.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.0001792960101738572,
0.00017823147936724126,
0.00017716694856062531,
0.00017823147936724126,
0.0000010645308066159487
] |
{
"id": 9,
"code_window": [
"\t\t\treturn this.tree.refresh(this.viewModel.searchResult);\n",
"\t\t}\n",
"\n",
"\t\tif (event.added || event.removed) {\n",
"\t\t\treturn this.tree.refresh(this.viewModel.searchResult).then(() => {\n",
"\t\t\t\tif (event.added) {\n",
"\t\t\t\t\tevent.elements.forEach(element => {\n",
"\t\t\t\t\t\tthis.autoExpandFileMatch(element, true);\n",
"\t\t\t\t\t});\n",
"\t\t\t\t}\n",
"\t\t\t});\n",
"\t\t} else {\n",
"\t\t\tif (event.elements.length === 1) {\n",
"\t\t\t\treturn this.tree.refresh(event.elements[0]);\n",
"\t\t\t} else {\n",
"\t\t\t\treturn this.tree.refresh(event.elements);\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 333
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import nls = require('vs/nls');
import strings = require('vs/base/common/strings');
import platform = require('vs/base/common/platform');
import errors = require('vs/base/common/errors');
import paths = require('vs/base/common/paths');
import dom = require('vs/base/browser/dom');
import { $ } from 'vs/base/browser/builder';
import { TPromise } from 'vs/base/common/winjs.base';
import { IAction, IActionRunner } from 'vs/base/common/actions';
import { ActionsRenderer } from 'vs/base/parts/tree/browser/actionsRenderer';
import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge';
import { FileLabel } from 'vs/workbench/browser/labels';
import { LeftRightWidget, IRenderer } from 'vs/base/browser/ui/leftRightWidget/leftRightWidget';
import { ITree, IElementCallback, IDataSource, ISorter, IAccessibilityProvider, IFilter } from 'vs/base/parts/tree/browser/tree';
import { ClickBehavior, DefaultController } from 'vs/base/parts/tree/browser/treeDefaults';
import { ContributableActionProvider } from 'vs/workbench/browser/actionBarRegistry';
import { Match, SearchResult, FileMatch, FileMatchOrMatch, SearchModel } from 'vs/workbench/parts/search/common/searchModel';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { Range } from 'vs/editor/common/core/range';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { SearchViewlet } from 'vs/workbench/parts/search/browser/searchViewlet';
import { RemoveAction, ReplaceAllAction, ReplaceAction } from 'vs/workbench/parts/search/browser/searchActions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
export class SearchDataSource implements IDataSource {
public getId(tree: ITree, element: any): string {
if (element instanceof FileMatch) {
return element.id();
}
if (element instanceof Match) {
return element.id();
}
return 'root';
}
public getChildren(tree: ITree, element: any): TPromise<any[]> {
let value: any[] = [];
if (element instanceof FileMatch) {
value = element.matches();
} else if (element instanceof SearchResult) {
value = element.matches();
}
return TPromise.as(value);
}
public hasChildren(tree: ITree, element: any): boolean {
return element instanceof FileMatch || element instanceof SearchResult;
}
public getParent(tree: ITree, element: any): TPromise<any> {
let value: any = null;
if (element instanceof Match) {
value = element.parent();
} else if (element instanceof FileMatch) {
value = element.parent();
}
return TPromise.as(value);
}
}
export class SearchSorter implements ISorter {
public compare(tree: ITree, elementA: FileMatchOrMatch, elementB: FileMatchOrMatch): number {
if (elementA instanceof FileMatch && elementB instanceof FileMatch) {
return elementA.resource().fsPath.localeCompare(elementB.resource().fsPath) || elementA.name().localeCompare(elementB.name());
}
if (elementA instanceof Match && elementB instanceof Match) {
return Range.compareRangesUsingStarts(elementA.range(), elementB.range());
}
return undefined;
}
}
class SearchActionProvider extends ContributableActionProvider {
constructor(private viewlet: SearchViewlet, @IInstantiationService private instantiationService: IInstantiationService) {
super();
}
public hasActions(tree: ITree, element: any): boolean {
let input = <SearchResult>tree.getInput();
return element instanceof FileMatch || (input.searchModel.isReplaceActive() || element instanceof Match) || super.hasActions(tree, element);
}
public getActions(tree: ITree, element: any): TPromise<IAction[]> {
return super.getActions(tree, element).then(actions => {
let input = <SearchResult>tree.getInput();
if (element instanceof FileMatch) {
actions.unshift(new RemoveAction(tree, element));
if (input.searchModel.isReplaceActive() && element.count() > 0) {
actions.unshift(this.instantiationService.createInstance(ReplaceAllAction, tree, element, this.viewlet));
}
}
if (element instanceof Match) {
if (input.searchModel.isReplaceActive()) {
actions.unshift(this.instantiationService.createInstance(ReplaceAction, tree, element, this.viewlet), new RemoveAction(tree, element));
}
}
return actions;
});
}
}
export class SearchRenderer extends ActionsRenderer {
constructor(actionRunner: IActionRunner, viewlet: SearchViewlet, @IWorkspaceContextService private contextService: IWorkspaceContextService,
@IInstantiationService private instantiationService: IInstantiationService) {
super({
actionProvider: instantiationService.createInstance(SearchActionProvider, viewlet),
actionRunner: actionRunner
});
}
public getContentHeight(tree: ITree, element: any): number {
return 22;
}
public renderContents(tree: ITree, element: FileMatchOrMatch, domElement: HTMLElement, previousCleanupFn: IElementCallback): IElementCallback {
// File
if (element instanceof FileMatch) {
let fileMatch = <FileMatch>element;
let container = $('.filematch');
let leftRenderer: IRenderer;
let rightRenderer: IRenderer;
let widget: LeftRightWidget;
leftRenderer = (left: HTMLElement): any => {
const label = this.instantiationService.createInstance(FileLabel, left, void 0);
label.setFile(fileMatch.resource());
return () => label.dispose();
};
rightRenderer = (right: HTMLElement) => {
let len = fileMatch.count();
new CountBadge(right, len, len > 1 ? nls.localize('searchMatches', "{0} matches found", len) : nls.localize('searchMatch', "{0} match found", len));
return null;
};
widget = new LeftRightWidget(container, leftRenderer, rightRenderer);
container.appendTo(domElement);
return widget.dispose.bind(widget);
}
// Match
else if (element instanceof Match) {
dom.addClass(domElement, 'linematch');
let match = <Match>element;
let elements: string[] = [];
let preview = match.preview();
elements.push('<span>');
elements.push(strings.escape(preview.before));
let searchModel: SearchModel = (<SearchResult>tree.getInput()).searchModel;
let showReplaceText = searchModel.isReplaceActive() && !!searchModel.replaceString;
elements.push('</span><span class="' + (showReplaceText ? 'replace ' : '') + 'findInFileMatch">');
elements.push(strings.escape(preview.inside));
if (showReplaceText) {
elements.push('</span><span class="replaceMatch">');
elements.push(strings.escape(match.replaceString));
}
elements.push('</span><span>');
elements.push(strings.escape(preview.after));
elements.push('</span>');
$('a.plain')
.innerHtml(elements.join(strings.empty))
.title((preview.before + (showReplaceText ? match.replaceString : preview.inside) + preview.after).trim().substr(0, 999))
.appendTo(domElement);
}
return null;
}
}
export class SearchAccessibilityProvider implements IAccessibilityProvider {
constructor( @IWorkspaceContextService private contextService: IWorkspaceContextService) {
}
public getAriaLabel(tree: ITree, element: FileMatchOrMatch): string {
if (element instanceof FileMatch) {
const path = this.contextService.toWorkspaceRelativePath(element.resource()) || element.resource().fsPath;
return nls.localize('fileMatchAriaLabel', "{0} matches in file {1} of folder {2}, Search result", element.count(), element.name(), paths.dirname(path));
}
if (element instanceof Match) {
let match = <Match>element;
let input = <SearchResult>tree.getInput();
if (input.searchModel.isReplaceActive()) {
let preview = match.preview();
return nls.localize('replacePreviewResultAria', "Replace preview result, {0}", preview.before + match.replaceString + preview.after);
}
return nls.localize('searchResultAria', "{0}, Search result", match.text());
}
return undefined;
}
}
export class SearchController extends DefaultController {
constructor(private viewlet: SearchViewlet, @IInstantiationService private instantiationService: IInstantiationService) {
super({ clickBehavior: ClickBehavior.ON_MOUSE_DOWN, keyboardSupport: false });
// TODO@Rob these should be commands
// Up (from results to inputs)
this.downKeyBindingDispatcher.set(KeyCode.UpArrow, this.onUp.bind(this));
// Open to side
this.upKeyBindingDispatcher.set(platform.isMacintosh ? KeyMod.WinCtrl | KeyCode.Enter : KeyMod.CtrlCmd | KeyCode.Enter, this.onEnter.bind(this));
// Delete
this.downKeyBindingDispatcher.set(platform.isMacintosh ? KeyMod.CtrlCmd | KeyCode.Backspace : KeyCode.Delete, (tree: ITree, event: any) => { this.onDelete(tree, event); });
// Cancel search
this.downKeyBindingDispatcher.set(KeyCode.Escape, (tree: ITree, event: any) => { this.onEscape(tree, event); });
// Replace / Replace All
this.downKeyBindingDispatcher.set(ReplaceAllAction.KEY_BINDING, (tree: ITree, event: any) => { this.onReplaceAll(tree, event); });
this.downKeyBindingDispatcher.set(ReplaceAction.KEY_BINDING, (tree: ITree, event: any) => { this.onReplace(tree, event); });
}
protected onEscape(tree: ITree, event: IKeyboardEvent): boolean {
if (this.viewlet.cancelSearch()) {
return true;
}
return super.onEscape(tree, event);
}
private onDelete(tree: ITree, event: IKeyboardEvent): boolean {
let input = <SearchResult>tree.getInput();
let result = false;
let element = tree.getFocus();
if (element instanceof FileMatch ||
(element instanceof Match && input.searchModel.isReplaceActive())) {
new RemoveAction(tree, element).run().done(null, errors.onUnexpectedError);
result = true;
}
return result;
}
private onReplace(tree: ITree, event: IKeyboardEvent): boolean {
let input = <SearchResult>tree.getInput();
let result = false;
let element = tree.getFocus();
if (element instanceof Match && input.searchModel.isReplaceActive()) {
this.instantiationService.createInstance(ReplaceAction, tree, element, this.viewlet).run().done(null, errors.onUnexpectedError);
result = true;
}
return result;
}
private onReplaceAll(tree: ITree, event: IKeyboardEvent): boolean {
let result = false;
let element = tree.getFocus();
if (element instanceof FileMatch && element.count() > 0) {
this.instantiationService.createInstance(ReplaceAllAction, tree, element, this.viewlet).run().done(null, errors.onUnexpectedError);
result = true;
}
return result;
}
protected onUp(tree: ITree, event: IKeyboardEvent): boolean {
if (tree.getNavigator().first() === tree.getFocus()) {
this.viewlet.moveFocusFromResults();
return true;
}
return false;
}
}
export class SearchFilter implements IFilter {
public isVisible(tree: ITree, element: any): boolean {
return !(element instanceof FileMatch) || element.matches().length > 0;
}
} | src/vs/workbench/parts/search/browser/searchResultsView.ts | 1 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.0018345757853239775,
0.0003668568388093263,
0.0001637931272853166,
0.0001800268073566258,
0.000389650376746431
] |
{
"id": 9,
"code_window": [
"\t\t\treturn this.tree.refresh(this.viewModel.searchResult);\n",
"\t\t}\n",
"\n",
"\t\tif (event.added || event.removed) {\n",
"\t\t\treturn this.tree.refresh(this.viewModel.searchResult).then(() => {\n",
"\t\t\t\tif (event.added) {\n",
"\t\t\t\t\tevent.elements.forEach(element => {\n",
"\t\t\t\t\t\tthis.autoExpandFileMatch(element, true);\n",
"\t\t\t\t\t});\n",
"\t\t\t\t}\n",
"\t\t\t});\n",
"\t\t} else {\n",
"\t\t\tif (event.elements.length === 1) {\n",
"\t\t\t\treturn this.tree.refresh(event.elements[0]);\n",
"\t\t\t} else {\n",
"\t\t\t\treturn this.tree.refresh(event.elements);\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 333
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"error.cannotloadtheme": "無法載入 {0}",
"error.cannotparse": "剖析 plist 檔案時發生問題: {0}",
"error.cannotparsejson": "剖析 JSON 佈景主題檔案 {0} 時發生問題",
"invalid.path.1": "要包含在擴充功能資料夾 ({2}) 中的預期 `contributes.{0}.path` ({1})。這可能會使擴充功能無法移植。",
"reqarray": "擴充點 `{0}` 必須是陣列。",
"reqpath": "`contributes.{0}.path` 中的預期字串。提供的值: {1}",
"vscode.extension.contributes.themes": "提供 textmate 色彩佈景主題。",
"vscode.extension.contributes.themes.label": "如 UI 中所示的色彩佈景主題標籤。",
"vscode.extension.contributes.themes.path": "tmTheme 檔案的路徑。此路徑是擴充功能資料夾的相對路徑,而且一般為 './themes/themeFile.tmTheme'。",
"vscode.extension.contributes.themes.uiTheme": "基礎佈景主題會定義編輯器的色彩: 'vs' 是淺色色彩佈景主題,'vs-dark' 是深色色彩佈景主題。"
} | i18n/cht/src/vs/workbench/services/themes/node/themeService.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.00017123257566709071,
0.0001675683888606727,
0.0001639042020542547,
0.0001675683888606727,
0.0000036641868064180017
] |
{
"id": 9,
"code_window": [
"\t\t\treturn this.tree.refresh(this.viewModel.searchResult);\n",
"\t\t}\n",
"\n",
"\t\tif (event.added || event.removed) {\n",
"\t\t\treturn this.tree.refresh(this.viewModel.searchResult).then(() => {\n",
"\t\t\t\tif (event.added) {\n",
"\t\t\t\t\tevent.elements.forEach(element => {\n",
"\t\t\t\t\t\tthis.autoExpandFileMatch(element, true);\n",
"\t\t\t\t\t});\n",
"\t\t\t\t}\n",
"\t\t\t});\n",
"\t\t} else {\n",
"\t\t\tif (event.elements.length === 1) {\n",
"\t\t\t\treturn this.tree.refresh(event.elements[0]);\n",
"\t\t\t} else {\n",
"\t\t\t\treturn this.tree.refresh(event.elements);\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 333
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"InstallVSIXAction.reloadNow": "Ricarica ora",
"InstallVSIXAction.success": "L'estensione è stata installata. Riavviare per abilitarla.",
"installVSIX": "Installa da VSIX...",
"openExtensionsFolder": "Apri cartella estensioni"
} | i18n/ita/src/vs/workbench/parts/extensions/electron-browser/extensionsActions.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.00017356879834551364,
0.00016903916548471898,
0.00016450953262392431,
0.00016903916548471898,
0.0000045296328607946634
] |
{
"id": 9,
"code_window": [
"\t\t\treturn this.tree.refresh(this.viewModel.searchResult);\n",
"\t\t}\n",
"\n",
"\t\tif (event.added || event.removed) {\n",
"\t\t\treturn this.tree.refresh(this.viewModel.searchResult).then(() => {\n",
"\t\t\t\tif (event.added) {\n",
"\t\t\t\t\tevent.elements.forEach(element => {\n",
"\t\t\t\t\t\tthis.autoExpandFileMatch(element, true);\n",
"\t\t\t\t\t});\n",
"\t\t\t\t}\n",
"\t\t\t});\n",
"\t\t} else {\n",
"\t\t\tif (event.elements.length === 1) {\n",
"\t\t\t\treturn this.tree.refresh(event.elements[0]);\n",
"\t\t\t} else {\n",
"\t\t\t\treturn this.tree.refresh(event.elements);\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 333
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"json.npm.error.repoaccess": "La richiesta al repository NPM non è riuscita: {0}",
"json.npm.latestversion": "Ultima versione attualmente disponibile del pacchetto",
"json.npm.majorversion": "Trova la versione principale più recente (1.x.x)",
"json.npm.minorversion": "Trova la versione secondaria più recente (1.2.x)",
"json.npm.package.hover": "{0}",
"json.npm.version.hover": "Ultima versione: {0}",
"json.package.default": "package.json predefinito"
} | i18n/ita/src/vs/languages/json/common/contributions/packageJSONContribution.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.00017519462562631816,
0.00017183503950946033,
0.00016847546794451773,
0.00017183503950946033,
0.0000033595788409002125
] |
{
"id": 10,
"code_window": [
"\t\t}\n",
"\t}\n",
"\n",
"\tprivate autoExpandFileMatch(fileMatch: FileMatch, alwaysExpandIfOneResult: boolean): void {\n",
"\t\tlet length = fileMatch.matches().length;\n",
"\t\tif (length < 10 || (alwaysExpandIfOneResult && this.viewModel.searchResult.count() === 1 && length < 50)) {\n",
"\t\t\tthis.tree.expand(fileMatch).done(null, errors.onUnexpectedError);\n",
"\t\t} else {\n",
"\t\t\tthis.tree.collapse(fileMatch).done(null, errors.onUnexpectedError);\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tprivate onQueryTriggered(query: ISearchQuery, excludePattern: string, includePattern: string): void {\n",
"\t\tthis.viewModel.cancelSearch();\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 976
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import 'vs/css!./media/searchviewlet';
import nls = require('vs/nls');
import { TPromise } from 'vs/base/common/winjs.base';
import { Emitter, debounceEvent } from 'vs/base/common/event';
import { EditorType, ICommonCodeEditor } from 'vs/editor/common/editorCommon';
import lifecycle = require('vs/base/common/lifecycle');
import errors = require('vs/base/common/errors');
import aria = require('vs/base/browser/ui/aria/aria');
import { IExpression } from 'vs/base/common/glob';
import env = require('vs/base/common/platform');
import { isFunction } from 'vs/base/common/types';
import { Delayer } from 'vs/base/common/async';
import URI from 'vs/base/common/uri';
import strings = require('vs/base/common/strings');
import dom = require('vs/base/browser/dom');
import { IAction, Action } from 'vs/base/common/actions';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { Dimension, Builder, $ } from 'vs/base/browser/builder';
import { FindInput } from 'vs/base/browser/ui/findinput/findInput';
import { ITree } from 'vs/base/parts/tree/browser/tree';
import { Tree } from 'vs/base/parts/tree/browser/treeImpl';
import { Scope } from 'vs/workbench/common/memento';
import { IPreferencesService } from 'vs/workbench/parts/preferences/common/preferences';
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
import { getOutOfWorkspaceEditorResources } from 'vs/workbench/common/editor';
import { FileChangeType, FileChangesEvent, IFileService, isEqual } from 'vs/platform/files/common/files';
import { Viewlet } from 'vs/workbench/browser/viewlet';
import { Match, FileMatch, SearchModel, FileMatchOrMatch, IChangeEvent, ISearchWorkbenchService } from 'vs/workbench/parts/search/common/searchModel';
import { QueryBuilder } from 'vs/workbench/parts/search/common/searchQuery';
import { MessageType, InputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { getExcludes, ISearchProgressItem, ISearchComplete, ISearchQuery, IQueryOptions, ISearchConfiguration } from 'vs/platform/search/common/search';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IMessageService } from 'vs/platform/message/common/message';
import { IProgressService } from 'vs/platform/progress/common/progress';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { KeyCode } from 'vs/base/common/keyCodes';
import { PatternInputWidget } from 'vs/workbench/parts/search/browser/patternInputWidget';
import { SearchRenderer, SearchDataSource, SearchSorter, SearchController, SearchAccessibilityProvider, SearchFilter } from 'vs/workbench/parts/search/browser/searchResultsView';
import { SearchWidget } from 'vs/workbench/parts/search/browser/searchWidget';
import { RefreshAction, CollapseAllAction, ClearSearchResultsAction, ConfigureGlobalExclusionsAction } from 'vs/workbench/parts/search/browser/searchActions';
import { IReplaceService } from 'vs/workbench/parts/search/common/replace';
import Severity from 'vs/base/common/severity';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { OpenFolderAction, OpenFileFolderAction } from 'vs/workbench/browser/actions/fileActions';
import * as Constants from 'vs/workbench/parts/search/common/constants';
import { IListService } from 'vs/platform/list/browser/listService';
import { IThemeService, ITheme, ICssStyleCollector, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { editorFindMatchHighlight } from 'vs/platform/theme/common/colorRegistry';
export class SearchViewlet extends Viewlet {
private static MAX_TEXT_RESULTS = 2048;
private static SHOW_REPLACE_STORAGE_KEY = 'vs.search.show.replace';
private isDisposed: boolean;
private toDispose: lifecycle.IDisposable[];
private loading: boolean;
private queryBuilder: QueryBuilder;
private viewModel: SearchModel;
private callOnModelChange: lifecycle.IDisposable[];
private viewletVisible: IContextKey<boolean>;
private inputBoxFocussed: IContextKey<boolean>;
private actionRegistry: { [key: string]: Action; };
private tree: ITree;
private viewletSettings: any;
private domNode: Builder;
private messages: Builder;
private searchWidgetsContainer: Builder;
private searchWidget: SearchWidget;
private size: Dimension;
private queryDetails: HTMLElement;
private inputPatternExclusions: PatternInputWidget;
private inputPatternGlobalExclusions: InputBox;
private inputPatternGlobalExclusionsContainer: Builder;
private inputPatternIncludes: PatternInputWidget;
private results: Builder;
private currentSelectedFileMatch: FileMatch;
private selectCurrentMatchEmitter: Emitter<string>;
private delayedRefresh: Delayer<void>;
constructor(
@ITelemetryService telemetryService: ITelemetryService,
@IFileService private fileService: IFileService,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
@IEditorGroupService private editorGroupService: IEditorGroupService,
@IProgressService private progressService: IProgressService,
@IMessageService private messageService: IMessageService,
@IStorageService private storageService: IStorageService,
@IContextViewService private contextViewService: IContextViewService,
@IInstantiationService private instantiationService: IInstantiationService,
@IConfigurationService private configurationService: IConfigurationService,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@ISearchWorkbenchService private searchWorkbenchService: ISearchWorkbenchService,
@IContextKeyService private contextKeyService: IContextKeyService,
@IKeybindingService private keybindingService: IKeybindingService,
@IReplaceService private replaceService: IReplaceService,
@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
@IPreferencesService private preferencesService: IPreferencesService,
@IListService private listService: IListService,
@IThemeService protected themeService: IThemeService
) {
super(Constants.VIEWLET_ID, telemetryService, themeService);
this.toDispose = [];
this.viewletVisible = Constants.SearchViewletVisibleKey.bindTo(contextKeyService);
this.inputBoxFocussed = Constants.InputBoxFocussedKey.bindTo(this.contextKeyService);
this.callOnModelChange = [];
this.queryBuilder = this.instantiationService.createInstance(QueryBuilder);
this.viewletSettings = this.getMemento(storageService, Scope.WORKSPACE);
this.toUnbind.push(this.fileService.onFileChanges(e => this.onFilesChanged(e)));
this.toUnbind.push(this.untitledEditorService.onDidChangeDirty(e => this.onUntitledDidChangeDirty(e)));
this.toUnbind.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationUpdated(e.config)));
this.selectCurrentMatchEmitter = new Emitter<string>();
debounceEvent(this.selectCurrentMatchEmitter.event, (l, e) => e, 100, /*leading=*/true)
(() => this.selectCurrentMatch());
this.delayedRefresh = new Delayer<void>(250);
}
private onConfigurationUpdated(configuration: any): void {
this.updateGlobalPatternExclusions(configuration);
}
public create(parent: Builder): TPromise<void> {
super.create(parent);
this.viewModel = this.searchWorkbenchService.searchModel;
let builder: Builder;
this.domNode = parent.div({
'class': 'search-viewlet'
}, (div) => {
builder = div;
});
builder.div({ 'class': ['search-widgets-container'] }, (div) => {
this.searchWidgetsContainer = div;
});
this.createSearchWidget(this.searchWidgetsContainer);
let filePatterns = this.viewletSettings['query.filePatterns'] || '';
let patternExclusions = this.viewletSettings['query.folderExclusions'] || '';
let exclusionsUsePattern = this.viewletSettings['query.exclusionsUsePattern'];
let includesUsePattern = this.viewletSettings['query.includesUsePattern'];
let patternIncludes = this.viewletSettings['query.folderIncludes'] || '';
let useIgnoreFiles = this.viewletSettings['query.useIgnoreFiles'];
this.queryDetails = this.searchWidgetsContainer.div({ 'class': ['query-details'] }, (builder) => {
builder.div({ 'class': 'more', 'tabindex': 0, 'role': 'button', 'title': nls.localize('moreSearch', "Toggle Search Details") })
.on(dom.EventType.CLICK, (e) => {
dom.EventHelper.stop(e);
this.toggleFileTypes(true);
}).on(dom.EventType.KEY_UP, (e: KeyboardEvent) => {
let event = new StandardKeyboardEvent(e);
if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) {
dom.EventHelper.stop(e);
this.toggleFileTypes();
}
});
//folder includes list
builder.div({ 'class': 'file-types' }, (builder) => {
let title = nls.localize('searchScope.includes', "files to include");
builder.element('h4', { text: title });
this.inputPatternIncludes = new PatternInputWidget(builder.getContainer(), this.contextViewService, {
ariaLabel: nls.localize('label.includes', 'Search Include Patterns')
});
this.inputPatternIncludes.setIsGlobPattern(includesUsePattern);
this.inputPatternIncludes.setValue(patternIncludes);
this.inputPatternIncludes
.on(FindInput.OPTION_CHANGE, (e) => {
this.onQueryChanged(false);
});
this.inputPatternIncludes.onSubmit(() => this.onQueryChanged(true));
this.trackInputBox(this.inputPatternIncludes.inputFocusTracker);
});
//pattern exclusion list
builder.div({ 'class': 'file-types' }, (builder) => {
let title = nls.localize('searchScope.excludes', "files to exclude");
builder.element('h4', { text: title });
const configuration = this.configurationService.getConfiguration<ISearchConfiguration>();
this.inputPatternExclusions = new PatternInputWidget(builder.getContainer(), this.contextViewService, {
ariaLabel: nls.localize('label.excludes', 'Search Exclude Patterns')
}, configuration.search.useRipgrep);
this.inputPatternExclusions.setIsGlobPattern(exclusionsUsePattern);
this.inputPatternExclusions.setValue(patternExclusions);
this.inputPatternExclusions.setUseIgnoreFiles(useIgnoreFiles);
this.inputPatternExclusions
.on(FindInput.OPTION_CHANGE, (e) => {
this.onQueryChanged(false);
});
this.inputPatternExclusions.onSubmit(() => this.onQueryChanged(true));
this.trackInputBox(this.inputPatternExclusions.inputFocusTracker);
});
// add hint if we have global exclusion
this.inputPatternGlobalExclusionsContainer = builder.div({ 'class': 'file-types global-exclude disabled' }, (builder) => {
let title = nls.localize('global.searchScope.folders', "files excluded through settings");
builder.element('h4', { text: title });
this.inputPatternGlobalExclusions = new InputBox(builder.getContainer(), this.contextViewService, {
actions: [this.instantiationService.createInstance(ConfigureGlobalExclusionsAction)],
ariaLabel: nls.localize('label.global.excludes', 'Configured Search Exclude Patterns')
});
this.inputPatternGlobalExclusions.inputElement.readOnly = true;
$(this.inputPatternGlobalExclusions.inputElement).attr('aria-readonly', 'true');
$(this.inputPatternGlobalExclusions.inputElement).addClass('disabled');
}).hide();
}).getHTMLElement();
this.messages = builder.div({ 'class': 'messages' }).hide().clone();
if (!this.contextService.hasWorkspace()) {
this.searchWithoutFolderMessage(this.clearMessage());
}
this.createSearchResultsView(builder);
this.actionRegistry = <any>{};
let actions: Action[] = [new CollapseAllAction(this), new RefreshAction(this), new ClearSearchResultsAction(this)];
actions.forEach((action) => {
this.actionRegistry[action.id] = action;
});
if (filePatterns !== '' || patternExclusions !== '' || patternIncludes !== '') {
this.toggleFileTypes(true, true, true);
}
this.updateGlobalPatternExclusions(this.configurationService.getConfiguration<ISearchConfiguration>());
this.toUnbind.push(this.viewModel.searchResult.onChange((event) => this.onSearchResultsChanged(event)));
return TPromise.as(null);
}
public get searchAndReplaceWidget(): SearchWidget {
return this.searchWidget;
}
private createSearchWidget(builder: Builder): void {
let contentPattern = this.viewletSettings['query.contentPattern'] || '';
let isRegex = this.viewletSettings['query.regex'] === true;
let isWholeWords = this.viewletSettings['query.wholeWords'] === true;
let isCaseSensitive = this.viewletSettings['query.caseSensitive'] === true;
this.searchWidget = new SearchWidget(builder, this.contextViewService, {
value: contentPattern,
isRegex: isRegex,
isCaseSensitive: isCaseSensitive,
isWholeWords: isWholeWords
}, this.contextKeyService, this.keybindingService, this.instantiationService);
if (this.storageService.getBoolean(SearchViewlet.SHOW_REPLACE_STORAGE_KEY, StorageScope.WORKSPACE, true)) {
this.searchWidget.toggleReplace(true);
}
this.toUnbind.push(this.searchWidget);
this.toUnbind.push(this.searchWidget.onSearchSubmit((refresh) => this.onQueryChanged(refresh)));
this.toUnbind.push(this.searchWidget.onSearchCancel(() => this.cancelSearch()));
this.toUnbind.push(this.searchWidget.searchInput.onDidOptionChange((viaKeyboard) => this.onQueryChanged(true, viaKeyboard)));
this.toUnbind.push(this.searchWidget.onReplaceToggled(() => this.onReplaceToggled()));
this.toUnbind.push(this.searchWidget.onReplaceStateChange((state) => {
this.viewModel.replaceActive = state;
this.tree.refresh();
}));
this.toUnbind.push(this.searchWidget.onReplaceValueChanged((value) => {
this.viewModel.replaceString = this.searchWidget.getReplaceValue();
this.delayedRefresh.trigger(() => this.tree.refresh());
}));
this.toUnbind.push(this.searchWidget.onReplaceAll(() => this.replaceAll()));
this.trackInputBox(this.searchWidget.searchInputFocusTracker);
this.trackInputBox(this.searchWidget.replaceInputFocusTracker);
}
private trackInputBox(inputFocusTracker: dom.IFocusTracker): void {
this.toUnbind.push(inputFocusTracker.addFocusListener(() => {
this.inputBoxFocussed.set(true);
}));
this.toUnbind.push(inputFocusTracker.addBlurListener(() => {
this.inputBoxFocussed.set(this.searchWidget.searchInputHasFocus()
|| this.searchWidget.replaceInputHasFocus()
|| this.inputPatternIncludes.inputHasFocus()
|| this.inputPatternExclusions.inputHasFocus());
}));
}
private onReplaceToggled(): void {
this.layout(this.size);
this.storageService.store(SearchViewlet.SHOW_REPLACE_STORAGE_KEY, this.searchAndReplaceWidget.isReplaceShown(), StorageScope.WORKSPACE);
}
private onSearchResultsChanged(event?: IChangeEvent): TPromise<any> {
return this.refreshTree(event).then(() => {
this.searchWidget.setReplaceAllActionState(!this.viewModel.searchResult.isEmpty());
this.updateSearchResultCount();
});
}
private refreshTree(event?: IChangeEvent): TPromise<any> {
if (!event) {
return this.tree.refresh(this.viewModel.searchResult);
}
if (event.added || event.removed) {
return this.tree.refresh(this.viewModel.searchResult).then(() => {
if (event.added) {
event.elements.forEach(element => {
this.autoExpandFileMatch(element, true);
});
}
});
} else {
if (event.elements.length === 1) {
return this.tree.refresh(event.elements[0]);
} else {
return this.tree.refresh(event.elements);
}
}
}
private replaceAll(): void {
if (this.viewModel.searchResult.count() === 0) {
return;
}
let progressRunner = this.progressService.show(100);
let occurrences = this.viewModel.searchResult.count();
let fileCount = this.viewModel.searchResult.fileCount();
let replaceValue = this.searchWidget.getReplaceValue() || '';
let afterReplaceAllMessage = this.buildAfterReplaceAllMessage(occurrences, fileCount, replaceValue);
let confirmation = {
title: nls.localize('replaceAll.confirmation.title', "Replace All"),
message: this.buildReplaceAllConfirmationMessage(occurrences, fileCount, replaceValue),
primaryButton: nls.localize('replaceAll.confirm.button', "Replace")
};
if (this.messageService.confirm(confirmation)) {
this.searchWidget.setReplaceAllActionState(false);
this.viewModel.searchResult.replaceAll(progressRunner).then(() => {
progressRunner.done();
this.clearMessage()
.p({ text: afterReplaceAllMessage });
}, (error) => {
progressRunner.done();
errors.isPromiseCanceledError(error);
this.messageService.show(Severity.Error, error);
});
}
}
private buildAfterReplaceAllMessage(occurrences: number, fileCount: number, replaceValue?: string) {
if (occurrences === 1) {
if (fileCount === 1) {
if (replaceValue) {
return nls.localize('replaceAll.occurrence.file.message', "Replaced {0} occurrence across {1} file with '{2}'.", occurrences, fileCount, replaceValue);
}
return nls.localize('removeAll.occurrence.file.message', "Replaced {0} occurrence across {1} file'.", occurrences, fileCount);
}
if (replaceValue) {
return nls.localize('replaceAll.occurrence.files.message', "Replaced {0} occurrence across {1} files with '{2}'.", occurrences, fileCount, replaceValue);
}
return nls.localize('removeAll.occurrence.files.message', "Replaced {0} occurrence across {1} files.", occurrences, fileCount);
}
if (fileCount === 1) {
if (replaceValue) {
return nls.localize('replaceAll.occurrences.file.message', "Replaced {0} occurrences across {1} file with '{2}'.", occurrences, fileCount, replaceValue);
}
return nls.localize('removeAll.occurrences.file.message', "Replaced {0} occurrences across {1} file'.", occurrences, fileCount);
}
if (replaceValue) {
return nls.localize('replaceAll.occurrences.files.message', "Replaced {0} occurrences across {1} files with '{2}'.", occurrences, fileCount, replaceValue);
}
return nls.localize('removeAll.occurrences.files.message', "Replaced {0} occurrences across {1} files.", occurrences, fileCount);
}
private buildReplaceAllConfirmationMessage(occurrences: number, fileCount: number, replaceValue?: string) {
if (occurrences === 1) {
if (fileCount === 1) {
if (replaceValue) {
return nls.localize('removeAll.occurrence.file.confirmation.message', "Replace {0} occurrence across {1} file with '{2}'?", occurrences, fileCount, replaceValue);
}
return nls.localize('replaceAll.occurrence.file.confirmation.message', "Replace {0} occurrence across {1} file'?", occurrences, fileCount);
}
if (replaceValue) {
return nls.localize('removeAll.occurrence.files.confirmation.message', "Replace {0} occurrence across {1} files with '{2}'?", occurrences, fileCount, replaceValue);
}
return nls.localize('replaceAll.occurrence.files.confirmation.message', "Replace {0} occurrence across {1} files?", occurrences, fileCount);
}
if (fileCount === 1) {
if (replaceValue) {
return nls.localize('removeAll.occurrences.file.confirmation.message', "Replace {0} occurrences across {1} file with '{2}'?", occurrences, fileCount, replaceValue);
}
return nls.localize('replaceAll.occurrences.file.confirmation.message', "Replace {0} occurrences across {1} file'?", occurrences, fileCount);
}
if (replaceValue) {
return nls.localize('removeAll.occurrences.files.confirmation.message', "Replace {0} occurrences across {1} files with '{2}'?", occurrences, fileCount, replaceValue);
}
return nls.localize('replaceAll.occurrences.files.confirmation.message', "Replace {0} occurrences across {1} files?", occurrences, fileCount);
}
private clearMessage(): Builder {
return this.messages.empty().show()
.asContainer().div({ 'class': 'message' })
.asContainer();
}
private createSearchResultsView(builder: Builder): void {
builder.div({ 'class': 'results' }, (div) => {
this.results = div;
this.results.addClass('show-file-icons');
let dataSource = new SearchDataSource();
let renderer = this.instantiationService.createInstance(SearchRenderer, this.getActionRunner(), this);
this.tree = new Tree(div.getHTMLElement(), {
dataSource: dataSource,
renderer: renderer,
sorter: new SearchSorter(),
filter: new SearchFilter(),
controller: new SearchController(this, this.instantiationService),
accessibilityProvider: this.instantiationService.createInstance(SearchAccessibilityProvider)
}, {
ariaLabel: nls.localize('treeAriaLabel', "Search Results"),
keyboardSupport: false
});
this.tree.setInput(this.viewModel.searchResult);
this.toUnbind.push(renderer);
this.toUnbind.push(this.listService.register(this.tree));
let focusToSelectionDelayHandle: number;
let lastFocusToSelection: number;
const focusToSelection = (originalEvent: KeyboardEvent | MouseEvent) => {
lastFocusToSelection = Date.now();
const focus = this.tree.getFocus();
let payload: any;
if (focus instanceof Match) {
payload = { origin: 'keyboard', originalEvent, preserveFocus: true };
}
this.tree.setSelection([focus], payload);
focusToSelectionDelayHandle = void 0;
};
this.toUnbind.push(this.tree.addListener2('focus', (event: any) => {
let keyboard = event.payload && event.payload.origin === 'keyboard';
if (keyboard) {
let originalEvent: KeyboardEvent | MouseEvent = event.payload && event.payload.originalEvent;
// debounce setting selection so that we are not too quickly opening
// when the user is pressing and holding the key to move focus
if (focusToSelectionDelayHandle || (Date.now() - lastFocusToSelection <= 75)) {
window.clearTimeout(focusToSelectionDelayHandle);
focusToSelectionDelayHandle = window.setTimeout(() => focusToSelection(originalEvent), 300);
} else {
focusToSelection(originalEvent);
}
}
}));
this.toUnbind.push(this.tree.addListener2('selection', (event: any) => {
let element: any;
let keyboard = event.payload && event.payload.origin === 'keyboard';
if (keyboard) {
element = this.tree.getFocus();
} else {
element = event.selection[0];
}
let originalEvent: KeyboardEvent | MouseEvent = event.payload && event.payload.originalEvent;
let doubleClick = (event.payload && event.payload.origin === 'mouse' && originalEvent && originalEvent.detail === 2);
if (doubleClick && originalEvent) {
originalEvent.preventDefault(); // focus moves to editor, we need to prevent default
}
let sideBySide = (originalEvent && (originalEvent.ctrlKey || originalEvent.metaKey));
let focusEditor = (keyboard && (!event.payload || !event.payload.preserveFocus)) || doubleClick;
if (element instanceof Match) {
let selectedMatch: Match = element;
if (this.currentSelectedFileMatch) {
this.currentSelectedFileMatch.setSelectedMatch(null);
}
this.currentSelectedFileMatch = selectedMatch.parent();
this.currentSelectedFileMatch.setSelectedMatch(selectedMatch);
if (!event.payload.preventEditorOpen) {
this.onFocus(selectedMatch, !focusEditor, sideBySide, doubleClick);
}
}
}));
});
}
private updateGlobalPatternExclusions(configuration: ISearchConfiguration): void {
if (this.inputPatternGlobalExclusionsContainer) {
let excludes = getExcludes(configuration);
if (excludes) {
let exclusions = Object.getOwnPropertyNames(excludes).filter(exclude => excludes[exclude] === true || typeof excludes[exclude].when === 'string').map(exclude => {
if (excludes[exclude] === true) {
return exclude;
}
return nls.localize('globLabel', "{0} when {1}", exclude, excludes[exclude].when);
});
if (exclusions.length) {
const values = exclusions.join(', ');
this.inputPatternGlobalExclusions.value = values;
this.inputPatternGlobalExclusions.inputElement.title = values;
this.inputPatternGlobalExclusionsContainer.show();
} else {
this.inputPatternGlobalExclusionsContainer.hide();
}
}
}
}
public selectCurrentMatch(): void {
const focused = this.tree.getFocus();
const eventPayload = { focusEditor: true };
this.tree.setSelection([focused], eventPayload);
}
public selectNextMatch(): void {
const [selected]: FileMatchOrMatch[] = this.tree.getSelection();
// Expand the initial selected node, if needed
if (selected instanceof FileMatch) {
if (!this.tree.isExpanded(selected)) {
this.tree.expand(selected);
}
}
let navigator = this.tree.getNavigator(selected, /*subTreeOnly=*/false);
let next = navigator.next();
if (!next) {
// Reached the end - get a new navigator from the root.
// .first and .last only work when subTreeOnly = true. Maybe there's a simpler way.
navigator = this.tree.getNavigator(this.tree.getInput(), /*subTreeOnly*/true);
next = navigator.first();
}
// Expand and go past FileMatch nodes
if (!(next instanceof Match)) {
if (!this.tree.isExpanded(next)) {
this.tree.expand(next);
}
// Select the FileMatch's first child
next = navigator.next();
}
// Reveal the newly selected element
const eventPayload = { preventEditorOpen: true };
this.tree.setFocus(next, eventPayload);
this.tree.setSelection([next], eventPayload);
this.tree.reveal(next);
this.selectCurrentMatchEmitter.fire();
}
public selectPreviousMatch(): void {
const [selected]: FileMatchOrMatch[] = this.tree.getSelection();
let navigator = this.tree.getNavigator(selected, /*subTreeOnly=*/false);
let prev = navigator.previous();
// Expand and go past FileMatch nodes
if (!(prev instanceof Match)) {
prev = navigator.previous();
if (!prev) {
// Wrap around. Get a new tree starting from the root
navigator = this.tree.getNavigator(this.tree.getInput(), /*subTreeOnly*/true);
prev = navigator.last();
// This is complicated because .last will set the navigator to the last FileMatch,
// so expand it and FF to its last child
this.tree.expand(prev);
let tmp;
while (tmp = navigator.next()) {
prev = tmp;
}
}
if (!(prev instanceof Match)) {
// There is a second non-Match result, which must be a collapsed FileMatch.
// Expand it then select its last child.
navigator.next();
this.tree.expand(prev);
prev = navigator.previous();
}
}
// Reveal the newly selected element
if (prev) {
const eventPayload = { preventEditorOpen: true };
this.tree.setFocus(prev, eventPayload);
this.tree.setSelection([prev], eventPayload);
this.tree.reveal(prev);
this.selectCurrentMatchEmitter.fire();
}
}
public setVisible(visible: boolean): TPromise<void> {
let promise: TPromise<void>;
this.viewletVisible.set(visible);
if (visible) {
promise = super.setVisible(visible);
this.tree.onVisible();
} else {
this.tree.onHidden();
promise = super.setVisible(visible);
}
// Enable highlights if there are searchresults
if (this.viewModel) {
this.viewModel.searchResult.toggleHighlights(visible);
}
// Open focused element from results in case the editor area is otherwise empty
if (visible && !this.editorService.getActiveEditor()) {
let focus = this.tree.getFocus();
if (focus) {
this.onFocus(focus, true);
}
}
return promise;
}
public focus(): void {
super.focus();
let selectedText = this.getSearchTextFromEditor();
if (selectedText) {
this.searchWidget.searchInput.setValue(selectedText);
}
this.searchWidget.focus();
}
public focusNextInputBox(): void {
if (this.searchWidget.searchInputHasFocus()) {
if (this.searchWidget.isReplaceShown()) {
this.searchWidget.focus(true, true);
} else {
this.moveFocusFromSearchOrReplace();
}
return;
}
if (this.searchWidget.replaceInputHasFocus()) {
this.moveFocusFromSearchOrReplace();
return;
}
if (this.inputPatternIncludes.inputHasFocus()) {
this.inputPatternExclusions.focus();
this.inputPatternExclusions.select();
return;
}
if (this.inputPatternExclusions.inputHasFocus()) {
this.selectTreeIfNotSelected();
return;
}
}
private moveFocusFromSearchOrReplace() {
if (this.showsFileTypes()) {
this.toggleFileTypes(true, this.showsFileTypes());
} else {
this.selectTreeIfNotSelected();
}
}
public focusPreviousInputBox(): void {
if (this.searchWidget.searchInputHasFocus()) {
return;
}
if (this.searchWidget.replaceInputHasFocus()) {
this.searchWidget.focus(true);
return;
}
if (this.inputPatternIncludes.inputHasFocus()) {
this.searchWidget.focus(true, true);
return;
}
if (this.inputPatternExclusions.inputHasFocus()) {
this.inputPatternIncludes.focus();
this.inputPatternIncludes.select();
return;
}
}
public moveFocusFromResults(): void {
if (this.showsFileTypes()) {
this.toggleFileTypes(true, true, false, true);
} else {
this.searchWidget.focus(true, true);
}
}
private reLayout(): void {
if (this.isDisposed) {
return;
}
this.searchWidget.setWidth(this.size.width - 25 /* container margin */);
this.inputPatternExclusions.setWidth(this.size.width - 28 /* container margin */);
this.inputPatternIncludes.setWidth(this.size.width - 28 /* container margin */);
this.inputPatternGlobalExclusions.width = this.size.width - 28 /* container margin */ - 24 /* actions */;
const messagesSize = this.messages.isHidden() ? 0 : dom.getTotalHeight(this.messages.getHTMLElement());
const searchResultContainerSize = this.size.height -
messagesSize -
dom.getTotalHeight(this.searchWidgetsContainer.getContainer());
this.results.style({ height: searchResultContainerSize + 'px' });
this.tree.layout(searchResultContainerSize);
}
public layout(dimension: Dimension): void {
this.size = dimension;
this.reLayout();
}
public getControl(): ITree {
return this.tree;
}
public clearSearchResults(): void {
this.viewModel.searchResult.clear();
this.showEmptyStage();
if (!this.contextService.hasWorkspace()) {
this.searchWithoutFolderMessage(this.clearMessage());
}
this.searchWidget.clear();
this.viewModel.cancelSearch();
}
public cancelSearch(): boolean {
if (this.viewModel.cancelSearch()) {
this.searchWidget.focus();
return true;
}
return false;
}
private selectTreeIfNotSelected(): void {
if (this.tree.getInput()) {
this.tree.DOMFocus();
let selection = this.tree.getSelection();
if (selection.length === 0) {
this.tree.focusNext();
}
}
}
private getSearchTextFromEditor(): string {
if (!this.editorService.getActiveEditor()) {
return null;
}
let editorControl: any = this.editorService.getActiveEditor().getControl();
if (!editorControl || !isFunction(editorControl.getEditorType) || editorControl.getEditorType() !== EditorType.ICodeEditor) { // Substitute for (editor instanceof ICodeEditor)
return null;
}
let range = editorControl.getSelection();
if (range && !range.isEmpty() && range.startLineNumber === range.endLineNumber) {
let searchText = editorControl.getModel().getLineContent(range.startLineNumber);
searchText = searchText.substring(range.startColumn - 1, range.endColumn - 1);
return searchText;
}
return null;
}
private showsFileTypes(): boolean {
return dom.hasClass(this.queryDetails, 'more');
}
public toggleCaseSensitive(): void {
this.searchWidget.searchInput.setCaseSensitive(!this.searchWidget.searchInput.getCaseSensitive());
this.onQueryChanged(true, true);
}
public toggleWholeWords(): void {
this.searchWidget.searchInput.setWholeWords(!this.searchWidget.searchInput.getWholeWords());
this.onQueryChanged(true, true);
}
public toggleRegex(): void {
this.searchWidget.searchInput.setRegex(!this.searchWidget.searchInput.getRegex());
this.onQueryChanged(true, true);
}
public toggleFileTypes(moveFocus?: boolean, show?: boolean, skipLayout?: boolean, reverse?: boolean): void {
let cls = 'more';
show = typeof show === 'undefined' ? !dom.hasClass(this.queryDetails, cls) : Boolean(show);
skipLayout = Boolean(skipLayout);
if (show) {
dom.addClass(this.queryDetails, cls);
if (moveFocus) {
if (reverse) {
this.inputPatternExclusions.focus();
this.inputPatternExclusions.select();
} else {
this.inputPatternIncludes.focus();
this.inputPatternIncludes.select();
}
}
} else {
dom.removeClass(this.queryDetails, cls);
if (moveFocus) {
this.searchWidget.focus();
}
}
if (!skipLayout && this.size) {
this.layout(this.size);
}
}
public searchInFolder(resource: URI): void {
const workspace = this.contextService.getWorkspace();
if (!workspace) {
return;
}
if (isEqual(workspace.resource.fsPath, resource.fsPath)) {
this.inputPatternIncludes.setValue('');
this.searchWidget.focus();
return;
}
if (!this.showsFileTypes()) {
this.toggleFileTypes(true, true);
}
const workspaceRelativePath = this.contextService.toWorkspaceRelativePath(resource);
if (workspaceRelativePath) {
this.inputPatternIncludes.setIsGlobPattern(false);
this.inputPatternIncludes.setValue(workspaceRelativePath);
this.searchWidget.focus(false);
}
}
public onQueryChanged(rerunQuery: boolean, preserveFocus?: boolean): void {
const isRegex = this.searchWidget.searchInput.getRegex();
const isWholeWords = this.searchWidget.searchInput.getWholeWords();
const isCaseSensitive = this.searchWidget.searchInput.getCaseSensitive();
const contentPattern = this.searchWidget.searchInput.getValue();
const patternExcludes = this.inputPatternExclusions.getValue().trim();
const exclusionsUsePattern = this.inputPatternExclusions.isGlobPattern();
const patternIncludes = this.inputPatternIncludes.getValue().trim();
const includesUsePattern = this.inputPatternIncludes.isGlobPattern();
const useIgnoreFiles = this.inputPatternExclusions.useIgnoreFiles();
// store memento
this.viewletSettings['query.contentPattern'] = contentPattern;
this.viewletSettings['query.regex'] = isRegex;
this.viewletSettings['query.wholeWords'] = isWholeWords;
this.viewletSettings['query.caseSensitive'] = isCaseSensitive;
this.viewletSettings['query.folderExclusions'] = patternExcludes;
this.viewletSettings['query.exclusionsUsePattern'] = exclusionsUsePattern;
this.viewletSettings['query.folderIncludes'] = patternIncludes;
this.viewletSettings['query.includesUsePattern'] = includesUsePattern;
this.viewletSettings['query.useIgnoreFiles'] = useIgnoreFiles;
if (!rerunQuery) {
return;
}
if (contentPattern.length === 0) {
return;
}
// Validate regex is OK
if (isRegex) {
let regExp: RegExp;
try {
regExp = new RegExp(contentPattern);
} catch (e) {
return; // malformed regex
}
if (strings.regExpLeadsToEndlessLoop(regExp)) {
return; // endless regex
}
}
let content = {
pattern: contentPattern,
isRegExp: isRegex,
isCaseSensitive: isCaseSensitive,
isWordMatch: isWholeWords
};
let excludes: IExpression = this.inputPatternExclusions.getGlob();
let includes: IExpression = this.inputPatternIncludes.getGlob();
let options: IQueryOptions = {
folderResources: this.contextService.hasWorkspace() ? [this.contextService.getWorkspace().resource] : [],
extraFileResources: getOutOfWorkspaceEditorResources(this.editorGroupService, this.contextService),
excludePattern: excludes,
maxResults: SearchViewlet.MAX_TEXT_RESULTS,
includePattern: includes,
useIgnoreFiles
};
this.onQueryTriggered(this.queryBuilder.text(content, options), patternExcludes, patternIncludes);
if (!preserveFocus) {
this.searchWidget.focus(false); // focus back to input field
}
}
private autoExpandFileMatch(fileMatch: FileMatch, alwaysExpandIfOneResult: boolean): void {
let length = fileMatch.matches().length;
if (length < 10 || (alwaysExpandIfOneResult && this.viewModel.searchResult.count() === 1 && length < 50)) {
this.tree.expand(fileMatch).done(null, errors.onUnexpectedError);
} else {
this.tree.collapse(fileMatch).done(null, errors.onUnexpectedError);
}
}
private onQueryTriggered(query: ISearchQuery, excludePattern: string, includePattern: string): void {
this.viewModel.cancelSearch();
// Progress total is 100.0% for more progress bar granularity
let progressTotal = 1000;
let progressWorked = 0;
let progressRunner = query.useRipgrep ?
this.progressService.show(/*infinite=*/true) :
this.progressService.show(progressTotal);
this.loading = true;
this.searchWidget.searchInput.clearMessage();
this.showEmptyStage();
let handledMatches: { [id: string]: boolean } = Object.create(null);
let autoExpand = (alwaysExpandIfOneResult: boolean) => {
// Auto-expand / collapse based on number of matches:
// - alwaysExpandIfOneResult: expand file results if we have just one file result and less than 50 matches on a file
// - expand file results if we have more than one file result and less than 10 matches on a file
let matches = this.viewModel.searchResult.matches();
matches.forEach((match) => {
if (handledMatches[match.id()]) {
return; // if we once handled a result, do not do it again to keep results stable (the user might have expanded/collapsed meanwhile)
}
handledMatches[match.id()] = true;
this.autoExpandFileMatch(match, alwaysExpandIfOneResult);
});
};
let isDone = false;
let onComplete = (completed?: ISearchComplete) => {
isDone = true;
// Complete up to 100% as needed
if (completed && !query.useRipgrep) {
progressRunner.worked(progressTotal - progressWorked);
setTimeout(() => progressRunner.done(), 200);
} else {
progressRunner.done();
}
this.onSearchResultsChanged().then(() => autoExpand(true));
this.viewModel.replaceString = this.searchWidget.getReplaceValue();
let hasResults = !this.viewModel.searchResult.isEmpty();
this.loading = false;
this.actionRegistry['refresh'].enabled = true;
this.actionRegistry['vs.tree.collapse'].enabled = hasResults;
this.actionRegistry['clearSearchResults'].enabled = hasResults;
if (completed && completed.limitHit) {
this.searchWidget.searchInput.showMessage({
content: nls.localize('searchMaxResultsWarning', "The result set only contains a subset of all matches. Please be more specific in your search to narrow down the results."),
type: MessageType.WARNING
});
}
if (!hasResults) {
let hasExcludes = !!excludePattern;
let hasIncludes = !!includePattern;
let message: string;
if (!completed) {
message = nls.localize('searchCanceled', "Search was canceled before any results could be found - ");
} else if (hasIncludes && hasExcludes) {
message = nls.localize('noResultsIncludesExcludes', "No results found in '{0}' excluding '{1}' - ", includePattern, excludePattern);
} else if (hasIncludes) {
message = nls.localize('noResultsIncludes', "No results found in '{0}' - ", includePattern);
} else if (hasExcludes) {
message = nls.localize('noResultsExcludes', "No results found excluding '{0}' - ", excludePattern);
} else {
message = nls.localize('noResultsFound', "No results found. Review your settings for configured exclusions - ");
}
// Indicate as status to ARIA
aria.status(message);
this.tree.onHidden();
this.results.hide();
const div = this.clearMessage();
const p = $(div).p({ text: message });
if (!completed) {
$(p).a({
'class': ['pointer', 'prominent'],
text: nls.localize('rerunSearch.message', "Search again")
}).on(dom.EventType.CLICK, (e: MouseEvent) => {
dom.EventHelper.stop(e, false);
this.onQueryChanged(true);
});
} else if (hasIncludes || hasExcludes) {
$(p).a({
'class': ['pointer', 'prominent'],
'tabindex': '0',
text: nls.localize('rerunSearchInAll.message', "Search again in all files")
}).on(dom.EventType.CLICK, (e: MouseEvent) => {
dom.EventHelper.stop(e, false);
this.inputPatternExclusions.setValue('');
this.inputPatternIncludes.setValue('');
this.onQueryChanged(true);
});
} else {
$(p).a({
'class': ['pointer', 'prominent'],
'tabindex': '0',
text: nls.localize('openSettings.message', "Open Settings")
}).on(dom.EventType.CLICK, (e: MouseEvent) => {
dom.EventHelper.stop(e, false);
if (this.contextService.hasWorkspace()) {
this.preferencesService.openWorkspaceSettings().done(() => null, errors.onUnexpectedError);
} else {
this.preferencesService.openGlobalSettings().done(() => null, errors.onUnexpectedError);
}
});
}
if (!this.contextService.hasWorkspace()) {
this.searchWithoutFolderMessage(div);
}
} else {
this.viewModel.searchResult.toggleHighlights(true); // show highlights
// Indicate final search result count for ARIA
aria.status(nls.localize('ariaSearchResultsStatus', "Search returned {0} results in {1} files", this.viewModel.searchResult.count(), this.viewModel.searchResult.fileCount()));
}
};
let onError = (e: any) => {
if (errors.isPromiseCanceledError(e)) {
onComplete(null);
} else {
this.loading = false;
isDone = true;
progressRunner.done();
this.messageService.show(2 /* ERROR */, e);
}
};
let total: number = 0;
let worked: number = 0;
let visibleMatches = 0;
let onProgress = (p: ISearchProgressItem) => {
// Progress
if (p.total) {
total = p.total;
}
if (p.worked) {
worked = p.worked;
}
};
// Handle UI updates in an interval to show frequent progress and results
let uiRefreshHandle = setInterval(() => {
if (isDone) {
window.clearInterval(uiRefreshHandle);
return;
}
if (!query.useRipgrep) {
// Progress bar update
let fakeProgress = true;
if (total > 0 && worked > 0) {
let ratio = Math.round((worked / total) * progressTotal);
if (ratio > progressWorked) { // never show less progress than what we have already
progressRunner.worked(ratio - progressWorked);
progressWorked = ratio;
fakeProgress = false;
}
}
// Fake progress up to 90%, or when actual progress beats it
const fakeMax = 900;
const fakeMultiplier = 12;
if (fakeProgress && progressWorked < fakeMax) {
// Linearly decrease the rate of fake progress.
// 1 is the smallest allowed amount of progress.
const fakeAmt = Math.round((fakeMax - progressWorked) / fakeMax * fakeMultiplier) || 1;
progressWorked += fakeAmt;
progressRunner.worked(fakeAmt);
}
}
// Search result tree update
const fileCount = this.viewModel.searchResult.fileCount();
if (visibleMatches !== fileCount) {
visibleMatches = fileCount;
this.tree.refresh().then(() => {
autoExpand(false);
}).done(null, errors.onUnexpectedError);
this.updateSearchResultCount();
}
if (fileCount > 0) {
// since we have results now, enable some actions
if (!this.actionRegistry['vs.tree.collapse'].enabled) {
this.actionRegistry['vs.tree.collapse'].enabled = true;
}
}
}, 100);
this.searchWidget.setReplaceAllActionState(false);
// this.replaceService.disposeAllReplacePreviews();
this.viewModel.search(query).done(onComplete, onError, query.useRipgrep ? undefined : onProgress);
}
private updateSearchResultCount(): void {
const fileCount = this.viewModel.searchResult.fileCount();
const msgWasHidden = this.messages.isHidden();
if (fileCount > 0) {
const div = this.clearMessage();
$(div).p({ text: this.buildResultCountMessage(this.viewModel.searchResult.count(), fileCount) });
if (msgWasHidden) {
this.reLayout();
}
} else if (!msgWasHidden) {
this.messages.hide();
}
}
private buildResultCountMessage(resultCount: number, fileCount: number): string {
if (resultCount === 1 && fileCount === 1) {
return nls.localize('search.file.result', "{0} result in {1} file", resultCount, fileCount);
} else if (resultCount === 1) {
return nls.localize('search.files.result', "{0} result in {1} files", resultCount, fileCount);
} else if (fileCount === 1) {
return nls.localize('search.file.results', "{0} results in {1} file", resultCount, fileCount);
} else {
return nls.localize('search.files.results', "{0} results in {1} files", resultCount, fileCount);
}
}
private searchWithoutFolderMessage(div: Builder): void {
$(div).p({ text: nls.localize('searchWithoutFolder', "You have not yet opened a folder. Only open files are currently searched - ") })
.asContainer().a({
'class': ['pointer', 'prominent'],
'tabindex': '0',
text: nls.localize('openFolder', "Open Folder")
}).on(dom.EventType.CLICK, (e: MouseEvent) => {
dom.EventHelper.stop(e, false);
const actionClass = env.isMacintosh ? OpenFileFolderAction : OpenFolderAction;
const action = this.instantiationService.createInstance<string, string, IAction>(actionClass, actionClass.ID, actionClass.LABEL);
this.actionRunner.run(action).done(() => {
action.dispose();
}, err => {
action.dispose();
errors.onUnexpectedError(err);
});
});
}
private showEmptyStage(): void {
// disable 'result'-actions
this.actionRegistry['refresh'].enabled = false;
this.actionRegistry['vs.tree.collapse'].enabled = false;
this.actionRegistry['clearSearchResults'].enabled = false;
// clean up ui
// this.replaceService.disposeAllReplacePreviews();
this.messages.hide();
this.results.show();
this.tree.onVisible();
this.currentSelectedFileMatch = null;
}
private onFocus(lineMatch: any, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): TPromise<any> {
if (!(lineMatch instanceof Match)) {
this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange();
return TPromise.as(true);
}
this.telemetryService.publicLog('searchResultChosen');
return (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) ?
this.replaceService.openReplacePreview(lineMatch, preserveFocus, sideBySide, pinned) :
this.open(lineMatch, preserveFocus, sideBySide, pinned);
}
public open(element: FileMatchOrMatch, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): TPromise<any> {
let selection = this.getSelectionFrom(element);
let resource = element instanceof Match ? element.parent().resource() : (<FileMatch>element).resource();
return this.editorService.openEditor({
resource: resource,
options: {
preserveFocus,
pinned,
selection,
revealIfVisible: !sideBySide
}
}, sideBySide).then(editor => {
if (editor && element instanceof Match && preserveFocus) {
this.viewModel.searchResult.rangeHighlightDecorations.highlightRange({
resource,
range: element.range()
}, <ICommonCodeEditor>editor.getControl());
} else {
this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange();
}
}, errors.onUnexpectedError);
}
private getSelectionFrom(element: FileMatchOrMatch): any {
let match: Match = null;
if (element instanceof Match) {
match = element;
}
if (element instanceof FileMatch && element.count() > 0) {
match = element.matches()[element.matches().length - 1];
}
if (match) {
let range = match.range();
if (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) {
let replaceString = match.replaceString;
return {
startLineNumber: range.startLineNumber,
startColumn: range.startColumn,
endLineNumber: range.startLineNumber,
endColumn: range.startColumn + replaceString.length
};
}
return range;
}
return void 0;
}
private onUntitledDidChangeDirty(resource: URI): void {
if (!this.viewModel) {
return;
}
// remove search results from this resource as it got disposed
if (!this.untitledEditorService.isDirty(resource)) {
let matches = this.viewModel.searchResult.matches();
for (let i = 0, len = matches.length; i < len; i++) {
if (resource.toString() === matches[i].resource().toString()) {
this.viewModel.searchResult.remove(matches[i]);
}
}
}
}
private onFilesChanged(e: FileChangesEvent): void {
if (!this.viewModel) {
return;
}
let matches = this.viewModel.searchResult.matches();
for (let i = 0, len = matches.length; i < len; i++) {
if (e.contains(matches[i].resource(), FileChangeType.DELETED)) {
this.viewModel.searchResult.remove(matches[i]);
}
}
}
public getActions(): IAction[] {
return [
this.actionRegistry['refresh'],
this.actionRegistry['vs.tree.collapse'],
this.actionRegistry['clearSearchResults']
];
}
public dispose(): void {
this.isDisposed = true;
this.toDispose = lifecycle.dispose(this.toDispose);
if (this.tree) {
this.tree.dispose();
}
this.searchWidget.dispose();
this.inputPatternIncludes.dispose();
this.inputPatternExclusions.dispose();
this.viewModel.dispose();
super.dispose();
}
}
registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
let matchHighlightColor = theme.getColor(editorFindMatchHighlight);
if (matchHighlightColor) {
collector.addRule(`.search-viewlet .findInFileMatch { background-color: ${matchHighlightColor}; }`);
collector.addRule(`.search-viewlet .highlight { background-color: ${matchHighlightColor}; }`);
}
}); | src/vs/workbench/parts/search/browser/searchViewlet.ts | 1 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.9985295534133911,
0.030326301231980324,
0.00016116008919198066,
0.00017373022274114192,
0.1659504920244217
] |
{
"id": 10,
"code_window": [
"\t\t}\n",
"\t}\n",
"\n",
"\tprivate autoExpandFileMatch(fileMatch: FileMatch, alwaysExpandIfOneResult: boolean): void {\n",
"\t\tlet length = fileMatch.matches().length;\n",
"\t\tif (length < 10 || (alwaysExpandIfOneResult && this.viewModel.searchResult.count() === 1 && length < 50)) {\n",
"\t\t\tthis.tree.expand(fileMatch).done(null, errors.onUnexpectedError);\n",
"\t\t} else {\n",
"\t\t\tthis.tree.collapse(fileMatch).done(null, errors.onUnexpectedError);\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tprivate onQueryTriggered(query: ISearchQuery, excludePattern: string, includePattern: string): void {\n",
"\t\tthis.viewModel.cancelSearch();\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 976
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"json.npm.error.repoaccess": "Сбой запроса в репозиторий NPM: {0}",
"json.npm.latestversion": "Последняя версия пакета, существующая на данный момент",
"json.npm.majorversion": "Сопоставление с последним основным номером версии (1.x.x)",
"json.npm.minorversion": "Сопоставление с последним дополнительным номером версии (1.2.x)",
"json.npm.package.hover": "{0}",
"json.npm.version.hover": "Последняя версия: {0}",
"json.package.default": "Файл package.json по умолчанию"
} | i18n/rus/extensions/json/server/out/jsoncontributions/packageJSONContribution.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.00017361018399242312,
0.00017154075612779707,
0.00016947132826317102,
0.00017154075612779707,
0.00000206942786462605
] |
{
"id": 10,
"code_window": [
"\t\t}\n",
"\t}\n",
"\n",
"\tprivate autoExpandFileMatch(fileMatch: FileMatch, alwaysExpandIfOneResult: boolean): void {\n",
"\t\tlet length = fileMatch.matches().length;\n",
"\t\tif (length < 10 || (alwaysExpandIfOneResult && this.viewModel.searchResult.count() === 1 && length < 50)) {\n",
"\t\t\tthis.tree.expand(fileMatch).done(null, errors.onUnexpectedError);\n",
"\t\t} else {\n",
"\t\t\tthis.tree.collapse(fileMatch).done(null, errors.onUnexpectedError);\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tprivate onQueryTriggered(query: ISearchQuery, excludePattern: string, includePattern: string): void {\n",
"\t\tthis.viewModel.cancelSearch();\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 976
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"DebugConfig.failed": "'launch.json' ファイルを '.vscode' フォルダー ({0}) 内に作成できません。",
"app.launch.json.compound.name": "複合の名前。起動構成のドロップダウン メニューに表示されます。",
"app.launch.json.compounds": "複合の一覧。各複合は、同時に起動される複数の構成を参照します。",
"app.launch.json.compounds.configurations": "この複合の一部として開始される構成の名前。",
"app.launch.json.configurations": "構成の一覧。IntelliSense を使用して、新しい構成を追加したり、既存の構成を編集したります。",
"app.launch.json.title": "起動",
"app.launch.json.version": "このファイル形式のバージョン。",
"debugNoType": "デバッグ アダプター 'type' は省略不可で、型 'string' でなければなりません。",
"selectDebug": "環境の選択",
"vscode.extension.contributes.breakpoints": "ブレークポイントを提供します。",
"vscode.extension.contributes.breakpoints.language": "この言語でブレークポイントを許可します。",
"vscode.extension.contributes.debuggers": "デバッグ アダプターを提供します。",
"vscode.extension.contributes.debuggers.adapterExecutableCommand": "指定されている場合、VS Code はこのコマンドを呼び出し、デバッグ アダプターの実行可能パスと、渡す引数を決定します。",
"vscode.extension.contributes.debuggers.args": "アダプターに渡すオプションの引数。",
"vscode.extension.contributes.debuggers.configurationAttributes": "'launch.json' を検証するための JSON スキーマ構成。",
"vscode.extension.contributes.debuggers.configurationSnippets": "'launch.json' に新しい構成を追加するためのスニペット。",
"vscode.extension.contributes.debuggers.initialConfigurations": "初期 'launch.json' を生成するための構成。",
"vscode.extension.contributes.debuggers.label": "このデバッグ アダプターの表示名。",
"vscode.extension.contributes.debuggers.languages": "デバッグ拡張機能が \"既定のデバッガー\" とされる言語の一覧。",
"vscode.extension.contributes.debuggers.linux": "Linux 固有の設定。",
"vscode.extension.contributes.debuggers.linux.runtime": "Linux で使用されるランタイム。",
"vscode.extension.contributes.debuggers.osx": "OS X 固有の設定。",
"vscode.extension.contributes.debuggers.osx.runtime": "OSX で使用されるランタイム。",
"vscode.extension.contributes.debuggers.program": "デバッグ アダプター プログラムへのパス。絶対パスか拡張機能フォルダーへの相対パスです。",
"vscode.extension.contributes.debuggers.runtime": "プログラム属性が実行可能でなく、ランタイムが必要な場合のオプション ランタイム。",
"vscode.extension.contributes.debuggers.runtimeArgs": "オプションのランタイム引数。",
"vscode.extension.contributes.debuggers.startSessionCommand": "VS Code が指定されている場合、この拡張機能を対象とする \"デバッグ\" または \"実行\" アクションにこのコマンドが呼び出されます。",
"vscode.extension.contributes.debuggers.type": "このデバッグ アダプターの一意識別子。",
"vscode.extension.contributes.debuggers.variables": "`launch.json` 内の対話型の変数 (例: ${action.pickProcess}) からコマンドへマッピングしています。",
"vscode.extension.contributes.debuggers.windows": "Windows 固有の設定。",
"vscode.extension.contributes.debuggers.windows.runtime": "Windows で使用されるランタイム。"
} | i18n/jpn/src/vs/workbench/parts/debug/electron-browser/debugConfigurationManager.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.0001705548638710752,
0.00016930179845076054,
0.0001680413115536794,
0.00016930550918914378,
9.743368991621537e-7
] |
{
"id": 10,
"code_window": [
"\t\t}\n",
"\t}\n",
"\n",
"\tprivate autoExpandFileMatch(fileMatch: FileMatch, alwaysExpandIfOneResult: boolean): void {\n",
"\t\tlet length = fileMatch.matches().length;\n",
"\t\tif (length < 10 || (alwaysExpandIfOneResult && this.viewModel.searchResult.count() === 1 && length < 50)) {\n",
"\t\t\tthis.tree.expand(fileMatch).done(null, errors.onUnexpectedError);\n",
"\t\t} else {\n",
"\t\t\tthis.tree.collapse(fileMatch).done(null, errors.onUnexpectedError);\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tprivate onQueryTriggered(query: ISearchQuery, excludePattern: string, includePattern: string): void {\n",
"\t\tthis.viewModel.cancelSearch();\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 976
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"json.npm.error.repoaccess": "NPM 리포지토리 요청 실패: {0}",
"json.npm.latestversion": "패키지의 최신 버전",
"json.npm.majorversion": "최신 주 버전(1.x.x)을 일치시킵니다.",
"json.npm.minorversion": "최신 부 버전(1.2.x)을 일치시킵니다.",
"json.npm.package.hover": "{0}",
"json.npm.version.hover": "최신 버전: {0}",
"json.package.default": "기본 package.json"
} | i18n/kor/src/vs/languages/json/common/contributions/packageJSONContribution.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.00017443635442759842,
0.00017358470358885825,
0.00017273305275011808,
0.00017358470358885825,
8.5165083874017e-7
] |
{
"id": 11,
"code_window": [
"\t\tthis.loading = true;\n",
"\t\tthis.searchWidget.searchInput.clearMessage();\n",
"\t\tthis.showEmptyStage();\n",
"\n",
"\t\tlet handledMatches: { [id: string]: boolean } = Object.create(null);\n",
"\t\tlet autoExpand = (alwaysExpandIfOneResult: boolean) => {\n",
"\t\t\t// Auto-expand / collapse based on number of matches:\n",
"\t\t\t// - alwaysExpandIfOneResult: expand file results if we have just one file result and less than 50 matches on a file\n",
"\t\t\t// - expand file results if we have more than one file result and less than 10 matches on a file\n",
"\t\t\tlet matches = this.viewModel.searchResult.matches();\n",
"\t\t\tmatches.forEach((match) => {\n",
"\t\t\t\tif (handledMatches[match.id()]) {\n",
"\t\t\t\t\treturn; // if we once handled a result, do not do it again to keep results stable (the user might have expanded/collapsed meanwhile)\n",
"\t\t\t\t}\n",
"\t\t\t\thandledMatches[match.id()] = true;\n",
"\t\t\t\tthis.autoExpandFileMatch(match, alwaysExpandIfOneResult);\n",
"\t\t\t});\n",
"\t\t};\n",
"\n",
"\t\tlet isDone = false;\n",
"\t\tlet onComplete = (completed?: ISearchComplete) => {\n",
"\t\t\tisDone = true;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 1000
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import nls = require('vs/nls');
import strings = require('vs/base/common/strings');
import platform = require('vs/base/common/platform');
import errors = require('vs/base/common/errors');
import paths = require('vs/base/common/paths');
import dom = require('vs/base/browser/dom');
import { $ } from 'vs/base/browser/builder';
import { TPromise } from 'vs/base/common/winjs.base';
import { IAction, IActionRunner } from 'vs/base/common/actions';
import { ActionsRenderer } from 'vs/base/parts/tree/browser/actionsRenderer';
import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge';
import { FileLabel } from 'vs/workbench/browser/labels';
import { LeftRightWidget, IRenderer } from 'vs/base/browser/ui/leftRightWidget/leftRightWidget';
import { ITree, IElementCallback, IDataSource, ISorter, IAccessibilityProvider, IFilter } from 'vs/base/parts/tree/browser/tree';
import { ClickBehavior, DefaultController } from 'vs/base/parts/tree/browser/treeDefaults';
import { ContributableActionProvider } from 'vs/workbench/browser/actionBarRegistry';
import { Match, SearchResult, FileMatch, FileMatchOrMatch, SearchModel } from 'vs/workbench/parts/search/common/searchModel';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { Range } from 'vs/editor/common/core/range';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { SearchViewlet } from 'vs/workbench/parts/search/browser/searchViewlet';
import { RemoveAction, ReplaceAllAction, ReplaceAction } from 'vs/workbench/parts/search/browser/searchActions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
export class SearchDataSource implements IDataSource {
public getId(tree: ITree, element: any): string {
if (element instanceof FileMatch) {
return element.id();
}
if (element instanceof Match) {
return element.id();
}
return 'root';
}
public getChildren(tree: ITree, element: any): TPromise<any[]> {
let value: any[] = [];
if (element instanceof FileMatch) {
value = element.matches();
} else if (element instanceof SearchResult) {
value = element.matches();
}
return TPromise.as(value);
}
public hasChildren(tree: ITree, element: any): boolean {
return element instanceof FileMatch || element instanceof SearchResult;
}
public getParent(tree: ITree, element: any): TPromise<any> {
let value: any = null;
if (element instanceof Match) {
value = element.parent();
} else if (element instanceof FileMatch) {
value = element.parent();
}
return TPromise.as(value);
}
}
export class SearchSorter implements ISorter {
public compare(tree: ITree, elementA: FileMatchOrMatch, elementB: FileMatchOrMatch): number {
if (elementA instanceof FileMatch && elementB instanceof FileMatch) {
return elementA.resource().fsPath.localeCompare(elementB.resource().fsPath) || elementA.name().localeCompare(elementB.name());
}
if (elementA instanceof Match && elementB instanceof Match) {
return Range.compareRangesUsingStarts(elementA.range(), elementB.range());
}
return undefined;
}
}
class SearchActionProvider extends ContributableActionProvider {
constructor(private viewlet: SearchViewlet, @IInstantiationService private instantiationService: IInstantiationService) {
super();
}
public hasActions(tree: ITree, element: any): boolean {
let input = <SearchResult>tree.getInput();
return element instanceof FileMatch || (input.searchModel.isReplaceActive() || element instanceof Match) || super.hasActions(tree, element);
}
public getActions(tree: ITree, element: any): TPromise<IAction[]> {
return super.getActions(tree, element).then(actions => {
let input = <SearchResult>tree.getInput();
if (element instanceof FileMatch) {
actions.unshift(new RemoveAction(tree, element));
if (input.searchModel.isReplaceActive() && element.count() > 0) {
actions.unshift(this.instantiationService.createInstance(ReplaceAllAction, tree, element, this.viewlet));
}
}
if (element instanceof Match) {
if (input.searchModel.isReplaceActive()) {
actions.unshift(this.instantiationService.createInstance(ReplaceAction, tree, element, this.viewlet), new RemoveAction(tree, element));
}
}
return actions;
});
}
}
export class SearchRenderer extends ActionsRenderer {
constructor(actionRunner: IActionRunner, viewlet: SearchViewlet, @IWorkspaceContextService private contextService: IWorkspaceContextService,
@IInstantiationService private instantiationService: IInstantiationService) {
super({
actionProvider: instantiationService.createInstance(SearchActionProvider, viewlet),
actionRunner: actionRunner
});
}
public getContentHeight(tree: ITree, element: any): number {
return 22;
}
public renderContents(tree: ITree, element: FileMatchOrMatch, domElement: HTMLElement, previousCleanupFn: IElementCallback): IElementCallback {
// File
if (element instanceof FileMatch) {
let fileMatch = <FileMatch>element;
let container = $('.filematch');
let leftRenderer: IRenderer;
let rightRenderer: IRenderer;
let widget: LeftRightWidget;
leftRenderer = (left: HTMLElement): any => {
const label = this.instantiationService.createInstance(FileLabel, left, void 0);
label.setFile(fileMatch.resource());
return () => label.dispose();
};
rightRenderer = (right: HTMLElement) => {
let len = fileMatch.count();
new CountBadge(right, len, len > 1 ? nls.localize('searchMatches', "{0} matches found", len) : nls.localize('searchMatch', "{0} match found", len));
return null;
};
widget = new LeftRightWidget(container, leftRenderer, rightRenderer);
container.appendTo(domElement);
return widget.dispose.bind(widget);
}
// Match
else if (element instanceof Match) {
dom.addClass(domElement, 'linematch');
let match = <Match>element;
let elements: string[] = [];
let preview = match.preview();
elements.push('<span>');
elements.push(strings.escape(preview.before));
let searchModel: SearchModel = (<SearchResult>tree.getInput()).searchModel;
let showReplaceText = searchModel.isReplaceActive() && !!searchModel.replaceString;
elements.push('</span><span class="' + (showReplaceText ? 'replace ' : '') + 'findInFileMatch">');
elements.push(strings.escape(preview.inside));
if (showReplaceText) {
elements.push('</span><span class="replaceMatch">');
elements.push(strings.escape(match.replaceString));
}
elements.push('</span><span>');
elements.push(strings.escape(preview.after));
elements.push('</span>');
$('a.plain')
.innerHtml(elements.join(strings.empty))
.title((preview.before + (showReplaceText ? match.replaceString : preview.inside) + preview.after).trim().substr(0, 999))
.appendTo(domElement);
}
return null;
}
}
export class SearchAccessibilityProvider implements IAccessibilityProvider {
constructor( @IWorkspaceContextService private contextService: IWorkspaceContextService) {
}
public getAriaLabel(tree: ITree, element: FileMatchOrMatch): string {
if (element instanceof FileMatch) {
const path = this.contextService.toWorkspaceRelativePath(element.resource()) || element.resource().fsPath;
return nls.localize('fileMatchAriaLabel', "{0} matches in file {1} of folder {2}, Search result", element.count(), element.name(), paths.dirname(path));
}
if (element instanceof Match) {
let match = <Match>element;
let input = <SearchResult>tree.getInput();
if (input.searchModel.isReplaceActive()) {
let preview = match.preview();
return nls.localize('replacePreviewResultAria', "Replace preview result, {0}", preview.before + match.replaceString + preview.after);
}
return nls.localize('searchResultAria', "{0}, Search result", match.text());
}
return undefined;
}
}
export class SearchController extends DefaultController {
constructor(private viewlet: SearchViewlet, @IInstantiationService private instantiationService: IInstantiationService) {
super({ clickBehavior: ClickBehavior.ON_MOUSE_DOWN, keyboardSupport: false });
// TODO@Rob these should be commands
// Up (from results to inputs)
this.downKeyBindingDispatcher.set(KeyCode.UpArrow, this.onUp.bind(this));
// Open to side
this.upKeyBindingDispatcher.set(platform.isMacintosh ? KeyMod.WinCtrl | KeyCode.Enter : KeyMod.CtrlCmd | KeyCode.Enter, this.onEnter.bind(this));
// Delete
this.downKeyBindingDispatcher.set(platform.isMacintosh ? KeyMod.CtrlCmd | KeyCode.Backspace : KeyCode.Delete, (tree: ITree, event: any) => { this.onDelete(tree, event); });
// Cancel search
this.downKeyBindingDispatcher.set(KeyCode.Escape, (tree: ITree, event: any) => { this.onEscape(tree, event); });
// Replace / Replace All
this.downKeyBindingDispatcher.set(ReplaceAllAction.KEY_BINDING, (tree: ITree, event: any) => { this.onReplaceAll(tree, event); });
this.downKeyBindingDispatcher.set(ReplaceAction.KEY_BINDING, (tree: ITree, event: any) => { this.onReplace(tree, event); });
}
protected onEscape(tree: ITree, event: IKeyboardEvent): boolean {
if (this.viewlet.cancelSearch()) {
return true;
}
return super.onEscape(tree, event);
}
private onDelete(tree: ITree, event: IKeyboardEvent): boolean {
let input = <SearchResult>tree.getInput();
let result = false;
let element = tree.getFocus();
if (element instanceof FileMatch ||
(element instanceof Match && input.searchModel.isReplaceActive())) {
new RemoveAction(tree, element).run().done(null, errors.onUnexpectedError);
result = true;
}
return result;
}
private onReplace(tree: ITree, event: IKeyboardEvent): boolean {
let input = <SearchResult>tree.getInput();
let result = false;
let element = tree.getFocus();
if (element instanceof Match && input.searchModel.isReplaceActive()) {
this.instantiationService.createInstance(ReplaceAction, tree, element, this.viewlet).run().done(null, errors.onUnexpectedError);
result = true;
}
return result;
}
private onReplaceAll(tree: ITree, event: IKeyboardEvent): boolean {
let result = false;
let element = tree.getFocus();
if (element instanceof FileMatch && element.count() > 0) {
this.instantiationService.createInstance(ReplaceAllAction, tree, element, this.viewlet).run().done(null, errors.onUnexpectedError);
result = true;
}
return result;
}
protected onUp(tree: ITree, event: IKeyboardEvent): boolean {
if (tree.getNavigator().first() === tree.getFocus()) {
this.viewlet.moveFocusFromResults();
return true;
}
return false;
}
}
export class SearchFilter implements IFilter {
public isVisible(tree: ITree, element: any): boolean {
return !(element instanceof FileMatch) || element.matches().length > 0;
}
} | src/vs/workbench/parts/search/browser/searchResultsView.ts | 1 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.002655674936249852,
0.00033833127235993743,
0.00016168771253433079,
0.00016935970052145422,
0.0005121197318658233
] |
{
"id": 11,
"code_window": [
"\t\tthis.loading = true;\n",
"\t\tthis.searchWidget.searchInput.clearMessage();\n",
"\t\tthis.showEmptyStage();\n",
"\n",
"\t\tlet handledMatches: { [id: string]: boolean } = Object.create(null);\n",
"\t\tlet autoExpand = (alwaysExpandIfOneResult: boolean) => {\n",
"\t\t\t// Auto-expand / collapse based on number of matches:\n",
"\t\t\t// - alwaysExpandIfOneResult: expand file results if we have just one file result and less than 50 matches on a file\n",
"\t\t\t// - expand file results if we have more than one file result and less than 10 matches on a file\n",
"\t\t\tlet matches = this.viewModel.searchResult.matches();\n",
"\t\t\tmatches.forEach((match) => {\n",
"\t\t\t\tif (handledMatches[match.id()]) {\n",
"\t\t\t\t\treturn; // if we once handled a result, do not do it again to keep results stable (the user might have expanded/collapsed meanwhile)\n",
"\t\t\t\t}\n",
"\t\t\t\thandledMatches[match.id()] = true;\n",
"\t\t\t\tthis.autoExpandFileMatch(match, alwaysExpandIfOneResult);\n",
"\t\t\t});\n",
"\t\t};\n",
"\n",
"\t\tlet isDone = false;\n",
"\t\tlet onComplete = (completed?: ISearchComplete) => {\n",
"\t\t\tisDone = true;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 1000
} | <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>fileTypes</key>
<array>
<string>md</string>
<string>mdown</string>
<string>markdown</string>
<string>markdn</string>
</array>
<key>keyEquivalent</key>
<string>^~M</string>
<key>name</key>
<string>Markdown</string>
<key>patterns</key>
<array>
<dict>
<key>include</key>
<string>#frontMatter</string>
</dict>
<dict>
<key>include</key>
<string>#block</string>
</dict>
</array>
<key>repository</key>
<dict>
<key>block</key>
<dict>
<key>patterns</key>
<array>
<dict>
<key>include</key>
<string>#separator</string>
</dict>
<dict>
<key>include</key>
<string>#heading</string>
</dict>
<dict>
<key>include</key>
<string>#blockquote</string>
</dict>
<dict>
<key>include</key>
<string>#lists</string>
</dict>
{{languageIncludes}}
<dict>
<key>include</key>
<string>#fenced_code_block_unknown</string>
</dict>
<dict>
<key>include</key>
<string>#raw_block</string>
</dict>
<dict>
<key>include</key>
<string>#link-def</string>
</dict>
<dict>
<key>include</key>
<string>#html</string>
</dict>
<dict>
<key>include</key>
<string>#paragraph</string>
</dict>
</array>
<key>repository</key>
<dict>
<key>blockquote</key>
<dict>
<key>begin</key>
<string>(^|\G)[ ]{0,3}(>) ?</string>
<key>captures</key>
<dict>
<key>2</key>
<dict>
<key>name</key>
<string>beginning.punctuation.definition.quote.markdown</string>
</dict>
</dict>
<key>name</key>
<string>markup.quote.markdown</string>
<key>patterns</key>
<array>
<dict>
<key>include</key>
<string>#block</string>
</dict>
</array>
<key>while</key>
<string>(^|\G)\s*(>) ?</string>
</dict>
<key>heading</key>
<dict>
<key>begin</key>
<string>(?:^|\G)[ ]{0,3}(#{1,6})\s*(?=[\S[^#]])</string>
<key>captures</key>
<dict>
<key>1</key>
<dict>
<key>name</key>
<string>punctuation.definition.heading.markdown</string>
</dict>
</dict>
<key>contentName</key>
<string>entity.name.section.markdown</string>
<key>end</key>
<string>\s*(#{1,6})?$\n?</string>
<key>name</key>
<string>markup.heading.markdown</string>
<key>patterns</key>
<array>
<dict>
<key>include</key>
<string>#inline</string>
</dict>
</array>
</dict>
<key>heading-setext</key>
<dict>
<key>patterns</key>
<array>
<dict>
<key>match</key>
<string>^(={3,})(?=[ \t]*$\n?)</string>
<key>name</key>
<string>markup.heading.setext.1.markdown</string>
</dict>
<dict>
<key>match</key>
<string>^(-{3,})(?=[ \t]*$\n?)</string>
<key>name</key>
<string>markup.heading.setext.2.markdown</string>
</dict>
</array>
</dict>
<key>html</key>
<dict>
<key>patterns</key>
<array>
<dict>
<key>begin</key>
<string>(^|\G)\s*(<!--)</string>
<key>end</key>
<string>(-->)</string>
<key>name</key>
<string>comment.block.html</string>
<key>captures</key>
<dict>
<key>1</key>
<dict>
<key>name</key>
<string>punctuation.definition.comment.html</string>
</dict>
<key>2</key>
<dict>
<key>name</key>
<string>punctuation.definition.comment.html</string>
</dict>
</dict>
</dict>
<dict>
<key>begin</key>
<string>(^|\G)\s*(?=<(script|style|pre)(\s|$|>)(?!.*?</(script|style|pre)>))</string>
<key>patterns</key>
<array>
<dict>
<key>begin</key>
<string>(\s*|$)</string>
<key>patterns</key>
<array>
<dict>
<key>include</key>
<string>text.html.basic</string>
</dict>
</array>
<key>while</key>
<string>^\s*(?!</(script|style|pre)>)</string>
</dict>
</array>
<key>end</key>
<string>(?=</(script|style|pre)>)</string>
</dict>
<dict>
<key>begin</key>
<string>(^|\G)\s*(?=</?(address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h1|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(\s|$|/?>))</string>
<key>patterns</key>
<array>
<dict>
<key>include</key>
<string>text.html.basic</string>
</dict>
</array>
<key>while</key>
<string>^(?!\s*$)</string>
</dict>
<dict>
<key>begin</key>
<string>(^|\G)\s*(?=(<[a-zA-Z0-9\-](/?>|\s.*?>)|</[a-zA-Z0-9\-]>)\s*$)</string>
<key>patterns</key>
<array>
<dict>
<key>include</key>
<string>text.html.basic</string>
</dict>
</array>
<key>while</key>
<string>^(?!\s*$)</string>
</dict>
</array>
</dict>
<key>link-def</key>
<dict>
<key>captures</key>
<dict>
<key>1</key>
<dict>
<key>name</key>
<string>punctuation.definition.constant.markdown</string>
</dict>
<key>10</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.end.markdown</string>
</dict>
<key>11</key>
<dict>
<key>name</key>
<string>string.other.link.description.title.markdown</string>
</dict>
<key>12</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.begin.markdown</string>
</dict>
<key>13</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.end.markdown</string>
</dict>
<key>2</key>
<dict>
<key>name</key>
<string>constant.other.reference.link.markdown</string>
</dict>
<key>3</key>
<dict>
<key>name</key>
<string>punctuation.definition.constant.markdown</string>
</dict>
<key>4</key>
<dict>
<key>name</key>
<string>punctuation.separator.key-value.markdown</string>
</dict>
<key>5</key>
<dict>
<key>name</key>
<string>punctuation.definition.link.markdown</string>
</dict>
<key>6</key>
<dict>
<key>name</key>
<string>markup.underline.link.markdown</string>
</dict>
<key>7</key>
<dict>
<key>name</key>
<string>punctuation.definition.link.markdown</string>
</dict>
<key>8</key>
<dict>
<key>name</key>
<string>string.other.link.description.title.markdown</string>
</dict>
<key>9</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.begin.markdown</string>
</dict>
</dict>
<key>match</key>
<string>^(?x:
\s* # Leading whitespace
(\[)(.+?)(\])(:) # Reference name
[ \t]* # Optional whitespace
(<?)(\S+?)(>?) # The url
[ \t]* # Optional whitespace
(?:
((\().+?(\))) # Match title in quotes…
| ((").+?(")) # or in parens.
)? # Title is optional
\s* # Optional whitespace
$
)</string>
<key>name</key>
<string>meta.link.reference.def.markdown</string>
</dict>
<key>list_paragraph</key>
<dict>
<key>begin</key>
<string>(^|\G)(?=\S)(?![*+-]\s|[0-9]+\.\s)</string>
<key>name</key>
<string>meta.paragraph.markdown</string>
<key>patterns</key>
<array>
<dict>
<key>include</key>
<string>#inline</string>
</dict>
<dict>
<key>include</key>
<string>text.html.basic</string>
</dict>
<dict>
<key>include</key>
<string>#heading-setext</string>
</dict>
</array>
<key>while</key>
<string>(^|\G)(?!\s*$|#|[ ]{0,3}([-*_][ ]{2,}){3,}[ \t]*$\n?|>|[ ]{0,3}[*+-]|[ ]{0,3}[0-9]+\.)</string>
</dict>
<key>lists</key>
<dict>
<key>patterns</key>
<array>
<dict>
<key>begin</key>
<string>(^|\G)([ ]{0,3})([*+-])([ ]{1,3}|\t)</string>
<key>beginCaptures</key>
<dict>
<key>3</key>
<dict>
<key>name</key>
<string>beginning.punctuation.definition.list.markdown</string>
</dict>
</dict>
<key>comment</key>
<string>Currently does not support un-indented second lines.</string>
<key>name</key>
<string>markup.list.unnumbered.markdown</string>
<key>patterns</key>
<array>
<dict>
<key>include</key>
<string>#list_paragraph</string>
</dict>
<dict>
<key>include</key>
<string>#block</string>
</dict>
</array>
<key>while</key>
<string>((^|\G)([ ]{4}|\t))|(^[ \t]*$)</string>
</dict>
<dict>
<key>begin</key>
<string>(^|\G)([ ]{0,3})([0-9]+\.)([ ]{1,3}|\t)</string>
<key>beginCaptures</key>
<dict>
<key>3</key>
<dict>
<key>name</key>
<string>beginning.punctuation.definition.list.markdown</string>
</dict>
</dict>
<key>name</key>
<string>markup.list.numbered.markdown</string>
<key>patterns</key>
<array>
<dict>
<key>include</key>
<string>#list_paragraph</string>
</dict>
<dict>
<key>include</key>
<string>#block</string>
</dict>
</array>
<key>while</key>
<string>((^|\G)([ ]{4}|\t))|(^[ \t]*$)</string>
</dict>
</array>
</dict>
<key>paragraph</key>
<dict>
<key>begin</key>
<string>(^|\G)[ ]{0,3}(?=\S)</string>
<key>name</key>
<string>meta.paragraph.markdown</string>
<key>patterns</key>
<array>
<dict>
<key>include</key>
<string>#inline</string>
</dict>
<dict>
<key>include</key>
<string>text.html.basic</string>
</dict>
<dict>
<key>include</key>
<string>#heading-setext</string>
</dict>
</array>
<key>while</key>
<string>(^|\G)((?=\s*[-=]{3,}\s*$)|[ ]{4,}(?=\S))</string>
</dict>
{{languageDefinitions}}
<key>fenced_code_block_unknown</key>
<dict>
<key>name</key>
<string>markup.fenced_code.block.markdown</string>
<key>begin</key>
<string>(^|\G)(\s*)([`~]{3,})\s*([^`~]*)?$</string>
<key>end</key>
<string>(^|\G)(\2|\s{0,3})(\3)\s*$</string>
<key>beginCaptures</key>
<dict>
<key>3</key>
<dict>
<key>name</key>
<string>punctuation.definition.markdown</string>
</dict>
<key>4</key>
<dict>
<key>name</key>
<string>fenced_code.block.language</string>
</dict>
</dict>
<key>endCaptures</key>
<dict>
<key>3</key>
<dict>
<key>name</key>
<string>punctuation.definition.markdown</string>
</dict>
</dict>
</dict>
<key>raw_block</key>
<dict>
<key>begin</key>
<string>(^|\G)([ ]{4}|\t)</string>
<key>name</key>
<string>markup.raw.block.markdown</string>
<key>while</key>
<string>(^|\G)([ ]{4}|\t)</string>
</dict>
<key>separator</key>
<dict>
<key>match</key>
<string>(^|\G)[ ]{0,3}([*-_])([ ]{0,2}\2){2,}[ \t]*$\n?</string>
<key>name</key>
<string>meta.separator.markdown</string>
</dict>
</dict>
</dict>
<key>inline</key>
<dict>
<key>patterns</key>
<array>
<dict>
<key>include</key>
<string>#ampersand</string>
</dict>
<dict>
<key>include</key>
<string>#bracket</string>
</dict>
<dict>
<key>include</key>
<string>#bold</string>
</dict>
<dict>
<key>include</key>
<string>#italic</string>
</dict>
<dict>
<key>include</key>
<string>#raw</string>
</dict>
<dict>
<key>include</key>
<string>#escape</string>
</dict>
<dict>
<key>include</key>
<string>#image-inline</string>
</dict>
<dict>
<key>include</key>
<string>#image-ref</string>
</dict>
<dict>
<key>include</key>
<string>#link-email</string>
</dict>
<dict>
<key>include</key>
<string>#link-inet</string>
</dict>
<dict>
<key>include</key>
<string>#link-inline</string>
</dict>
<dict>
<key>include</key>
<string>#link-ref</string>
</dict>
<dict>
<key>include</key>
<string>#link-ref-literal</string>
</dict>
</array>
<key>repository</key>
<dict>
<key>ampersand</key>
<dict>
<key>comment</key>
<string>
Markdown will convert this for us. We match it so that the
HTML grammar will not mark it up as invalid.
</string>
<key>match</key>
<string>&(?!([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+);)</string>
<key>name</key>
<string>meta.other.valid-ampersand.markdown</string>
</dict>
<key>bold</key>
<dict>
<key>begin</key>
<string>(?x)
(\*\*|__)(?=\S) # Open
(?=
(
<[^>]*+> # HTML tags
| (?<raw>`+)([^`]|(?!(?<!`)\k<raw>(?!`))`)*+\k<raw>
# Raw
| \\[\\`*_{}\[\]()#.!+\->]?+ # Escapes
| \[
(
(?<square> # Named group
[^\[\]\\] # Match most chars
| \\. # Escaped chars
| \[ \g<square>*+ \] # Nested brackets
)*+
\]
(
( # Reference Link
[ ]? # Optional space
\[[^\]]*+\] # Ref name
)
| ( # Inline Link
\( # Opening paren
[ \t]*+ # Optional whitespace
<?(.*?)>? # URL
[ \t]*+ # Optional whitespace
( # Optional Title
(?<title>['"])
(.*?)
\k<title>
)?
\)
)
)
)
| (?!(?<=\S)\1). # Everything besides
# style closer
)++
(?<=\S)\1 # Close
)
</string>
<key>captures</key>
<dict>
<key>1</key>
<dict>
<key>name</key>
<string>punctuation.definition.bold.markdown</string>
</dict>
</dict>
<key>end</key>
<string>(?<=\S)(\1)</string>
<key>name</key>
<string>markup.bold.markdown</string>
<key>patterns</key>
<array>
<dict>
<key>applyEndPatternLast</key>
<integer>1</integer>
<key>begin</key>
<string>(?=<[^>]*?>)</string>
<key>end</key>
<string>(?<=>)</string>
<key>patterns</key>
<array>
<dict>
<key>include</key>
<string>text.html.basic</string>
</dict>
</array>
</dict>
<dict>
<key>include</key>
<string>#escape</string>
</dict>
<dict>
<key>include</key>
<string>#ampersand</string>
</dict>
<dict>
<key>include</key>
<string>#bracket</string>
</dict>
<dict>
<key>include</key>
<string>#raw</string>
</dict>
<dict>
<key>include</key>
<string>#italic</string>
</dict>
<dict>
<key>include</key>
<string>#image-inline</string>
</dict>
<dict>
<key>include</key>
<string>#link-inline</string>
</dict>
<dict>
<key>include</key>
<string>#link-inet</string>
</dict>
<dict>
<key>include</key>
<string>#link-email</string>
</dict>
<dict>
<key>include</key>
<string>#image-ref</string>
</dict>
<dict>
<key>include</key>
<string>#link-ref-literal</string>
</dict>
<dict>
<key>include</key>
<string>#link-ref</string>
</dict>
</array>
</dict>
<key>bracket</key>
<dict>
<key>comment</key>
<string>
Markdown will convert this for us. We match it so that the
HTML grammar will not mark it up as invalid.
</string>
<key>match</key>
<string><(?![a-z/?\$!])</string>
<key>name</key>
<string>meta.other.valid-bracket.markdown</string>
</dict>
<key>escape</key>
<dict>
<key>match</key>
<string>\\[-`*_#+.!(){}\[\]\\>]</string>
<key>name</key>
<string>constant.character.escape.markdown</string>
</dict>
<key>image-inline</key>
<dict>
<key>captures</key>
<dict>
<key>1</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.begin.markdown</string>
</dict>
<key>10</key>
<dict>
<key>name</key>
<string>string.other.link.description.title.markdown</string>
</dict>
<key>11</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.markdown</string>
</dict>
<key>12</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.markdown</string>
</dict>
<key>13</key>
<dict>
<key>name</key>
<string>string.other.link.description.title.markdown</string>
</dict>
<key>14</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.markdown</string>
</dict>
<key>15</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.markdown</string>
</dict>
<key>16</key>
<dict>
<key>name</key>
<string>punctuation.definition.metadata.markdown</string>
</dict>
<key>2</key>
<dict>
<key>name</key>
<string>string.other.link.description.markdown</string>
</dict>
<key>4</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.end.markdown</string>
</dict>
<key>5</key>
<dict>
<key>name</key>
<string>invalid.illegal.whitespace.markdown</string>
</dict>
<key>6</key>
<dict>
<key>name</key>
<string>punctuation.definition.metadata.markdown</string>
</dict>
<key>7</key>
<dict>
<key>name</key>
<string>punctuation.definition.link.markdown</string>
</dict>
<key>8</key>
<dict>
<key>name</key>
<string>markup.underline.link.image.markdown</string>
</dict>
<key>9</key>
<dict>
<key>name</key>
<string>punctuation.definition.link.markdown</string>
</dict>
</dict>
<key>match</key>
<string>(?x:
(\!\[)((?<square>[^\[\]\\]|\\.|\[\g<square>*+\])*+)(\])
# Match the link text.
([ ])? # Space not allowed
(\() # Opening paren for url
(<?)(\S+?)(>?) # The url
[ \t]* # Optional whitespace
(?:
((\().+?(\))) # Match title in parens…
| ((").+?(")) # or in quotes.
)? # Title is optional
\s* # Optional whitespace
(\))
)</string>
<key>name</key>
<string>meta.image.inline.markdown</string>
</dict>
<key>image-ref</key>
<dict>
<key>captures</key>
<dict>
<key>1</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.begin.markdown</string>
</dict>
<key>2</key>
<dict>
<key>name</key>
<string>string.other.link.description.markdown</string>
</dict>
<key>4</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.begin.markdown</string>
</dict>
<key>5</key>
<dict>
<key>name</key>
<string>punctuation.definition.constant.markdown</string>
</dict>
<key>6</key>
<dict>
<key>name</key>
<string>constant.other.reference.link.markdown</string>
</dict>
<key>7</key>
<dict>
<key>name</key>
<string>punctuation.definition.constant.markdown</string>
</dict>
</dict>
<key>match</key>
<string>(\!\[)((?<square>[^\[\]\\]|\\.|\[\g<square>*+\])*+)(\])[ ]?(\[)(.*?)(\])</string>
<key>name</key>
<string>meta.image.reference.markdown</string>
</dict>
<key>italic</key>
<dict>
<key>begin</key>
<string>(?x)
(\*|_)(?=\S) # Open
(?=
(
<[^>]*+> # HTML tags
| (?<raw>`+)([^`]|(?!(?<!`)\k<raw>(?!`))`)*+\k<raw>
# Raw
| \\[\\`*_{}\[\]()#.!+\->]?+ # Escapes
| \[
(
(?<square> # Named group
[^\[\]\\] # Match most chars
| \\. # Escaped chars
| \[ \g<square>*+ \] # Nested brackets
)*+
\]
(
( # Reference Link
[ ]? # Optional space
\[[^\]]*+\] # Ref name
)
| ( # Inline Link
\( # Opening paren
[ \t]*+ # Optional whtiespace
<?(.*?)>? # URL
[ \t]*+ # Optional whtiespace
( # Optional Title
(?<title>['"])
(.*?)
\k<title>
)?
\)
)
)
)
| \1\1 # Must be bold closer
| (?!(?<=\S)\1). # Everything besides
# style closer
)++
(?<=\S)\1 # Close
)
</string>
<key>captures</key>
<dict>
<key>1</key>
<dict>
<key>name</key>
<string>punctuation.definition.italic.markdown</string>
</dict>
</dict>
<key>end</key>
<string>(?<=\S)(\1)((?!\1)|(?=\1\1))</string>
<key>name</key>
<string>markup.italic.markdown</string>
<key>patterns</key>
<array>
<dict>
<key>applyEndPatternLast</key>
<integer>1</integer>
<key>begin</key>
<string>(?=<[^>]*?>)</string>
<key>end</key>
<string>(?<=>)</string>
<key>patterns</key>
<array>
<dict>
<key>include</key>
<string>text.html.basic</string>
</dict>
</array>
</dict>
<dict>
<key>include</key>
<string>#escape</string>
</dict>
<dict>
<key>include</key>
<string>#ampersand</string>
</dict>
<dict>
<key>include</key>
<string>#bracket</string>
</dict>
<dict>
<key>include</key>
<string>#raw</string>
</dict>
<dict>
<key>include</key>
<string>#bold</string>
</dict>
<dict>
<key>include</key>
<string>#image-inline</string>
</dict>
<dict>
<key>include</key>
<string>#link-inline</string>
</dict>
<dict>
<key>include</key>
<string>#link-inet</string>
</dict>
<dict>
<key>include</key>
<string>#link-email</string>
</dict>
<dict>
<key>include</key>
<string>#image-ref</string>
</dict>
<dict>
<key>include</key>
<string>#link-ref-literal</string>
</dict>
<dict>
<key>include</key>
<string>#link-ref</string>
</dict>
</array>
</dict>
<key>link-email</key>
<dict>
<key>captures</key>
<dict>
<key>1</key>
<dict>
<key>name</key>
<string>punctuation.definition.link.markdown</string>
</dict>
<key>2</key>
<dict>
<key>name</key>
<string>markup.underline.link.markdown</string>
</dict>
<key>4</key>
<dict>
<key>name</key>
<string>punctuation.definition.link.markdown</string>
</dict>
</dict>
<key>match</key>
<string>(<)((?:mailto:)?[-.\w]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)(>)</string>
<key>name</key>
<string>meta.link.email.lt-gt.markdown</string>
</dict>
<key>link-inet</key>
<dict>
<key>captures</key>
<dict>
<key>1</key>
<dict>
<key>name</key>
<string>punctuation.definition.link.markdown</string>
</dict>
<key>2</key>
<dict>
<key>name</key>
<string>markup.underline.link.markdown</string>
</dict>
<key>3</key>
<dict>
<key>name</key>
<string>punctuation.definition.link.markdown</string>
</dict>
</dict>
<key>match</key>
<string>(<)((?:https?|ftp)://.*?)(>)</string>
<key>name</key>
<string>meta.link.inet.markdown</string>
</dict>
<key>link-inline</key>
<dict>
<key>captures</key>
<dict>
<key>1</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.begin.markdown</string>
</dict>
<key>10</key>
<dict>
<key>name</key>
<string>string.other.link.description.title.markdown</string>
</dict>
<key>11</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.begin.markdown</string>
</dict>
<key>12</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.end.markdown</string>
</dict>
<key>13</key>
<dict>
<key>name</key>
<string>string.other.link.description.title.markdown</string>
</dict>
<key>14</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.begin.markdown</string>
</dict>
<key>15</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.end.markdown</string>
</dict>
<key>16</key>
<dict>
<key>name</key>
<string>punctuation.definition.metadata.markdown</string>
</dict>
<key>2</key>
<dict>
<key>name</key>
<string>string.other.link.title.markdown</string>
</dict>
<key>4</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.end.markdown</string>
</dict>
<key>5</key>
<dict>
<key>name</key>
<string>invalid.illegal.whitespace.markdown</string>
</dict>
<key>6</key>
<dict>
<key>name</key>
<string>punctuation.definition.metadata.markdown</string>
</dict>
<key>7</key>
<dict>
<key>name</key>
<string>punctuation.definition.link.markdown</string>
</dict>
<key>8</key>
<dict>
<key>name</key>
<string>markup.underline.link.markdown</string>
</dict>
<key>9</key>
<dict>
<key>name</key>
<string>punctuation.definition.link.markdown</string>
</dict>
</dict>
<key>match</key>
<string>(?x:
(\[)((?<square>[^\[\]\\]|\\.|\[\g<square>*+\])*+)(\])
# Match the link text.
([ ])? # Space not allowed
(\() # Opening paren for url
(<?)(.*?)(>?) # The url
[ \t]* # Optional whitespace
(?:
((\().+?(\))) # Match title in parens…
| ((").+?(")) # or in quotes.
)? # Title is optional
\s* # Optional whitespace
(\))
)</string>
<key>name</key>
<string>meta.link.inline.markdown</string>
</dict>
<key>link-ref</key>
<dict>
<key>captures</key>
<dict>
<key>1</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.begin.markdown</string>
</dict>
<key>2</key>
<dict>
<key>name</key>
<string>string.other.link.title.markdown</string>
</dict>
<key>4</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.end.markdown</string>
</dict>
<key>5</key>
<dict>
<key>name</key>
<string>punctuation.definition.constant.begin.markdown</string>
</dict>
<key>6</key>
<dict>
<key>name</key>
<string>constant.other.reference.link.markdown</string>
</dict>
<key>7</key>
<dict>
<key>name</key>
<string>punctuation.definition.constant.end.markdown</string>
</dict>
</dict>
<key>match</key>
<string>(\[)((?<square>[^\[\]\\]|\\.|\[\g<square>*+\])*+)(\])[ ]?(\[)([^\]]*+)(\])</string>
<key>name</key>
<string>meta.link.reference.markdown</string>
</dict>
<key>link-ref-literal</key>
<dict>
<key>captures</key>
<dict>
<key>1</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.begin.markdown</string>
</dict>
<key>2</key>
<dict>
<key>name</key>
<string>string.other.link.title.markdown</string>
</dict>
<key>4</key>
<dict>
<key>name</key>
<string>punctuation.definition.string.end.markdown</string>
</dict>
<key>5</key>
<dict>
<key>name</key>
<string>punctuation.definition.constant.begin.markdown</string>
</dict>
<key>6</key>
<dict>
<key>name</key>
<string>punctuation.definition.constant.end.markdown</string>
</dict>
</dict>
<key>match</key>
<string>(\[)((?<square>[^\[\]\\]|\\.|\[\g<square>*+\])*+)(\])[ ]?(\[)(\])</string>
<key>name</key>
<string>meta.link.reference.literal.markdown</string>
</dict>
<key>raw</key>
<dict>
<key>captures</key>
<dict>
<key>1</key>
<dict>
<key>name</key>
<string>punctuation.definition.raw.markdown</string>
</dict>
<key>3</key>
<dict>
<key>name</key>
<string>punctuation.definition.raw.markdown</string>
</dict>
</dict>
<key>match</key>
<string>(`+)([^`]|(?!(?<!`)\1(?!`))`)*+(\1)</string>
<key>name</key>
<string>markup.inline.raw.markdown</string>
</dict>
</dict>
</dict>
<key>frontMatter</key>
<dict>
<key>begin</key>
<string>\A-{3}\s*$</string>
<key>while</key>
<string>^(?!-{3}\s*$)</string>
<key>patterns</key>
<array>
<dict>
<key>include</key>
<string>source.yaml</string>
</dict>
</array>
</dict>
</dict>
<key>scopeName</key>
<string>text.html.markdown</string>
<key>uuid</key>
<string>0A1D9874-B448-11D9-BD50-000D93B6E43C</string>
</dict>
</plist>
| extensions/markdown/syntaxes/markdown.tmLanguage.base | 0 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.00018691581499297172,
0.0001680433633737266,
0.00016170668823178858,
0.00016817887080833316,
0.00000238534516938671
] |
{
"id": 11,
"code_window": [
"\t\tthis.loading = true;\n",
"\t\tthis.searchWidget.searchInput.clearMessage();\n",
"\t\tthis.showEmptyStage();\n",
"\n",
"\t\tlet handledMatches: { [id: string]: boolean } = Object.create(null);\n",
"\t\tlet autoExpand = (alwaysExpandIfOneResult: boolean) => {\n",
"\t\t\t// Auto-expand / collapse based on number of matches:\n",
"\t\t\t// - alwaysExpandIfOneResult: expand file results if we have just one file result and less than 50 matches on a file\n",
"\t\t\t// - expand file results if we have more than one file result and less than 10 matches on a file\n",
"\t\t\tlet matches = this.viewModel.searchResult.matches();\n",
"\t\t\tmatches.forEach((match) => {\n",
"\t\t\t\tif (handledMatches[match.id()]) {\n",
"\t\t\t\t\treturn; // if we once handled a result, do not do it again to keep results stable (the user might have expanded/collapsed meanwhile)\n",
"\t\t\t\t}\n",
"\t\t\t\thandledMatches[match.id()] = true;\n",
"\t\t\t\tthis.autoExpandFileMatch(match, alwaysExpandIfOneResult);\n",
"\t\t\t});\n",
"\t\t};\n",
"\n",
"\t\tlet isDone = false;\n",
"\t\tlet onComplete = (completed?: ISearchComplete) => {\n",
"\t\t\tisDone = true;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 1000
} | @echo off
setlocal
set VSCODE_DEV=
set ELECTRON_RUN_AS_NODE=1
call "%~dp0..\@@NAME@@.exe" "%~dp0..\resources\app\out\cli.js" %*
endlocal | resources/win32/bin/code.cmd | 0 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.00016923090151976794,
0.00016923090151976794,
0.00016923090151976794,
0.00016923090151976794,
0
] |
{
"id": 11,
"code_window": [
"\t\tthis.loading = true;\n",
"\t\tthis.searchWidget.searchInput.clearMessage();\n",
"\t\tthis.showEmptyStage();\n",
"\n",
"\t\tlet handledMatches: { [id: string]: boolean } = Object.create(null);\n",
"\t\tlet autoExpand = (alwaysExpandIfOneResult: boolean) => {\n",
"\t\t\t// Auto-expand / collapse based on number of matches:\n",
"\t\t\t// - alwaysExpandIfOneResult: expand file results if we have just one file result and less than 50 matches on a file\n",
"\t\t\t// - expand file results if we have more than one file result and less than 10 matches on a file\n",
"\t\t\tlet matches = this.viewModel.searchResult.matches();\n",
"\t\t\tmatches.forEach((match) => {\n",
"\t\t\t\tif (handledMatches[match.id()]) {\n",
"\t\t\t\t\treturn; // if we once handled a result, do not do it again to keep results stable (the user might have expanded/collapsed meanwhile)\n",
"\t\t\t\t}\n",
"\t\t\t\thandledMatches[match.id()] = true;\n",
"\t\t\t\tthis.autoExpandFileMatch(match, alwaysExpandIfOneResult);\n",
"\t\t\t});\n",
"\t\t};\n",
"\n",
"\t\tlet isDone = false;\n",
"\t\tlet onComplete = (completed?: ISearchComplete) => {\n",
"\t\t\tisDone = true;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 1000
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"activateBreakpoints": "중단점 활성화",
"addConditionalBreakpoint": "조건부 중단점 추가...",
"addFunctionBreakpoint": "함수 중단점 추가",
"addToWatchExpressions": "조사식에 추가",
"addWatchExpression": "식 추가",
"clearRepl": "콘솔 지우기",
"continueDebug": "계속",
"deactivateBreakpoints": "중단점 비활성화",
"debugConsoleAction": "디버그 콘솔",
"debugFocusConsole": "디버그 콘솔에 포커스",
"disableAllBreakpoints": "모든 중단점 해제",
"disableBreakpoint": "중단점 사용 안 함",
"disconnectDebug": "연결 끊기",
"editConditionalBreakpoint": "중단점 편집...",
"enableAllBreakpoints": "모든 중단점 설정",
"enableBreakpoint": "중단점 사용",
"focusProcess": "프로세스에 포커스",
"launchJsonNeedsConfigurtion": "'launch.json' 구성 또는 수정",
"openLaunchJson": "{0} 열기",
"pauseDebug": "일시 중지",
"reapplyAllBreakpoints": "모든 중단점 다시 적용",
"reconnectDebug": "다시 연결",
"removeAllBreakpoints": "모든 중단점 제거",
"removeAllWatchExpressions": "모든 식 제거",
"removeBreakpoint": "중단점 제거",
"removeWatchExpression": "식 제거",
"renameFunctionBreakpoint": "함수 중단점 이름 바꾸기",
"restartDebug": "다시 시작",
"restartFrame": "프레임 다시 시작",
"reverseContinue": "반전",
"selectAndStartDebugging": "디버깅 선택 및 시작",
"setValue": "값 설정",
"startDebug": "디버깅 시작",
"startWithoutDebugging": "디버깅하지 않고 시작",
"stepBackDebug": "뒤로 이동",
"stepIntoDebug": "단계 정보",
"stepOutDebug": "단계 출력",
"stepOverDebug": "단위 실행",
"stopDebug": "중지",
"unreadOutput": "디버그 콘솔의 새 출력"
} | i18n/kor/src/vs/workbench/parts/debug/browser/debugActions.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.00017038696387317032,
0.00016780028818175197,
0.0001655172964092344,
0.00016732247604522854,
0.0000016336945236616884
] |
{
"id": 12,
"code_window": [
"\t\t\t} else {\n",
"\t\t\t\tprogressRunner.done();\n",
"\t\t\t}\n",
"\n",
"\t\t\tthis.onSearchResultsChanged().then(() => autoExpand(true));\n",
"\t\t\tthis.viewModel.replaceString = this.searchWidget.getReplaceValue();\n",
"\n",
"\t\t\tlet hasResults = !this.viewModel.searchResult.isEmpty();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t// Do final render, then expand if just 1 file with less than 50 matches\n",
"\t\t\tthis.onSearchResultsChanged().then(() => {\n",
"\t\t\t\tif (this.viewModel.searchResult.count() === 1) {\n",
"\t\t\t\t\tconst onlyMatch = this.viewModel.searchResult.matches()[0];\n",
"\t\t\t\t\tif (onlyMatch.count() < 50) {\n",
"\t\t\t\t\t\treturn this.tree.expand(onlyMatch);\n",
"\t\t\t\t\t}\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\treturn null;\n",
"\t\t\t}).done(null, errors.onUnexpectedError);\n",
"\n"
],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 1027
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import 'vs/css!./media/searchviewlet';
import nls = require('vs/nls');
import { TPromise } from 'vs/base/common/winjs.base';
import { Emitter, debounceEvent } from 'vs/base/common/event';
import { EditorType, ICommonCodeEditor } from 'vs/editor/common/editorCommon';
import lifecycle = require('vs/base/common/lifecycle');
import errors = require('vs/base/common/errors');
import aria = require('vs/base/browser/ui/aria/aria');
import { IExpression } from 'vs/base/common/glob';
import env = require('vs/base/common/platform');
import { isFunction } from 'vs/base/common/types';
import { Delayer } from 'vs/base/common/async';
import URI from 'vs/base/common/uri';
import strings = require('vs/base/common/strings');
import dom = require('vs/base/browser/dom');
import { IAction, Action } from 'vs/base/common/actions';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { Dimension, Builder, $ } from 'vs/base/browser/builder';
import { FindInput } from 'vs/base/browser/ui/findinput/findInput';
import { ITree } from 'vs/base/parts/tree/browser/tree';
import { Tree } from 'vs/base/parts/tree/browser/treeImpl';
import { Scope } from 'vs/workbench/common/memento';
import { IPreferencesService } from 'vs/workbench/parts/preferences/common/preferences';
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
import { getOutOfWorkspaceEditorResources } from 'vs/workbench/common/editor';
import { FileChangeType, FileChangesEvent, IFileService, isEqual } from 'vs/platform/files/common/files';
import { Viewlet } from 'vs/workbench/browser/viewlet';
import { Match, FileMatch, SearchModel, FileMatchOrMatch, IChangeEvent, ISearchWorkbenchService } from 'vs/workbench/parts/search/common/searchModel';
import { QueryBuilder } from 'vs/workbench/parts/search/common/searchQuery';
import { MessageType, InputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { getExcludes, ISearchProgressItem, ISearchComplete, ISearchQuery, IQueryOptions, ISearchConfiguration } from 'vs/platform/search/common/search';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IMessageService } from 'vs/platform/message/common/message';
import { IProgressService } from 'vs/platform/progress/common/progress';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { KeyCode } from 'vs/base/common/keyCodes';
import { PatternInputWidget } from 'vs/workbench/parts/search/browser/patternInputWidget';
import { SearchRenderer, SearchDataSource, SearchSorter, SearchController, SearchAccessibilityProvider, SearchFilter } from 'vs/workbench/parts/search/browser/searchResultsView';
import { SearchWidget } from 'vs/workbench/parts/search/browser/searchWidget';
import { RefreshAction, CollapseAllAction, ClearSearchResultsAction, ConfigureGlobalExclusionsAction } from 'vs/workbench/parts/search/browser/searchActions';
import { IReplaceService } from 'vs/workbench/parts/search/common/replace';
import Severity from 'vs/base/common/severity';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { OpenFolderAction, OpenFileFolderAction } from 'vs/workbench/browser/actions/fileActions';
import * as Constants from 'vs/workbench/parts/search/common/constants';
import { IListService } from 'vs/platform/list/browser/listService';
import { IThemeService, ITheme, ICssStyleCollector, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { editorFindMatchHighlight } from 'vs/platform/theme/common/colorRegistry';
export class SearchViewlet extends Viewlet {
private static MAX_TEXT_RESULTS = 2048;
private static SHOW_REPLACE_STORAGE_KEY = 'vs.search.show.replace';
private isDisposed: boolean;
private toDispose: lifecycle.IDisposable[];
private loading: boolean;
private queryBuilder: QueryBuilder;
private viewModel: SearchModel;
private callOnModelChange: lifecycle.IDisposable[];
private viewletVisible: IContextKey<boolean>;
private inputBoxFocussed: IContextKey<boolean>;
private actionRegistry: { [key: string]: Action; };
private tree: ITree;
private viewletSettings: any;
private domNode: Builder;
private messages: Builder;
private searchWidgetsContainer: Builder;
private searchWidget: SearchWidget;
private size: Dimension;
private queryDetails: HTMLElement;
private inputPatternExclusions: PatternInputWidget;
private inputPatternGlobalExclusions: InputBox;
private inputPatternGlobalExclusionsContainer: Builder;
private inputPatternIncludes: PatternInputWidget;
private results: Builder;
private currentSelectedFileMatch: FileMatch;
private selectCurrentMatchEmitter: Emitter<string>;
private delayedRefresh: Delayer<void>;
constructor(
@ITelemetryService telemetryService: ITelemetryService,
@IFileService private fileService: IFileService,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
@IEditorGroupService private editorGroupService: IEditorGroupService,
@IProgressService private progressService: IProgressService,
@IMessageService private messageService: IMessageService,
@IStorageService private storageService: IStorageService,
@IContextViewService private contextViewService: IContextViewService,
@IInstantiationService private instantiationService: IInstantiationService,
@IConfigurationService private configurationService: IConfigurationService,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@ISearchWorkbenchService private searchWorkbenchService: ISearchWorkbenchService,
@IContextKeyService private contextKeyService: IContextKeyService,
@IKeybindingService private keybindingService: IKeybindingService,
@IReplaceService private replaceService: IReplaceService,
@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
@IPreferencesService private preferencesService: IPreferencesService,
@IListService private listService: IListService,
@IThemeService protected themeService: IThemeService
) {
super(Constants.VIEWLET_ID, telemetryService, themeService);
this.toDispose = [];
this.viewletVisible = Constants.SearchViewletVisibleKey.bindTo(contextKeyService);
this.inputBoxFocussed = Constants.InputBoxFocussedKey.bindTo(this.contextKeyService);
this.callOnModelChange = [];
this.queryBuilder = this.instantiationService.createInstance(QueryBuilder);
this.viewletSettings = this.getMemento(storageService, Scope.WORKSPACE);
this.toUnbind.push(this.fileService.onFileChanges(e => this.onFilesChanged(e)));
this.toUnbind.push(this.untitledEditorService.onDidChangeDirty(e => this.onUntitledDidChangeDirty(e)));
this.toUnbind.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationUpdated(e.config)));
this.selectCurrentMatchEmitter = new Emitter<string>();
debounceEvent(this.selectCurrentMatchEmitter.event, (l, e) => e, 100, /*leading=*/true)
(() => this.selectCurrentMatch());
this.delayedRefresh = new Delayer<void>(250);
}
private onConfigurationUpdated(configuration: any): void {
this.updateGlobalPatternExclusions(configuration);
}
public create(parent: Builder): TPromise<void> {
super.create(parent);
this.viewModel = this.searchWorkbenchService.searchModel;
let builder: Builder;
this.domNode = parent.div({
'class': 'search-viewlet'
}, (div) => {
builder = div;
});
builder.div({ 'class': ['search-widgets-container'] }, (div) => {
this.searchWidgetsContainer = div;
});
this.createSearchWidget(this.searchWidgetsContainer);
let filePatterns = this.viewletSettings['query.filePatterns'] || '';
let patternExclusions = this.viewletSettings['query.folderExclusions'] || '';
let exclusionsUsePattern = this.viewletSettings['query.exclusionsUsePattern'];
let includesUsePattern = this.viewletSettings['query.includesUsePattern'];
let patternIncludes = this.viewletSettings['query.folderIncludes'] || '';
let useIgnoreFiles = this.viewletSettings['query.useIgnoreFiles'];
this.queryDetails = this.searchWidgetsContainer.div({ 'class': ['query-details'] }, (builder) => {
builder.div({ 'class': 'more', 'tabindex': 0, 'role': 'button', 'title': nls.localize('moreSearch', "Toggle Search Details") })
.on(dom.EventType.CLICK, (e) => {
dom.EventHelper.stop(e);
this.toggleFileTypes(true);
}).on(dom.EventType.KEY_UP, (e: KeyboardEvent) => {
let event = new StandardKeyboardEvent(e);
if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) {
dom.EventHelper.stop(e);
this.toggleFileTypes();
}
});
//folder includes list
builder.div({ 'class': 'file-types' }, (builder) => {
let title = nls.localize('searchScope.includes', "files to include");
builder.element('h4', { text: title });
this.inputPatternIncludes = new PatternInputWidget(builder.getContainer(), this.contextViewService, {
ariaLabel: nls.localize('label.includes', 'Search Include Patterns')
});
this.inputPatternIncludes.setIsGlobPattern(includesUsePattern);
this.inputPatternIncludes.setValue(patternIncludes);
this.inputPatternIncludes
.on(FindInput.OPTION_CHANGE, (e) => {
this.onQueryChanged(false);
});
this.inputPatternIncludes.onSubmit(() => this.onQueryChanged(true));
this.trackInputBox(this.inputPatternIncludes.inputFocusTracker);
});
//pattern exclusion list
builder.div({ 'class': 'file-types' }, (builder) => {
let title = nls.localize('searchScope.excludes', "files to exclude");
builder.element('h4', { text: title });
const configuration = this.configurationService.getConfiguration<ISearchConfiguration>();
this.inputPatternExclusions = new PatternInputWidget(builder.getContainer(), this.contextViewService, {
ariaLabel: nls.localize('label.excludes', 'Search Exclude Patterns')
}, configuration.search.useRipgrep);
this.inputPatternExclusions.setIsGlobPattern(exclusionsUsePattern);
this.inputPatternExclusions.setValue(patternExclusions);
this.inputPatternExclusions.setUseIgnoreFiles(useIgnoreFiles);
this.inputPatternExclusions
.on(FindInput.OPTION_CHANGE, (e) => {
this.onQueryChanged(false);
});
this.inputPatternExclusions.onSubmit(() => this.onQueryChanged(true));
this.trackInputBox(this.inputPatternExclusions.inputFocusTracker);
});
// add hint if we have global exclusion
this.inputPatternGlobalExclusionsContainer = builder.div({ 'class': 'file-types global-exclude disabled' }, (builder) => {
let title = nls.localize('global.searchScope.folders', "files excluded through settings");
builder.element('h4', { text: title });
this.inputPatternGlobalExclusions = new InputBox(builder.getContainer(), this.contextViewService, {
actions: [this.instantiationService.createInstance(ConfigureGlobalExclusionsAction)],
ariaLabel: nls.localize('label.global.excludes', 'Configured Search Exclude Patterns')
});
this.inputPatternGlobalExclusions.inputElement.readOnly = true;
$(this.inputPatternGlobalExclusions.inputElement).attr('aria-readonly', 'true');
$(this.inputPatternGlobalExclusions.inputElement).addClass('disabled');
}).hide();
}).getHTMLElement();
this.messages = builder.div({ 'class': 'messages' }).hide().clone();
if (!this.contextService.hasWorkspace()) {
this.searchWithoutFolderMessage(this.clearMessage());
}
this.createSearchResultsView(builder);
this.actionRegistry = <any>{};
let actions: Action[] = [new CollapseAllAction(this), new RefreshAction(this), new ClearSearchResultsAction(this)];
actions.forEach((action) => {
this.actionRegistry[action.id] = action;
});
if (filePatterns !== '' || patternExclusions !== '' || patternIncludes !== '') {
this.toggleFileTypes(true, true, true);
}
this.updateGlobalPatternExclusions(this.configurationService.getConfiguration<ISearchConfiguration>());
this.toUnbind.push(this.viewModel.searchResult.onChange((event) => this.onSearchResultsChanged(event)));
return TPromise.as(null);
}
public get searchAndReplaceWidget(): SearchWidget {
return this.searchWidget;
}
private createSearchWidget(builder: Builder): void {
let contentPattern = this.viewletSettings['query.contentPattern'] || '';
let isRegex = this.viewletSettings['query.regex'] === true;
let isWholeWords = this.viewletSettings['query.wholeWords'] === true;
let isCaseSensitive = this.viewletSettings['query.caseSensitive'] === true;
this.searchWidget = new SearchWidget(builder, this.contextViewService, {
value: contentPattern,
isRegex: isRegex,
isCaseSensitive: isCaseSensitive,
isWholeWords: isWholeWords
}, this.contextKeyService, this.keybindingService, this.instantiationService);
if (this.storageService.getBoolean(SearchViewlet.SHOW_REPLACE_STORAGE_KEY, StorageScope.WORKSPACE, true)) {
this.searchWidget.toggleReplace(true);
}
this.toUnbind.push(this.searchWidget);
this.toUnbind.push(this.searchWidget.onSearchSubmit((refresh) => this.onQueryChanged(refresh)));
this.toUnbind.push(this.searchWidget.onSearchCancel(() => this.cancelSearch()));
this.toUnbind.push(this.searchWidget.searchInput.onDidOptionChange((viaKeyboard) => this.onQueryChanged(true, viaKeyboard)));
this.toUnbind.push(this.searchWidget.onReplaceToggled(() => this.onReplaceToggled()));
this.toUnbind.push(this.searchWidget.onReplaceStateChange((state) => {
this.viewModel.replaceActive = state;
this.tree.refresh();
}));
this.toUnbind.push(this.searchWidget.onReplaceValueChanged((value) => {
this.viewModel.replaceString = this.searchWidget.getReplaceValue();
this.delayedRefresh.trigger(() => this.tree.refresh());
}));
this.toUnbind.push(this.searchWidget.onReplaceAll(() => this.replaceAll()));
this.trackInputBox(this.searchWidget.searchInputFocusTracker);
this.trackInputBox(this.searchWidget.replaceInputFocusTracker);
}
private trackInputBox(inputFocusTracker: dom.IFocusTracker): void {
this.toUnbind.push(inputFocusTracker.addFocusListener(() => {
this.inputBoxFocussed.set(true);
}));
this.toUnbind.push(inputFocusTracker.addBlurListener(() => {
this.inputBoxFocussed.set(this.searchWidget.searchInputHasFocus()
|| this.searchWidget.replaceInputHasFocus()
|| this.inputPatternIncludes.inputHasFocus()
|| this.inputPatternExclusions.inputHasFocus());
}));
}
private onReplaceToggled(): void {
this.layout(this.size);
this.storageService.store(SearchViewlet.SHOW_REPLACE_STORAGE_KEY, this.searchAndReplaceWidget.isReplaceShown(), StorageScope.WORKSPACE);
}
private onSearchResultsChanged(event?: IChangeEvent): TPromise<any> {
return this.refreshTree(event).then(() => {
this.searchWidget.setReplaceAllActionState(!this.viewModel.searchResult.isEmpty());
this.updateSearchResultCount();
});
}
private refreshTree(event?: IChangeEvent): TPromise<any> {
if (!event) {
return this.tree.refresh(this.viewModel.searchResult);
}
if (event.added || event.removed) {
return this.tree.refresh(this.viewModel.searchResult).then(() => {
if (event.added) {
event.elements.forEach(element => {
this.autoExpandFileMatch(element, true);
});
}
});
} else {
if (event.elements.length === 1) {
return this.tree.refresh(event.elements[0]);
} else {
return this.tree.refresh(event.elements);
}
}
}
private replaceAll(): void {
if (this.viewModel.searchResult.count() === 0) {
return;
}
let progressRunner = this.progressService.show(100);
let occurrences = this.viewModel.searchResult.count();
let fileCount = this.viewModel.searchResult.fileCount();
let replaceValue = this.searchWidget.getReplaceValue() || '';
let afterReplaceAllMessage = this.buildAfterReplaceAllMessage(occurrences, fileCount, replaceValue);
let confirmation = {
title: nls.localize('replaceAll.confirmation.title', "Replace All"),
message: this.buildReplaceAllConfirmationMessage(occurrences, fileCount, replaceValue),
primaryButton: nls.localize('replaceAll.confirm.button', "Replace")
};
if (this.messageService.confirm(confirmation)) {
this.searchWidget.setReplaceAllActionState(false);
this.viewModel.searchResult.replaceAll(progressRunner).then(() => {
progressRunner.done();
this.clearMessage()
.p({ text: afterReplaceAllMessage });
}, (error) => {
progressRunner.done();
errors.isPromiseCanceledError(error);
this.messageService.show(Severity.Error, error);
});
}
}
private buildAfterReplaceAllMessage(occurrences: number, fileCount: number, replaceValue?: string) {
if (occurrences === 1) {
if (fileCount === 1) {
if (replaceValue) {
return nls.localize('replaceAll.occurrence.file.message', "Replaced {0} occurrence across {1} file with '{2}'.", occurrences, fileCount, replaceValue);
}
return nls.localize('removeAll.occurrence.file.message', "Replaced {0} occurrence across {1} file'.", occurrences, fileCount);
}
if (replaceValue) {
return nls.localize('replaceAll.occurrence.files.message', "Replaced {0} occurrence across {1} files with '{2}'.", occurrences, fileCount, replaceValue);
}
return nls.localize('removeAll.occurrence.files.message', "Replaced {0} occurrence across {1} files.", occurrences, fileCount);
}
if (fileCount === 1) {
if (replaceValue) {
return nls.localize('replaceAll.occurrences.file.message', "Replaced {0} occurrences across {1} file with '{2}'.", occurrences, fileCount, replaceValue);
}
return nls.localize('removeAll.occurrences.file.message', "Replaced {0} occurrences across {1} file'.", occurrences, fileCount);
}
if (replaceValue) {
return nls.localize('replaceAll.occurrences.files.message', "Replaced {0} occurrences across {1} files with '{2}'.", occurrences, fileCount, replaceValue);
}
return nls.localize('removeAll.occurrences.files.message', "Replaced {0} occurrences across {1} files.", occurrences, fileCount);
}
private buildReplaceAllConfirmationMessage(occurrences: number, fileCount: number, replaceValue?: string) {
if (occurrences === 1) {
if (fileCount === 1) {
if (replaceValue) {
return nls.localize('removeAll.occurrence.file.confirmation.message', "Replace {0} occurrence across {1} file with '{2}'?", occurrences, fileCount, replaceValue);
}
return nls.localize('replaceAll.occurrence.file.confirmation.message', "Replace {0} occurrence across {1} file'?", occurrences, fileCount);
}
if (replaceValue) {
return nls.localize('removeAll.occurrence.files.confirmation.message', "Replace {0} occurrence across {1} files with '{2}'?", occurrences, fileCount, replaceValue);
}
return nls.localize('replaceAll.occurrence.files.confirmation.message', "Replace {0} occurrence across {1} files?", occurrences, fileCount);
}
if (fileCount === 1) {
if (replaceValue) {
return nls.localize('removeAll.occurrences.file.confirmation.message', "Replace {0} occurrences across {1} file with '{2}'?", occurrences, fileCount, replaceValue);
}
return nls.localize('replaceAll.occurrences.file.confirmation.message', "Replace {0} occurrences across {1} file'?", occurrences, fileCount);
}
if (replaceValue) {
return nls.localize('removeAll.occurrences.files.confirmation.message', "Replace {0} occurrences across {1} files with '{2}'?", occurrences, fileCount, replaceValue);
}
return nls.localize('replaceAll.occurrences.files.confirmation.message', "Replace {0} occurrences across {1} files?", occurrences, fileCount);
}
private clearMessage(): Builder {
return this.messages.empty().show()
.asContainer().div({ 'class': 'message' })
.asContainer();
}
private createSearchResultsView(builder: Builder): void {
builder.div({ 'class': 'results' }, (div) => {
this.results = div;
this.results.addClass('show-file-icons');
let dataSource = new SearchDataSource();
let renderer = this.instantiationService.createInstance(SearchRenderer, this.getActionRunner(), this);
this.tree = new Tree(div.getHTMLElement(), {
dataSource: dataSource,
renderer: renderer,
sorter: new SearchSorter(),
filter: new SearchFilter(),
controller: new SearchController(this, this.instantiationService),
accessibilityProvider: this.instantiationService.createInstance(SearchAccessibilityProvider)
}, {
ariaLabel: nls.localize('treeAriaLabel', "Search Results"),
keyboardSupport: false
});
this.tree.setInput(this.viewModel.searchResult);
this.toUnbind.push(renderer);
this.toUnbind.push(this.listService.register(this.tree));
let focusToSelectionDelayHandle: number;
let lastFocusToSelection: number;
const focusToSelection = (originalEvent: KeyboardEvent | MouseEvent) => {
lastFocusToSelection = Date.now();
const focus = this.tree.getFocus();
let payload: any;
if (focus instanceof Match) {
payload = { origin: 'keyboard', originalEvent, preserveFocus: true };
}
this.tree.setSelection([focus], payload);
focusToSelectionDelayHandle = void 0;
};
this.toUnbind.push(this.tree.addListener2('focus', (event: any) => {
let keyboard = event.payload && event.payload.origin === 'keyboard';
if (keyboard) {
let originalEvent: KeyboardEvent | MouseEvent = event.payload && event.payload.originalEvent;
// debounce setting selection so that we are not too quickly opening
// when the user is pressing and holding the key to move focus
if (focusToSelectionDelayHandle || (Date.now() - lastFocusToSelection <= 75)) {
window.clearTimeout(focusToSelectionDelayHandle);
focusToSelectionDelayHandle = window.setTimeout(() => focusToSelection(originalEvent), 300);
} else {
focusToSelection(originalEvent);
}
}
}));
this.toUnbind.push(this.tree.addListener2('selection', (event: any) => {
let element: any;
let keyboard = event.payload && event.payload.origin === 'keyboard';
if (keyboard) {
element = this.tree.getFocus();
} else {
element = event.selection[0];
}
let originalEvent: KeyboardEvent | MouseEvent = event.payload && event.payload.originalEvent;
let doubleClick = (event.payload && event.payload.origin === 'mouse' && originalEvent && originalEvent.detail === 2);
if (doubleClick && originalEvent) {
originalEvent.preventDefault(); // focus moves to editor, we need to prevent default
}
let sideBySide = (originalEvent && (originalEvent.ctrlKey || originalEvent.metaKey));
let focusEditor = (keyboard && (!event.payload || !event.payload.preserveFocus)) || doubleClick;
if (element instanceof Match) {
let selectedMatch: Match = element;
if (this.currentSelectedFileMatch) {
this.currentSelectedFileMatch.setSelectedMatch(null);
}
this.currentSelectedFileMatch = selectedMatch.parent();
this.currentSelectedFileMatch.setSelectedMatch(selectedMatch);
if (!event.payload.preventEditorOpen) {
this.onFocus(selectedMatch, !focusEditor, sideBySide, doubleClick);
}
}
}));
});
}
private updateGlobalPatternExclusions(configuration: ISearchConfiguration): void {
if (this.inputPatternGlobalExclusionsContainer) {
let excludes = getExcludes(configuration);
if (excludes) {
let exclusions = Object.getOwnPropertyNames(excludes).filter(exclude => excludes[exclude] === true || typeof excludes[exclude].when === 'string').map(exclude => {
if (excludes[exclude] === true) {
return exclude;
}
return nls.localize('globLabel', "{0} when {1}", exclude, excludes[exclude].when);
});
if (exclusions.length) {
const values = exclusions.join(', ');
this.inputPatternGlobalExclusions.value = values;
this.inputPatternGlobalExclusions.inputElement.title = values;
this.inputPatternGlobalExclusionsContainer.show();
} else {
this.inputPatternGlobalExclusionsContainer.hide();
}
}
}
}
public selectCurrentMatch(): void {
const focused = this.tree.getFocus();
const eventPayload = { focusEditor: true };
this.tree.setSelection([focused], eventPayload);
}
public selectNextMatch(): void {
const [selected]: FileMatchOrMatch[] = this.tree.getSelection();
// Expand the initial selected node, if needed
if (selected instanceof FileMatch) {
if (!this.tree.isExpanded(selected)) {
this.tree.expand(selected);
}
}
let navigator = this.tree.getNavigator(selected, /*subTreeOnly=*/false);
let next = navigator.next();
if (!next) {
// Reached the end - get a new navigator from the root.
// .first and .last only work when subTreeOnly = true. Maybe there's a simpler way.
navigator = this.tree.getNavigator(this.tree.getInput(), /*subTreeOnly*/true);
next = navigator.first();
}
// Expand and go past FileMatch nodes
if (!(next instanceof Match)) {
if (!this.tree.isExpanded(next)) {
this.tree.expand(next);
}
// Select the FileMatch's first child
next = navigator.next();
}
// Reveal the newly selected element
const eventPayload = { preventEditorOpen: true };
this.tree.setFocus(next, eventPayload);
this.tree.setSelection([next], eventPayload);
this.tree.reveal(next);
this.selectCurrentMatchEmitter.fire();
}
public selectPreviousMatch(): void {
const [selected]: FileMatchOrMatch[] = this.tree.getSelection();
let navigator = this.tree.getNavigator(selected, /*subTreeOnly=*/false);
let prev = navigator.previous();
// Expand and go past FileMatch nodes
if (!(prev instanceof Match)) {
prev = navigator.previous();
if (!prev) {
// Wrap around. Get a new tree starting from the root
navigator = this.tree.getNavigator(this.tree.getInput(), /*subTreeOnly*/true);
prev = navigator.last();
// This is complicated because .last will set the navigator to the last FileMatch,
// so expand it and FF to its last child
this.tree.expand(prev);
let tmp;
while (tmp = navigator.next()) {
prev = tmp;
}
}
if (!(prev instanceof Match)) {
// There is a second non-Match result, which must be a collapsed FileMatch.
// Expand it then select its last child.
navigator.next();
this.tree.expand(prev);
prev = navigator.previous();
}
}
// Reveal the newly selected element
if (prev) {
const eventPayload = { preventEditorOpen: true };
this.tree.setFocus(prev, eventPayload);
this.tree.setSelection([prev], eventPayload);
this.tree.reveal(prev);
this.selectCurrentMatchEmitter.fire();
}
}
public setVisible(visible: boolean): TPromise<void> {
let promise: TPromise<void>;
this.viewletVisible.set(visible);
if (visible) {
promise = super.setVisible(visible);
this.tree.onVisible();
} else {
this.tree.onHidden();
promise = super.setVisible(visible);
}
// Enable highlights if there are searchresults
if (this.viewModel) {
this.viewModel.searchResult.toggleHighlights(visible);
}
// Open focused element from results in case the editor area is otherwise empty
if (visible && !this.editorService.getActiveEditor()) {
let focus = this.tree.getFocus();
if (focus) {
this.onFocus(focus, true);
}
}
return promise;
}
public focus(): void {
super.focus();
let selectedText = this.getSearchTextFromEditor();
if (selectedText) {
this.searchWidget.searchInput.setValue(selectedText);
}
this.searchWidget.focus();
}
public focusNextInputBox(): void {
if (this.searchWidget.searchInputHasFocus()) {
if (this.searchWidget.isReplaceShown()) {
this.searchWidget.focus(true, true);
} else {
this.moveFocusFromSearchOrReplace();
}
return;
}
if (this.searchWidget.replaceInputHasFocus()) {
this.moveFocusFromSearchOrReplace();
return;
}
if (this.inputPatternIncludes.inputHasFocus()) {
this.inputPatternExclusions.focus();
this.inputPatternExclusions.select();
return;
}
if (this.inputPatternExclusions.inputHasFocus()) {
this.selectTreeIfNotSelected();
return;
}
}
private moveFocusFromSearchOrReplace() {
if (this.showsFileTypes()) {
this.toggleFileTypes(true, this.showsFileTypes());
} else {
this.selectTreeIfNotSelected();
}
}
public focusPreviousInputBox(): void {
if (this.searchWidget.searchInputHasFocus()) {
return;
}
if (this.searchWidget.replaceInputHasFocus()) {
this.searchWidget.focus(true);
return;
}
if (this.inputPatternIncludes.inputHasFocus()) {
this.searchWidget.focus(true, true);
return;
}
if (this.inputPatternExclusions.inputHasFocus()) {
this.inputPatternIncludes.focus();
this.inputPatternIncludes.select();
return;
}
}
public moveFocusFromResults(): void {
if (this.showsFileTypes()) {
this.toggleFileTypes(true, true, false, true);
} else {
this.searchWidget.focus(true, true);
}
}
private reLayout(): void {
if (this.isDisposed) {
return;
}
this.searchWidget.setWidth(this.size.width - 25 /* container margin */);
this.inputPatternExclusions.setWidth(this.size.width - 28 /* container margin */);
this.inputPatternIncludes.setWidth(this.size.width - 28 /* container margin */);
this.inputPatternGlobalExclusions.width = this.size.width - 28 /* container margin */ - 24 /* actions */;
const messagesSize = this.messages.isHidden() ? 0 : dom.getTotalHeight(this.messages.getHTMLElement());
const searchResultContainerSize = this.size.height -
messagesSize -
dom.getTotalHeight(this.searchWidgetsContainer.getContainer());
this.results.style({ height: searchResultContainerSize + 'px' });
this.tree.layout(searchResultContainerSize);
}
public layout(dimension: Dimension): void {
this.size = dimension;
this.reLayout();
}
public getControl(): ITree {
return this.tree;
}
public clearSearchResults(): void {
this.viewModel.searchResult.clear();
this.showEmptyStage();
if (!this.contextService.hasWorkspace()) {
this.searchWithoutFolderMessage(this.clearMessage());
}
this.searchWidget.clear();
this.viewModel.cancelSearch();
}
public cancelSearch(): boolean {
if (this.viewModel.cancelSearch()) {
this.searchWidget.focus();
return true;
}
return false;
}
private selectTreeIfNotSelected(): void {
if (this.tree.getInput()) {
this.tree.DOMFocus();
let selection = this.tree.getSelection();
if (selection.length === 0) {
this.tree.focusNext();
}
}
}
private getSearchTextFromEditor(): string {
if (!this.editorService.getActiveEditor()) {
return null;
}
let editorControl: any = this.editorService.getActiveEditor().getControl();
if (!editorControl || !isFunction(editorControl.getEditorType) || editorControl.getEditorType() !== EditorType.ICodeEditor) { // Substitute for (editor instanceof ICodeEditor)
return null;
}
let range = editorControl.getSelection();
if (range && !range.isEmpty() && range.startLineNumber === range.endLineNumber) {
let searchText = editorControl.getModel().getLineContent(range.startLineNumber);
searchText = searchText.substring(range.startColumn - 1, range.endColumn - 1);
return searchText;
}
return null;
}
private showsFileTypes(): boolean {
return dom.hasClass(this.queryDetails, 'more');
}
public toggleCaseSensitive(): void {
this.searchWidget.searchInput.setCaseSensitive(!this.searchWidget.searchInput.getCaseSensitive());
this.onQueryChanged(true, true);
}
public toggleWholeWords(): void {
this.searchWidget.searchInput.setWholeWords(!this.searchWidget.searchInput.getWholeWords());
this.onQueryChanged(true, true);
}
public toggleRegex(): void {
this.searchWidget.searchInput.setRegex(!this.searchWidget.searchInput.getRegex());
this.onQueryChanged(true, true);
}
public toggleFileTypes(moveFocus?: boolean, show?: boolean, skipLayout?: boolean, reverse?: boolean): void {
let cls = 'more';
show = typeof show === 'undefined' ? !dom.hasClass(this.queryDetails, cls) : Boolean(show);
skipLayout = Boolean(skipLayout);
if (show) {
dom.addClass(this.queryDetails, cls);
if (moveFocus) {
if (reverse) {
this.inputPatternExclusions.focus();
this.inputPatternExclusions.select();
} else {
this.inputPatternIncludes.focus();
this.inputPatternIncludes.select();
}
}
} else {
dom.removeClass(this.queryDetails, cls);
if (moveFocus) {
this.searchWidget.focus();
}
}
if (!skipLayout && this.size) {
this.layout(this.size);
}
}
public searchInFolder(resource: URI): void {
const workspace = this.contextService.getWorkspace();
if (!workspace) {
return;
}
if (isEqual(workspace.resource.fsPath, resource.fsPath)) {
this.inputPatternIncludes.setValue('');
this.searchWidget.focus();
return;
}
if (!this.showsFileTypes()) {
this.toggleFileTypes(true, true);
}
const workspaceRelativePath = this.contextService.toWorkspaceRelativePath(resource);
if (workspaceRelativePath) {
this.inputPatternIncludes.setIsGlobPattern(false);
this.inputPatternIncludes.setValue(workspaceRelativePath);
this.searchWidget.focus(false);
}
}
public onQueryChanged(rerunQuery: boolean, preserveFocus?: boolean): void {
const isRegex = this.searchWidget.searchInput.getRegex();
const isWholeWords = this.searchWidget.searchInput.getWholeWords();
const isCaseSensitive = this.searchWidget.searchInput.getCaseSensitive();
const contentPattern = this.searchWidget.searchInput.getValue();
const patternExcludes = this.inputPatternExclusions.getValue().trim();
const exclusionsUsePattern = this.inputPatternExclusions.isGlobPattern();
const patternIncludes = this.inputPatternIncludes.getValue().trim();
const includesUsePattern = this.inputPatternIncludes.isGlobPattern();
const useIgnoreFiles = this.inputPatternExclusions.useIgnoreFiles();
// store memento
this.viewletSettings['query.contentPattern'] = contentPattern;
this.viewletSettings['query.regex'] = isRegex;
this.viewletSettings['query.wholeWords'] = isWholeWords;
this.viewletSettings['query.caseSensitive'] = isCaseSensitive;
this.viewletSettings['query.folderExclusions'] = patternExcludes;
this.viewletSettings['query.exclusionsUsePattern'] = exclusionsUsePattern;
this.viewletSettings['query.folderIncludes'] = patternIncludes;
this.viewletSettings['query.includesUsePattern'] = includesUsePattern;
this.viewletSettings['query.useIgnoreFiles'] = useIgnoreFiles;
if (!rerunQuery) {
return;
}
if (contentPattern.length === 0) {
return;
}
// Validate regex is OK
if (isRegex) {
let regExp: RegExp;
try {
regExp = new RegExp(contentPattern);
} catch (e) {
return; // malformed regex
}
if (strings.regExpLeadsToEndlessLoop(regExp)) {
return; // endless regex
}
}
let content = {
pattern: contentPattern,
isRegExp: isRegex,
isCaseSensitive: isCaseSensitive,
isWordMatch: isWholeWords
};
let excludes: IExpression = this.inputPatternExclusions.getGlob();
let includes: IExpression = this.inputPatternIncludes.getGlob();
let options: IQueryOptions = {
folderResources: this.contextService.hasWorkspace() ? [this.contextService.getWorkspace().resource] : [],
extraFileResources: getOutOfWorkspaceEditorResources(this.editorGroupService, this.contextService),
excludePattern: excludes,
maxResults: SearchViewlet.MAX_TEXT_RESULTS,
includePattern: includes,
useIgnoreFiles
};
this.onQueryTriggered(this.queryBuilder.text(content, options), patternExcludes, patternIncludes);
if (!preserveFocus) {
this.searchWidget.focus(false); // focus back to input field
}
}
private autoExpandFileMatch(fileMatch: FileMatch, alwaysExpandIfOneResult: boolean): void {
let length = fileMatch.matches().length;
if (length < 10 || (alwaysExpandIfOneResult && this.viewModel.searchResult.count() === 1 && length < 50)) {
this.tree.expand(fileMatch).done(null, errors.onUnexpectedError);
} else {
this.tree.collapse(fileMatch).done(null, errors.onUnexpectedError);
}
}
private onQueryTriggered(query: ISearchQuery, excludePattern: string, includePattern: string): void {
this.viewModel.cancelSearch();
// Progress total is 100.0% for more progress bar granularity
let progressTotal = 1000;
let progressWorked = 0;
let progressRunner = query.useRipgrep ?
this.progressService.show(/*infinite=*/true) :
this.progressService.show(progressTotal);
this.loading = true;
this.searchWidget.searchInput.clearMessage();
this.showEmptyStage();
let handledMatches: { [id: string]: boolean } = Object.create(null);
let autoExpand = (alwaysExpandIfOneResult: boolean) => {
// Auto-expand / collapse based on number of matches:
// - alwaysExpandIfOneResult: expand file results if we have just one file result and less than 50 matches on a file
// - expand file results if we have more than one file result and less than 10 matches on a file
let matches = this.viewModel.searchResult.matches();
matches.forEach((match) => {
if (handledMatches[match.id()]) {
return; // if we once handled a result, do not do it again to keep results stable (the user might have expanded/collapsed meanwhile)
}
handledMatches[match.id()] = true;
this.autoExpandFileMatch(match, alwaysExpandIfOneResult);
});
};
let isDone = false;
let onComplete = (completed?: ISearchComplete) => {
isDone = true;
// Complete up to 100% as needed
if (completed && !query.useRipgrep) {
progressRunner.worked(progressTotal - progressWorked);
setTimeout(() => progressRunner.done(), 200);
} else {
progressRunner.done();
}
this.onSearchResultsChanged().then(() => autoExpand(true));
this.viewModel.replaceString = this.searchWidget.getReplaceValue();
let hasResults = !this.viewModel.searchResult.isEmpty();
this.loading = false;
this.actionRegistry['refresh'].enabled = true;
this.actionRegistry['vs.tree.collapse'].enabled = hasResults;
this.actionRegistry['clearSearchResults'].enabled = hasResults;
if (completed && completed.limitHit) {
this.searchWidget.searchInput.showMessage({
content: nls.localize('searchMaxResultsWarning', "The result set only contains a subset of all matches. Please be more specific in your search to narrow down the results."),
type: MessageType.WARNING
});
}
if (!hasResults) {
let hasExcludes = !!excludePattern;
let hasIncludes = !!includePattern;
let message: string;
if (!completed) {
message = nls.localize('searchCanceled', "Search was canceled before any results could be found - ");
} else if (hasIncludes && hasExcludes) {
message = nls.localize('noResultsIncludesExcludes', "No results found in '{0}' excluding '{1}' - ", includePattern, excludePattern);
} else if (hasIncludes) {
message = nls.localize('noResultsIncludes', "No results found in '{0}' - ", includePattern);
} else if (hasExcludes) {
message = nls.localize('noResultsExcludes', "No results found excluding '{0}' - ", excludePattern);
} else {
message = nls.localize('noResultsFound', "No results found. Review your settings for configured exclusions - ");
}
// Indicate as status to ARIA
aria.status(message);
this.tree.onHidden();
this.results.hide();
const div = this.clearMessage();
const p = $(div).p({ text: message });
if (!completed) {
$(p).a({
'class': ['pointer', 'prominent'],
text: nls.localize('rerunSearch.message', "Search again")
}).on(dom.EventType.CLICK, (e: MouseEvent) => {
dom.EventHelper.stop(e, false);
this.onQueryChanged(true);
});
} else if (hasIncludes || hasExcludes) {
$(p).a({
'class': ['pointer', 'prominent'],
'tabindex': '0',
text: nls.localize('rerunSearchInAll.message', "Search again in all files")
}).on(dom.EventType.CLICK, (e: MouseEvent) => {
dom.EventHelper.stop(e, false);
this.inputPatternExclusions.setValue('');
this.inputPatternIncludes.setValue('');
this.onQueryChanged(true);
});
} else {
$(p).a({
'class': ['pointer', 'prominent'],
'tabindex': '0',
text: nls.localize('openSettings.message', "Open Settings")
}).on(dom.EventType.CLICK, (e: MouseEvent) => {
dom.EventHelper.stop(e, false);
if (this.contextService.hasWorkspace()) {
this.preferencesService.openWorkspaceSettings().done(() => null, errors.onUnexpectedError);
} else {
this.preferencesService.openGlobalSettings().done(() => null, errors.onUnexpectedError);
}
});
}
if (!this.contextService.hasWorkspace()) {
this.searchWithoutFolderMessage(div);
}
} else {
this.viewModel.searchResult.toggleHighlights(true); // show highlights
// Indicate final search result count for ARIA
aria.status(nls.localize('ariaSearchResultsStatus', "Search returned {0} results in {1} files", this.viewModel.searchResult.count(), this.viewModel.searchResult.fileCount()));
}
};
let onError = (e: any) => {
if (errors.isPromiseCanceledError(e)) {
onComplete(null);
} else {
this.loading = false;
isDone = true;
progressRunner.done();
this.messageService.show(2 /* ERROR */, e);
}
};
let total: number = 0;
let worked: number = 0;
let visibleMatches = 0;
let onProgress = (p: ISearchProgressItem) => {
// Progress
if (p.total) {
total = p.total;
}
if (p.worked) {
worked = p.worked;
}
};
// Handle UI updates in an interval to show frequent progress and results
let uiRefreshHandle = setInterval(() => {
if (isDone) {
window.clearInterval(uiRefreshHandle);
return;
}
if (!query.useRipgrep) {
// Progress bar update
let fakeProgress = true;
if (total > 0 && worked > 0) {
let ratio = Math.round((worked / total) * progressTotal);
if (ratio > progressWorked) { // never show less progress than what we have already
progressRunner.worked(ratio - progressWorked);
progressWorked = ratio;
fakeProgress = false;
}
}
// Fake progress up to 90%, or when actual progress beats it
const fakeMax = 900;
const fakeMultiplier = 12;
if (fakeProgress && progressWorked < fakeMax) {
// Linearly decrease the rate of fake progress.
// 1 is the smallest allowed amount of progress.
const fakeAmt = Math.round((fakeMax - progressWorked) / fakeMax * fakeMultiplier) || 1;
progressWorked += fakeAmt;
progressRunner.worked(fakeAmt);
}
}
// Search result tree update
const fileCount = this.viewModel.searchResult.fileCount();
if (visibleMatches !== fileCount) {
visibleMatches = fileCount;
this.tree.refresh().then(() => {
autoExpand(false);
}).done(null, errors.onUnexpectedError);
this.updateSearchResultCount();
}
if (fileCount > 0) {
// since we have results now, enable some actions
if (!this.actionRegistry['vs.tree.collapse'].enabled) {
this.actionRegistry['vs.tree.collapse'].enabled = true;
}
}
}, 100);
this.searchWidget.setReplaceAllActionState(false);
// this.replaceService.disposeAllReplacePreviews();
this.viewModel.search(query).done(onComplete, onError, query.useRipgrep ? undefined : onProgress);
}
private updateSearchResultCount(): void {
const fileCount = this.viewModel.searchResult.fileCount();
const msgWasHidden = this.messages.isHidden();
if (fileCount > 0) {
const div = this.clearMessage();
$(div).p({ text: this.buildResultCountMessage(this.viewModel.searchResult.count(), fileCount) });
if (msgWasHidden) {
this.reLayout();
}
} else if (!msgWasHidden) {
this.messages.hide();
}
}
private buildResultCountMessage(resultCount: number, fileCount: number): string {
if (resultCount === 1 && fileCount === 1) {
return nls.localize('search.file.result', "{0} result in {1} file", resultCount, fileCount);
} else if (resultCount === 1) {
return nls.localize('search.files.result', "{0} result in {1} files", resultCount, fileCount);
} else if (fileCount === 1) {
return nls.localize('search.file.results', "{0} results in {1} file", resultCount, fileCount);
} else {
return nls.localize('search.files.results', "{0} results in {1} files", resultCount, fileCount);
}
}
private searchWithoutFolderMessage(div: Builder): void {
$(div).p({ text: nls.localize('searchWithoutFolder', "You have not yet opened a folder. Only open files are currently searched - ") })
.asContainer().a({
'class': ['pointer', 'prominent'],
'tabindex': '0',
text: nls.localize('openFolder', "Open Folder")
}).on(dom.EventType.CLICK, (e: MouseEvent) => {
dom.EventHelper.stop(e, false);
const actionClass = env.isMacintosh ? OpenFileFolderAction : OpenFolderAction;
const action = this.instantiationService.createInstance<string, string, IAction>(actionClass, actionClass.ID, actionClass.LABEL);
this.actionRunner.run(action).done(() => {
action.dispose();
}, err => {
action.dispose();
errors.onUnexpectedError(err);
});
});
}
private showEmptyStage(): void {
// disable 'result'-actions
this.actionRegistry['refresh'].enabled = false;
this.actionRegistry['vs.tree.collapse'].enabled = false;
this.actionRegistry['clearSearchResults'].enabled = false;
// clean up ui
// this.replaceService.disposeAllReplacePreviews();
this.messages.hide();
this.results.show();
this.tree.onVisible();
this.currentSelectedFileMatch = null;
}
private onFocus(lineMatch: any, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): TPromise<any> {
if (!(lineMatch instanceof Match)) {
this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange();
return TPromise.as(true);
}
this.telemetryService.publicLog('searchResultChosen');
return (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) ?
this.replaceService.openReplacePreview(lineMatch, preserveFocus, sideBySide, pinned) :
this.open(lineMatch, preserveFocus, sideBySide, pinned);
}
public open(element: FileMatchOrMatch, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): TPromise<any> {
let selection = this.getSelectionFrom(element);
let resource = element instanceof Match ? element.parent().resource() : (<FileMatch>element).resource();
return this.editorService.openEditor({
resource: resource,
options: {
preserveFocus,
pinned,
selection,
revealIfVisible: !sideBySide
}
}, sideBySide).then(editor => {
if (editor && element instanceof Match && preserveFocus) {
this.viewModel.searchResult.rangeHighlightDecorations.highlightRange({
resource,
range: element.range()
}, <ICommonCodeEditor>editor.getControl());
} else {
this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange();
}
}, errors.onUnexpectedError);
}
private getSelectionFrom(element: FileMatchOrMatch): any {
let match: Match = null;
if (element instanceof Match) {
match = element;
}
if (element instanceof FileMatch && element.count() > 0) {
match = element.matches()[element.matches().length - 1];
}
if (match) {
let range = match.range();
if (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) {
let replaceString = match.replaceString;
return {
startLineNumber: range.startLineNumber,
startColumn: range.startColumn,
endLineNumber: range.startLineNumber,
endColumn: range.startColumn + replaceString.length
};
}
return range;
}
return void 0;
}
private onUntitledDidChangeDirty(resource: URI): void {
if (!this.viewModel) {
return;
}
// remove search results from this resource as it got disposed
if (!this.untitledEditorService.isDirty(resource)) {
let matches = this.viewModel.searchResult.matches();
for (let i = 0, len = matches.length; i < len; i++) {
if (resource.toString() === matches[i].resource().toString()) {
this.viewModel.searchResult.remove(matches[i]);
}
}
}
}
private onFilesChanged(e: FileChangesEvent): void {
if (!this.viewModel) {
return;
}
let matches = this.viewModel.searchResult.matches();
for (let i = 0, len = matches.length; i < len; i++) {
if (e.contains(matches[i].resource(), FileChangeType.DELETED)) {
this.viewModel.searchResult.remove(matches[i]);
}
}
}
public getActions(): IAction[] {
return [
this.actionRegistry['refresh'],
this.actionRegistry['vs.tree.collapse'],
this.actionRegistry['clearSearchResults']
];
}
public dispose(): void {
this.isDisposed = true;
this.toDispose = lifecycle.dispose(this.toDispose);
if (this.tree) {
this.tree.dispose();
}
this.searchWidget.dispose();
this.inputPatternIncludes.dispose();
this.inputPatternExclusions.dispose();
this.viewModel.dispose();
super.dispose();
}
}
registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => {
let matchHighlightColor = theme.getColor(editorFindMatchHighlight);
if (matchHighlightColor) {
collector.addRule(`.search-viewlet .findInFileMatch { background-color: ${matchHighlightColor}; }`);
collector.addRule(`.search-viewlet .highlight { background-color: ${matchHighlightColor}; }`);
}
}); | src/vs/workbench/parts/search/browser/searchViewlet.ts | 1 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.9980754852294922,
0.022306861355900764,
0.00016193752526305616,
0.00017312169075012207,
0.14444240927696228
] |
{
"id": 12,
"code_window": [
"\t\t\t} else {\n",
"\t\t\t\tprogressRunner.done();\n",
"\t\t\t}\n",
"\n",
"\t\t\tthis.onSearchResultsChanged().then(() => autoExpand(true));\n",
"\t\t\tthis.viewModel.replaceString = this.searchWidget.getReplaceValue();\n",
"\n",
"\t\t\tlet hasResults = !this.viewModel.searchResult.isEmpty();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t// Do final render, then expand if just 1 file with less than 50 matches\n",
"\t\t\tthis.onSearchResultsChanged().then(() => {\n",
"\t\t\t\tif (this.viewModel.searchResult.count() === 1) {\n",
"\t\t\t\t\tconst onlyMatch = this.viewModel.searchResult.matches()[0];\n",
"\t\t\t\t\tif (onlyMatch.count() < 50) {\n",
"\t\t\t\t\t\treturn this.tree.expand(onlyMatch);\n",
"\t\t\t\t\t}\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\treturn null;\n",
"\t\t\t}).done(null, errors.onUnexpectedError);\n",
"\n"
],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 1027
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"httpConfigurationTitle": "HTTP",
"proxy": "Die zu verwendende Proxyeinstellung. Wenn diese Option nicht festgelegt wird, wird der Wert aus den Umgebungsvariablen \"http_proxy\" und \"https_proxy\" übernommen.",
"proxyAuthorization": "Der Wert, der als Proxy-Authorization-Header für jede Netzwerkanforderung gesendet werden soll.",
"strictSSL": "Gibt an, ob das Proxyserverzertifikat anhand der Liste der bereitgestellten Zertifizierungsstellen überprüft werden soll."
} | i18n/deu/src/vs/platform/request/node/request.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.00017636567645240575,
0.00017295140423811972,
0.00016953711747191846,
0.00017295140423811972,
0.0000034142794902436435
] |
{
"id": 12,
"code_window": [
"\t\t\t} else {\n",
"\t\t\t\tprogressRunner.done();\n",
"\t\t\t}\n",
"\n",
"\t\t\tthis.onSearchResultsChanged().then(() => autoExpand(true));\n",
"\t\t\tthis.viewModel.replaceString = this.searchWidget.getReplaceValue();\n",
"\n",
"\t\t\tlet hasResults = !this.viewModel.searchResult.isEmpty();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t// Do final render, then expand if just 1 file with less than 50 matches\n",
"\t\t\tthis.onSearchResultsChanged().then(() => {\n",
"\t\t\t\tif (this.viewModel.searchResult.count() === 1) {\n",
"\t\t\t\t\tconst onlyMatch = this.viewModel.searchResult.matches()[0];\n",
"\t\t\t\t\tif (onlyMatch.count() < 50) {\n",
"\t\t\t\t\t\treturn this.tree.expand(onlyMatch);\n",
"\t\t\t\t\t}\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\treturn null;\n",
"\t\t\t}).done(null, errors.onUnexpectedError);\n",
"\n"
],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 1027
} | <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><style>.icon-canvas-transparent{opacity:0;fill:#2d2d30}.icon-vs-out{fill:#2d2d30}.icon-vs-bg{fill:#c5c5c5}.icon-vs-fg{fill:#2b282e}</style><path class="icon-canvas-transparent" d="M16 16H0V0h16v16z" id="canvas"/><path class="icon-vs-out" d="M16 15H0V1h16v14z" id="outline" style="display: none;"/><path class="icon-vs-bg" d="M1 2v12h14V2H1zm13 11H2v-3h12v3zm0-5H2V5h12v3z" id="iconBg"/><g id="iconFg" style="display: none;"><path class="icon-vs-fg" d="M14 8H2V5h12v3zm0 2H2v3h12v-3z"/></g></svg> | src/vs/workbench/browser/parts/editor/media/split-editor-horizontal-inverse.svg | 0 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.0001712591911200434,
0.0001712591911200434,
0.0001712591911200434,
0.0001712591911200434,
0
] |
{
"id": 12,
"code_window": [
"\t\t\t} else {\n",
"\t\t\t\tprogressRunner.done();\n",
"\t\t\t}\n",
"\n",
"\t\t\tthis.onSearchResultsChanged().then(() => autoExpand(true));\n",
"\t\t\tthis.viewModel.replaceString = this.searchWidget.getReplaceValue();\n",
"\n",
"\t\t\tlet hasResults = !this.viewModel.searchResult.isEmpty();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t// Do final render, then expand if just 1 file with less than 50 matches\n",
"\t\t\tthis.onSearchResultsChanged().then(() => {\n",
"\t\t\t\tif (this.viewModel.searchResult.count() === 1) {\n",
"\t\t\t\t\tconst onlyMatch = this.viewModel.searchResult.matches()[0];\n",
"\t\t\t\t\tif (onlyMatch.count() < 50) {\n",
"\t\t\t\t\t\treturn this.tree.expand(onlyMatch);\n",
"\t\t\t\t\t}\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\treturn null;\n",
"\t\t\t}).done(null, errors.onUnexpectedError);\n",
"\n"
],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 1027
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"vscode.extension.contributes.grammars": "textmate 토크나이저를 적용합니다.",
"vscode.extension.contributes.grammars.embeddedLanguages": "이 문법에 포함된 언어가 있는 경우 언어 ID에 대한 범위 이름의 맵입니다.",
"vscode.extension.contributes.grammars.injectTo": "이 문법이 삽입되는 언어 범위 이름 목록입니다.",
"vscode.extension.contributes.grammars.language": "이 구문이 적용되는 언어 식별자입니다.",
"vscode.extension.contributes.grammars.path": "tmLanguage 파일의 경로입니다. 확장 폴더의 상대 경로이며 일반적으로 './syntaxes/'로 시작합니다.",
"vscode.extension.contributes.grammars.scopeName": "tmLanguage 파일에 사용되는 Textmate 범위 이름입니다."
} | i18n/kor/src/vs/editor/node/textMate/TMGrammars.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.00016989701543934643,
0.00016967480769380927,
0.00016945258539635688,
0.00016967480769380927,
2.22215021494776e-7
] |
{
"id": 13,
"code_window": [
"\n",
"\t\t\t// Search result tree update\n",
"\t\t\tconst fileCount = this.viewModel.searchResult.fileCount();\n",
"\t\t\tif (visibleMatches !== fileCount) {\n",
"\t\t\t\tvisibleMatches = fileCount;\n",
"\t\t\t\tthis.tree.refresh().then(() => {\n",
"\t\t\t\t\tautoExpand(false);\n",
"\t\t\t\t}).done(null, errors.onUnexpectedError);\n",
"\n",
"\t\t\t\tthis.updateSearchResultCount();\n",
"\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tthis.tree.refresh().done(null, errors.onUnexpectedError);\n"
],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 1177
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import nls = require('vs/nls');
import strings = require('vs/base/common/strings');
import platform = require('vs/base/common/platform');
import errors = require('vs/base/common/errors');
import paths = require('vs/base/common/paths');
import dom = require('vs/base/browser/dom');
import { $ } from 'vs/base/browser/builder';
import { TPromise } from 'vs/base/common/winjs.base';
import { IAction, IActionRunner } from 'vs/base/common/actions';
import { ActionsRenderer } from 'vs/base/parts/tree/browser/actionsRenderer';
import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge';
import { FileLabel } from 'vs/workbench/browser/labels';
import { LeftRightWidget, IRenderer } from 'vs/base/browser/ui/leftRightWidget/leftRightWidget';
import { ITree, IElementCallback, IDataSource, ISorter, IAccessibilityProvider, IFilter } from 'vs/base/parts/tree/browser/tree';
import { ClickBehavior, DefaultController } from 'vs/base/parts/tree/browser/treeDefaults';
import { ContributableActionProvider } from 'vs/workbench/browser/actionBarRegistry';
import { Match, SearchResult, FileMatch, FileMatchOrMatch, SearchModel } from 'vs/workbench/parts/search/common/searchModel';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { Range } from 'vs/editor/common/core/range';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { SearchViewlet } from 'vs/workbench/parts/search/browser/searchViewlet';
import { RemoveAction, ReplaceAllAction, ReplaceAction } from 'vs/workbench/parts/search/browser/searchActions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
export class SearchDataSource implements IDataSource {
public getId(tree: ITree, element: any): string {
if (element instanceof FileMatch) {
return element.id();
}
if (element instanceof Match) {
return element.id();
}
return 'root';
}
public getChildren(tree: ITree, element: any): TPromise<any[]> {
let value: any[] = [];
if (element instanceof FileMatch) {
value = element.matches();
} else if (element instanceof SearchResult) {
value = element.matches();
}
return TPromise.as(value);
}
public hasChildren(tree: ITree, element: any): boolean {
return element instanceof FileMatch || element instanceof SearchResult;
}
public getParent(tree: ITree, element: any): TPromise<any> {
let value: any = null;
if (element instanceof Match) {
value = element.parent();
} else if (element instanceof FileMatch) {
value = element.parent();
}
return TPromise.as(value);
}
}
export class SearchSorter implements ISorter {
public compare(tree: ITree, elementA: FileMatchOrMatch, elementB: FileMatchOrMatch): number {
if (elementA instanceof FileMatch && elementB instanceof FileMatch) {
return elementA.resource().fsPath.localeCompare(elementB.resource().fsPath) || elementA.name().localeCompare(elementB.name());
}
if (elementA instanceof Match && elementB instanceof Match) {
return Range.compareRangesUsingStarts(elementA.range(), elementB.range());
}
return undefined;
}
}
class SearchActionProvider extends ContributableActionProvider {
constructor(private viewlet: SearchViewlet, @IInstantiationService private instantiationService: IInstantiationService) {
super();
}
public hasActions(tree: ITree, element: any): boolean {
let input = <SearchResult>tree.getInput();
return element instanceof FileMatch || (input.searchModel.isReplaceActive() || element instanceof Match) || super.hasActions(tree, element);
}
public getActions(tree: ITree, element: any): TPromise<IAction[]> {
return super.getActions(tree, element).then(actions => {
let input = <SearchResult>tree.getInput();
if (element instanceof FileMatch) {
actions.unshift(new RemoveAction(tree, element));
if (input.searchModel.isReplaceActive() && element.count() > 0) {
actions.unshift(this.instantiationService.createInstance(ReplaceAllAction, tree, element, this.viewlet));
}
}
if (element instanceof Match) {
if (input.searchModel.isReplaceActive()) {
actions.unshift(this.instantiationService.createInstance(ReplaceAction, tree, element, this.viewlet), new RemoveAction(tree, element));
}
}
return actions;
});
}
}
export class SearchRenderer extends ActionsRenderer {
constructor(actionRunner: IActionRunner, viewlet: SearchViewlet, @IWorkspaceContextService private contextService: IWorkspaceContextService,
@IInstantiationService private instantiationService: IInstantiationService) {
super({
actionProvider: instantiationService.createInstance(SearchActionProvider, viewlet),
actionRunner: actionRunner
});
}
public getContentHeight(tree: ITree, element: any): number {
return 22;
}
public renderContents(tree: ITree, element: FileMatchOrMatch, domElement: HTMLElement, previousCleanupFn: IElementCallback): IElementCallback {
// File
if (element instanceof FileMatch) {
let fileMatch = <FileMatch>element;
let container = $('.filematch');
let leftRenderer: IRenderer;
let rightRenderer: IRenderer;
let widget: LeftRightWidget;
leftRenderer = (left: HTMLElement): any => {
const label = this.instantiationService.createInstance(FileLabel, left, void 0);
label.setFile(fileMatch.resource());
return () => label.dispose();
};
rightRenderer = (right: HTMLElement) => {
let len = fileMatch.count();
new CountBadge(right, len, len > 1 ? nls.localize('searchMatches', "{0} matches found", len) : nls.localize('searchMatch', "{0} match found", len));
return null;
};
widget = new LeftRightWidget(container, leftRenderer, rightRenderer);
container.appendTo(domElement);
return widget.dispose.bind(widget);
}
// Match
else if (element instanceof Match) {
dom.addClass(domElement, 'linematch');
let match = <Match>element;
let elements: string[] = [];
let preview = match.preview();
elements.push('<span>');
elements.push(strings.escape(preview.before));
let searchModel: SearchModel = (<SearchResult>tree.getInput()).searchModel;
let showReplaceText = searchModel.isReplaceActive() && !!searchModel.replaceString;
elements.push('</span><span class="' + (showReplaceText ? 'replace ' : '') + 'findInFileMatch">');
elements.push(strings.escape(preview.inside));
if (showReplaceText) {
elements.push('</span><span class="replaceMatch">');
elements.push(strings.escape(match.replaceString));
}
elements.push('</span><span>');
elements.push(strings.escape(preview.after));
elements.push('</span>');
$('a.plain')
.innerHtml(elements.join(strings.empty))
.title((preview.before + (showReplaceText ? match.replaceString : preview.inside) + preview.after).trim().substr(0, 999))
.appendTo(domElement);
}
return null;
}
}
export class SearchAccessibilityProvider implements IAccessibilityProvider {
constructor( @IWorkspaceContextService private contextService: IWorkspaceContextService) {
}
public getAriaLabel(tree: ITree, element: FileMatchOrMatch): string {
if (element instanceof FileMatch) {
const path = this.contextService.toWorkspaceRelativePath(element.resource()) || element.resource().fsPath;
return nls.localize('fileMatchAriaLabel', "{0} matches in file {1} of folder {2}, Search result", element.count(), element.name(), paths.dirname(path));
}
if (element instanceof Match) {
let match = <Match>element;
let input = <SearchResult>tree.getInput();
if (input.searchModel.isReplaceActive()) {
let preview = match.preview();
return nls.localize('replacePreviewResultAria', "Replace preview result, {0}", preview.before + match.replaceString + preview.after);
}
return nls.localize('searchResultAria', "{0}, Search result", match.text());
}
return undefined;
}
}
export class SearchController extends DefaultController {
constructor(private viewlet: SearchViewlet, @IInstantiationService private instantiationService: IInstantiationService) {
super({ clickBehavior: ClickBehavior.ON_MOUSE_DOWN, keyboardSupport: false });
// TODO@Rob these should be commands
// Up (from results to inputs)
this.downKeyBindingDispatcher.set(KeyCode.UpArrow, this.onUp.bind(this));
// Open to side
this.upKeyBindingDispatcher.set(platform.isMacintosh ? KeyMod.WinCtrl | KeyCode.Enter : KeyMod.CtrlCmd | KeyCode.Enter, this.onEnter.bind(this));
// Delete
this.downKeyBindingDispatcher.set(platform.isMacintosh ? KeyMod.CtrlCmd | KeyCode.Backspace : KeyCode.Delete, (tree: ITree, event: any) => { this.onDelete(tree, event); });
// Cancel search
this.downKeyBindingDispatcher.set(KeyCode.Escape, (tree: ITree, event: any) => { this.onEscape(tree, event); });
// Replace / Replace All
this.downKeyBindingDispatcher.set(ReplaceAllAction.KEY_BINDING, (tree: ITree, event: any) => { this.onReplaceAll(tree, event); });
this.downKeyBindingDispatcher.set(ReplaceAction.KEY_BINDING, (tree: ITree, event: any) => { this.onReplace(tree, event); });
}
protected onEscape(tree: ITree, event: IKeyboardEvent): boolean {
if (this.viewlet.cancelSearch()) {
return true;
}
return super.onEscape(tree, event);
}
private onDelete(tree: ITree, event: IKeyboardEvent): boolean {
let input = <SearchResult>tree.getInput();
let result = false;
let element = tree.getFocus();
if (element instanceof FileMatch ||
(element instanceof Match && input.searchModel.isReplaceActive())) {
new RemoveAction(tree, element).run().done(null, errors.onUnexpectedError);
result = true;
}
return result;
}
private onReplace(tree: ITree, event: IKeyboardEvent): boolean {
let input = <SearchResult>tree.getInput();
let result = false;
let element = tree.getFocus();
if (element instanceof Match && input.searchModel.isReplaceActive()) {
this.instantiationService.createInstance(ReplaceAction, tree, element, this.viewlet).run().done(null, errors.onUnexpectedError);
result = true;
}
return result;
}
private onReplaceAll(tree: ITree, event: IKeyboardEvent): boolean {
let result = false;
let element = tree.getFocus();
if (element instanceof FileMatch && element.count() > 0) {
this.instantiationService.createInstance(ReplaceAllAction, tree, element, this.viewlet).run().done(null, errors.onUnexpectedError);
result = true;
}
return result;
}
protected onUp(tree: ITree, event: IKeyboardEvent): boolean {
if (tree.getNavigator().first() === tree.getFocus()) {
this.viewlet.moveFocusFromResults();
return true;
}
return false;
}
}
export class SearchFilter implements IFilter {
public isVisible(tree: ITree, element: any): boolean {
return !(element instanceof FileMatch) || element.matches().length > 0;
}
} | src/vs/workbench/parts/search/browser/searchResultsView.ts | 1 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.003827260807156563,
0.00044449957204051316,
0.0001636858651181683,
0.00018694790196605027,
0.0007391984690912068
] |
{
"id": 13,
"code_window": [
"\n",
"\t\t\t// Search result tree update\n",
"\t\t\tconst fileCount = this.viewModel.searchResult.fileCount();\n",
"\t\t\tif (visibleMatches !== fileCount) {\n",
"\t\t\t\tvisibleMatches = fileCount;\n",
"\t\t\t\tthis.tree.refresh().then(() => {\n",
"\t\t\t\t\tautoExpand(false);\n",
"\t\t\t\t}).done(null, errors.onUnexpectedError);\n",
"\n",
"\t\t\t\tthis.updateSearchResultCount();\n",
"\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tthis.tree.refresh().done(null, errors.onUnexpectedError);\n"
],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 1177
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"welcomePage.atom": "Atom",
"welcomePage.atomCurrent": "Atom (目前)",
"welcomePage.cloneGitRepository": "複製 Git 存放庫...",
"welcomePage.colorTheme": "彩色佈景主題",
"welcomePage.colorThemeDescription": "將編輯器及您的程式碼設定成您喜愛的外觀",
"welcomePage.configureSettings": "組態設定",
"welcomePage.configureSettingsDescription": "微調設定就能發揮 VS Code 的所有功能",
"welcomePage.editingEvolved": "編輯進化了",
"welcomePage.gitHubRepository": "GitHub 存放庫",
"welcomePage.help": "說明",
"welcomePage.installKeymap": "安裝鍵盤快速鍵 {0}、{1}、{2} 及 {3}",
"welcomePage.installKeymapDescription": "安裝鍵盤快速鍵",
"welcomePage.interactivePlayground": "Interactive Playground",
"welcomePage.interactivePlaygroundDescription": "嘗試使用逐步解說短片中的一些基本編輯器功能",
"welcomePage.interfaceOverview": "介面概觀",
"welcomePage.interfaceOverviewDescription": "使用視覺覆疊效果強調顯示 UI 的主要元件",
"welcomePage.introductoryVideos": "簡介影片",
"welcomePage.keybindingsReference": "鍵盤快速鍵參考",
"welcomePage.keybindingsReferenceDescription": "可列印的 PDF,附有最常用的鍵盤快速鍵",
"welcomePage.newFile": "新增檔案",
"welcomePage.noRecentFolders": "沒有最近使用的資料夾",
"welcomePage.openFolder": "開啟資料夾...",
"welcomePage.others": "其他",
"welcomePage.productDocumentation": "產品文件",
"welcomePage.quickLinks": "快速連結",
"welcomePage.recent": "最近使用",
"welcomePage.showCommands": "尋找並執行所有命令",
"welcomePage.showCommandsDescription": "從控制台快速存取及搜尋命令 ({0})",
"welcomePage.showOnStartup": "啟動時顯示歡迎頁面",
"welcomePage.stackOverflow": "堆疊溢位",
"welcomePage.start": "開始",
"welcomePage.sublime": "壯麗",
"welcomePage.sublimeCurrent": "壯麗 (目前)",
"welcomePage.vim": "活力",
"welcomePage.vimCurrent": "活力 (目前)",
"welcomePage.vscode": "Visual Studio Code"
} | i18n/cht/src/vs/workbench/parts/welcome/page/electron-browser/vs_code_welcome_page.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.0001764677872415632,
0.0001723525783745572,
0.00016476023301947862,
0.0001734855759423226,
0.000004021399945486337
] |
{
"id": 13,
"code_window": [
"\n",
"\t\t\t// Search result tree update\n",
"\t\t\tconst fileCount = this.viewModel.searchResult.fileCount();\n",
"\t\t\tif (visibleMatches !== fileCount) {\n",
"\t\t\t\tvisibleMatches = fileCount;\n",
"\t\t\t\tthis.tree.refresh().then(() => {\n",
"\t\t\t\t\tautoExpand(false);\n",
"\t\t\t\t}).done(null, errors.onUnexpectedError);\n",
"\n",
"\t\t\t\tthis.updateSearchResultCount();\n",
"\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tthis.tree.refresh().done(null, errors.onUnexpectedError);\n"
],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 1177
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"dirtyFiles": "{0}개의 저장되지 않은 파일"
} | i18n/kor/src/vs/workbench/parts/files/browser/fileTracker.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.00017465405107941478,
0.00017465405107941478,
0.00017465405107941478,
0.00017465405107941478,
0
] |
{
"id": 13,
"code_window": [
"\n",
"\t\t\t// Search result tree update\n",
"\t\t\tconst fileCount = this.viewModel.searchResult.fileCount();\n",
"\t\t\tif (visibleMatches !== fileCount) {\n",
"\t\t\t\tvisibleMatches = fileCount;\n",
"\t\t\t\tthis.tree.refresh().then(() => {\n",
"\t\t\t\t\tautoExpand(false);\n",
"\t\t\t\t}).done(null, errors.onUnexpectedError);\n",
"\n",
"\t\t\t\tthis.updateSearchResultCount();\n",
"\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tthis.tree.refresh().done(null, errors.onUnexpectedError);\n"
],
"file_path": "src/vs/workbench/parts/search/browser/searchViewlet.ts",
"type": "replace",
"edit_start_line_idx": 1177
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"ariaCurrentSuggestion": "{0}, предложение",
"ariaCurrentSuggestionWithDetails": "{0}, предложение, содержит данные",
"goback": "Вернуться",
"readMore": "Подробнее...{0}",
"suggestWidget.loading": "Загрузка...",
"suggestWidget.noSuggestions": "Предложения отсутствуют.",
"suggestionAriaAccepted": "{0}, принято",
"suggestionAriaLabel": "{0}, предложение",
"suggestionWithDetailsAriaLabel": "{0}, предложение, содержит данные"
} | i18n/rus/src/vs/editor/contrib/suggest/browser/suggestWidget.i18n.json | 0 | https://github.com/microsoft/vscode/commit/5b6dfc0293aaafd998cf5f70670385d5433b7154 | [
0.00017487835430074483,
0.00017325014050584286,
0.0001716219267109409,
0.00017325014050584286,
0.000001628213794901967
] |
{
"id": 0,
"code_window": [
"import {ConnectionBackend, Connection} from '../interfaces';\n",
"import {ReadyStates, RequestMethods} from '../enums';\n",
"import {Request} from '../static_request';\n",
"import {Response} from '../static_response';\n",
"import {ResponseOptions, BaseResponseOptions} from '../base_response_options';\n",
"import {Injectable} from 'angular2/angular2';\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {ReadyStates, RequestMethods, ResponseTypes} from '../enums';\n"
],
"file_path": "modules/angular2/src/http/backends/jsonp_backend.ts",
"type": "replace",
"edit_start_line_idx": 1
} | import {
AsyncTestCompleter,
afterEach,
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xit,
SpyObject
} from 'angular2/testing_internal';
import {ObservableWrapper} from 'angular2/src/core/facade/async';
import {BrowserJsonp} from 'angular2/src/http/backends/browser_jsonp';
import {
JSONPConnection,
JSONPConnection_,
JSONPBackend,
JSONPBackend_
} from 'angular2/src/http/backends/jsonp_backend';
import {provide, Injector} from 'angular2/core';
import {isPresent, StringWrapper} from 'angular2/src/core/facade/lang';
import {TimerWrapper} from 'angular2/src/core/facade/async';
import {Request} from 'angular2/src/http/static_request';
import {Response} from 'angular2/src/http/static_response';
import {Map} from 'angular2/src/core/facade/collection';
import {RequestOptions, BaseRequestOptions} from 'angular2/src/http/base_request_options';
import {BaseResponseOptions, ResponseOptions} from 'angular2/src/http/base_response_options';
import {ResponseTypes, ReadyStates, RequestMethods} from 'angular2/src/http/enums';
var addEventListenerSpy;
var existingScripts = [];
var unused: Response;
class MockBrowserJsonp extends BrowserJsonp {
src: string;
callbacks = new Map<string, (data: any) => any>();
constructor() { super(); }
addEventListener(type: string, cb: (data: any) => any) { this.callbacks.set(type, cb); }
removeEventListener(type: string, cb: Function) { this.callbacks.delete(type); }
dispatchEvent(type: string, argument?: any) {
if (!isPresent(argument)) {
argument = {};
}
let cb = this.callbacks.get(type);
if (isPresent(cb)) {
cb(argument);
}
}
build(url: string) {
var script = new MockBrowserJsonp();
script.src = url;
existingScripts.push(script);
return script;
}
send(node: any) { /* noop */
}
cleanup(node: any) { /* noop */
}
}
export function main() {
describe('JSONPBackend', () => {
let backend;
let sampleRequest;
beforeEach(() => {
let injector = Injector.resolveAndCreate([
provide(ResponseOptions, {useClass: BaseResponseOptions}),
provide(BrowserJsonp, {useClass: MockBrowserJsonp}),
provide(JSONPBackend, {useClass: JSONPBackend_})
]);
backend = injector.get(JSONPBackend);
let base = new BaseRequestOptions();
sampleRequest = new Request(base.merge(new RequestOptions({url: 'https://google.com'})));
});
afterEach(() => { existingScripts = []; });
it('should create a connection', () => {
var instance;
expect(() => instance = backend.createConnection(sampleRequest)).not.toThrow();
expect(instance).toBeAnInstanceOf(JSONPConnection);
});
describe('JSONPConnection', () => {
it('should use the injected BaseResponseOptions to create the response',
inject([AsyncTestCompleter], async => {
let connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp(),
new ResponseOptions({type: ResponseTypes.Error}));
connection.response.subscribe(res => {
expect(res.type).toBe(ResponseTypes.Error);
async.done();
});
connection.finished();
existingScripts[0].dispatchEvent('load');
}));
it('should ignore load/callback when disposed', inject([AsyncTestCompleter], async => {
var connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp());
let spy = new SpyObject();
let loadSpy = spy.spy('load');
let errorSpy = spy.spy('error');
let returnSpy = spy.spy('cancelled');
let request = connection.response.subscribe(loadSpy, errorSpy, returnSpy);
request.unsubscribe();
connection.finished('Fake data');
existingScripts[0].dispatchEvent('load');
TimerWrapper.setTimeout(() => {
expect(connection.readyState).toBe(ReadyStates.Cancelled);
expect(loadSpy).not.toHaveBeenCalled();
expect(errorSpy).not.toHaveBeenCalled();
expect(returnSpy).not.toHaveBeenCalled();
async.done();
}, 10);
}));
it('should report error if loaded without invoking callback',
inject([AsyncTestCompleter], async => {
let connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp());
connection.response.subscribe(
res => {
expect("response listener called").toBe(false);
async.done();
},
err => {
expect(StringWrapper.contains(err.message, 'did not invoke callback')).toBe(true);
async.done();
});
existingScripts[0].dispatchEvent('load');
}));
it('should report error if script contains error', inject([AsyncTestCompleter], async => {
let connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp());
connection.response.subscribe(
res => {
expect("response listener called").toBe(false);
async.done();
},
err => {
expect(err['message']).toBe('Oops!');
async.done();
});
existingScripts[0].dispatchEvent('error', ({message: "Oops!"}));
}));
it('should throw if request method is not GET', () => {
[RequestMethods.Post, RequestMethods.Put, RequestMethods.Delete, RequestMethods.Options,
RequestMethods.Head, RequestMethods.Patch]
.forEach(method => {
let base = new BaseRequestOptions();
let req = new Request(
base.merge(new RequestOptions({url: 'https://google.com', method: method})));
expect(() => new JSONPConnection_(req, new MockBrowserJsonp()).response.subscribe())
.toThrowError();
});
});
it('should respond with data passed to callback', inject([AsyncTestCompleter], async => {
let connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp());
connection.response.subscribe(res => {
expect(res.json()).toEqual(({fake_payload: true, blob_id: 12345}));
async.done();
});
connection.finished(({fake_payload: true, blob_id: 12345}));
existingScripts[0].dispatchEvent('load');
}));
});
});
}
| modules/angular2/test/http/backends/jsonp_backend_spec.ts | 1 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.002266280585899949,
0.0003390632919035852,
0.00016526026593055576,
0.0001752567768562585,
0.00046854012180119753
] |
{
"id": 0,
"code_window": [
"import {ConnectionBackend, Connection} from '../interfaces';\n",
"import {ReadyStates, RequestMethods} from '../enums';\n",
"import {Request} from '../static_request';\n",
"import {Response} from '../static_response';\n",
"import {ResponseOptions, BaseResponseOptions} from '../base_response_options';\n",
"import {Injectable} from 'angular2/angular2';\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {ReadyStates, RequestMethods, ResponseTypes} from '../enums';\n"
],
"file_path": "modules/angular2/src/http/backends/jsonp_backend.ts",
"type": "replace",
"edit_start_line_idx": 1
} | import {
ddescribe,
describe,
xdescribe,
it,
iit,
xit,
expect,
beforeEach,
afterEach,
AsyncTestCompleter,
inject,
beforeEachBindings
} from 'angular2/testing_internal';
import {Promise, PromiseWrapper} from 'angular2/src/core/facade/async';
import {Type, isPresent, isBlank, stringify, isString} from 'angular2/src/core/facade/lang';
import {MapWrapper, SetWrapper, ListWrapper} from 'angular2/src/core/facade/collection';
import {RuntimeMetadataResolver} from 'angular2/src/core/compiler/runtime_metadata';
import {
TemplateCompiler,
NormalizedComponentWithViewDirectives
} from 'angular2/src/core/compiler/template_compiler';
import {CompileDirectiveMetadata} from 'angular2/src/core/compiler/directive_metadata';
import {evalModule} from './eval_module';
import {SourceModule, moduleRef} from 'angular2/src/core/compiler/source_module';
import {XHR} from 'angular2/src/core/compiler/xhr';
import {MockXHR} from 'angular2/src/core/compiler/xhr_mock';
import {ViewEncapsulation} from 'angular2/src/core/metadata/view';
import {Locals} from 'angular2/src/core/change_detection/change_detection';
import {
CommandVisitor,
TextCmd,
NgContentCmd,
BeginElementCmd,
BeginComponentCmd,
EmbeddedTemplateCmd,
TemplateCmd,
visitAllCommands,
CompiledTemplate
} from 'angular2/src/core/linker/template_commands';
import {Component, View, Directive, provide} from 'angular2/core';
import {TEST_PROVIDERS} from './test_bindings';
import {TestDispatcher, TestPipes} from './change_detector_mocks';
import {
codeGenValueFn,
codeGenExportVariable,
MODULE_SUFFIX
} from 'angular2/src/core/compiler/util';
import {APP_ID} from 'angular2/src/core/application_tokens';
// Attention: This path has to point to this test file!
const THIS_MODULE_ID = 'angular2/test/core/compiler/template_compiler_spec';
var THIS_MODULE_REF = moduleRef(`package:${THIS_MODULE_ID}${MODULE_SUFFIX}`);
const APP_ID_VALUE = 'app1';
export function main() {
describe('TemplateCompiler', () => {
var compiler: TemplateCompiler;
var runtimeMetadataResolver: RuntimeMetadataResolver;
beforeEachBindings(() => [provide(APP_ID, {useValue: APP_ID_VALUE}), TEST_PROVIDERS]);
beforeEach(inject([TemplateCompiler, RuntimeMetadataResolver],
(_compiler, _runtimeMetadataResolver) => {
compiler = _compiler;
runtimeMetadataResolver = _runtimeMetadataResolver;
}));
describe('compile templates', () => {
function runTests(compile) {
it('should throw for non components', inject([AsyncTestCompleter], (async) => {
PromiseWrapper.catchError(PromiseWrapper.wrap(() => compile([NonComponent])), (error) => {
expect(error.message)
.toEqual(
`Could not compile '${stringify(NonComponent)}' because it is not a component.`);
async.done();
});
}));
it('should compile host components', inject([AsyncTestCompleter], (async) => {
compile([CompWithBindingsAndStyles])
.then((humanizedTemplate) => {
expect(humanizedTemplate['styles']).toEqual([]);
expect(humanizedTemplate['commands'][0]).toEqual('<comp-a>');
expect(humanizedTemplate['cd']).toEqual(['elementProperty(title)=someDirValue']);
async.done();
});
}));
it('should compile nested components', inject([AsyncTestCompleter], (async) => {
compile([CompWithBindingsAndStyles])
.then((humanizedTemplate) => {
var nestedTemplate = humanizedTemplate['commands'][1];
expect(nestedTemplate['styles']).toEqual(['div {color: red}']);
expect(nestedTemplate['commands'][0]).toEqual('<a>');
expect(nestedTemplate['cd']).toEqual(['elementProperty(href)=someCtxValue']);
async.done();
});
}));
it('should compile recursive components', inject([AsyncTestCompleter], (async) => {
compile([TreeComp])
.then((humanizedTemplate) => {
expect(humanizedTemplate['commands'][0]).toEqual('<tree>');
expect(humanizedTemplate['commands'][1]['commands'][0]).toEqual('<tree>');
expect(humanizedTemplate['commands'][1]['commands'][1]['commands'][0])
.toEqual('<tree>');
async.done();
});
}));
it('should pass the right change detector to embedded templates',
inject([AsyncTestCompleter], (async) => {
compile([CompWithEmbeddedTemplate])
.then((humanizedTemplate) => {
expect(humanizedTemplate['commands'][1]['commands'][0]).toEqual('<template>');
expect(humanizedTemplate['commands'][1]['commands'][1]['cd'])
.toEqual(['elementProperty(href)=someCtxValue']);
async.done();
});
}));
}
describe('compileHostComponentRuntime', () => {
function compile(components: Type[]): Promise<any[]> {
return compiler.compileHostComponentRuntime(components[0])
.then((compiledHostTemplate) => humanizeTemplate(compiledHostTemplate.getTemplate()));
}
runTests(compile);
it('should cache components for parallel requests',
inject([AsyncTestCompleter, XHR], (async, xhr: MockXHR) => {
xhr.expect('package:angular2/test/core/compiler/compUrl.html', 'a');
PromiseWrapper.all([compile([CompWithTemplateUrl]), compile([CompWithTemplateUrl])])
.then((humanizedTemplates) => {
expect(humanizedTemplates[0]['commands'][1]['commands']).toEqual(['#text(a)']);
expect(humanizedTemplates[1]['commands'][1]['commands']).toEqual(['#text(a)']);
async.done();
});
xhr.flush();
}));
it('should cache components for sequential requests',
inject([AsyncTestCompleter, XHR], (async, xhr: MockXHR) => {
xhr.expect('package:angular2/test/core/compiler/compUrl.html', 'a');
compile([CompWithTemplateUrl])
.then((humanizedTemplate0) => {
return compile([CompWithTemplateUrl])
.then((humanizedTemplate1) => {
expect(humanizedTemplate0['commands'][1]['commands'])
.toEqual(['#text(a)']);
expect(humanizedTemplate1['commands'][1]['commands'])
.toEqual(['#text(a)']);
async.done();
});
});
xhr.flush();
}));
it('should allow to clear the cache',
inject([AsyncTestCompleter, XHR], (async, xhr: MockXHR) => {
xhr.expect('package:angular2/test/core/compiler/compUrl.html', 'a');
compile([CompWithTemplateUrl])
.then((humanizedTemplate) => {
compiler.clearCache();
xhr.expect('package:angular2/test/core/compiler/compUrl.html', 'b');
var result = compile([CompWithTemplateUrl]);
xhr.flush();
return result;
})
.then((humanizedTemplate) => {
expect(humanizedTemplate['commands'][1]['commands']).toEqual(['#text(b)']);
async.done();
});
xhr.flush();
}));
});
describe('compileTemplatesCodeGen', () => {
function normalizeComponent(
component: Type): Promise<NormalizedComponentWithViewDirectives> {
var compAndViewDirMetas = [runtimeMetadataResolver.getMetadata(component)].concat(
runtimeMetadataResolver.getViewDirectivesMetadata(component));
return PromiseWrapper.all(compAndViewDirMetas.map(
meta => compiler.normalizeDirectiveMetadata(meta)))
.then((normalizedCompAndViewDirMetas: CompileDirectiveMetadata[]) =>
new NormalizedComponentWithViewDirectives(
normalizedCompAndViewDirMetas[0],
normalizedCompAndViewDirMetas.slice(1)));
}
function compile(components: Type[]): Promise<any[]> {
return PromiseWrapper.all(components.map(normalizeComponent))
.then((normalizedCompWithViewDirMetas: NormalizedComponentWithViewDirectives[]) => {
var sourceModule = compiler.compileTemplatesCodeGen(normalizedCompWithViewDirMetas);
var sourceWithImports =
testableTemplateModule(sourceModule,
normalizedCompWithViewDirMetas[0].component)
.getSourceWithImports();
return evalModule(sourceWithImports.source, sourceWithImports.imports, null);
});
}
runTests(compile);
});
});
describe('normalizeDirectiveMetadata', () => {
it('should return the given DirectiveMetadata for non components',
inject([AsyncTestCompleter], (async) => {
var meta = runtimeMetadataResolver.getMetadata(NonComponent);
compiler.normalizeDirectiveMetadata(meta).then(normMeta => {
expect(normMeta).toBe(meta);
async.done();
});
}));
it('should normalize the template',
inject([AsyncTestCompleter, XHR], (async, xhr: MockXHR) => {
xhr.expect('package:angular2/test/core/compiler/compUrl.html', 'loadedTemplate');
compiler.normalizeDirectiveMetadata(
runtimeMetadataResolver.getMetadata(CompWithTemplateUrl))
.then((meta: CompileDirectiveMetadata) => {
expect(meta.template.template).toEqual('loadedTemplate');
async.done();
});
xhr.flush();
}));
it('should copy all the other fields', inject([AsyncTestCompleter], (async) => {
var meta = runtimeMetadataResolver.getMetadata(CompWithBindingsAndStyles);
compiler.normalizeDirectiveMetadata(meta).then((normMeta: CompileDirectiveMetadata) => {
expect(normMeta.type).toEqual(meta.type);
expect(normMeta.isComponent).toEqual(meta.isComponent);
expect(normMeta.dynamicLoadable).toEqual(meta.dynamicLoadable);
expect(normMeta.selector).toEqual(meta.selector);
expect(normMeta.exportAs).toEqual(meta.exportAs);
expect(normMeta.changeDetection).toEqual(meta.changeDetection);
expect(normMeta.inputs).toEqual(meta.inputs);
expect(normMeta.outputs).toEqual(meta.outputs);
expect(normMeta.hostListeners).toEqual(meta.hostListeners);
expect(normMeta.hostProperties).toEqual(meta.hostProperties);
expect(normMeta.hostAttributes).toEqual(meta.hostAttributes);
expect(normMeta.lifecycleHooks).toEqual(meta.lifecycleHooks);
async.done();
});
}));
});
describe('compileStylesheetCodeGen', () => {
it('should compile stylesheets into code', inject([AsyncTestCompleter], (async) => {
var cssText = 'div {color: red}';
var sourceModule =
compiler.compileStylesheetCodeGen('package:someModuleUrl', cssText)[0];
var sourceWithImports = testableStylesModule(sourceModule).getSourceWithImports();
evalModule(sourceWithImports.source, sourceWithImports.imports, null)
.then(loadedCssText => {
expect(loadedCssText).toEqual([cssText]);
async.done();
});
}));
});
});
}
@Component({
selector: 'comp-a',
host: {'[title]': 'someProp'},
moduleId: THIS_MODULE_ID,
exportAs: 'someExportAs'
})
@View({
template: '<a [href]="someProp"></a>',
styles: ['div {color: red}'],
encapsulation: ViewEncapsulation.None
})
class CompWithBindingsAndStyles {
}
@Component({selector: 'tree', moduleId: THIS_MODULE_ID})
@View({template: '<tree></tree>', directives: [TreeComp], encapsulation: ViewEncapsulation.None})
class TreeComp {
}
@Component({selector: 'comp-url', moduleId: THIS_MODULE_ID})
@View({templateUrl: 'compUrl.html', encapsulation: ViewEncapsulation.None})
class CompWithTemplateUrl {
}
@Component({selector: 'comp-tpl', moduleId: THIS_MODULE_ID})
@View({
template: '<template><a [href]="someProp"></a></template>',
encapsulation: ViewEncapsulation.None
})
class CompWithEmbeddedTemplate {
}
@Directive({selector: 'plain', moduleId: THIS_MODULE_ID})
@View({template: ''})
class NonComponent {
}
function testableTemplateModule(sourceModule: SourceModule,
normComp: CompileDirectiveMetadata): SourceModule {
var resultExpression =
`${THIS_MODULE_REF}humanizeTemplate(Host${normComp.type.name}Template.getTemplate())`;
var testableSource = `${sourceModule.sourceWithModuleRefs}
${codeGenExportVariable('run')}${codeGenValueFn(['_'], resultExpression)};`;
return new SourceModule(sourceModule.moduleUrl, testableSource);
}
function testableStylesModule(sourceModule: SourceModule): SourceModule {
var testableSource = `${sourceModule.sourceWithModuleRefs}
${codeGenExportVariable('run')}${codeGenValueFn(['_'], 'STYLES')};`;
return new SourceModule(sourceModule.moduleUrl, testableSource);
}
// Attention: read by eval!
export function humanizeTemplate(
template: CompiledTemplate,
humanizedTemplates: Map<number, {[key: string]: any}> = null): {[key: string]: any} {
if (isBlank(humanizedTemplates)) {
humanizedTemplates = new Map<number, {[key: string]: any}>();
}
var result = humanizedTemplates.get(template.id);
if (isPresent(result)) {
return result;
}
var templateData = template.getData(APP_ID_VALUE);
var commands = [];
result = {
'styles': templateData.styles,
'commands': commands,
'cd': testChangeDetector(templateData.changeDetectorFactory)
};
humanizedTemplates.set(template.id, result);
visitAllCommands(new CommandHumanizer(commands, humanizedTemplates), templateData.commands);
return result;
}
class TestContext implements CompWithBindingsAndStyles, TreeComp, CompWithTemplateUrl,
CompWithEmbeddedTemplate {
someProp: string;
}
function testChangeDetector(changeDetectorFactory: Function): string[] {
var ctx = new TestContext();
ctx.someProp = 'someCtxValue';
var dir1 = new TestContext();
dir1.someProp = 'someDirValue';
var dispatcher = new TestDispatcher([dir1], []);
var cd = changeDetectorFactory(dispatcher);
var locals = new Locals(null, MapWrapper.createFromStringMap({'someVar': null}));
cd.hydrate(ctx, locals, dispatcher, new TestPipes());
cd.detectChanges();
return dispatcher.log;
}
class CommandHumanizer implements CommandVisitor {
constructor(private result: any[],
private humanizedTemplates: Map<number, {[key: string]: any}>) {}
visitText(cmd: TextCmd, context: any): any {
this.result.push(`#text(${cmd.value})`);
return null;
}
visitNgContent(cmd: NgContentCmd, context: any): any { return null; }
visitBeginElement(cmd: BeginElementCmd, context: any): any {
this.result.push(`<${cmd.name}>`);
return null;
}
visitEndElement(context: any): any {
this.result.push('</>');
return null;
}
visitBeginComponent(cmd: BeginComponentCmd, context: any): any {
this.result.push(`<${cmd.name}>`);
this.result.push(humanizeTemplate(cmd.template, this.humanizedTemplates));
return null;
}
visitEndComponent(context: any): any { return this.visitEndElement(context); }
visitEmbeddedTemplate(cmd: EmbeddedTemplateCmd, context: any): any {
this.result.push(`<template>`);
this.result.push({'cd': testChangeDetector(cmd.changeDetectorFactory)});
this.result.push(`</template>`);
return null;
}
}
| modules/angular2/test/core/compiler/template_compiler_spec.ts | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.00017954441136680543,
0.00017397441843058914,
0.0001653660146985203,
0.00017473549814894795,
0.0000036323392578196945
] |
{
"id": 0,
"code_window": [
"import {ConnectionBackend, Connection} from '../interfaces';\n",
"import {ReadyStates, RequestMethods} from '../enums';\n",
"import {Request} from '../static_request';\n",
"import {Response} from '../static_response';\n",
"import {ResponseOptions, BaseResponseOptions} from '../base_response_options';\n",
"import {Injectable} from 'angular2/angular2';\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {ReadyStates, RequestMethods, ResponseTypes} from '../enums';\n"
],
"file_path": "modules/angular2/src/http/backends/jsonp_backend.ts",
"type": "replace",
"edit_start_line_idx": 1
} | import {FORM_PROVIDERS} from 'angular2/src/core/forms';
import {provide, Provider} from 'angular2/src/core/di';
import {Type, isBlank, isPresent, stringify} from 'angular2/src/core/facade/lang';
import {BrowserDomAdapter} from 'angular2/src/core/dom/browser_adapter';
import {BrowserGetTestability} from 'angular2/src/core/testability/browser_testability';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {Promise} from 'angular2/src/core/facade/async';
import {XHR} from 'angular2/src/core/compiler/xhr';
import {XHRImpl} from 'angular2/src/core/compiler/xhr_impl';
import {
EventManager,
DomEventsPlugin,
EVENT_MANAGER_PLUGINS
} from 'angular2/src/core/render/dom/events/event_manager';
import {KeyEventsPlugin} from 'angular2/src/core/render/dom/events/key_events';
import {HammerGesturesPlugin} from 'angular2/src/core/render/dom/events/hammer_gestures';
import {ComponentRef} from 'angular2/src/core/linker/dynamic_component_loader';
import {Testability} from 'angular2/src/core/testability/testability';
import {Renderer} from 'angular2/src/core/render/api';
import {DomRenderer, DomRenderer_, DOCUMENT} from 'angular2/src/core/render/render';
import {
SharedStylesHost,
DomSharedStylesHost
} from 'angular2/src/core/render/dom/shared_styles_host';
import {EXCEPTION_PROVIDER} from './platform_bindings';
import {AnimationBuilder} from 'angular2/src/animate/animation_builder';
import {BrowserDetails} from 'angular2/src/animate/browser_details';
import {wtfInit} from './profile/wtf_init';
import {platformCommon, PlatformRef, applicationCommonProviders} from './application_ref';
/**
* A default set of providers which apply only to an Angular application running on
* the UI thread.
*/
export function applicationDomProviders(): Array<Type | Provider | any[]> {
if (isBlank(DOM)) {
throw "Must set a root DOM adapter first.";
}
return [
provide(DOCUMENT, {useValue: DOM.defaultDoc()}),
EventManager,
new Provider(EVENT_MANAGER_PLUGINS, {useClass: DomEventsPlugin, multi: true}),
new Provider(EVENT_MANAGER_PLUGINS, {useClass: KeyEventsPlugin, multi: true}),
new Provider(EVENT_MANAGER_PLUGINS, {useClass: HammerGesturesPlugin, multi: true}),
provide(DomRenderer, {useClass: DomRenderer_}),
provide(Renderer, {useExisting: DomRenderer}),
DomSharedStylesHost,
provide(SharedStylesHost, {useExisting: DomSharedStylesHost}),
EXCEPTION_PROVIDER,
provide(XHR, {useValue: new XHRImpl()}),
Testability,
BrowserDetails,
AnimationBuilder,
FORM_PROVIDERS
];
}
/**
* Initialize the Angular 'platform' on the page.
*
* See {@link PlatformRef} for details on the Angular platform.
*
*##Without specified providers
*
* If no providers are specified, `platform`'s behavior depends on whether an existing
* platform exists:
*
* If no platform exists, a new one will be created with the default {@link platformProviders}.
*
* If a platform already exists, it will be returned (regardless of what providers it
* was created with). This is a convenience feature, allowing for multiple applications
* to be loaded into the same platform without awareness of each other.
*
*##With specified providers
*
* It is also possible to specify providers to be made in the new platform. These providers
* will be shared between all applications on the page. For example, an abstraction for
* the browser cookie jar should be bound at the platform level, because there is only one
* cookie jar regardless of how many applications on the page will be accessing it.
*
* If providers are specified directly, `platform` will create the Angular platform with
* them if a platform did not exist already. If it did exist, however, an error will be
* thrown.
*
*##DOM Applications
*
* This version of `platform` initializes Angular to run in the UI thread, with direct
* DOM access. Web-worker applications should call `platform` from
* `src/web_workers/worker/application_common` instead.
*/
export function platform(providers?: Array<Type | Provider | any[]>): PlatformRef {
return platformCommon(providers, () => {
BrowserDomAdapter.makeCurrent();
wtfInit();
BrowserGetTestability.init();
});
}
/**
* Bootstrapping for Angular applications.
*
* You instantiate an Angular application by explicitly specifying a component to use
* as the root component for your application via the `bootstrap()` method.
*
* ## Simple Example
*
* Assuming this `index.html`:
*
* ```html
* <html>
* <!-- load Angular script tags here. -->
* <body>
* <my-app>loading...</my-app>
* </body>
* </html>
* ```
*
* An application is bootstrapped inside an existing browser DOM, typically `index.html`.
* Unlike Angular 1, Angular 2 does not compile/process providers in `index.html`. This is
* mainly for security reasons, as well as architectural changes in Angular 2. This means
* that `index.html` can safely be processed using server-side technologies such as
* providers. Bindings can thus use double-curly `{{ syntax }}` without collision from
* Angular 2 component double-curly `{{ syntax }}`.
*
* We can use this script code:
*
* ```
* @Component({
* selector: 'my-app',
* template: 'Hello {{ name }}!'
* })
* class MyApp {
* name:string;
*
* constructor() {
* this.name = 'World';
* }
* }
*
* main() {
* return bootstrap(MyApp);
* }
* ```
*
* When the app developer invokes `bootstrap()` with the root component `MyApp` as its
* argument, Angular performs the following tasks:
*
* 1. It uses the component's `selector` property to locate the DOM element which needs
* to be upgraded into the angular component.
* 2. It creates a new child injector (from the platform injector). Optionally, you can
* also override the injector configuration for an app by invoking `bootstrap` with the
* `componentInjectableBindings` argument.
* 3. It creates a new `Zone` and connects it to the angular application's change detection
* domain instance.
* 4. It creates an emulated or shadow DOM on the selected component's host element and loads the
* template into it.
* 5. It instantiates the specified component.
* 6. Finally, Angular performs change detection to apply the initial data providers for the
* application.
*
*
* ## Instantiating Multiple Applications on a Single Page
*
* There are two ways to do this.
*
* ### Isolated Applications
*
* Angular creates a new application each time that the `bootstrap()` method is invoked.
* When multiple applications are created for a page, Angular treats each application as
* independent within an isolated change detection and `Zone` domain. If you need to share
* data between applications, use the strategy described in the next section, "Applications
* That Share Change Detection."
*
*
* ### Applications That Share Change Detection
*
* If you need to bootstrap multiple applications that share common data, the applications
* must share a common change detection and zone. To do that, create a meta-component that
* lists the application components in its template.
*
* By only invoking the `bootstrap()` method once, with the meta-component as its argument,
* you ensure that only a single change detection zone is created and therefore data can be
* shared across the applications.
*
*
* ## Platform Injector
*
* When working within a browser window, there are many singleton resources: cookies, title,
* location, and others. Angular services that represent these resources must likewise be
* shared across all Angular applications that occupy the same browser window. For this
* reason, Angular creates exactly one global platform injector which stores all shared
* services, and each angular application injector has the platform injector as its parent.
*
* Each application has its own private injector as well. When there are multiple
* applications on a page, Angular treats each application injector's services as private
* to that application.
*
*
*##API
* - `appComponentType`: The root component which should act as the application. This is
* a reference to a `Type` which is annotated with `@Component(...)`.
* - `componentInjectableBindings`: An additional set of providers that can be added to the
* app injector to override default injection behavior.
* - `errorReporter`: `function(exception:any, stackTrace:string)` a default error reporter
* for unhandled exceptions.
*
* Returns a `Promise` of {@link ComponentRef}.
*/
export function commonBootstrap(
appComponentType: /*Type*/ any,
appProviders: Array<Type | Provider | any[]> = null): Promise<ComponentRef> {
var p = platform();
var bindings = [applicationCommonProviders(), applicationDomProviders()];
if (isPresent(appProviders)) {
bindings.push(appProviders);
}
return p.application(bindings).bootstrap(appComponentType);
}
| modules/angular2/src/core/application_common.ts | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.00022545200772583485,
0.00016938011685851961,
0.0001600608229637146,
0.0001664878218434751,
0.000013162994946469553
] |
{
"id": 0,
"code_window": [
"import {ConnectionBackend, Connection} from '../interfaces';\n",
"import {ReadyStates, RequestMethods} from '../enums';\n",
"import {Request} from '../static_request';\n",
"import {Response} from '../static_response';\n",
"import {ResponseOptions, BaseResponseOptions} from '../base_response_options';\n",
"import {Injectable} from 'angular2/angular2';\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {ReadyStates, RequestMethods, ResponseTypes} from '../enums';\n"
],
"file_path": "modules/angular2/src/http/backends/jsonp_backend.ts",
"type": "replace",
"edit_start_line_idx": 1
} | library angular2.core.util.decorators;
| modules/angular2/src/core/util/decorators.dart | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.00016034570580814034,
0.00016034570580814034,
0.00016034570580814034,
0.00016034570580814034,
0
] |
{
"id": 1,
"code_window": [
"// todo(robwormald): temporary until https://github.com/angular/angular/issues/4390 decided\n",
"var Rx = require('@reactivex/rxjs/dist/cjs/Rx');\n",
"var {Observable} = Rx;\n",
"export abstract class JSONPConnection implements Connection {\n",
" readyState: ReadyStates;\n",
" request: Request;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"const JSONP_ERR_NO_CALLBACK = 'JSONP injected script did not invoke callback.';\n",
"const JSONP_ERR_WRONG_METHOD = 'JSONP requests must use GET request method.';\n",
"\n"
],
"file_path": "modules/angular2/src/http/backends/jsonp_backend.ts",
"type": "add",
"edit_start_line_idx": 13
} | import {ConnectionBackend, Connection} from '../interfaces';
import {ReadyStates, RequestMethods} from '../enums';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {ResponseOptions, BaseResponseOptions} from '../base_response_options';
import {Injectable} from 'angular2/angular2';
import {BrowserJsonp} from './browser_jsonp';
import {EventEmitter, ObservableWrapper} from 'angular2/src/core/facade/async';
import {makeTypeError} from 'angular2/src/core/facade/exceptions';
import {StringWrapper, isPresent} from 'angular2/src/core/facade/lang';
// todo(robwormald): temporary until https://github.com/angular/angular/issues/4390 decided
var Rx = require('@reactivex/rxjs/dist/cjs/Rx');
var {Observable} = Rx;
export abstract class JSONPConnection implements Connection {
readyState: ReadyStates;
request: Request;
response: any;
abstract finished(data?: any): void;
}
export class JSONPConnection_ extends JSONPConnection {
private _id: string;
private _script: Element;
private _responseData: any;
private _finished: boolean = false;
constructor(req: Request, private _dom: BrowserJsonp,
private baseResponseOptions?: ResponseOptions) {
super();
if (req.method !== RequestMethods.Get) {
throw makeTypeError("JSONP requests must use GET request method.");
}
this.request = req;
this.response = new Observable(responseObserver => {
this.readyState = ReadyStates.Loading;
let id = this._id = _dom.nextRequestID();
_dom.exposeConnection(id, this);
// Workaround Dart
// url = url.replace(/=JSONP_CALLBACK(&|$)/, `generated method`);
let callback = _dom.requestCallback(this._id);
let url: string = req.url;
if (url.indexOf('=JSONP_CALLBACK&') > -1) {
url = StringWrapper.replace(url, '=JSONP_CALLBACK&', `=${callback}&`);
} else if (url.lastIndexOf('=JSONP_CALLBACK') === url.length - '=JSONP_CALLBACK'.length) {
url =
StringWrapper.substring(url, 0, url.length - '=JSONP_CALLBACK'.length) + `=${callback}`;
}
let script = this._script = _dom.build(url);
let onLoad = event => {
if (this.readyState === ReadyStates.Cancelled) return;
this.readyState = ReadyStates.Done;
_dom.cleanup(script);
if (!this._finished) {
responseObserver.error(makeTypeError('JSONP injected script did not invoke callback.'));
return;
}
let responseOptions = new ResponseOptions({body: this._responseData});
if (isPresent(this.baseResponseOptions)) {
responseOptions = this.baseResponseOptions.merge(responseOptions);
}
responseObserver.next(new Response(responseOptions));
responseObserver.complete();
};
let onError = error => {
if (this.readyState === ReadyStates.Cancelled) return;
this.readyState = ReadyStates.Done;
_dom.cleanup(script);
responseObserver.error(error);
};
script.addEventListener('load', onLoad);
script.addEventListener('error', onError);
_dom.send(script);
return () => {
this.readyState = ReadyStates.Cancelled;
script.removeEventListener('load', onLoad);
script.removeEventListener('error', onError);
if (isPresent(script)) {
this._dom.cleanup(script);
}
};
});
}
finished(data?: any) {
// Don't leak connections
this._finished = true;
this._dom.removeConnection(this._id);
if (this.readyState === ReadyStates.Cancelled) return;
this._responseData = data;
}
}
export abstract class JSONPBackend extends ConnectionBackend {}
@Injectable()
export class JSONPBackend_ extends JSONPBackend {
constructor(private _browserJSONP: BrowserJsonp, private _baseResponseOptions: ResponseOptions) {
super();
}
createConnection(request: Request): JSONPConnection {
return new JSONPConnection_(request, this._browserJSONP, this._baseResponseOptions);
}
}
| modules/angular2/src/http/backends/jsonp_backend.ts | 1 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.9992678761482239,
0.41005465388298035,
0.00016479352780152112,
0.0020503406412899494,
0.4845513105392456
] |
{
"id": 1,
"code_window": [
"// todo(robwormald): temporary until https://github.com/angular/angular/issues/4390 decided\n",
"var Rx = require('@reactivex/rxjs/dist/cjs/Rx');\n",
"var {Observable} = Rx;\n",
"export abstract class JSONPConnection implements Connection {\n",
" readyState: ReadyStates;\n",
" request: Request;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"const JSONP_ERR_NO_CALLBACK = 'JSONP injected script did not invoke callback.';\n",
"const JSONP_ERR_WRONG_METHOD = 'JSONP requests must use GET request method.';\n",
"\n"
],
"file_path": "modules/angular2/src/http/backends/jsonp_backend.ts",
"type": "add",
"edit_start_line_idx": 13
} | import {verifyNoBrowserErrors} from 'angular2/src/testing/e2e_util';
describe('key_events', function() {
var URL = 'playground/src/key_events/index.html';
afterEach(verifyNoBrowserErrors);
beforeEach(() => { browser.get(URL); });
it('should display correct key names', function() {
var firstArea = element.all(by.css('.sample-area')).get(0);
expect(firstArea.getText()).toEqual('(none)');
// testing different key categories:
firstArea.sendKeys(protractor.Key.ENTER);
expect(firstArea.getText()).toEqual('enter');
firstArea.sendKeys(protractor.Key.SHIFT, protractor.Key.ENTER);
expect(firstArea.getText()).toEqual('shift.enter');
firstArea.sendKeys(protractor.Key.CONTROL, protractor.Key.SHIFT, protractor.Key.ENTER);
expect(firstArea.getText()).toEqual('control.shift.enter');
firstArea.sendKeys(' ');
expect(firstArea.getText()).toEqual('space');
// It would not work with a letter which position depends on the keyboard layout (ie AZERTY vs
// QWERTY), see https://code.google.com/p/chromedriver/issues/detail?id=553
firstArea.sendKeys('u');
expect(firstArea.getText()).toEqual('u');
firstArea.sendKeys(protractor.Key.CONTROL, 'b');
expect(firstArea.getText()).toEqual('control.b');
firstArea.sendKeys(protractor.Key.F1);
expect(firstArea.getText()).toEqual('f1');
firstArea.sendKeys(protractor.Key.ALT, protractor.Key.F1);
expect(firstArea.getText()).toEqual('alt.f1');
firstArea.sendKeys(protractor.Key.CONTROL, protractor.Key.F1);
expect(firstArea.getText()).toEqual('control.f1');
// There is an issue with protractor.Key.NUMPAD0 (and other NUMPADx):
// chromedriver does not correctly set the location property on the event to
// specify that the key is on the numeric keypad (event.location = 3)
// so the following test fails:
// firstArea.sendKeys(protractor.Key.NUMPAD0);
// expect(firstArea.getText()).toEqual('0');
});
it('should correctly react to the specified key', function() {
var secondArea = element.all(by.css('.sample-area')).get(1);
secondArea.sendKeys(protractor.Key.SHIFT, protractor.Key.ENTER);
expect(secondArea.getText()).toEqual('You pressed shift.enter!');
});
it('should not react to incomplete keys', function() {
var secondArea = element.all(by.css('.sample-area')).get(1);
secondArea.sendKeys(protractor.Key.ENTER);
expect(secondArea.getText()).toEqual('');
});
it('should not react to keys with more modifiers', function() {
var secondArea = element.all(by.css('.sample-area')).get(1);
secondArea.sendKeys(protractor.Key.CONTROL, protractor.Key.SHIFT, protractor.Key.ENTER);
expect(secondArea.getText()).toEqual('');
});
});
| modules/playground/e2e_test/key_events/key_events_spec.ts | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.00017962505808100104,
0.00017757463501766324,
0.00017453885811846703,
0.000178248985321261,
0.0000018336623952563968
] |
{
"id": 1,
"code_window": [
"// todo(robwormald): temporary until https://github.com/angular/angular/issues/4390 decided\n",
"var Rx = require('@reactivex/rxjs/dist/cjs/Rx');\n",
"var {Observable} = Rx;\n",
"export abstract class JSONPConnection implements Connection {\n",
" readyState: ReadyStates;\n",
" request: Request;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"const JSONP_ERR_NO_CALLBACK = 'JSONP injected script did not invoke callback.';\n",
"const JSONP_ERR_WRONG_METHOD = 'JSONP requests must use GET request method.';\n",
"\n"
],
"file_path": "modules/angular2/src/http/backends/jsonp_backend.ts",
"type": "add",
"edit_start_line_idx": 13
} | import {MapWrapper} from 'angular2/src/core/facade/collection';
import {SimpleChange} from 'angular2/src/core/change_detection/change_detection_util';
export enum LifecycleHooks {
OnInit,
OnDestroy,
DoCheck,
OnChanges,
AfterContentInit,
AfterContentChecked,
AfterViewInit,
AfterViewChecked
}
/**
* @internal
*/
export var LIFECYCLE_HOOKS_VALUES = [
LifecycleHooks.OnInit,
LifecycleHooks.OnDestroy,
LifecycleHooks.DoCheck,
LifecycleHooks.OnChanges,
LifecycleHooks.AfterContentInit,
LifecycleHooks.AfterContentChecked,
LifecycleHooks.AfterViewInit,
LifecycleHooks.AfterViewChecked
];
/**
* Lifecycle hooks are guaranteed to be called in the following order:
* - `OnChanges` (if any bindings have changed),
* - `OnInit` (after the first check only),
* - `DoCheck`,
* - `AfterContentInit`,
* - `AfterContentChecked`,
* - `AfterViewInit`,
* - `AfterViewChecked`,
* - `OnDestroy` (at the very end before destruction)
*/
/**
* Implement this interface to get notified when any data-bound property of your directive changes.
*
* `onChanges` is called right after the data-bound properties have been checked and before view
* and content children are checked if at least one of them has changed.
*
* The `changes` parameter contains an entry for each of the changed data-bound property. The key is
* the property name and the value is an instance of {@link SimpleChange}.
*
* ### Example ([live example](http://plnkr.co/edit/AHrB6opLqHDBPkt4KpdT?p=preview)):
*
* ```typescript
* @Component({
* selector: 'my-cmp',
* template: `<p>myProp = {{myProp}}</p>`
* })
* class MyComponent implements OnChanges {
* @Input() myProp: any;
*
* onChanges(changes: {[propName: string]: SimpleChange}) {
* console.log('onChanges - myProp = ' + changes['myProp'].currentValue);
* }
* }
*
* @Component({
* selector: 'app',
* template: `
* <button (click)="value = value + 1">Change MyComponent</button>
* <my-cmp [my-prop]="value"></my-cmp>`,
* directives: [MyComponent]
* })
* export class App {
* value = 0;
* }
*
* bootstrap(App).catch(err => console.error(err));
* ```
*/
export interface OnChanges { onChanges(changes: {[key: string]: SimpleChange}); }
/**
* Implement this interface to execute custom initialization logic after your directive's
* data-bound properties have been initialized.
*
* `onInit` is called right after the directive's data-bound properties have been checked for the
* first time, and before any of its children have been checked. It is invoked only once when the
* directive is instantiated.
*
* ### Example ([live example](http://plnkr.co/edit/1MBypRryXd64v4pV03Yn?p=preview))
*
* ```typescript
* @Component({
* selector: 'my-cmp',
* template: `<p>my-component</p>`
* })
* class MyComponent implements OnInit, OnDestroy {
* onInit() {
* console.log('onInit');
* }
*
* onDestroy() {
* console.log('onDestroy');
* }
* }
*
* @Component({
* selector: 'app',
* template: `
* <button (click)="hasChild = !hasChild">
* {{hasChild ? 'Destroy' : 'Create'}} MyComponent
* </button>
* <my-cmp *ng-if="hasChild"></my-cmp>`,
* directives: [MyComponent, NgIf]
* })
* export class App {
* hasChild = true;
* }
*
* bootstrap(App).catch(err => console.error(err));
* ```
*/
export interface OnInit { onInit(); }
/**
* Implement this interface to override the default change detection algorithm for your directive.
*
* `doCheck` gets called to check the changes in the directives instead of the default algorithm.
*
* The default change detection algorithm looks for differences by comparing bound-property values
* by reference across change detection runs. When `DoCheck` is implemented, the default algorithm
* is disabled and `doCheck` is responsible for checking for changes.
*
* Implementing this interface allows improving performance by using insights about the component,
* its implementation and data types of its properties.
*
* Note that a directive should not implement both `DoCheck` and {@link OnChanges} at the same time.
* `onChanges` would not be called when a directive implements `DoCheck`. Reaction to the changes
* have to be handled from within the `doCheck` callback.
*
* Use {@link KeyValueDiffers} and {@link IterableDiffers} to add your custom check mechanisms.
*
* ### Example ([live demo](http://plnkr.co/edit/QpnIlF0CR2i5bcYbHEUJ?p=preview))
*
* In the following example `doCheck` uses an {@link IterableDiffers} to detect the updates to the
* array `list`:
*
* ```typescript
* @Component({
* selector: 'custom-check',
* template: `
* <p>Changes:</p>
* <ul>
* <li *ng-for="#line of logs">{{line}}</li>
* </ul>`,
* directives: [NgFor]
* })
* class CustomCheckComponent implements DoCheck {
* @Input() list: any[];
* differ: any;
* logs = [];
*
* constructor(differs: IterableDiffers) {
* this.differ = differs.find([]).create(null);
* }
*
* doCheck() {
* var changes = this.differ.diff(this.list);
*
* if (changes) {
* changes.forEachAddedItem(r => this.logs.push('added ' + r.item));
* changes.forEachRemovedItem(r => this.logs.push('removed ' + r.item))
* }
* }
* }
*
* @Component({
* selector: 'app',
* template: `
* <button (click)="list.push(list.length)">Push</button>
* <button (click)="list.pop()">Pop</button>
* <custom-check [list]="list"></custom-check>`,
* directives: [CustomCheckComponent]
* })
* export class App {
* list = [];
* }
* ```
*/
export interface DoCheck { doCheck(); }
/**
* Implement this interface to get notified when your directive is destroyed.
*
* `onDestroy` callback is typically used for any custom cleanup that needs to occur when the
* instance is destroyed
*
* ### Example ([live example](http://plnkr.co/edit/1MBypRryXd64v4pV03Yn?p=preview))
*
* ```typesript
* @Component({
* selector: 'my-cmp',
* template: `<p>my-component</p>`
* })
* class MyComponent implements OnInit, OnDestroy {
* onInit() {
* console.log('onInit');
* }
*
* onDestroy() {
* console.log('onDestroy');
* }
* }
*
* @Component({
* selector: 'app',
* template: `
* <button (click)="hasChild = !hasChild">
* {{hasChild ? 'Destroy' : 'Create'}} MyComponent
* </button>
* <my-cmp *ng-if="hasChild"></my-cmp>`,
* directives: [MyComponent, NgIf]
* })
* export class App {
* hasChild = true;
* }
*
* bootstrap(App).catch(err => console.error(err));
* ```
*/
export interface OnDestroy { onDestroy(); }
/**
* Implement this interface to get notified when your directive's content has been fully
* initialized.
*
* ### Example ([live demo](http://plnkr.co/edit/plamXUpsLQbIXpViZhUO?p=preview))
*
* ```typescript
* @Component({
* selector: 'child-cmp',
* template: `{{where}} child`
* })
* class ChildComponent {
* @Input() where: string;
* }
*
* @Component({
* selector: 'parent-cmp',
* template: `<ng-content></ng-content>`
* })
* class ParentComponent implements AfterContentInit {
* @ContentChild(ChildComponent) contentChild: ChildComponent;
*
* constructor() {
* // contentChild is not initialized yet
* console.log(this.getMessage(this.contentChild));
* }
*
* afterContentInit() {
* // contentChild is updated after the content has been checked
* console.log('AfterContentInit: ' + this.getMessage(this.contentChild));
* }
*
* private getMessage(cmp: ChildComponent): string {
* return cmp ? cmp.where + ' child' : 'no child';
* }
* }
*
* @Component({
* selector: 'app',
* template: `
* <parent-cmp>
* <child-cmp where="content"></child-cmp>
* </parent-cmp>`,
* directives: [ParentComponent, ChildComponent]
* })
* export class App {
* }
*
* bootstrap(App).catch(err => console.error(err));
* ```
*/
export interface AfterContentInit { afterContentInit(); }
/**
* Implement this interface to get notified after every check of your directive's content.
*
* ### Example ([live demo](http://plnkr.co/edit/tGdrytNEKQnecIPkD7NU?p=preview))
*
* ```typescript
* @Component({selector: 'child-cmp', template: `{{where}} child`})
* class ChildComponent {
* @Input() where: string;
* }
*
* @Component({selector: 'parent-cmp', template: `<ng-content></ng-content>`})
* class ParentComponent implements AfterContentChecked {
* @ContentChild(ChildComponent) contentChild: ChildComponent;
*
* constructor() {
* // contentChild is not initialized yet
* console.log(this.getMessage(this.contentChild));
* }
*
* afterContentChecked() {
* // contentChild is updated after the content has been checked
* console.log('AfterContentChecked: ' + this.getMessage(this.contentChild));
* }
*
* private getMessage(cmp: ChildComponent): string {
* return cmp ? cmp.where + ' child' : 'no child';
* }
* }
*
* @Component({
* selector: 'app',
* template: `
* <parent-cmp>
* <button (click)="hasContent = !hasContent">Toggle content child</button>
* <child-cmp *ng-if="hasContent" where="content"></child-cmp>
* </parent-cmp>`,
* directives: [NgIf, ParentComponent, ChildComponent]
* })
* export class App {
* hasContent = true;
* }
*
* bootstrap(App).catch(err => console.error(err));
* ```
*/
export interface AfterContentChecked { afterContentChecked(); }
/**
* Implement this interface to get notified when your component's view has been fully initialized.
*
* ### Example ([live demo](http://plnkr.co/edit/LhTKVMEM0fkJgyp4CI1W?p=preview))
*
* ```typescript
* @Component({selector: 'child-cmp', template: `{{where}} child`})
* class ChildComponent {
* @Input() where: string;
* }
*
* @Component({
* selector: 'parent-cmp',
* template: `<child-cmp where="view"></child-cmp>`,
* directives: [ChildComponent]
* })
* class ParentComponent implements AfterViewInit {
* @ViewChild(ChildComponent) viewChild: ChildComponent;
*
* constructor() {
* // viewChild is not initialized yet
* console.log(this.getMessage(this.viewChild));
* }
*
* afterViewInit() {
* // viewChild is updated after the view has been initialized
* console.log('afterViewInit: ' + this.getMessage(this.viewChild));
* }
*
* private getMessage(cmp: ChildComponent): string {
* return cmp ? cmp.where + ' child' : 'no child';
* }
* }
*
* @Component({
* selector: 'app',
* template: `<parent-cmp></parent-cmp>`,
* directives: [ParentComponent]
* })
* export class App {
* }
*
* bootstrap(App).catch(err => console.error(err));
* ```
*/
export interface AfterViewInit { afterViewInit(); }
/**
* Implement this interface to get notified after every check of your component's view.
*
* ### Example ([live demo](http://plnkr.co/edit/0qDGHcPQkc25CXhTNzKU?p=preview))
*
* ```typescript
* @Component({selector: 'child-cmp', template: `{{where}} child`})
* class ChildComponent {
* @Input() where: string;
* }
*
* @Component({
* selector: 'parent-cmp',
* template: `
* <button (click)="showView = !showView">Toggle view child</button>
* <child-cmp *ng-if="showView" where="view"></child-cmp>`,
* directives: [NgIf, ChildComponent]
* })
* class ParentComponent implements AfterViewChecked {
* @ViewChild(ChildComponent) viewChild: ChildComponent;
* showView = true;
*
* constructor() {
* // viewChild is not initialized yet
* console.log(this.getMessage(this.viewChild));
* }
*
* afterViewChecked() {
* // viewChild is updated after the view has been checked
* console.log('AfterViewChecked: ' + this.getMessage(this.viewChild));
* }
*
* private getMessage(cmp: ChildComponent): string {
* return cmp ? cmp.where + ' child' : 'no child';
* }
* }
*
* @Component({
* selector: 'app',
* template: `<parent-cmp></parent-cmp>`,
* directives: [ParentComponent]
* })
* export class App {
* }
*
* bootstrap(App).catch(err => console.error(err));
* ```
*/
export interface AfterViewChecked { afterViewChecked(); }
| modules/angular2/src/core/linker/interfaces.ts | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.0001938760542543605,
0.00017097636009566486,
0.00016013409185688943,
0.00017212341481354088,
0.0000060724169088643976
] |
{
"id": 1,
"code_window": [
"// todo(robwormald): temporary until https://github.com/angular/angular/issues/4390 decided\n",
"var Rx = require('@reactivex/rxjs/dist/cjs/Rx');\n",
"var {Observable} = Rx;\n",
"export abstract class JSONPConnection implements Connection {\n",
" readyState: ReadyStates;\n",
" request: Request;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"const JSONP_ERR_NO_CALLBACK = 'JSONP injected script did not invoke callback.';\n",
"const JSONP_ERR_WRONG_METHOD = 'JSONP requests must use GET request method.';\n",
"\n"
],
"file_path": "modules/angular2/src/http/backends/jsonp_backend.ts",
"type": "add",
"edit_start_line_idx": 13
} | #!/bin/bash
# Script for removing specified release dir from code.angularjs.org.
echo "################################################"
echo "## Remove a version from code.angular.js.org ###"
echo "################################################"
ARG_DEFS=(
"--action=(prepare|publish)"
"--version-number=([0-9]+\.[0-9]+\.[0-9]+(-[a-z]+\.[0-9]+)?)"
)
function init {
TMP_DIR=$(resolveDir ../../tmp)
REPO_DIR=$TMP_DIR/code.angularjs.org
echo "code tmp $TMP_DIR"
}
function prepare {
echo "-- Cloning code.angularjs.org"
git clone [email protected]:angular/code.angularjs.org.git $REPO_DIR
#
# Remove the files from the repo
#
echo "-- Removing $VERSION_NUMBER from code.angularjs.org"
cd $REPO_DIR
if [ -d "$VERSION_NUMBER" ]; then
git rm -r $VERSION_NUMBER
echo "-- Committing removal to code.angularjs.org"
git commit -m "removing v$VERSION_NUMBER"
else
echo "-- Version: $VERSION_NUMBER does not exist in code.angularjs.org!"
fi
}
function publish {
cd $REPO_DIR
echo "-- Pushing code.angularjs.org to github"
git push origin master
}
source $(dirname $0)/../utils.inc
| tools/code.angularjs.org/unpublish.sh | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.00017745285003911704,
0.00017254229169338942,
0.0001662304566707462,
0.00017398569616489112,
0.000004480882580537582
] |
{
"id": 2,
"code_window": [
"\n",
" constructor(req: Request, private _dom: BrowserJsonp,\n",
" private baseResponseOptions?: ResponseOptions) {\n",
" super();\n",
" if (req.method !== RequestMethods.Get) {\n",
" throw makeTypeError(\"JSONP requests must use GET request method.\");\n",
" }\n",
" this.request = req;\n",
" this.response = new Observable(responseObserver => {\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" throw makeTypeError(JSONP_ERR_WRONG_METHOD);\n"
],
"file_path": "modules/angular2/src/http/backends/jsonp_backend.ts",
"type": "replace",
"edit_start_line_idx": 30
} | import {
AsyncTestCompleter,
afterEach,
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xit,
SpyObject
} from 'angular2/testing_internal';
import {ObservableWrapper} from 'angular2/src/core/facade/async';
import {BrowserJsonp} from 'angular2/src/http/backends/browser_jsonp';
import {
JSONPConnection,
JSONPConnection_,
JSONPBackend,
JSONPBackend_
} from 'angular2/src/http/backends/jsonp_backend';
import {provide, Injector} from 'angular2/core';
import {isPresent, StringWrapper} from 'angular2/src/core/facade/lang';
import {TimerWrapper} from 'angular2/src/core/facade/async';
import {Request} from 'angular2/src/http/static_request';
import {Response} from 'angular2/src/http/static_response';
import {Map} from 'angular2/src/core/facade/collection';
import {RequestOptions, BaseRequestOptions} from 'angular2/src/http/base_request_options';
import {BaseResponseOptions, ResponseOptions} from 'angular2/src/http/base_response_options';
import {ResponseTypes, ReadyStates, RequestMethods} from 'angular2/src/http/enums';
var addEventListenerSpy;
var existingScripts = [];
var unused: Response;
class MockBrowserJsonp extends BrowserJsonp {
src: string;
callbacks = new Map<string, (data: any) => any>();
constructor() { super(); }
addEventListener(type: string, cb: (data: any) => any) { this.callbacks.set(type, cb); }
removeEventListener(type: string, cb: Function) { this.callbacks.delete(type); }
dispatchEvent(type: string, argument?: any) {
if (!isPresent(argument)) {
argument = {};
}
let cb = this.callbacks.get(type);
if (isPresent(cb)) {
cb(argument);
}
}
build(url: string) {
var script = new MockBrowserJsonp();
script.src = url;
existingScripts.push(script);
return script;
}
send(node: any) { /* noop */
}
cleanup(node: any) { /* noop */
}
}
export function main() {
describe('JSONPBackend', () => {
let backend;
let sampleRequest;
beforeEach(() => {
let injector = Injector.resolveAndCreate([
provide(ResponseOptions, {useClass: BaseResponseOptions}),
provide(BrowserJsonp, {useClass: MockBrowserJsonp}),
provide(JSONPBackend, {useClass: JSONPBackend_})
]);
backend = injector.get(JSONPBackend);
let base = new BaseRequestOptions();
sampleRequest = new Request(base.merge(new RequestOptions({url: 'https://google.com'})));
});
afterEach(() => { existingScripts = []; });
it('should create a connection', () => {
var instance;
expect(() => instance = backend.createConnection(sampleRequest)).not.toThrow();
expect(instance).toBeAnInstanceOf(JSONPConnection);
});
describe('JSONPConnection', () => {
it('should use the injected BaseResponseOptions to create the response',
inject([AsyncTestCompleter], async => {
let connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp(),
new ResponseOptions({type: ResponseTypes.Error}));
connection.response.subscribe(res => {
expect(res.type).toBe(ResponseTypes.Error);
async.done();
});
connection.finished();
existingScripts[0].dispatchEvent('load');
}));
it('should ignore load/callback when disposed', inject([AsyncTestCompleter], async => {
var connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp());
let spy = new SpyObject();
let loadSpy = spy.spy('load');
let errorSpy = spy.spy('error');
let returnSpy = spy.spy('cancelled');
let request = connection.response.subscribe(loadSpy, errorSpy, returnSpy);
request.unsubscribe();
connection.finished('Fake data');
existingScripts[0].dispatchEvent('load');
TimerWrapper.setTimeout(() => {
expect(connection.readyState).toBe(ReadyStates.Cancelled);
expect(loadSpy).not.toHaveBeenCalled();
expect(errorSpy).not.toHaveBeenCalled();
expect(returnSpy).not.toHaveBeenCalled();
async.done();
}, 10);
}));
it('should report error if loaded without invoking callback',
inject([AsyncTestCompleter], async => {
let connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp());
connection.response.subscribe(
res => {
expect("response listener called").toBe(false);
async.done();
},
err => {
expect(StringWrapper.contains(err.message, 'did not invoke callback')).toBe(true);
async.done();
});
existingScripts[0].dispatchEvent('load');
}));
it('should report error if script contains error', inject([AsyncTestCompleter], async => {
let connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp());
connection.response.subscribe(
res => {
expect("response listener called").toBe(false);
async.done();
},
err => {
expect(err['message']).toBe('Oops!');
async.done();
});
existingScripts[0].dispatchEvent('error', ({message: "Oops!"}));
}));
it('should throw if request method is not GET', () => {
[RequestMethods.Post, RequestMethods.Put, RequestMethods.Delete, RequestMethods.Options,
RequestMethods.Head, RequestMethods.Patch]
.forEach(method => {
let base = new BaseRequestOptions();
let req = new Request(
base.merge(new RequestOptions({url: 'https://google.com', method: method})));
expect(() => new JSONPConnection_(req, new MockBrowserJsonp()).response.subscribe())
.toThrowError();
});
});
it('should respond with data passed to callback', inject([AsyncTestCompleter], async => {
let connection = new JSONPConnection_(sampleRequest, new MockBrowserJsonp());
connection.response.subscribe(res => {
expect(res.json()).toEqual(({fake_payload: true, blob_id: 12345}));
async.done();
});
connection.finished(({fake_payload: true, blob_id: 12345}));
existingScripts[0].dispatchEvent('load');
}));
});
});
}
| modules/angular2/test/http/backends/jsonp_backend_spec.ts | 1 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.015008409507572651,
0.001555349212139845,
0.00016630830941721797,
0.0001775706623448059,
0.003658245550468564
] |
{
"id": 2,
"code_window": [
"\n",
" constructor(req: Request, private _dom: BrowserJsonp,\n",
" private baseResponseOptions?: ResponseOptions) {\n",
" super();\n",
" if (req.method !== RequestMethods.Get) {\n",
" throw makeTypeError(\"JSONP requests must use GET request method.\");\n",
" }\n",
" this.request = req;\n",
" this.response = new Observable(responseObserver => {\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" throw makeTypeError(JSONP_ERR_WRONG_METHOD);\n"
],
"file_path": "modules/angular2/src/http/backends/jsonp_backend.ts",
"type": "replace",
"edit_start_line_idx": 30
} | var Q = require('q');
var readline = require('readline');
var spawn = require('child_process').spawn;
var util = require('./util');
module.exports = function(gulp, plugins, config) {
config.output = config.output || 'doc/api';
return function() {
return util.forEachSubDirSequential(config.dest, function(dir) {
var defer = Q.defer();
var done = defer.makeNodeResolver();
var supportedModules = [
'dist/dart/angular2',
// TODO: blocked by https://github.com/angular/angular/issues/3518
// 'dist/dart/angular2_material',
'dist/dart/benchpress'
];
if (supportedModules.indexOf(dir) === -1) {
done();
} else {
console.log('INFO: running dartdoc for ', dir);
var stream = spawn(config.command, ['--input=.', '--output=' + config.output], {
stdio: [process.stdin, process.stdout, process.stderr],
cwd: dir
});
stream.on('exit', function(code) {
if (code !== 0) {
done('ERROR: dartdoc exited with non-zero status ' + code);
} else {
done();
}
});
stream.on('error', function(e) {
done('ERROR: dartdoc reported error: ' + e);
});
}
return defer.promise;
});
};
};
| tools/build/dartapidocs.js | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.00017515318177174777,
0.0001739113067742437,
0.00017125136218965054,
0.00017468552687205374,
0.0000014184163319441723
] |
{
"id": 2,
"code_window": [
"\n",
" constructor(req: Request, private _dom: BrowserJsonp,\n",
" private baseResponseOptions?: ResponseOptions) {\n",
" super();\n",
" if (req.method !== RequestMethods.Get) {\n",
" throw makeTypeError(\"JSONP requests must use GET request method.\");\n",
" }\n",
" this.request = req;\n",
" this.response = new Observable(responseObserver => {\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" throw makeTypeError(JSONP_ERR_WRONG_METHOD);\n"
],
"file_path": "modules/angular2/src/http/backends/jsonp_backend.ts",
"type": "replace",
"edit_start_line_idx": 30
} | class ClassDecorator {
final dynamic value;
const ClassDecorator(this.value);
}
class ParamDecorator {
final dynamic value;
const ParamDecorator(this.value);
}
class PropDecorator {
final dynamic value;
const PropDecorator(this.value);
}
ClassDecorator classDecorator(value) {
return new ClassDecorator(value);
}
ParamDecorator paramDecorator(value) {
return new ParamDecorator(value);
}
PropDecorator propDecorator(value) {
return new PropDecorator(value);
}
class HasGetterAndSetterDecorators {
@PropDecorator("get") get a {}
@PropDecorator("set") set a(v) {}
}
| modules/angular2/test/core/reflection/reflector_common.dart | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.00018544185149949044,
0.00017536555242259055,
0.00016838536248542368,
0.0001738174760248512,
0.000006378012585628312
] |
{
"id": 2,
"code_window": [
"\n",
" constructor(req: Request, private _dom: BrowserJsonp,\n",
" private baseResponseOptions?: ResponseOptions) {\n",
" super();\n",
" if (req.method !== RequestMethods.Get) {\n",
" throw makeTypeError(\"JSONP requests must use GET request method.\");\n",
" }\n",
" this.request = req;\n",
" this.response = new Observable(responseObserver => {\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" throw makeTypeError(JSONP_ERR_WRONG_METHOD);\n"
],
"file_path": "modules/angular2/src/http/backends/jsonp_backend.ts",
"type": "replace",
"edit_start_line_idx": 30
} | import {Directive} from 'angular2/src/core/metadata';
import {Host} from 'angular2/src/core/di';
import {ViewContainerRef, TemplateRef} from 'angular2/src/core/linker';
import {isPresent, isBlank, normalizeBlank, CONST_EXPR} from 'angular2/src/core/facade/lang';
import {ListWrapper, Map} from 'angular2/src/core/facade/collection';
const _WHEN_DEFAULT = CONST_EXPR(new Object());
export class SwitchView {
constructor(private _viewContainerRef: ViewContainerRef, private _templateRef: TemplateRef) {}
create(): void { this._viewContainerRef.createEmbeddedView(this._templateRef); }
destroy(): void { this._viewContainerRef.clear(); }
}
/**
* The `NgSwitch` directive is used to conditionally swap DOM structure on your template based on a
* scope expression.
* Elements within `NgSwitch` but without `NgSwitchWhen` or `NgSwitchDefault` directives will be
* preserved at the location as specified in the template.
*
* `NgSwitch` simply chooses nested elements and makes them visible based on which element matches
* the value obtained from the evaluated expression. In other words, you define a container element
* (where you place the directive), place an expression on the **`[ng-switch]="..."` attribute**),
* define any inner elements inside of the directive and place a `[ng-switch-when]` attribute per
* element.
* The when attribute is used to inform NgSwitch which element to display when the expression is
* evaluated. If a matching expression is not found via a when attribute then an element with the
* default attribute is displayed.
*
* ### Example
*
* ```
* <ANY [ng-switch]="expression">
* <template [ng-switch-when]="whenExpression1">...</template>
* <template [ng-switch-when]="whenExpression1">...</template>
* <template ng-switch-default>...</template>
* </ANY>
* ```
*/
@Directive({selector: '[ng-switch]', inputs: ['ngSwitch']})
export class NgSwitch {
private _switchValue: any;
private _useDefault: boolean = false;
private _valueViews = new Map<any, SwitchView[]>();
private _activeViews: SwitchView[] = [];
set ngSwitch(value) {
// Empty the currently active ViewContainers
this._emptyAllActiveViews();
// Add the ViewContainers matching the value (with a fallback to default)
this._useDefault = false;
var views = this._valueViews.get(value);
if (isBlank(views)) {
this._useDefault = true;
views = normalizeBlank(this._valueViews.get(_WHEN_DEFAULT));
}
this._activateViews(views);
this._switchValue = value;
}
/** @internal */
_onWhenValueChanged(oldWhen, newWhen, view: SwitchView): void {
this._deregisterView(oldWhen, view);
this._registerView(newWhen, view);
if (oldWhen === this._switchValue) {
view.destroy();
ListWrapper.remove(this._activeViews, view);
} else if (newWhen === this._switchValue) {
if (this._useDefault) {
this._useDefault = false;
this._emptyAllActiveViews();
}
view.create();
this._activeViews.push(view);
}
// Switch to default when there is no more active ViewContainers
if (this._activeViews.length === 0 && !this._useDefault) {
this._useDefault = true;
this._activateViews(this._valueViews.get(_WHEN_DEFAULT));
}
}
/** @internal */
_emptyAllActiveViews(): void {
var activeContainers = this._activeViews;
for (var i = 0; i < activeContainers.length; i++) {
activeContainers[i].destroy();
}
this._activeViews = [];
}
/** @internal */
_activateViews(views: SwitchView[]): void {
// TODO(vicb): assert(this._activeViews.length === 0);
if (isPresent(views)) {
for (var i = 0; i < views.length; i++) {
views[i].create();
}
this._activeViews = views;
}
}
/** @internal */
_registerView(value, view: SwitchView): void {
var views = this._valueViews.get(value);
if (isBlank(views)) {
views = [];
this._valueViews.set(value, views);
}
views.push(view);
}
/** @internal */
_deregisterView(value, view: SwitchView): void {
// `_WHEN_DEFAULT` is used a marker for non-registered whens
if (value === _WHEN_DEFAULT) return;
var views = this._valueViews.get(value);
if (views.length == 1) {
this._valueViews.delete(value);
} else {
ListWrapper.remove(views, view);
}
}
}
/**
* Defines a case statement as an expression.
*
* If multiple `NgSwitchWhen` match the `NgSwitch` value, all of them are displayed.
*
* Example:
*
* ```
* // match against a context variable
* <template [ng-switch-when]="contextVariable">...</template>
*
* // match against a constant string
* <template ng-switch-when="stringValue">...</template>
* ```
*/
@Directive({selector: '[ng-switch-when]', inputs: ['ngSwitchWhen']})
export class NgSwitchWhen {
// `_WHEN_DEFAULT` is used as a marker for a not yet initialized value
/** @internal */
_value: any = _WHEN_DEFAULT;
/** @internal */
_view: SwitchView;
constructor(viewContainer: ViewContainerRef, templateRef: TemplateRef,
@Host() private _switch: NgSwitch) {
this._view = new SwitchView(viewContainer, templateRef);
}
set ngSwitchWhen(value) {
this._switch._onWhenValueChanged(this._value, value, this._view);
this._value = value;
}
}
/**
* Defines a default case statement.
*
* Default case statements are displayed when no `NgSwitchWhen` match the `ng-switch` value.
*
* Example:
*
* ```
* <template ng-switch-default>...</template>
* ```
*/
@Directive({selector: '[ng-switch-default]'})
export class NgSwitchDefault {
constructor(viewContainer: ViewContainerRef, templateRef: TemplateRef,
@Host() sswitch: NgSwitch) {
sswitch._registerView(_WHEN_DEFAULT, new SwitchView(viewContainer, templateRef));
}
}
| modules/angular2/src/core/directives/ng_switch.ts | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.001559379044920206,
0.0002467554004397243,
0.00016476005839649588,
0.0001733785611577332,
0.0003094518033321947
] |
{
"id": 3,
"code_window": [
" let onLoad = event => {\n",
" if (this.readyState === ReadyStates.Cancelled) return;\n",
" this.readyState = ReadyStates.Done;\n",
" _dom.cleanup(script);\n",
" if (!this._finished) {\n",
" responseObserver.error(makeTypeError('JSONP injected script did not invoke callback.'));\n",
" return;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" let responseOptions =\n",
" new ResponseOptions({body: JSONP_ERR_NO_CALLBACK, type: ResponseTypes.Error});\n",
" if (isPresent(baseResponseOptions)) {\n",
" responseOptions = baseResponseOptions.merge(responseOptions);\n",
" }\n",
" responseObserver.error(new Response(responseOptions));\n"
],
"file_path": "modules/angular2/src/http/backends/jsonp_backend.ts",
"type": "replace",
"edit_start_line_idx": 58
} | import {ConnectionBackend, Connection} from '../interfaces';
import {ReadyStates, RequestMethods} from '../enums';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {ResponseOptions, BaseResponseOptions} from '../base_response_options';
import {Injectable} from 'angular2/angular2';
import {BrowserJsonp} from './browser_jsonp';
import {EventEmitter, ObservableWrapper} from 'angular2/src/core/facade/async';
import {makeTypeError} from 'angular2/src/core/facade/exceptions';
import {StringWrapper, isPresent} from 'angular2/src/core/facade/lang';
// todo(robwormald): temporary until https://github.com/angular/angular/issues/4390 decided
var Rx = require('@reactivex/rxjs/dist/cjs/Rx');
var {Observable} = Rx;
export abstract class JSONPConnection implements Connection {
readyState: ReadyStates;
request: Request;
response: any;
abstract finished(data?: any): void;
}
export class JSONPConnection_ extends JSONPConnection {
private _id: string;
private _script: Element;
private _responseData: any;
private _finished: boolean = false;
constructor(req: Request, private _dom: BrowserJsonp,
private baseResponseOptions?: ResponseOptions) {
super();
if (req.method !== RequestMethods.Get) {
throw makeTypeError("JSONP requests must use GET request method.");
}
this.request = req;
this.response = new Observable(responseObserver => {
this.readyState = ReadyStates.Loading;
let id = this._id = _dom.nextRequestID();
_dom.exposeConnection(id, this);
// Workaround Dart
// url = url.replace(/=JSONP_CALLBACK(&|$)/, `generated method`);
let callback = _dom.requestCallback(this._id);
let url: string = req.url;
if (url.indexOf('=JSONP_CALLBACK&') > -1) {
url = StringWrapper.replace(url, '=JSONP_CALLBACK&', `=${callback}&`);
} else if (url.lastIndexOf('=JSONP_CALLBACK') === url.length - '=JSONP_CALLBACK'.length) {
url =
StringWrapper.substring(url, 0, url.length - '=JSONP_CALLBACK'.length) + `=${callback}`;
}
let script = this._script = _dom.build(url);
let onLoad = event => {
if (this.readyState === ReadyStates.Cancelled) return;
this.readyState = ReadyStates.Done;
_dom.cleanup(script);
if (!this._finished) {
responseObserver.error(makeTypeError('JSONP injected script did not invoke callback.'));
return;
}
let responseOptions = new ResponseOptions({body: this._responseData});
if (isPresent(this.baseResponseOptions)) {
responseOptions = this.baseResponseOptions.merge(responseOptions);
}
responseObserver.next(new Response(responseOptions));
responseObserver.complete();
};
let onError = error => {
if (this.readyState === ReadyStates.Cancelled) return;
this.readyState = ReadyStates.Done;
_dom.cleanup(script);
responseObserver.error(error);
};
script.addEventListener('load', onLoad);
script.addEventListener('error', onError);
_dom.send(script);
return () => {
this.readyState = ReadyStates.Cancelled;
script.removeEventListener('load', onLoad);
script.removeEventListener('error', onError);
if (isPresent(script)) {
this._dom.cleanup(script);
}
};
});
}
finished(data?: any) {
// Don't leak connections
this._finished = true;
this._dom.removeConnection(this._id);
if (this.readyState === ReadyStates.Cancelled) return;
this._responseData = data;
}
}
export abstract class JSONPBackend extends ConnectionBackend {}
@Injectable()
export class JSONPBackend_ extends JSONPBackend {
constructor(private _browserJSONP: BrowserJsonp, private _baseResponseOptions: ResponseOptions) {
super();
}
createConnection(request: Request): JSONPConnection {
return new JSONPConnection_(request, this._browserJSONP, this._baseResponseOptions);
}
}
| modules/angular2/src/http/backends/jsonp_backend.ts | 1 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.99839848279953,
0.2501533031463623,
0.00016520952340215445,
0.0018575000576674938,
0.4309008717536926
] |
{
"id": 3,
"code_window": [
" let onLoad = event => {\n",
" if (this.readyState === ReadyStates.Cancelled) return;\n",
" this.readyState = ReadyStates.Done;\n",
" _dom.cleanup(script);\n",
" if (!this._finished) {\n",
" responseObserver.error(makeTypeError('JSONP injected script did not invoke callback.'));\n",
" return;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" let responseOptions =\n",
" new ResponseOptions({body: JSONP_ERR_NO_CALLBACK, type: ResponseTypes.Error});\n",
" if (isPresent(baseResponseOptions)) {\n",
" responseOptions = baseResponseOptions.merge(responseOptions);\n",
" }\n",
" responseObserver.error(new Response(responseOptions));\n"
],
"file_path": "modules/angular2/src/http/backends/jsonp_backend.ts",
"type": "replace",
"edit_start_line_idx": 58
} | import {
AsyncTestCompleter,
beforeEach,
ddescribe,
describe,
el,
expect,
iit,
inject,
it,
xit,
TestComponentBuilder,
beforeEachBindings
} from 'angular2/testing_internal';
import {MapWrapper} from 'angular2/src/core/facade/collection';
import {
CompileDirectiveMetadata,
CompileTypeMetadata
} from 'angular2/src/core/compiler/directive_metadata';
import {TemplateParser} from 'angular2/src/core/compiler/template_parser';
import {
Parser,
Lexer,
ChangeDetectorDefinition,
ChangeDetectorGenConfig,
DynamicProtoChangeDetector,
ChangeDetectionStrategy,
ChangeDispatcher,
DirectiveIndex,
Locals,
BindingTarget,
ChangeDetector
} from 'angular2/src/core/change_detection/change_detection';
import {Pipes} from 'angular2/src/core/change_detection/pipes';
import {
createChangeDetectorDefinitions
} from 'angular2/src/core/compiler/change_definition_factory';
import {TestDirective, TestDispatcher, TestPipes} from './change_detector_mocks';
import {TEST_PROVIDERS} from './test_bindings';
export function main() {
describe('ChangeDefinitionFactory', () => {
beforeEachBindings(() => TEST_PROVIDERS);
var parser: TemplateParser;
var dispatcher: TestDispatcher;
var context: TestContext;
var directive: TestDirective;
var locals: Locals;
var pipes: Pipes;
var eventLocals: Locals;
beforeEach(inject([TemplateParser], (_templateParser) => {
parser = _templateParser;
context = new TestContext();
directive = new TestDirective();
dispatcher = new TestDispatcher([directive], []);
locals = new Locals(null, MapWrapper.createFromStringMap({'someVar': null}));
eventLocals = new Locals(null, MapWrapper.createFromStringMap({'$event': null}));
pipes = new TestPipes();
}));
function createChangeDetector(template: string, directives: CompileDirectiveMetadata[],
protoViewIndex: number = 0): ChangeDetector {
var protoChangeDetectors =
createChangeDetectorDefinitions(new CompileTypeMetadata({name: 'SomeComp'}),
ChangeDetectionStrategy.Default,
new ChangeDetectorGenConfig(true, true, false, false),
parser.parse(template, directives, 'TestComp'))
.map(definition => new DynamicProtoChangeDetector(definition));
var changeDetector = protoChangeDetectors[protoViewIndex].instantiate(dispatcher);
changeDetector.hydrate(context, locals, dispatcher, pipes);
return changeDetector;
}
it('should watch element properties', () => {
var changeDetector = createChangeDetector('<div [el-prop]="someProp">', [], 0);
context.someProp = 'someValue';
changeDetector.detectChanges();
expect(dispatcher.log).toEqual(['elementProperty(elProp)=someValue']);
});
it('should watch text nodes', () => {
var changeDetector = createChangeDetector('{{someProp}}', [], 0);
context.someProp = 'someValue';
changeDetector.detectChanges();
expect(dispatcher.log).toEqual(['textNode(null)=someValue']);
});
it('should handle events on regular elements', () => {
var changeDetector = createChangeDetector('<div on-click="onEvent($event)">', [], 0);
eventLocals.set('$event', 'click');
changeDetector.handleEvent('click', 0, eventLocals);
expect(context.eventLog).toEqual(['click']);
});
it('should handle events on template elements', () => {
var dirMeta = CompileDirectiveMetadata.create({
type: new CompileTypeMetadata({name: 'SomeDir'}),
selector: 'template',
outputs: ['click']
});
var changeDetector =
createChangeDetector('<template on-click="onEvent($event)">', [dirMeta], 0);
eventLocals.set('$event', 'click');
changeDetector.handleEvent('click', 0, eventLocals);
expect(context.eventLog).toEqual(['click']);
});
it('should handle events with targets', () => {
var changeDetector = createChangeDetector('<div (window:click)="onEvent($event)">', [], 0);
eventLocals.set('$event', 'click');
changeDetector.handleEvent('window:click', 0, eventLocals);
expect(context.eventLog).toEqual(['click']);
});
it('should watch variables', () => {
var changeDetector = createChangeDetector('<div #some-var [el-prop]="someVar">', [], 0);
locals.set('someVar', 'someValue');
changeDetector.detectChanges();
expect(dispatcher.log).toEqual(['elementProperty(elProp)=someValue']);
});
it('should write directive properties', () => {
var dirMeta = CompileDirectiveMetadata.create({
type: new CompileTypeMetadata({name: 'SomeDir'}),
selector: '[dir-prop]',
inputs: ['dirProp']
});
var changeDetector = createChangeDetector('<div [dir-prop]="someProp">', [dirMeta], 0);
context.someProp = 'someValue';
changeDetector.detectChanges();
expect(directive.dirProp).toEqual('someValue');
});
it('should write template directive properties', () => {
var dirMeta = CompileDirectiveMetadata.create({
type: new CompileTypeMetadata({name: 'SomeDir'}),
selector: '[dir-prop]',
inputs: ['dirProp']
});
var changeDetector = createChangeDetector('<template [dir-prop]="someProp">', [dirMeta], 0);
context.someProp = 'someValue';
changeDetector.detectChanges();
expect(directive.dirProp).toEqual('someValue');
});
it('should watch directive host properties', () => {
var dirMeta = CompileDirectiveMetadata.create({
type: new CompileTypeMetadata({name: 'SomeDir'}),
selector: 'div',
host: {'[elProp]': 'dirProp'}
});
var changeDetector = createChangeDetector('<div>', [dirMeta], 0);
directive.dirProp = 'someValue';
changeDetector.detectChanges();
expect(dispatcher.log).toEqual(['elementProperty(elProp)=someValue']);
});
it('should handle directive events', () => {
var dirMeta = CompileDirectiveMetadata.create({
type: new CompileTypeMetadata({name: 'SomeDir'}),
selector: 'div',
host: {'(click)': 'onEvent($event)'}
});
var changeDetector = createChangeDetector('<div>', [dirMeta], 0);
eventLocals.set('$event', 'click');
changeDetector.handleEvent('click', 0, eventLocals);
expect(directive.eventLog).toEqual(['click']);
});
it('should create change detectors for embedded templates', () => {
var changeDetector = createChangeDetector('<template>{{someProp}}<template>', [], 1);
context.someProp = 'someValue';
changeDetector.detectChanges();
expect(dispatcher.log).toEqual(['textNode(null)=someValue']);
});
it('should watch expressions after embedded templates', () => {
var changeDetector =
createChangeDetector('<template>{{someProp2}}</template>{{someProp}}', [], 0);
context.someProp = 'someValue';
changeDetector.detectChanges();
expect(dispatcher.log).toEqual(['textNode(null)=someValue']);
});
});
}
class TestContext {
eventLog: string[] = [];
someProp: string;
someProp2: string;
onEvent(value: string) { this.eventLog.push(value); }
}
| modules/angular2/test/core/compiler/change_definition_factory_spec.ts | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.00017891636525746435,
0.00017430755542591214,
0.00016358726134058088,
0.0001759046717779711,
0.000003987253421655623
] |
{
"id": 3,
"code_window": [
" let onLoad = event => {\n",
" if (this.readyState === ReadyStates.Cancelled) return;\n",
" this.readyState = ReadyStates.Done;\n",
" _dom.cleanup(script);\n",
" if (!this._finished) {\n",
" responseObserver.error(makeTypeError('JSONP injected script did not invoke callback.'));\n",
" return;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" let responseOptions =\n",
" new ResponseOptions({body: JSONP_ERR_NO_CALLBACK, type: ResponseTypes.Error});\n",
" if (isPresent(baseResponseOptions)) {\n",
" responseOptions = baseResponseOptions.merge(responseOptions);\n",
" }\n",
" responseObserver.error(new Response(responseOptions));\n"
],
"file_path": "modules/angular2/src/http/backends/jsonp_backend.ts",
"type": "replace",
"edit_start_line_idx": 58
} |
export function stringify(obj: any): string {
if (typeof obj == 'function') return obj.name || obj.toString();
return '' + obj;
}
export function onError(e: any) {
// TODO: (misko): We seem to not have a stack trace here!
console.log(e, e.stack);
throw e;
}
export function controllerKey(name: string): string {
return '$' + name + 'Controller';
}
| modules/angular2/src/upgrade/util.ts | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.0001832830166677013,
0.00017863990797195584,
0.00017399679927621037,
0.00017863990797195584,
0.000004643108695745468
] |
{
"id": 3,
"code_window": [
" let onLoad = event => {\n",
" if (this.readyState === ReadyStates.Cancelled) return;\n",
" this.readyState = ReadyStates.Done;\n",
" _dom.cleanup(script);\n",
" if (!this._finished) {\n",
" responseObserver.error(makeTypeError('JSONP injected script did not invoke callback.'));\n",
" return;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" let responseOptions =\n",
" new ResponseOptions({body: JSONP_ERR_NO_CALLBACK, type: ResponseTypes.Error});\n",
" if (isPresent(baseResponseOptions)) {\n",
" responseOptions = baseResponseOptions.merge(responseOptions);\n",
" }\n",
" responseObserver.error(new Response(responseOptions));\n"
],
"file_path": "modules/angular2/src/http/backends/jsonp_backend.ts",
"type": "replace",
"edit_start_line_idx": 58
} | library benchmarks.e2e_test.largetable_perf;
main() {}
| modules/benchmarks/e2e_test/largetable_perf.dart | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.0001748901850078255,
0.0001748901850078255,
0.0001748901850078255,
0.0001748901850078255,
0
] |
{
"id": 4,
"code_window": [
" let onError = error => {\n",
" if (this.readyState === ReadyStates.Cancelled) return;\n",
" this.readyState = ReadyStates.Done;\n",
" _dom.cleanup(script);\n",
" responseObserver.error(error);\n",
" };\n",
"\n",
" script.addEventListener('load', onLoad);\n",
" script.addEventListener('error', onError);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" let responseOptions = new ResponseOptions({body: error.message, type: ResponseTypes.Error});\n",
" if (isPresent(baseResponseOptions)) {\n",
" responseOptions = baseResponseOptions.merge(responseOptions);\n",
" }\n",
" responseObserver.error(new Response(responseOptions));\n"
],
"file_path": "modules/angular2/src/http/backends/jsonp_backend.ts",
"type": "replace",
"edit_start_line_idx": 75
} | import {ConnectionBackend, Connection} from '../interfaces';
import {ReadyStates, RequestMethods} from '../enums';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {ResponseOptions, BaseResponseOptions} from '../base_response_options';
import {Injectable} from 'angular2/angular2';
import {BrowserJsonp} from './browser_jsonp';
import {EventEmitter, ObservableWrapper} from 'angular2/src/core/facade/async';
import {makeTypeError} from 'angular2/src/core/facade/exceptions';
import {StringWrapper, isPresent} from 'angular2/src/core/facade/lang';
// todo(robwormald): temporary until https://github.com/angular/angular/issues/4390 decided
var Rx = require('@reactivex/rxjs/dist/cjs/Rx');
var {Observable} = Rx;
export abstract class JSONPConnection implements Connection {
readyState: ReadyStates;
request: Request;
response: any;
abstract finished(data?: any): void;
}
export class JSONPConnection_ extends JSONPConnection {
private _id: string;
private _script: Element;
private _responseData: any;
private _finished: boolean = false;
constructor(req: Request, private _dom: BrowserJsonp,
private baseResponseOptions?: ResponseOptions) {
super();
if (req.method !== RequestMethods.Get) {
throw makeTypeError("JSONP requests must use GET request method.");
}
this.request = req;
this.response = new Observable(responseObserver => {
this.readyState = ReadyStates.Loading;
let id = this._id = _dom.nextRequestID();
_dom.exposeConnection(id, this);
// Workaround Dart
// url = url.replace(/=JSONP_CALLBACK(&|$)/, `generated method`);
let callback = _dom.requestCallback(this._id);
let url: string = req.url;
if (url.indexOf('=JSONP_CALLBACK&') > -1) {
url = StringWrapper.replace(url, '=JSONP_CALLBACK&', `=${callback}&`);
} else if (url.lastIndexOf('=JSONP_CALLBACK') === url.length - '=JSONP_CALLBACK'.length) {
url =
StringWrapper.substring(url, 0, url.length - '=JSONP_CALLBACK'.length) + `=${callback}`;
}
let script = this._script = _dom.build(url);
let onLoad = event => {
if (this.readyState === ReadyStates.Cancelled) return;
this.readyState = ReadyStates.Done;
_dom.cleanup(script);
if (!this._finished) {
responseObserver.error(makeTypeError('JSONP injected script did not invoke callback.'));
return;
}
let responseOptions = new ResponseOptions({body: this._responseData});
if (isPresent(this.baseResponseOptions)) {
responseOptions = this.baseResponseOptions.merge(responseOptions);
}
responseObserver.next(new Response(responseOptions));
responseObserver.complete();
};
let onError = error => {
if (this.readyState === ReadyStates.Cancelled) return;
this.readyState = ReadyStates.Done;
_dom.cleanup(script);
responseObserver.error(error);
};
script.addEventListener('load', onLoad);
script.addEventListener('error', onError);
_dom.send(script);
return () => {
this.readyState = ReadyStates.Cancelled;
script.removeEventListener('load', onLoad);
script.removeEventListener('error', onError);
if (isPresent(script)) {
this._dom.cleanup(script);
}
};
});
}
finished(data?: any) {
// Don't leak connections
this._finished = true;
this._dom.removeConnection(this._id);
if (this.readyState === ReadyStates.Cancelled) return;
this._responseData = data;
}
}
export abstract class JSONPBackend extends ConnectionBackend {}
@Injectable()
export class JSONPBackend_ extends JSONPBackend {
constructor(private _browserJSONP: BrowserJsonp, private _baseResponseOptions: ResponseOptions) {
super();
}
createConnection(request: Request): JSONPConnection {
return new JSONPConnection_(request, this._browserJSONP, this._baseResponseOptions);
}
}
| modules/angular2/src/http/backends/jsonp_backend.ts | 1 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.9986093044281006,
0.24777992069721222,
0.00016474576841574162,
0.00036580575397238135,
0.4282805323600769
] |
{
"id": 4,
"code_window": [
" let onError = error => {\n",
" if (this.readyState === ReadyStates.Cancelled) return;\n",
" this.readyState = ReadyStates.Done;\n",
" _dom.cleanup(script);\n",
" responseObserver.error(error);\n",
" };\n",
"\n",
" script.addEventListener('load', onLoad);\n",
" script.addEventListener('error', onError);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" let responseOptions = new ResponseOptions({body: error.message, type: ResponseTypes.Error});\n",
" if (isPresent(baseResponseOptions)) {\n",
" responseOptions = baseResponseOptions.merge(responseOptions);\n",
" }\n",
" responseObserver.error(new Response(responseOptions));\n"
],
"file_path": "modules/angular2/src/http/backends/jsonp_backend.ts",
"type": "replace",
"edit_start_line_idx": 75
} | library angular2.transform.reflection_remover.codegen;
import 'package:angular2/src/transform/common/names.dart';
import 'package:barback/barback.dart';
import 'package:path/path.dart' as path;
class Codegen {
static const _PREFIX_BASE = 'ngStaticInit';
final AssetId reflectionEntryPoint;
/// The prefix used to import our generated file.
final String prefix;
Codegen(this.reflectionEntryPoint, {String prefix})
: this.prefix = prefix == null ? _PREFIX_BASE : prefix {
if (this.prefix.isEmpty) throw new ArgumentError.value('(empty)', 'prefix');
}
/// Generates code to import the library containing the method which sets up
/// Angular2 reflection statically.
///
/// The code generated here should follow the example of code generated for
/// an {@link ImportDirective} node.
String codegenImport() {
var importUri = path
.basename(reflectionEntryPoint.changeExtension(DEPS_EXTENSION).path);
return '''import '$importUri' as $prefix;''';
}
/// Generates code to call the method which sets up Angular2 reflection
/// statically.
String codegenSetupReflectionCall() {
return '$prefix.$SETUP_METHOD_NAME();';
}
}
| modules_dart/transform/lib/src/transform/reflection_remover/codegen.dart | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.00017283651686739177,
0.00017122409190051258,
0.0001697342813713476,
0.00017116277012974024,
0.000001116040607485047
] |
{
"id": 4,
"code_window": [
" let onError = error => {\n",
" if (this.readyState === ReadyStates.Cancelled) return;\n",
" this.readyState = ReadyStates.Done;\n",
" _dom.cleanup(script);\n",
" responseObserver.error(error);\n",
" };\n",
"\n",
" script.addEventListener('load', onLoad);\n",
" script.addEventListener('error', onError);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" let responseOptions = new ResponseOptions({body: error.message, type: ResponseTypes.Error});\n",
" if (isPresent(baseResponseOptions)) {\n",
" responseOptions = baseResponseOptions.merge(responseOptions);\n",
" }\n",
" responseObserver.error(new Response(responseOptions));\n"
],
"file_path": "modules/angular2/src/http/backends/jsonp_backend.ts",
"type": "replace",
"edit_start_line_idx": 75
} | name: angular
environment:
sdk: '>=1.12.0-dev.5.10 <2.0.0'
dependencies:
observe: '^0.13.1'
dev_dependencies:
guinness: '^0.1.17'
intl: '^0.12.4'
unittest: '^0.11.5+4'
quiver: '^0.21.4'
| pubspec.yaml | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.00017276254948228598,
0.00017086330626625568,
0.00016896406305022538,
0.00017086330626625568,
0.0000018992432160302997
] |
{
"id": 4,
"code_window": [
" let onError = error => {\n",
" if (this.readyState === ReadyStates.Cancelled) return;\n",
" this.readyState = ReadyStates.Done;\n",
" _dom.cleanup(script);\n",
" responseObserver.error(error);\n",
" };\n",
"\n",
" script.addEventListener('load', onLoad);\n",
" script.addEventListener('error', onError);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" let responseOptions = new ResponseOptions({body: error.message, type: ResponseTypes.Error});\n",
" if (isPresent(baseResponseOptions)) {\n",
" responseOptions = baseResponseOptions.merge(responseOptions);\n",
" }\n",
" responseObserver.error(new Response(responseOptions));\n"
],
"file_path": "modules/angular2/src/http/backends/jsonp_backend.ts",
"type": "replace",
"edit_start_line_idx": 75
} | library playground.e2e_test.material.progress_linear_spec;
main() {}
| modules/playground/e2e_test/material/progress_linear_spec.dart | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.00017098082753363997,
0.00017098082753363997,
0.00017098082753363997,
0.00017098082753363997,
0
] |
{
"id": 5,
"code_window": [
" res => {\n",
" expect(\"response listener called\").toBe(false);\n",
" async.done();\n",
" },\n",
" err => {\n",
" expect(StringWrapper.contains(err.message, 'did not invoke callback')).toBe(true);\n",
" async.done();\n",
" });\n",
"\n",
" existingScripts[0].dispatchEvent('load');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(err.text()).toEqual('JSONP injected script did not invoke callback.');\n"
],
"file_path": "modules/angular2/test/http/backends/jsonp_backend_spec.ts",
"type": "replace",
"edit_start_line_idx": 136
} | import {ConnectionBackend, Connection} from '../interfaces';
import {ReadyStates, RequestMethods} from '../enums';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {ResponseOptions, BaseResponseOptions} from '../base_response_options';
import {Injectable} from 'angular2/angular2';
import {BrowserJsonp} from './browser_jsonp';
import {EventEmitter, ObservableWrapper} from 'angular2/src/core/facade/async';
import {makeTypeError} from 'angular2/src/core/facade/exceptions';
import {StringWrapper, isPresent} from 'angular2/src/core/facade/lang';
// todo(robwormald): temporary until https://github.com/angular/angular/issues/4390 decided
var Rx = require('@reactivex/rxjs/dist/cjs/Rx');
var {Observable} = Rx;
export abstract class JSONPConnection implements Connection {
readyState: ReadyStates;
request: Request;
response: any;
abstract finished(data?: any): void;
}
export class JSONPConnection_ extends JSONPConnection {
private _id: string;
private _script: Element;
private _responseData: any;
private _finished: boolean = false;
constructor(req: Request, private _dom: BrowserJsonp,
private baseResponseOptions?: ResponseOptions) {
super();
if (req.method !== RequestMethods.Get) {
throw makeTypeError("JSONP requests must use GET request method.");
}
this.request = req;
this.response = new Observable(responseObserver => {
this.readyState = ReadyStates.Loading;
let id = this._id = _dom.nextRequestID();
_dom.exposeConnection(id, this);
// Workaround Dart
// url = url.replace(/=JSONP_CALLBACK(&|$)/, `generated method`);
let callback = _dom.requestCallback(this._id);
let url: string = req.url;
if (url.indexOf('=JSONP_CALLBACK&') > -1) {
url = StringWrapper.replace(url, '=JSONP_CALLBACK&', `=${callback}&`);
} else if (url.lastIndexOf('=JSONP_CALLBACK') === url.length - '=JSONP_CALLBACK'.length) {
url =
StringWrapper.substring(url, 0, url.length - '=JSONP_CALLBACK'.length) + `=${callback}`;
}
let script = this._script = _dom.build(url);
let onLoad = event => {
if (this.readyState === ReadyStates.Cancelled) return;
this.readyState = ReadyStates.Done;
_dom.cleanup(script);
if (!this._finished) {
responseObserver.error(makeTypeError('JSONP injected script did not invoke callback.'));
return;
}
let responseOptions = new ResponseOptions({body: this._responseData});
if (isPresent(this.baseResponseOptions)) {
responseOptions = this.baseResponseOptions.merge(responseOptions);
}
responseObserver.next(new Response(responseOptions));
responseObserver.complete();
};
let onError = error => {
if (this.readyState === ReadyStates.Cancelled) return;
this.readyState = ReadyStates.Done;
_dom.cleanup(script);
responseObserver.error(error);
};
script.addEventListener('load', onLoad);
script.addEventListener('error', onError);
_dom.send(script);
return () => {
this.readyState = ReadyStates.Cancelled;
script.removeEventListener('load', onLoad);
script.removeEventListener('error', onError);
if (isPresent(script)) {
this._dom.cleanup(script);
}
};
});
}
finished(data?: any) {
// Don't leak connections
this._finished = true;
this._dom.removeConnection(this._id);
if (this.readyState === ReadyStates.Cancelled) return;
this._responseData = data;
}
}
export abstract class JSONPBackend extends ConnectionBackend {}
@Injectable()
export class JSONPBackend_ extends JSONPBackend {
constructor(private _browserJSONP: BrowserJsonp, private _baseResponseOptions: ResponseOptions) {
super();
}
createConnection(request: Request): JSONPConnection {
return new JSONPConnection_(request, this._browserJSONP, this._baseResponseOptions);
}
}
| modules/angular2/src/http/backends/jsonp_backend.ts | 1 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.0003676866181194782,
0.00019010134565178305,
0.00016416555445175618,
0.00016675145889166743,
0.000056483997468603775
] |
{
"id": 5,
"code_window": [
" res => {\n",
" expect(\"response listener called\").toBe(false);\n",
" async.done();\n",
" },\n",
" err => {\n",
" expect(StringWrapper.contains(err.message, 'did not invoke callback')).toBe(true);\n",
" async.done();\n",
" });\n",
"\n",
" existingScripts[0].dispatchEvent('load');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(err.text()).toEqual('JSONP injected script did not invoke callback.');\n"
],
"file_path": "modules/angular2/test/http/backends/jsonp_backend_spec.ts",
"type": "replace",
"edit_start_line_idx": 136
} | ///
// Generated code. Do not modify.
///
library angular2.src.transform.common.model.proto_ng_deps_model;
import 'package:protobuf/protobuf.dart';
import 'import_export_model.pb.dart';
import 'reflection_info_model.pb.dart';
class NgDepsModel extends GeneratedMessage {
static final BuilderInfo _i = new BuilderInfo('NgDepsModel')
..a(1, 'libraryUri', PbFieldType.OS)
..p(2, 'partUris', PbFieldType.PS)
..pp(3, 'imports', PbFieldType.PM, ImportModel.$checkItem,
ImportModel.create)
..pp(4, 'exports', PbFieldType.PM, ExportModel.$checkItem,
ExportModel.create)
..pp(5, 'reflectables', PbFieldType.PM, ReflectionInfoModel.$checkItem,
ReflectionInfoModel.create)
..a(6, 'sourceFile', PbFieldType.OS)
..p(7, 'getters', PbFieldType.PS)
..p(8, 'setters', PbFieldType.PS)
..p(9, 'methods', PbFieldType.PS);
NgDepsModel() : super();
NgDepsModel.fromBuffer(List<int> i,
[ExtensionRegistry r = ExtensionRegistry.EMPTY])
: super.fromBuffer(i, r);
NgDepsModel.fromJson(String i,
[ExtensionRegistry r = ExtensionRegistry.EMPTY])
: super.fromJson(i, r);
NgDepsModel clone() => new NgDepsModel()..mergeFromMessage(this);
BuilderInfo get info_ => _i;
static NgDepsModel create() => new NgDepsModel();
static PbList<NgDepsModel> createRepeated() => new PbList<NgDepsModel>();
static NgDepsModel getDefault() {
if (_defaultInstance == null) _defaultInstance = new _ReadonlyNgDepsModel();
return _defaultInstance;
}
static NgDepsModel _defaultInstance;
static void $checkItem(NgDepsModel v) {
if (v is! NgDepsModel) checkItemFailed(v, 'NgDepsModel');
}
String get libraryUri => $_get(0, 1, '');
void set libraryUri(String v) {
$_setString(0, 1, v);
}
bool hasLibraryUri() => $_has(0, 1);
void clearLibraryUri() => clearField(1);
List<String> get partUris => $_get(1, 2, null);
List<ImportModel> get imports => $_get(2, 3, null);
List<ExportModel> get exports => $_get(3, 4, null);
List<ReflectionInfoModel> get reflectables => $_get(4, 5, null);
String get sourceFile => $_get(5, 6, '');
void set sourceFile(String v) {
$_setString(5, 6, v);
}
bool hasSourceFile() => $_has(5, 6);
void clearSourceFile() => clearField(6);
List<String> get getters => $_get(6, 7, null);
List<String> get setters => $_get(7, 8, null);
List<String> get methods => $_get(8, 9, null);
}
class _ReadonlyNgDepsModel extends NgDepsModel with ReadonlyMessageMixin {}
const NgDepsModel$json = const {
'1': 'NgDepsModel',
'2': const [
const {'1': 'library_uri', '3': 1, '4': 1, '5': 9},
const {'1': 'part_uris', '3': 2, '4': 3, '5': 9},
const {
'1': 'imports',
'3': 3,
'4': 3,
'5': 11,
'6': '.angular2.src.transform.common.model.proto.ImportModel'
},
const {
'1': 'exports',
'3': 4,
'4': 3,
'5': 11,
'6': '.angular2.src.transform.common.model.proto.ExportModel'
},
const {
'1': 'reflectables',
'3': 5,
'4': 3,
'5': 11,
'6': '.angular2.src.transform.common.model.proto.ReflectionInfoModel'
},
const {'1': 'source_file', '3': 6, '4': 1, '5': 9},
const {'1': 'getters', '3': 7, '4': 3, '5': 9},
const {'1': 'setters', '3': 8, '4': 3, '5': 9},
const {'1': 'methods', '3': 9, '4': 3, '5': 9},
],
};
/**
* Generated with:
* ng_deps_model.proto (ab93a7f3c411be8a6dafe914f8aae56027e1bac6)
* libprotoc 2.6.1
* dart-protoc-plugin (af5fc2bf1de367a434c3b1847ab260510878ffc0)
*/
| modules_dart/transform/lib/src/transform/common/model/ng_deps_model.pb.dart | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.00018260515935253352,
0.00017306323570664972,
0.000167742749908939,
0.0001731495140120387,
0.000003922571977454936
] |
{
"id": 5,
"code_window": [
" res => {\n",
" expect(\"response listener called\").toBe(false);\n",
" async.done();\n",
" },\n",
" err => {\n",
" expect(StringWrapper.contains(err.message, 'did not invoke callback')).toBe(true);\n",
" async.done();\n",
" });\n",
"\n",
" existingScripts[0].dispatchEvent('load');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(err.text()).toEqual('JSONP injected script did not invoke callback.');\n"
],
"file_path": "modules/angular2/test/http/backends/jsonp_backend_spec.ts",
"type": "replace",
"edit_start_line_idx": 136
} | import {StringWrapper, isBlank} from 'angular2/src/core/facade/lang';
var MODULE_REGEXP = /#MODULE\[([^\]]*)\]/g;
export function moduleRef(moduleUrl): string {
return `#MODULE[${moduleUrl}]`;
}
export class SourceModule {
constructor(public moduleUrl: string, public sourceWithModuleRefs: string) {}
getSourceWithImports(): SourceWithImports {
var moduleAliases = {};
var imports: string[][] = [];
var newSource =
StringWrapper.replaceAllMapped(this.sourceWithModuleRefs, MODULE_REGEXP, (match) => {
var moduleUrl = match[1];
var alias = moduleAliases[moduleUrl];
if (isBlank(alias)) {
if (moduleUrl == this.moduleUrl) {
alias = '';
} else {
alias = `import${imports.length}`;
imports.push([moduleUrl, alias]);
}
moduleAliases[moduleUrl] = alias;
}
return alias.length > 0 ? `${alias}.` : '';
});
return new SourceWithImports(newSource, imports);
}
}
export class SourceExpression {
constructor(public declarations: string[], public expression: string) {}
}
export class SourceExpressions {
constructor(public declarations: string[], public expressions: string[]) {}
}
export class SourceWithImports {
constructor(public source: string, public imports: string[][]) {}
}
| modules/angular2/src/core/compiler/source_module.ts | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.0001703214948065579,
0.00016733226948417723,
0.00016464699001517147,
0.00016668486932758242,
0.000002116690666298382
] |
{
"id": 5,
"code_window": [
" res => {\n",
" expect(\"response listener called\").toBe(false);\n",
" async.done();\n",
" },\n",
" err => {\n",
" expect(StringWrapper.contains(err.message, 'did not invoke callback')).toBe(true);\n",
" async.done();\n",
" });\n",
"\n",
" existingScripts[0].dispatchEvent('load');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(err.text()).toEqual('JSONP injected script did not invoke callback.');\n"
],
"file_path": "modules/angular2/test/http/backends/jsonp_backend_spec.ts",
"type": "replace",
"edit_start_line_idx": 136
} | import {Type, CONST_EXPR, CONST, isPresent, isBlank} from 'angular2/src/core/facade/lang';
import {
RenderTemplateCmd,
RenderCommandVisitor,
RenderBeginElementCmd,
RenderTextCmd,
RenderNgContentCmd,
RenderBeginComponentCmd,
RenderEmbeddedTemplateCmd
} from 'angular2/src/core/render/render';
var _nextTemplateId: number = 0;
export function nextTemplateId(): number {
return _nextTemplateId++;
}
/**
* A compiled host template.
*
* This is const as we are storing it as annotation
* for the compiled component type.
*/
@CONST()
export class CompiledHostTemplate {
// Note: _templateGetter is a function so that CompiledHostTemplate can be
// a const!
constructor(private _templateGetter: Function) {}
getTemplate(): CompiledTemplate { return this._templateGetter(); }
}
/**
* A compiled template.
*/
export class CompiledTemplate {
// Note: paramGetter is a function so that we can have cycles between templates!
// paramGetter returns a tuple with:
// - ChangeDetector factory function
// - TemplateCmd[]
// - styles
constructor(public id: number,
private _dataGetter: /*()=>Array<Function, TemplateCmd[], string[]>*/ Function) {}
getData(appId: string): CompiledTemplateData {
var data = this._dataGetter(appId, this.id);
return new CompiledTemplateData(data[0], data[1], data[2]);
}
}
export class CompiledTemplateData {
constructor(public changeDetectorFactory: Function, public commands: TemplateCmd[],
public styles: string[]) {}
}
const EMPTY_ARR = CONST_EXPR([]);
export interface TemplateCmd extends RenderTemplateCmd {
visit(visitor: RenderCommandVisitor, context: any): any;
}
export class TextCmd implements TemplateCmd, RenderTextCmd {
constructor(public value: string, public isBound: boolean, public ngContentIndex: number) {}
visit(visitor: RenderCommandVisitor, context: any): any {
return visitor.visitText(this, context);
}
}
export function text(value: string, isBound: boolean, ngContentIndex: number): TextCmd {
return new TextCmd(value, isBound, ngContentIndex);
}
export class NgContentCmd implements TemplateCmd, RenderNgContentCmd {
isBound: boolean = false;
constructor(public index: number, public ngContentIndex: number) {}
visit(visitor: RenderCommandVisitor, context: any): any {
return visitor.visitNgContent(this, context);
}
}
export function ngContent(index: number, ngContentIndex: number): NgContentCmd {
return new NgContentCmd(index, ngContentIndex);
}
export interface IBeginElementCmd extends TemplateCmd, RenderBeginElementCmd {
variableNameAndValues: Array<string | number>;
eventTargetAndNames: string[];
directives: Type[];
visit(visitor: RenderCommandVisitor, context: any): any;
}
export class BeginElementCmd implements TemplateCmd, IBeginElementCmd, RenderBeginElementCmd {
constructor(public name: string, public attrNameAndValues: string[],
public eventTargetAndNames: string[],
public variableNameAndValues: Array<string | number>, public directives: Type[],
public isBound: boolean, public ngContentIndex: number) {}
visit(visitor: RenderCommandVisitor, context: any): any {
return visitor.visitBeginElement(this, context);
}
}
export function beginElement(name: string, attrNameAndValues: string[],
eventTargetAndNames: string[],
variableNameAndValues: Array<string | number>, directives: Type[],
isBound: boolean, ngContentIndex: number): BeginElementCmd {
return new BeginElementCmd(name, attrNameAndValues, eventTargetAndNames, variableNameAndValues,
directives, isBound, ngContentIndex);
}
export class EndElementCmd implements TemplateCmd {
visit(visitor: RenderCommandVisitor, context: any): any {
return visitor.visitEndElement(context);
}
}
export function endElement(): TemplateCmd {
return new EndElementCmd();
}
export class BeginComponentCmd implements TemplateCmd, IBeginElementCmd, RenderBeginComponentCmd {
isBound: boolean = true;
templateId: number;
constructor(public name: string, public attrNameAndValues: string[],
public eventTargetAndNames: string[],
public variableNameAndValues: Array<string | number>, public directives: Type[],
public nativeShadow: boolean, public ngContentIndex: number,
public template: CompiledTemplate) {
this.templateId = template.id;
}
visit(visitor: RenderCommandVisitor, context: any): any {
return visitor.visitBeginComponent(this, context);
}
}
export function beginComponent(
name: string, attrNameAnsValues: string[], eventTargetAndNames: string[],
variableNameAndValues: Array<string | number>, directives: Type[], nativeShadow: boolean,
ngContentIndex: number, template: CompiledTemplate): BeginComponentCmd {
return new BeginComponentCmd(name, attrNameAnsValues, eventTargetAndNames, variableNameAndValues,
directives, nativeShadow, ngContentIndex, template);
}
export class EndComponentCmd implements TemplateCmd {
visit(visitor: RenderCommandVisitor, context: any): any {
return visitor.visitEndComponent(context);
}
}
export function endComponent(): TemplateCmd {
return new EndComponentCmd();
}
export class EmbeddedTemplateCmd implements TemplateCmd, IBeginElementCmd,
RenderEmbeddedTemplateCmd {
isBound: boolean = true;
name: string = null;
eventTargetAndNames: string[] = EMPTY_ARR;
constructor(public attrNameAndValues: string[], public variableNameAndValues: string[],
public directives: Type[], public isMerged: boolean, public ngContentIndex: number,
public changeDetectorFactory: Function, public children: TemplateCmd[]) {}
visit(visitor: RenderCommandVisitor, context: any): any {
return visitor.visitEmbeddedTemplate(this, context);
}
}
export function embeddedTemplate(attrNameAndValues: string[], variableNameAndValues: string[],
directives: Type[], isMerged: boolean, ngContentIndex: number,
changeDetectorFactory: Function,
children: TemplateCmd[]): EmbeddedTemplateCmd {
return new EmbeddedTemplateCmd(attrNameAndValues, variableNameAndValues, directives, isMerged,
ngContentIndex, changeDetectorFactory, children);
}
export interface CommandVisitor extends RenderCommandVisitor {
visitText(cmd: TextCmd, context: any): any;
visitNgContent(cmd: NgContentCmd, context: any): any;
visitBeginElement(cmd: BeginElementCmd, context: any): any;
visitEndElement(context: any): any;
visitBeginComponent(cmd: BeginComponentCmd, context: any): any;
visitEndComponent(context: any): any;
visitEmbeddedTemplate(cmd: EmbeddedTemplateCmd, context: any): any;
}
export function visitAllCommands(visitor: CommandVisitor, cmds: TemplateCmd[],
context: any = null) {
for (var i = 0; i < cmds.length; i++) {
cmds[i].visit(visitor, context);
}
}
| modules/angular2/src/core/linker/template_commands.ts | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.0016924458323046565,
0.00024903082521632314,
0.00016326749755535275,
0.0001693724625511095,
0.0003402293659746647
] |
{
"id": 6,
"code_window": [
" expect(\"response listener called\").toBe(false);\n",
" async.done();\n",
" },\n",
" err => {\n",
" expect(err['message']).toBe('Oops!');\n",
" async.done();\n",
" });\n",
"\n",
" existingScripts[0].dispatchEvent('error', ({message: \"Oops!\"}));\n",
" }));\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(err.text()).toBe('Oops!');\n"
],
"file_path": "modules/angular2/test/http/backends/jsonp_backend_spec.ts",
"type": "replace",
"edit_start_line_idx": 152
} | import {ConnectionBackend, Connection} from '../interfaces';
import {ReadyStates, RequestMethods} from '../enums';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {ResponseOptions, BaseResponseOptions} from '../base_response_options';
import {Injectable} from 'angular2/angular2';
import {BrowserJsonp} from './browser_jsonp';
import {EventEmitter, ObservableWrapper} from 'angular2/src/core/facade/async';
import {makeTypeError} from 'angular2/src/core/facade/exceptions';
import {StringWrapper, isPresent} from 'angular2/src/core/facade/lang';
// todo(robwormald): temporary until https://github.com/angular/angular/issues/4390 decided
var Rx = require('@reactivex/rxjs/dist/cjs/Rx');
var {Observable} = Rx;
export abstract class JSONPConnection implements Connection {
readyState: ReadyStates;
request: Request;
response: any;
abstract finished(data?: any): void;
}
export class JSONPConnection_ extends JSONPConnection {
private _id: string;
private _script: Element;
private _responseData: any;
private _finished: boolean = false;
constructor(req: Request, private _dom: BrowserJsonp,
private baseResponseOptions?: ResponseOptions) {
super();
if (req.method !== RequestMethods.Get) {
throw makeTypeError("JSONP requests must use GET request method.");
}
this.request = req;
this.response = new Observable(responseObserver => {
this.readyState = ReadyStates.Loading;
let id = this._id = _dom.nextRequestID();
_dom.exposeConnection(id, this);
// Workaround Dart
// url = url.replace(/=JSONP_CALLBACK(&|$)/, `generated method`);
let callback = _dom.requestCallback(this._id);
let url: string = req.url;
if (url.indexOf('=JSONP_CALLBACK&') > -1) {
url = StringWrapper.replace(url, '=JSONP_CALLBACK&', `=${callback}&`);
} else if (url.lastIndexOf('=JSONP_CALLBACK') === url.length - '=JSONP_CALLBACK'.length) {
url =
StringWrapper.substring(url, 0, url.length - '=JSONP_CALLBACK'.length) + `=${callback}`;
}
let script = this._script = _dom.build(url);
let onLoad = event => {
if (this.readyState === ReadyStates.Cancelled) return;
this.readyState = ReadyStates.Done;
_dom.cleanup(script);
if (!this._finished) {
responseObserver.error(makeTypeError('JSONP injected script did not invoke callback.'));
return;
}
let responseOptions = new ResponseOptions({body: this._responseData});
if (isPresent(this.baseResponseOptions)) {
responseOptions = this.baseResponseOptions.merge(responseOptions);
}
responseObserver.next(new Response(responseOptions));
responseObserver.complete();
};
let onError = error => {
if (this.readyState === ReadyStates.Cancelled) return;
this.readyState = ReadyStates.Done;
_dom.cleanup(script);
responseObserver.error(error);
};
script.addEventListener('load', onLoad);
script.addEventListener('error', onError);
_dom.send(script);
return () => {
this.readyState = ReadyStates.Cancelled;
script.removeEventListener('load', onLoad);
script.removeEventListener('error', onError);
if (isPresent(script)) {
this._dom.cleanup(script);
}
};
});
}
finished(data?: any) {
// Don't leak connections
this._finished = true;
this._dom.removeConnection(this._id);
if (this.readyState === ReadyStates.Cancelled) return;
this._responseData = data;
}
}
export abstract class JSONPBackend extends ConnectionBackend {}
@Injectable()
export class JSONPBackend_ extends JSONPBackend {
constructor(private _browserJSONP: BrowserJsonp, private _baseResponseOptions: ResponseOptions) {
super();
}
createConnection(request: Request): JSONPConnection {
return new JSONPConnection_(request, this._browserJSONP, this._baseResponseOptions);
}
}
| modules/angular2/src/http/backends/jsonp_backend.ts | 1 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.00018501833255868405,
0.00016899734328035265,
0.00016376891289837658,
0.00016838604642543942,
0.000005195159246795811
] |
{
"id": 6,
"code_window": [
" expect(\"response listener called\").toBe(false);\n",
" async.done();\n",
" },\n",
" err => {\n",
" expect(err['message']).toBe('Oops!');\n",
" async.done();\n",
" });\n",
"\n",
" existingScripts[0].dispatchEvent('error', ({message: \"Oops!\"}));\n",
" }));\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(err.text()).toBe('Oops!');\n"
],
"file_path": "modules/angular2/test/http/backends/jsonp_backend_spec.ts",
"type": "replace",
"edit_start_line_idx": 152
} | import {
AsyncTestCompleter,
beforeEach,
ddescribe,
xdescribe,
describe,
el,
dispatchEvent,
expect,
iit,
inject,
beforeEachBindings,
it,
xit,
SpyObject,
proxy
} from 'angular2/testing_internal';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {DomSharedStylesHost} from 'angular2/src/core/render/dom/shared_styles_host';
export function main() {
describe('DomSharedStylesHost', () => {
var doc;
var ssh: DomSharedStylesHost;
var someHost: Element;
beforeEach(() => {
doc = DOM.createHtmlDocument();
doc.title = '';
ssh = new DomSharedStylesHost(doc);
someHost = DOM.createElement('div');
});
it('should add existing styles to new hosts', () => {
ssh.addStyles(['a {};']);
ssh.addHost(someHost);
expect(DOM.getInnerHTML(someHost)).toEqual('<style>a {};</style>');
});
it('should add new styles to hosts', () => {
ssh.addHost(someHost);
ssh.addStyles(['a {};']);
expect(DOM.getInnerHTML(someHost)).toEqual('<style>a {};</style>');
});
it('should add styles only once to hosts', () => {
ssh.addStyles(['a {};']);
ssh.addHost(someHost);
ssh.addStyles(['a {};']);
expect(DOM.getInnerHTML(someHost)).toEqual('<style>a {};</style>');
});
it('should use the document head as default host', () => {
ssh.addStyles(['a {};', 'b {};']);
expect(doc.head).toHaveText('a {};b {};');
});
});
}
| modules/angular2/test/core/render/dom/shared_styles_host_spec.ts | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.00017431564629077911,
0.00017066042346414179,
0.0001613575150258839,
0.00017249891243409365,
0.0000044759012780559715
] |
{
"id": 6,
"code_window": [
" expect(\"response listener called\").toBe(false);\n",
" async.done();\n",
" },\n",
" err => {\n",
" expect(err['message']).toBe('Oops!');\n",
" async.done();\n",
" });\n",
"\n",
" existingScripts[0].dispatchEvent('error', ({message: \"Oops!\"}));\n",
" }));\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(err.text()).toBe('Oops!');\n"
],
"file_path": "modules/angular2/test/http/backends/jsonp_backend_spec.ts",
"type": "replace",
"edit_start_line_idx": 152
} | var fs = require('fs');
var path = require('path');
module.exports = read;
function read(file) {
var content = fs.readFileSync(path.join('tools/broccoli/html-replace', file + '.html'),
{encoding: 'utf-8'});
// TODO(broccoli): we don't really need this, it's here to make the output match the
// tools/build/html
return content.substring(0, content.lastIndexOf("\n"));
}
| tools/broccoli/html-replace/index.ts | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.0001714228856144473,
0.00016978282656054944,
0.00016814276750665158,
0.00016978282656054944,
0.0000016400590538978577
] |
{
"id": 6,
"code_window": [
" expect(\"response listener called\").toBe(false);\n",
" async.done();\n",
" },\n",
" err => {\n",
" expect(err['message']).toBe('Oops!');\n",
" async.done();\n",
" });\n",
"\n",
" existingScripts[0].dispatchEvent('error', ({message: \"Oops!\"}));\n",
" }));\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(err.text()).toBe('Oops!');\n"
],
"file_path": "modules/angular2/test/http/backends/jsonp_backend_spec.ts",
"type": "replace",
"edit_start_line_idx": 152
} | #!/bin/bash
set -e -o pipefail
# Setup and start Sauce Connect for your TravisCI build
# This script requires your .travis.yml to include the following two private env variables:
# SAUCE_USERNAME
# SAUCE_ACCESS_KEY
# Follow the steps at https://saucelabs.com/opensource/travis to set that up.
#
# Curl and run this script as part of your .travis.yml before_script section:
# before_script:
# - curl https://gist.github.com/santiycr/5139565/raw/sauce_connect_setup.sh | bash
CONNECT_URL="https://saucelabs.com/downloads/sc-4.3.11-linux.tar.gz"
CONNECT_DIR="/tmp/sauce-connect-$RANDOM"
CONNECT_DOWNLOAD="sc-latest-linux.tar.gz"
CONNECT_LOG="$LOGS_DIR/sauce-connect"
CONNECT_STDOUT="$LOGS_DIR/sauce-connect.stdout"
CONNECT_STDERR="$LOGS_DIR/sauce-connect.stderr"
# Get Connect and start it
mkdir -p $CONNECT_DIR
cd $CONNECT_DIR
curl $CONNECT_URL -o $CONNECT_DOWNLOAD 2> /dev/null 1> /dev/null
mkdir sauce-connect
tar --extract --file=$CONNECT_DOWNLOAD --strip-components=1 --directory=sauce-connect > /dev/null
rm $CONNECT_DOWNLOAD
SAUCE_ACCESS_KEY=`echo $SAUCE_ACCESS_KEY | rev`
ARGS=""
# Set tunnel-id only on Travis, to make local testing easier.
if [ ! -z "$TRAVIS_JOB_NUMBER" ]; then
ARGS="$ARGS --tunnel-identifier $TRAVIS_JOB_NUMBER"
fi
if [ ! -z "$BROWSER_PROVIDER_READY_FILE" ]; then
ARGS="$ARGS --readyfile $BROWSER_PROVIDER_READY_FILE"
fi
echo "Starting Sauce Connect in the background, logging into:"
echo " $CONNECT_LOG"
echo " $CONNECT_STDOUT"
echo " $CONNECT_STDERR"
sauce-connect/bin/sc -u $SAUCE_USERNAME -k $SAUCE_ACCESS_KEY $ARGS \
--logfile $CONNECT_LOG 2> $CONNECT_STDERR 1> $CONNECT_STDOUT &
| scripts/sauce/sauce_connect_setup.sh | 0 | https://github.com/angular/angular/commit/31687efd6403ce9fd95576966544c170f62a67a6 | [
0.0001661872083786875,
0.000164414566825144,
0.00016169481386896223,
0.00016444538778159767,
0.000001603960868123977
] |
{
"id": 0,
"code_window": [
" case 'expanded': {\n",
" validateSupportedRole(attr.name, kAriaExpandedRoles, role);\n",
" validateSupportedValues(attr, [true, false]);\n",
" validateSupportedOp(attr, ['<truthy>', '=']);\n",
" break;\n",
" }\n",
" case 'level': {\n",
" validateSupportedRole(attr.name, kAriaLevelRoles, role);\n",
" // Level is a number, convert it from string.\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (attr.op === '<truthy>') {\n",
" // Do not match \"none\" in \"treeitem[expanded]\".\n",
" attr.op = '=';\n",
" attr.value = true;\n",
" }\n"
],
"file_path": "packages/playwright-core/src/server/injected/roleSelectorEngine.ts",
"type": "add",
"edit_start_line_idx": 74
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { test, expect } from './pageTest';
test('should detect roles', async ({ page }) => {
await page.setContent(`
<button>Hello</button>
<select multiple="" size="2"></select>
<select></select>
<h3>Heading</h3>
<details><summary>Hello</summary></details>
<div role="dialog">I am a dialog</div>
`);
expect(await page.locator(`role=button`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hello</button>`,
]);
expect(await page.locator(`role=listbox`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<select multiple="" size="2"></select>`,
]);
expect(await page.locator(`role=combobox`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<select></select>`,
]);
expect(await page.locator(`role=heading`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<h3>Heading</h3>`,
]);
expect(await page.locator(`role=group`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<details><summary>Hello</summary></details>`,
]);
expect(await page.locator(`role=dialog`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="dialog">I am a dialog</div>`,
]);
expect(await page.locator(`role=menuitem`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
]);
expect(await page.getByRole('menuitem').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
]);
});
test('should support selected', async ({ page }) => {
await page.setContent(`
<select>
<option>Hi</option>
<option selected>Hello</option>
</select>
<div>
<div role="option" aria-selected="true">Hi</div>
<div role="option" aria-selected="false">Hello</div>
</div>
`);
expect(await page.locator(`role=option[selected]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<option selected="">Hello</option>`,
`<div role="option" aria-selected="true">Hi</div>`,
]);
expect(await page.locator(`role=option[selected=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<option selected="">Hello</option>`,
`<div role="option" aria-selected="true">Hi</div>`,
]);
expect(await page.getByRole('option', { selected: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<option selected="">Hello</option>`,
`<div role="option" aria-selected="true">Hi</div>`,
]);
expect(await page.locator(`role=option[selected=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<option>Hi</option>`,
`<div role="option" aria-selected="false">Hello</div>`,
]);
expect(await page.getByRole('option', { selected: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<option>Hi</option>`,
`<div role="option" aria-selected="false">Hello</div>`,
]);
});
test('should support checked', async ({ page }) => {
await page.setContent(`
<input type=checkbox>
<input type=checkbox checked>
<input type=checkbox indeterminate>
<div role=checkbox aria-checked="true">Hi</div>
<div role=checkbox aria-checked="false">Hello</div>
<div role=checkbox>Unknown</div>
`);
await page.$eval('[indeterminate]', input => (input as HTMLInputElement).indeterminate = true);
expect(await page.locator(`role=checkbox[checked]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox" checked="">`,
`<div role="checkbox" aria-checked="true">Hi</div>`,
]);
expect(await page.locator(`role=checkbox[checked=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox" checked="">`,
`<div role="checkbox" aria-checked="true">Hi</div>`,
]);
expect(await page.getByRole('checkbox', { checked: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox" checked="">`,
`<div role="checkbox" aria-checked="true">Hi</div>`,
]);
expect(await page.locator(`role=checkbox[checked=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox">`,
`<div role="checkbox" aria-checked="false">Hello</div>`,
`<div role="checkbox">Unknown</div>`,
]);
expect(await page.getByRole('checkbox', { checked: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox">`,
`<div role="checkbox" aria-checked="false">Hello</div>`,
`<div role="checkbox">Unknown</div>`,
]);
expect(await page.locator(`role=checkbox[checked="mixed"]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox" indeterminate="">`,
]);
expect(await page.locator(`role=checkbox`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox">`,
`<input type="checkbox" checked="">`,
`<input type="checkbox" indeterminate="">`,
`<div role="checkbox" aria-checked="true">Hi</div>`,
`<div role="checkbox" aria-checked="false">Hello</div>`,
`<div role="checkbox">Unknown</div>`,
]);
});
test('should support pressed', async ({ page }) => {
await page.setContent(`
<button>Hi</button>
<button aria-pressed="true">Hello</button>
<button aria-pressed="false">Bye</button>
<button aria-pressed="mixed">Mixed</button>
`);
expect(await page.locator(`role=button[pressed]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-pressed="true">Hello</button>`,
]);
expect(await page.locator(`role=button[pressed=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-pressed="true">Hello</button>`,
]);
expect(await page.getByRole('button', { pressed: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-pressed="true">Hello</button>`,
]);
expect(await page.locator(`role=button[pressed=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-pressed="false">Bye</button>`,
]);
expect(await page.getByRole('button', { pressed: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-pressed="false">Bye</button>`,
]);
expect(await page.locator(`role=button[pressed="mixed"]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-pressed="mixed">Mixed</button>`,
]);
expect(await page.locator(`role=button`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-pressed="true">Hello</button>`,
`<button aria-pressed="false">Bye</button>`,
`<button aria-pressed="mixed">Mixed</button>`,
]);
});
test('should support expanded', async ({ page }) => {
await page.setContent(`
<button>Hi</button>
<button aria-expanded="true">Hello</button>
<button aria-expanded="false">Bye</button>
`);
expect(await page.locator(`role=button[expanded]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-expanded="true">Hello</button>`,
]);
expect(await page.locator(`role=button[expanded=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-expanded="true">Hello</button>`,
]);
expect(await page.getByRole('button', { expanded: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-expanded="true">Hello</button>`,
]);
expect(await page.locator(`role=button[expanded=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-expanded="false">Bye</button>`,
]);
expect(await page.getByRole('button', { expanded: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-expanded="false">Bye</button>`,
]);
});
test('should support disabled', async ({ page }) => {
await page.setContent(`
<button>Hi</button>
<button disabled>Bye</button>
<button aria-disabled="true">Hello</button>
<button aria-disabled="false">Oh</button>
<fieldset disabled>
<button>Yay</button>
</fieldset>
`);
expect(await page.locator(`role=button[disabled]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button disabled="">Bye</button>`,
`<button aria-disabled="true">Hello</button>`,
`<button>Yay</button>`,
]);
expect(await page.locator(`role=button[disabled=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button disabled="">Bye</button>`,
`<button aria-disabled="true">Hello</button>`,
`<button>Yay</button>`,
]);
expect(await page.getByRole('button', { disabled: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button disabled="">Bye</button>`,
`<button aria-disabled="true">Hello</button>`,
`<button>Yay</button>`,
]);
expect(await page.locator(`role=button[disabled=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-disabled="false">Oh</button>`,
]);
expect(await page.getByRole('button', { disabled: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-disabled="false">Oh</button>`,
]);
});
test('should support level', async ({ page }) => {
await page.setContent(`
<h1>Hello</h1>
<h3>Hi</h3>
<div role="heading" aria-level="5">Bye</div>
`);
expect(await page.locator(`role=heading[level=1]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<h1>Hello</h1>`,
]);
expect(await page.getByRole('heading', { level: 1 }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<h1>Hello</h1>`,
]);
expect(await page.locator(`role=heading[level=3]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<h3>Hi</h3>`,
]);
expect(await page.getByRole('heading', { level: 3 }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<h3>Hi</h3>`,
]);
expect(await page.locator(`role=heading[level=5]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="heading" aria-level="5">Bye</div>`,
]);
});
test('should filter hidden, unless explicitly asked for', async ({ page }) => {
await page.setContent(`
<button>Hi</button>
<button hidden>Hello</button>
<button aria-hidden="true">Yay</button>
<button aria-hidden="false">Nay</button>
<button style="visibility:hidden">Bye</button>
<div style="visibility:hidden">
<button>Oh</button>
</div>
<div style="visibility:hidden">
<button style="visibility:visible">Still here</button>
</div>
<button style="display:none">Never</button>
<div id=host1></div>
<div id=host2 style="display:none"></div>
<script>
function addButton(host, text) {
const root = host.attachShadow({ mode: 'open' });
const button = document.createElement('button');
button.textContent = text;
root.appendChild(button);
}
addButton(document.getElementById('host1'), 'Shadow1');
addButton(document.getElementById('host2'), 'Shadow2');
</script>
`);
expect(await page.locator(`role=button`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-hidden="false">Nay</button>`,
`<button style="visibility:visible">Still here</button>`,
`<button>Shadow1</button>`,
]);
expect(await page.locator(`role=button[include-hidden]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button hidden="">Hello</button>`,
`<button aria-hidden="true">Yay</button>`,
`<button aria-hidden="false">Nay</button>`,
`<button style="visibility:hidden">Bye</button>`,
`<button>Oh</button>`,
`<button style="visibility:visible">Still here</button>`,
`<button style="display:none">Never</button>`,
`<button>Shadow1</button>`,
`<button>Shadow2</button>`,
]);
expect(await page.locator(`role=button[include-hidden=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button hidden="">Hello</button>`,
`<button aria-hidden="true">Yay</button>`,
`<button aria-hidden="false">Nay</button>`,
`<button style="visibility:hidden">Bye</button>`,
`<button>Oh</button>`,
`<button style="visibility:visible">Still here</button>`,
`<button style="display:none">Never</button>`,
`<button>Shadow1</button>`,
`<button>Shadow2</button>`,
]);
expect(await page.locator(`role=button[include-hidden=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-hidden="false">Nay</button>`,
`<button style="visibility:visible">Still here</button>`,
`<button>Shadow1</button>`,
]);
});
test('should support name', async ({ page }) => {
await page.setContent(`
<div role="button" aria-label=" Hello "></div>
<div role="button" aria-label="Hallo"></div>
<div role="button" aria-label="Hello" aria-hidden="true"></div>
<div role="button" aria-label="123" aria-hidden="true"></div>
<div role="button" aria-label='foo"bar' aria-hidden="true"></div>
`);
expect(await page.locator(`role=button[name="Hello"]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
]);
expect(await page.locator(`role=button[name=" \n Hello "]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
]);
expect(await page.getByRole('button', { name: 'Hello' }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
]);
expect(await page.locator(`role=button[name*="all"]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label="Hallo"></div>`,
]);
expect(await page.locator(`role=button[name=/^H[ae]llo$/]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hallo"></div>`,
]);
expect(await page.getByRole('button', { name: /^H[ae]llo$/ }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hallo"></div>`,
]);
expect(await page.locator(`role=button[name=/h.*o/i]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hallo"></div>`,
]);
expect(await page.getByRole('button', { name: /h.*o/i }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hallo"></div>`,
]);
expect(await page.locator(`role=button[name="Hello"][include-hidden]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hello" aria-hidden="true"></div>`,
]);
expect(await page.getByRole('button', { name: 'Hello', includeHidden: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hello" aria-hidden="true"></div>`,
]);
expect(await page.getByRole('button', { name: 'hello', includeHidden: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hello" aria-hidden="true"></div>`,
]);
expect(await page.locator(`role=button[name=Hello]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
]);
expect(await page.locator(`role=button[name=123][include-hidden]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label="123" aria-hidden="true"></div>`,
]);
expect(await page.getByRole('button', { name: '123', includeHidden: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label="123" aria-hidden="true"></div>`,
]);
});
test('errors', async ({ page }) => {
const e0 = await page.$('role=[bar]').catch(e => e);
expect(e0.message).toContain(`Role must not be empty`);
const e1 = await page.$('role=foo[sElected]').catch(e => e);
expect(e1.message).toContain(`Unknown attribute "sElected", must be one of "checked", "disabled", "expanded", "include-hidden", "level", "name", "pressed", "selected"`);
const e2 = await page.$('role=foo[bar . qux=true]').catch(e => e);
expect(e2.message).toContain(`Unknown attribute "bar.qux"`);
const e3 = await page.$('role=heading[level="bar"]').catch(e => e);
expect(e3.message).toContain(`"level" attribute must be compared to a number`);
const e4 = await page.$('role=checkbox[checked="bar"]').catch(e => e);
expect(e4.message).toContain(`"checked" must be one of true, false, "mixed"`);
const e5 = await page.$('role=checkbox[checked~=true]').catch(e => e);
expect(e5.message).toContain(`cannot use ~= in attribute with non-string matching value`);
const e6 = await page.$('role=button[level=3]').catch(e => e);
expect(e6.message).toContain(`"level" attribute is only supported for roles: "heading", "listitem", "row", "treeitem"`);
const e7 = await page.$('role=button[name]').catch(e => e);
expect(e7.message).toContain(`"name" attribute must have a value`);
});
| tests/page/selectors-role.spec.ts | 1 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00017788213153835386,
0.0001725043694023043,
0.00016425967623945326,
0.00017278017185162753,
0.000003001185177708976
] |
{
"id": 0,
"code_window": [
" case 'expanded': {\n",
" validateSupportedRole(attr.name, kAriaExpandedRoles, role);\n",
" validateSupportedValues(attr, [true, false]);\n",
" validateSupportedOp(attr, ['<truthy>', '=']);\n",
" break;\n",
" }\n",
" case 'level': {\n",
" validateSupportedRole(attr.name, kAriaLevelRoles, role);\n",
" // Level is a number, convert it from string.\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (attr.op === '<truthy>') {\n",
" // Do not match \"none\" in \"treeitem[expanded]\".\n",
" attr.op = '=';\n",
" attr.value = true;\n",
" }\n"
],
"file_path": "packages/playwright-core/src/server/injected/roleSelectorEngine.ts",
"type": "add",
"edit_start_line_idx": 74
} | /**
* Copyright 2018 Google Inc. All rights reserved.
* Modifications copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { test as it, expect } from './pageTest';
import type { Route } from 'playwright-core';
it('should pick up ongoing navigation', async ({ page, server }) => {
let response = null;
server.setRoute('/one-style.css', (req, res) => response = res);
await Promise.all([
server.waitForRequest('/one-style.css'),
page.goto(server.PREFIX + '/one-style.html', { waitUntil: 'domcontentloaded' }),
]);
const waitPromise = page.waitForLoadState();
response.statusCode = 404;
response.end('Not found');
await waitPromise;
});
it('should respect timeout', async ({ page, server }) => {
server.setRoute('/one-style.css', (req, res) => void 0);
await page.goto(server.PREFIX + '/one-style.html', { waitUntil: 'domcontentloaded' });
const error = await page.waitForLoadState('load', { timeout: 1 }).catch(e => e);
expect(error.message).toContain('page.waitForLoadState: Timeout 1ms exceeded.');
expect(error.stack.split('\n')[1]).toContain(__filename);
});
it('should resolve immediately if loaded', async ({ page, server }) => {
await page.goto(server.PREFIX + '/one-style.html');
await page.waitForLoadState();
});
it('should throw for bad state', async ({ page, server }) => {
await page.goto(server.PREFIX + '/one-style.html');
// @ts-expect-error 'bad' is not a valid load state
const error = await page.waitForLoadState('bad').catch(e => e);
expect(error.message).toContain(`state: expected one of (load|domcontentloaded|networkidle|commit)`);
});
it('should resolve immediately if load state matches', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
server.setRoute('/one-style.css', (req, res) => void 0);
await page.goto(server.PREFIX + '/one-style.html', { waitUntil: 'domcontentloaded' });
await page.waitForLoadState('domcontentloaded');
});
it('should work with pages that have loaded before being connected to', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => window['_popup'] = window.open(document.location.href)),
]);
// The url is about:blank in FF.
// expect(popup.url()).toBe(server.EMPTY_PAGE);
await popup.waitForLoadState();
expect(popup.url()).toBe(server.EMPTY_PAGE);
});
it('should wait for load state of empty url popup', async ({ page, browserName }) => {
const [popup, readyState] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => {
const popup = window.open('');
return popup.document.readyState;
}),
]);
await popup.waitForLoadState();
expect(readyState).toBe(browserName === 'firefox' ? 'uninitialized' : 'complete');
expect(await popup.evaluate(() => document.readyState)).toBe(browserName === 'firefox' ? 'uninitialized' : 'complete');
});
it('should wait for load state of about:blank popup ', async ({ page }) => {
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => window.open('about:blank') && 1),
]);
await popup.waitForLoadState();
expect(await popup.evaluate(() => document.readyState)).toBe('complete');
});
it('should wait for load state of about:blank popup with noopener ', async ({ page }) => {
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => window.open('about:blank', null, 'noopener') && 1),
]);
await popup.waitForLoadState();
expect(await popup.evaluate(() => document.readyState)).toBe('complete');
});
it('should wait for load state of popup with network url ', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(url => window.open(url) && 1, server.EMPTY_PAGE),
]);
await popup.waitForLoadState();
expect(await popup.evaluate(() => document.readyState)).toBe('complete');
});
it('should wait for load state of popup with network url and noopener ', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(url => window.open(url, null, 'noopener') && 1, server.EMPTY_PAGE),
]);
await popup.waitForLoadState();
expect(await popup.evaluate(() => document.readyState)).toBe('complete');
});
it('should work with clicking target=_blank', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
await page.setContent('<a target=_blank rel="opener" href="/one-style.html">yo</a>');
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.click('a'),
]);
await popup.waitForLoadState();
expect(await popup.evaluate(() => document.readyState)).toBe('complete');
});
it('should wait for load state of newPage', async ({ page, isElectron }) => {
it.fixme(isElectron, 'BrowserContext.newPage does not work in Electron');
const [newPage] = await Promise.all([
page.context().waitForEvent('page'),
page.context().newPage(),
]);
await newPage.waitForLoadState();
expect(await newPage.evaluate(() => document.readyState)).toBe('complete');
});
it('should resolve after popup load', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
// Stall the 'load' by delaying css.
let cssResponse;
server.setRoute('/one-style.css', (req, res) => cssResponse = res);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
server.waitForRequest('/one-style.css'),
page.evaluate(url => window['popup'] = window.open(url), server.PREFIX + '/one-style.html'),
]);
let resolved = false;
const loadSatePromise = popup.waitForLoadState().then(() => resolved = true);
// Round trips!
for (let i = 0; i < 5; i++)
await page.evaluate('window');
expect(resolved).toBe(false);
cssResponse.end('');
await loadSatePromise;
expect(resolved).toBe(true);
expect(popup.url()).toBe(server.PREFIX + '/one-style.html');
});
it('should work for frame', async ({ page, server }) => {
await page.goto(server.PREFIX + '/frames/one-frame.html');
const frame = page.frames()[1];
const requestPromise = new Promise<Route>(resolve => page.route(server.PREFIX + '/one-style.css', resolve));
await frame.goto(server.PREFIX + '/one-style.html', { waitUntil: 'domcontentloaded' });
const request = await requestPromise;
let resolved = false;
const loadPromise = frame.waitForLoadState().then(() => resolved = true);
// give the promise a chance to resolve, even though it shouldn't
await page.evaluate('1');
expect(resolved).toBe(false);
request.continue();
await loadPromise;
});
it('should work with javascript: iframe', async ({ page, server, browserName }) => {
it.fixme(browserName === 'firefox', 'no load event');
await page.goto(server.EMPTY_PAGE);
await page.setContent(`<iframe src="javascript:false"></iframe>`, { waitUntil: 'commit' });
await page.waitForLoadState('domcontentloaded');
await page.waitForLoadState('load');
await page.waitForLoadState('networkidle');
});
it('should work with broken data-url iframe', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
await page.setContent(`<iframe src="data:text/html"></iframe>`, { waitUntil: 'commit' });
await page.waitForLoadState('domcontentloaded');
await page.waitForLoadState('load');
await page.waitForLoadState('networkidle');
});
it('should work with broken blob-url iframe', async ({ page, server, browserName }) => {
it.fixme(browserName === 'chromium', 'no load event');
it.fixme(browserName === 'firefox', 'no load event');
await page.goto(server.EMPTY_PAGE);
await page.setContent(`<iframe src="blob:"></iframe>`, { waitUntil: 'commit' });
await page.waitForLoadState('domcontentloaded');
await page.waitForLoadState('load');
await page.waitForLoadState('networkidle');
});
| tests/page/page-wait-for-load-state.spec.ts | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.0001781921018846333,
0.0001740437000989914,
0.00017112582281697541,
0.00017363461665809155,
0.0000017288980416196864
] |
{
"id": 0,
"code_window": [
" case 'expanded': {\n",
" validateSupportedRole(attr.name, kAriaExpandedRoles, role);\n",
" validateSupportedValues(attr, [true, false]);\n",
" validateSupportedOp(attr, ['<truthy>', '=']);\n",
" break;\n",
" }\n",
" case 'level': {\n",
" validateSupportedRole(attr.name, kAriaLevelRoles, role);\n",
" // Level is a number, convert it from string.\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (attr.op === '<truthy>') {\n",
" // Do not match \"none\" in \"treeitem[expanded]\".\n",
" attr.op = '=';\n",
" attr.value = true;\n",
" }\n"
],
"file_path": "packages/playwright-core/src/server/injected/roleSelectorEngine.ts",
"type": "add",
"edit_start_line_idx": 74
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// eslint-disable-next-line spaced-comment
/// <reference path="./expect.d.ts" />
import { test as _test, expect as _expect } from '@playwright/test';
import fs from 'fs';
import os from 'os';
import path from 'path';
import debugLogger from 'debug';
import { Registry } from './registry';
import { spawnAsync } from './spawnAsync';
import type { CommonFixtures, CommonWorkerFixtures } from '../config/commonFixtures';
import { commonFixtures } from '../config/commonFixtures';
export const TMP_WORKSPACES = path.join(os.platform() === 'darwin' ? '/tmp' : os.tmpdir(), 'pwt', 'workspaces');
const debug = debugLogger('itest');
/**
* A minimal NPM Registry Server that can serve local packages, or proxy to the upstream registry.
* This is useful in test installation behavior of packages that aren't yet published. It's particularly helpful
* when your installation requires transitive dependencies that are also not yet published.
*
* See https://github.com/npm/registry/blob/master/docs/REGISTRY-API.md for information on the offical APIs.
*/
_expect.extend({
async toExistOnFS(received: any) {
if (typeof received !== 'string')
throw new Error(`Expected argument to be a string.`);
try {
await fs.promises.access(received);
return { pass: true };
} catch (e) {
return { pass: false, message: () => 'file does not exist' };
}
},
toHaveLoggedSoftwareDownload(received: any, browsers: ('chromium' | 'firefox' | 'webkit' | 'ffmpeg')[]) {
if (typeof received !== 'string')
throw new Error(`Expected argument to be a string.`);
const downloaded = new Set();
for (const [, browser] of received.matchAll(/^.*(chromium|firefox|webkit|ffmpeg).*playwright build v\d+\)? downloaded.*$/img))
downloaded.add(browser.toLowerCase());
const expected = browsers;
if (expected.length === downloaded.size && expected.every(browser => downloaded.has(browser)))
return { pass: true };
return {
pass: false,
message: () => [
`Browser download expectation failed!`,
` expected: ${[...expected].sort().join(', ')}`,
` actual: ${[...downloaded].sort().join(', ')}`,
].join('\n'),
};
}
});
const expect = _expect;
export type ExecOptions = { cwd?: string, env?: Record<string, string>, message?: string, expectToExitWithError?: boolean };
export type ArgsOrOptions = [] | [...string[]] | [...string[], ExecOptions] | [ExecOptions];
export type NPMTestFixtures = {
_auto: void,
tmpWorkspace: string,
nodeMajorVersion: number,
installedSoftwareOnDisk: (registryPath?: string) => Promise<string[]>;
writeFiles: (nameToContents: Record<string, string>) => Promise<void>,
exec: (cmd: string, ...argsAndOrOptions: ArgsOrOptions) => Promise<string>
tsc: (...argsAndOrOptions: ArgsOrOptions) => Promise<string>,
registry: Registry,
};
export const test = _test
.extend<CommonFixtures, CommonWorkerFixtures>(commonFixtures)
.extend<NPMTestFixtures>({
_auto: [async ({ tmpWorkspace, exec }, use) => {
await exec('npm init -y');
const sourceDir = path.join(__dirname, 'fixture-scripts');
const contents = await fs.promises.readdir(sourceDir);
await Promise.all(contents.map(f => fs.promises.copyFile(path.join(sourceDir, f), path.join(tmpWorkspace, f))));
await use();
}, {
auto: true,
}],
nodeMajorVersion: async ({}, use) => {
await use(+process.versions.node.split('.')[0]);
},
writeFiles: async ({ tmpWorkspace }, use) => {
await use(async (nameToContents: Record<string, string>) => {
for (const [name, contents] of Object.entries(nameToContents))
await fs.promises.writeFile(path.join(tmpWorkspace, name), contents);
});
},
tmpWorkspace: async ({}, use) => {
// We want a location that won't have a node_modules dir anywhere along its path
const tmpWorkspace = path.join(TMP_WORKSPACES, path.basename(test.info().outputDir));
await fs.promises.mkdir(tmpWorkspace);
debug(`Workspace Folder: ${tmpWorkspace}`);
await use(tmpWorkspace);
},
registry: async ({}, use, testInfo) => {
const port = testInfo.workerIndex + 16123;
const url = `http://127.0.0.1:${port}`;
const registry = new Registry(testInfo.outputPath('registry'), url);
await registry.start(JSON.parse((await fs.promises.readFile(path.join(__dirname, '.registry.json'), 'utf8'))));
await use(registry);
await registry.shutdown();
},
installedSoftwareOnDisk: async ({ tmpWorkspace }, use) => {
await use(async (registryPath?: string) => fs.promises.readdir(registryPath || path.join(tmpWorkspace, 'browsers')).catch(() => []).then(files => files.map(f => f.split('-')[0]).filter(f => !f.startsWith('.'))));
},
exec: async ({ registry, tmpWorkspace }, use, testInfo) => {
await use(async (cmd: string, ...argsAndOrOptions: [] | [...string[]] | [...string[], ExecOptions] | [ExecOptions]) => {
let args: string[] = [];
let options: ExecOptions = {};
if (typeof argsAndOrOptions[argsAndOrOptions.length - 1] === 'object')
options = argsAndOrOptions.pop() as ExecOptions;
args = argsAndOrOptions as string[];
let result!: Awaited<ReturnType<typeof spawnAsync>>;
await test.step(`exec: ${[cmd, ...args].join(' ')}`, async () => {
result = await spawnAsync(cmd, args, {
shell: true,
cwd: options.cwd ?? tmpWorkspace,
// NB: We end up running npm-in-npm, so it's important that we do NOT forward process.env and instead cherry-pick environment variables.
env: {
'PATH': process.env.PATH,
'DISPLAY': process.env.DISPLAY,
'XAUTHORITY': process.env.XAUTHORITY,
'PLAYWRIGHT_BROWSERS_PATH': path.join(tmpWorkspace, 'browsers'),
'npm_config_cache': testInfo.outputPath('npm_cache'),
'npm_config_registry': registry.url(),
'npm_config_prefix': testInfo.outputPath('npm_global'),
...options.env,
}
});
});
const command = [cmd, ...args].join(' ');
const stdio = result.stdout + result.stderr;
await testInfo.attach(command, { body: `COMMAND: ${command}\n\nEXIT CODE: ${result.code}\n\n====== STDOUT + STDERR ======\n\n${stdio}` });
// This means something is really off with spawn
if (result.error)
throw result.error;
const error: string[] = [];
if (options.expectToExitWithError && result.code === 0)
error.push(`Expected the command to exit with an error, but exited cleanly.`);
else if (!options.expectToExitWithError && result.code !== 0)
error.push(`Expected the command to exit cleanly (0 status code), but exited with ${result.code}.`);
if (!error.length)
return stdio;
if (options.message)
error.push(`Message: ${options.message}`);
error.push(`Command: ${command}`);
error.push(`EXIT CODE: ${result.code}`);
error.push(`====== STDIO ======\n${stdio}`);
throw new Error(error.join('\n'));
});
},
tsc: async ({ exec }, use) => {
await exec('npm i --foreground-scripts [email protected] @types/node@14');
await use((...args: ArgsOrOptions) => exec('npx', '-p', '[email protected]', 'tsc', ...args));
},
});
export { expect };
| tests/installation/npmTest.ts | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00017799375928007066,
0.0001728305796859786,
0.0001664136361796409,
0.00017327586829196662,
0.0000029090181214996846
] |
{
"id": 0,
"code_window": [
" case 'expanded': {\n",
" validateSupportedRole(attr.name, kAriaExpandedRoles, role);\n",
" validateSupportedValues(attr, [true, false]);\n",
" validateSupportedOp(attr, ['<truthy>', '=']);\n",
" break;\n",
" }\n",
" case 'level': {\n",
" validateSupportedRole(attr.name, kAriaLevelRoles, role);\n",
" // Level is a number, convert it from string.\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (attr.op === '<truthy>') {\n",
" // Do not match \"none\" in \"treeitem[expanded]\".\n",
" attr.op = '=';\n",
" attr.value = true;\n",
" }\n"
],
"file_path": "packages/playwright-core/src/server/injected/roleSelectorEngine.ts",
"type": "add",
"edit_start_line_idx": 74
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const pwt = require('./lib/index');
const playwright = require('playwright-core');
const combinedExports = {
...playwright,
...pwt,
};
Object.defineProperty(combinedExports, '__esModule', { value: true });
module.exports = combinedExports;
| packages/playwright-test/index.js | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00017891499737743288,
0.00017653655959293246,
0.00017351964197587222,
0.00017717505397740752,
0.0000022484391593025066
] |
{
"id": 1,
"code_window": [
"}\n",
"\n",
"export const kAriaExpandedRoles = ['application', 'button', 'checkbox', 'combobox', 'gridcell', 'link', 'listbox', 'menuitem', 'row', 'rowheader', 'tab', 'treeitem', 'columnheader', 'menuitemcheckbox', 'menuitemradio', 'rowheader', 'switch'];\n",
"export function getAriaExpanded(element: Element): boolean {\n",
" // https://www.w3.org/TR/wai-aria-1.2/#aria-expanded\n",
" // https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings\n",
" if (element.tagName === 'DETAILS')\n",
" return (element as HTMLDetailsElement).open;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export function getAriaExpanded(element: Element): boolean | 'none' {\n"
],
"file_path": "packages/playwright-core/src/server/injected/roleUtils.ts",
"type": "replace",
"edit_start_line_idx": 672
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { closestCrossShadow, enclosingShadowRootOrDocument, parentElementOrShadowHost } from './domUtils';
function hasExplicitAccessibleName(e: Element) {
return e.hasAttribute('aria-label') || e.hasAttribute('aria-labelledby');
}
// https://www.w3.org/TR/wai-aria-practices/examples/landmarks/HTML5.html
const kAncestorPreventingLandmark = 'article:not([role]), aside:not([role]), main:not([role]), nav:not([role]), section:not([role]), [role=article], [role=complementary], [role=main], [role=navigation], [role=region]';
// https://www.w3.org/TR/wai-aria-1.2/#global_states
const kGlobalAriaAttributes = [
'aria-atomic',
'aria-busy',
'aria-controls',
'aria-current',
'aria-describedby',
'aria-details',
'aria-disabled',
'aria-dropeffect',
'aria-errormessage',
'aria-flowto',
'aria-grabbed',
'aria-haspopup',
'aria-hidden',
'aria-invalid',
'aria-keyshortcuts',
'aria-label',
'aria-labelledby',
'aria-live',
'aria-owns',
'aria-relevant',
'aria-roledescription',
];
function hasGlobalAriaAttribute(e: Element) {
return kGlobalAriaAttributes.some(a => e.hasAttribute(a));
}
// https://w3c.github.io/html-aam/#html-element-role-mappings
const kImplicitRoleByTagName: { [tagName: string]: (e: Element) => string | null } = {
'A': (e: Element) => {
return e.hasAttribute('href') ? 'link' : null;
},
'AREA': (e: Element) => {
return e.hasAttribute('href') ? 'link' : null;
},
'ARTICLE': () => 'article',
'ASIDE': () => 'complementary',
'BLOCKQUOTE': () => 'blockquote',
'BUTTON': () => 'button',
'CAPTION': () => 'caption',
'CODE': () => 'code',
'DATALIST': () => 'listbox',
'DD': () => 'definition',
'DEL': () => 'deletion',
'DETAILS': () => 'group',
'DFN': () => 'term',
'DIALOG': () => 'dialog',
'DT': () => 'term',
'EM': () => 'emphasis',
'FIELDSET': () => 'group',
'FIGURE': () => 'figure',
'FOOTER': (e: Element) => closestCrossShadow(e, kAncestorPreventingLandmark) ? null : 'contentinfo',
'FORM': (e: Element) => hasExplicitAccessibleName(e) ? 'form' : null,
'H1': () => 'heading',
'H2': () => 'heading',
'H3': () => 'heading',
'H4': () => 'heading',
'H5': () => 'heading',
'H6': () => 'heading',
'HEADER': (e: Element) => closestCrossShadow(e, kAncestorPreventingLandmark) ? null : 'banner',
'HR': () => 'separator',
'HTML': () => 'document',
'IMG': (e: Element) => (e.getAttribute('alt') === '') && !hasGlobalAriaAttribute(e) && Number.isNaN(Number(String(e.getAttribute('tabindex')))) ? 'presentation' : 'img',
'INPUT': (e: Element) => {
const type = (e as HTMLInputElement).type.toLowerCase();
if (type === 'search')
return e.hasAttribute('list') ? 'combobox' : 'searchbox';
if (['email', 'tel', 'text', 'url', ''].includes(type)) {
// https://html.spec.whatwg.org/multipage/input.html#concept-input-list
const list = getIdRefs(e, e.getAttribute('list'))[0];
return (list && list.tagName === 'DATALIST') ? 'combobox' : 'textbox';
}
if (type === 'hidden')
return '';
return {
'button': 'button',
'checkbox': 'checkbox',
'image': 'button',
'number': 'spinbutton',
'radio': 'radio',
'range': 'slider',
'reset': 'button',
'submit': 'button',
}[type] || 'textbox';
},
'INS': () => 'insertion',
'LI': () => 'listitem',
'MAIN': () => 'main',
'MARK': () => 'mark',
'MATH': () => 'math',
'MENU': () => 'list',
'METER': () => 'meter',
'NAV': () => 'navigation',
'OL': () => 'list',
'OPTGROUP': () => 'group',
'OPTION': () => 'option',
'OUTPUT': () => 'status',
'P': () => 'paragraph',
'PROGRESS': () => 'progressbar',
'SECTION': (e: Element) => hasExplicitAccessibleName(e) ? 'region' : null,
'SELECT': (e: Element) => e.hasAttribute('multiple') || (e as HTMLSelectElement).size > 1 ? 'listbox' : 'combobox',
'STRONG': () => 'strong',
'SUB': () => 'subscript',
'SUP': () => 'superscript',
'TABLE': () => 'table',
'TBODY': () => 'rowgroup',
'TD': (e: Element) => {
const table = closestCrossShadow(e, 'table');
const role = table ? getExplicitAriaRole(table) : '';
return (role === 'grid' || role === 'treegrid') ? 'gridcell' : 'cell';
},
'TEXTAREA': () => 'textbox',
'TFOOT': () => 'rowgroup',
'TH': (e: Element) => {
if (e.getAttribute('scope') === 'col')
return 'columnheader';
if (e.getAttribute('scope') === 'row')
return 'rowheader';
const table = closestCrossShadow(e, 'table');
const role = table ? getExplicitAriaRole(table) : '';
return (role === 'grid' || role === 'treegrid') ? 'gridcell' : 'cell';
},
'THEAD': () => 'rowgroup',
'TIME': () => 'time',
'TR': () => 'row',
'UL': () => 'list',
};
const kPresentationInheritanceParents: { [tagName: string]: string[] } = {
'DD': ['DL', 'DIV'],
'DIV': ['DL'],
'DT': ['DL', 'DIV'],
'LI': ['OL', 'UL'],
'TBODY': ['TABLE'],
'TD': ['TR'],
'TFOOT': ['TABLE'],
'TH': ['TR'],
'THEAD': ['TABLE'],
'TR': ['THEAD', 'TBODY', 'TFOOT', 'TABLE'],
};
function getImplicitAriaRole(element: Element): string | null {
const implicitRole = kImplicitRoleByTagName[element.tagName]?.(element) || '';
if (!implicitRole)
return null;
// Inherit presentation role when required.
// https://www.w3.org/TR/wai-aria-1.2/#conflict_resolution_presentation_none
let ancestor: Element | null = element;
while (ancestor) {
const parent = parentElementOrShadowHost(ancestor);
const parents = kPresentationInheritanceParents[ancestor.tagName];
if (!parents || !parent || !parents.includes(parent.tagName))
break;
const parentExplicitRole = getExplicitAriaRole(parent);
if ((parentExplicitRole === 'none' || parentExplicitRole === 'presentation') && !hasPresentationConflictResolution(parent))
return parentExplicitRole;
ancestor = parent;
}
return implicitRole;
}
// https://www.w3.org/TR/wai-aria-1.2/#role_definitions
const allRoles = [
'alert', 'alertdialog', 'application', 'article', 'banner', 'blockquote', 'button', 'caption', 'cell', 'checkbox', 'code', 'columnheader', 'combobox', 'command',
'complementary', 'composite', 'contentinfo', 'definition', 'deletion', 'dialog', 'directory', 'document', 'emphasis', 'feed', 'figure', 'form', 'generic', 'grid',
'gridcell', 'group', 'heading', 'img', 'input', 'insertion', 'landmark', 'link', 'list', 'listbox', 'listitem', 'log', 'main', 'marquee', 'math', 'meter', 'menu',
'menubar', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'navigation', 'none', 'note', 'option', 'paragraph', 'presentation', 'progressbar', 'radio', 'radiogroup',
'range', 'region', 'roletype', 'row', 'rowgroup', 'rowheader', 'scrollbar', 'search', 'searchbox', 'section', 'sectionhead', 'select', 'separator', 'slider',
'spinbutton', 'status', 'strong', 'structure', 'subscript', 'superscript', 'switch', 'tab', 'table', 'tablist', 'tabpanel', 'term', 'textbox', 'time', 'timer',
'toolbar', 'tooltip', 'tree', 'treegrid', 'treeitem', 'widget', 'window'
];
// https://www.w3.org/TR/wai-aria-1.2/#abstract_roles
const abstractRoles = ['command', 'composite', 'input', 'landmark', 'range', 'roletype', 'section', 'sectionhead', 'select', 'structure', 'widget', 'window'];
const validRoles = allRoles.filter(role => !abstractRoles.includes(role));
function getExplicitAriaRole(element: Element): string | null {
// https://www.w3.org/TR/wai-aria-1.2/#document-handling_author-errors_roles
const roles = (element.getAttribute('role') || '').split(' ').map(role => role.trim());
return roles.find(role => validRoles.includes(role)) || null;
}
function hasPresentationConflictResolution(element: Element) {
// https://www.w3.org/TR/wai-aria-1.2/#conflict_resolution_presentation_none
// TODO: this should include "|| focusable" check.
return !hasGlobalAriaAttribute(element);
}
export function getAriaRole(element: Element): string | null {
const explicitRole = getExplicitAriaRole(element);
if (!explicitRole)
return getImplicitAriaRole(element);
if ((explicitRole === 'none' || explicitRole === 'presentation') && hasPresentationConflictResolution(element))
return getImplicitAriaRole(element);
return explicitRole;
}
function getAriaBoolean(attr: string | null) {
return attr === null ? undefined : attr.toLowerCase() === 'true';
}
function getComputedStyle(element: Element, pseudo?: string): CSSStyleDeclaration | undefined {
return element.ownerDocument && element.ownerDocument.defaultView ? element.ownerDocument.defaultView.getComputedStyle(element, pseudo) : undefined;
}
// https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion, but including "none" and "presentation" roles
// https://www.w3.org/TR/wai-aria-1.2/#aria-hidden
export function isElementHiddenForAria(element: Element, cache: Map<Element, boolean>): boolean {
if (['STYLE', 'SCRIPT', 'NOSCRIPT', 'TEMPLATE'].includes(element.tagName))
return true;
const style: CSSStyleDeclaration | undefined = getComputedStyle(element);
if (!style || style.visibility === 'hidden')
return true;
return belongsToDisplayNoneOrAriaHidden(element, cache);
}
function belongsToDisplayNoneOrAriaHidden(element: Element, cache: Map<Element, boolean>): boolean {
if (!cache.has(element)) {
const style = getComputedStyle(element);
let hidden = !style || style.display === 'none' || getAriaBoolean(element.getAttribute('aria-hidden')) === true;
if (!hidden) {
const parent = parentElementOrShadowHost(element);
if (parent)
hidden = hidden || belongsToDisplayNoneOrAriaHidden(parent, cache);
}
cache.set(element, hidden);
}
return cache.get(element)!;
}
function getIdRefs(element: Element, ref: string | null): Element[] {
if (!ref)
return [];
const root = enclosingShadowRootOrDocument(element);
if (!root)
return [];
try {
const ids = ref.split(' ').filter(id => !!id);
const set = new Set<Element>();
for (const id of ids) {
// https://www.w3.org/TR/wai-aria-1.2/#mapping_additional_relations_error_processing
// "If more than one element has the same ID, the user agent SHOULD use the first element found with the given ID"
const firstElement = root.querySelector('#' + CSS.escape(id));
if (firstElement)
set.add(firstElement);
}
return [...set];
} catch (e) {
return [];
}
}
function normalizeAccessbileName(s: string): string {
// "Flat string" at https://w3c.github.io/accname/#terminology
return s.replace(/\r\n/g, '\n').replace(/\u00A0/g, ' ').replace(/\s\s+/g, ' ').trim();
}
function queryInAriaOwned(element: Element, selector: string): Element[] {
const result = [...element.querySelectorAll(selector)];
for (const owned of getIdRefs(element, element.getAttribute('aria-owns'))) {
if (owned.matches(selector))
result.push(owned);
result.push(...owned.querySelectorAll(selector));
}
return result;
}
function getPseudoContent(pseudoStyle: CSSStyleDeclaration | undefined) {
if (!pseudoStyle)
return '';
const content = pseudoStyle.getPropertyValue('content');
if ((content[0] === '\'' && content[content.length - 1] === '\'') ||
(content[0] === '"' && content[content.length - 1] === '"')) {
const unquoted = content.substring(1, content.length - 1);
// SPEC DIFFERENCE.
// Spec says "CSS textual content, without a space", but we account for display
// to pass "name_file-label-inline-block-styles-manual.html"
const display = pseudoStyle.getPropertyValue('display') || 'inline';
if (display !== 'inline')
return ' ' + unquoted + ' ';
return unquoted;
}
return '';
}
export function getElementAccessibleName(element: Element, includeHidden: boolean, hiddenCache: Map<Element, boolean>): string {
// https://w3c.github.io/accname/#computation-steps
// step 1.
// https://w3c.github.io/aria/#namefromprohibited
const elementProhibitsNaming = ['caption', 'code', 'definition', 'deletion', 'emphasis', 'generic', 'insertion', 'mark', 'paragraph', 'presentation', 'strong', 'subscript', 'suggestion', 'superscript', 'term', 'time'].includes(getAriaRole(element) || '');
if (elementProhibitsNaming)
return '';
// step 2.
const accessibleName = normalizeAccessbileName(getElementAccessibleNameInternal(element, {
includeHidden,
hiddenCache,
visitedElements: new Set(),
embeddedInLabelledBy: 'none',
embeddedInLabel: 'none',
embeddedInTextAlternativeElement: false,
embeddedInTargetElement: 'self',
}));
return accessibleName;
}
type AccessibleNameOptions = {
includeHidden: boolean,
hiddenCache: Map<Element, boolean>,
visitedElements: Set<Element>,
embeddedInLabelledBy: 'none' | 'self' | 'descendant',
embeddedInLabel: 'none' | 'self' | 'descendant',
embeddedInTextAlternativeElement: boolean,
embeddedInTargetElement: 'none' | 'self' | 'descendant',
};
function getElementAccessibleNameInternal(element: Element, options: AccessibleNameOptions): string {
if (options.visitedElements.has(element))
return '';
const childOptions: AccessibleNameOptions = {
...options,
embeddedInLabel: options.embeddedInLabel === 'self' ? 'descendant' : options.embeddedInLabel,
embeddedInLabelledBy: options.embeddedInLabelledBy === 'self' ? 'descendant' : options.embeddedInLabelledBy,
embeddedInTargetElement: options.embeddedInTargetElement === 'self' ? 'descendant' : options.embeddedInTargetElement,
};
// step 2a.
if (!options.includeHidden && options.embeddedInLabelledBy !== 'self' && isElementHiddenForAria(element, options.hiddenCache)) {
options.visitedElements.add(element);
return '';
}
// step 2b.
if (options.embeddedInLabelledBy === 'none') {
const refs = getIdRefs(element, element.getAttribute('aria-labelledby'));
const accessibleName = refs.map(ref => getElementAccessibleNameInternal(ref, {
...options,
embeddedInLabelledBy: 'self',
embeddedInTargetElement: 'none',
embeddedInLabel: 'none',
embeddedInTextAlternativeElement: false,
})).join(' ');
if (accessibleName)
return accessibleName;
}
const role = getAriaRole(element) || '';
// step 2c.
if (options.embeddedInLabel !== 'none' || options.embeddedInLabelledBy !== 'none') {
const isOwnLabel = [...(element as (HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement)).labels || []].includes(element as any);
const isOwnLabelledBy = getIdRefs(element, element.getAttribute('aria-labelledby')).includes(element);
if (!isOwnLabel && !isOwnLabelledBy) {
if (role === 'textbox') {
options.visitedElements.add(element);
if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA')
return (element as HTMLInputElement | HTMLTextAreaElement).value;
return element.textContent || '';
}
if (['combobox', 'listbox'].includes(role)) {
options.visitedElements.add(element);
let selectedOptions: Element[];
if (element.tagName === 'SELECT') {
selectedOptions = [...(element as HTMLSelectElement).selectedOptions];
if (!selectedOptions.length && (element as HTMLSelectElement).options.length)
selectedOptions.push((element as HTMLSelectElement).options[0]);
} else {
const listbox = role === 'combobox' ? queryInAriaOwned(element, '*').find(e => getAriaRole(e) === 'listbox') : element;
selectedOptions = listbox ? queryInAriaOwned(listbox, '[aria-selected="true"]').filter(e => getAriaRole(e) === 'option') : [];
}
return selectedOptions.map(option => getElementAccessibleNameInternal(option, childOptions)).join(' ');
}
if (['progressbar', 'scrollbar', 'slider', 'spinbutton', 'meter'].includes(role)) {
options.visitedElements.add(element);
if (element.hasAttribute('aria-valuetext'))
return element.getAttribute('aria-valuetext') || '';
if (element.hasAttribute('aria-valuenow'))
return element.getAttribute('aria-valuenow') || '';
return element.getAttribute('value') || '';
}
if (['menu'].includes(role)) {
// https://github.com/w3c/accname/issues/67#issuecomment-553196887
options.visitedElements.add(element);
return '';
}
}
}
// step 2d.
const ariaLabel = element.getAttribute('aria-label') || '';
if (ariaLabel.trim()) {
options.visitedElements.add(element);
return ariaLabel;
}
// step 2e.
if (!['presentation', 'none'].includes(role)) {
// https://w3c.github.io/html-aam/#input-type-button-input-type-submit-and-input-type-reset
if (element.tagName === 'INPUT' && ['button', 'submit', 'reset'].includes((element as HTMLInputElement).type)) {
options.visitedElements.add(element);
const value = (element as HTMLInputElement).value || '';
if (value.trim())
return value;
if ((element as HTMLInputElement).type === 'submit')
return 'Submit';
if ((element as HTMLInputElement).type === 'reset')
return 'Reset';
const title = element.getAttribute('title') || '';
return title;
}
// https://w3c.github.io/html-aam/#input-type-image
if (element.tagName === 'INPUT' && (element as HTMLInputElement).type === 'image') {
options.visitedElements.add(element);
const alt = element.getAttribute('alt') || '';
if (alt.trim())
return alt;
// SPEC DIFFERENCE.
// Spec does not mention "label" elements, but we account for labels
// to pass "name_test_case_616-manual.html"
const labels = (element as HTMLInputElement).labels || [];
if (labels.length) {
return [...labels].map(label => getElementAccessibleNameInternal(label, {
...options,
embeddedInLabel: 'self',
embeddedInTextAlternativeElement: false,
embeddedInLabelledBy: 'none',
embeddedInTargetElement: 'none',
})).filter(accessibleName => !!accessibleName).join(' ');
}
const title = element.getAttribute('title') || '';
if (title.trim())
return title;
// SPEC DIFFERENCE.
// Spec says return localized "Submit Query", but browsers and axe-core insist on "Sumbit".
return 'Submit';
}
// https://w3c.github.io/html-aam/#input-type-text-input-type-password-input-type-search-input-type-tel-input-type-url-and-textarea-element
// https://w3c.github.io/html-aam/#other-form-elements
// For "other form elements", we count select and any other input.
if (element.tagName === 'TEXTAREA' || element.tagName === 'SELECT' || element.tagName === 'INPUT') {
options.visitedElements.add(element);
const labels = (element as (HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement)).labels || [];
if (labels.length) {
return [...labels].map(label => getElementAccessibleNameInternal(label, {
...options,
embeddedInLabel: 'self',
embeddedInTextAlternativeElement: false,
embeddedInLabelledBy: 'none',
embeddedInTargetElement: 'none',
})).filter(accessibleName => !!accessibleName).join(' ');
}
const usePlaceholder = (element.tagName === 'INPUT' && ['text', 'password', 'search', 'tel', 'email', 'url'].includes((element as HTMLInputElement).type)) || element.tagName === 'TEXTAREA';
const placeholder = element.getAttribute('placeholder') || '';
const title = element.getAttribute('title') || '';
if (!usePlaceholder || title)
return title;
return placeholder;
}
// https://w3c.github.io/html-aam/#fieldset-and-legend-elements
if (element.tagName === 'FIELDSET') {
options.visitedElements.add(element);
for (let child = element.firstElementChild; child; child = child.nextElementSibling) {
if (child.tagName === 'LEGEND') {
return getElementAccessibleNameInternal(child, {
...childOptions,
embeddedInTextAlternativeElement: true,
});
}
}
const title = element.getAttribute('title') || '';
return title;
}
// https://w3c.github.io/html-aam/#figure-and-figcaption-elements
if (element.tagName === 'FIGURE') {
options.visitedElements.add(element);
for (let child = element.firstElementChild; child; child = child.nextElementSibling) {
if (child.tagName === 'FIGCAPTION') {
return getElementAccessibleNameInternal(child, {
...childOptions,
embeddedInTextAlternativeElement: true,
});
}
}
const title = element.getAttribute('title') || '';
return title;
}
// https://w3c.github.io/html-aam/#img-element
if (element.tagName === 'IMG') {
options.visitedElements.add(element);
const alt = element.getAttribute('alt') || '';
if (alt.trim())
return alt;
const title = element.getAttribute('title') || '';
return title;
}
// https://w3c.github.io/html-aam/#table-element
if (element.tagName === 'TABLE') {
options.visitedElements.add(element);
for (let child = element.firstElementChild; child; child = child.nextElementSibling) {
if (child.tagName === 'CAPTION') {
return getElementAccessibleNameInternal(child, {
...childOptions,
embeddedInTextAlternativeElement: true,
});
}
}
// SPEC DIFFERENCE.
// Spec does not say a word about <table summary="...">, but all browsers actually support it.
const summary = element.getAttribute('summary') || '';
if (summary)
return summary;
// SPEC DIFFERENCE.
// Spec says "if the table element has a title attribute, then use that attribute".
// We ignore title to pass "name_from_content-manual.html".
}
// https://w3c.github.io/html-aam/#area-element
if (element.tagName === 'AREA') {
options.visitedElements.add(element);
const alt = element.getAttribute('alt') || '';
if (alt.trim())
return alt;
const title = element.getAttribute('title') || '';
return title;
}
// https://www.w3.org/TR/svg-aam-1.0/
if (element.tagName === 'SVG' && (element as SVGElement).ownerSVGElement) {
options.visitedElements.add(element);
for (let child = element.firstElementChild; child; child = child.nextElementSibling) {
if (child.tagName === 'TITLE' && (element as SVGElement).ownerSVGElement) {
return getElementAccessibleNameInternal(child, {
...childOptions,
embeddedInTextAlternativeElement: true,
});
}
}
}
}
// step 2f + step 2h.
// https://w3c.github.io/aria/#namefromcontent
const allowsNameFromContent = ['button', 'cell', 'checkbox', 'columnheader', 'gridcell', 'heading', 'link', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'radio', 'row', 'rowheader', 'switch', 'tab', 'tooltip', 'treeitem'].includes(role);
if (allowsNameFromContent || options.embeddedInLabelledBy !== 'none' || options.embeddedInLabel !== 'none' || options.embeddedInTextAlternativeElement || options.embeddedInTargetElement === 'descendant') {
options.visitedElements.add(element);
const tokens: string[] = [];
const visit = (node: Node) => {
if (node.nodeType === 1 /* Node.ELEMENT_NODE */) {
const display = getComputedStyle(node as Element)?.getPropertyValue('display') || 'inline';
let token = getElementAccessibleNameInternal(node as Element, childOptions);
// SPEC DIFFERENCE.
// Spec says "append the result to the accumulated text", assuming "with space".
// However, multiple tests insist that inline elements do not add a space.
// Additionally, <br> insists on a space anyway, see "name_file-label-inline-block-elements-manual.html"
if (display !== 'inline' || node.nodeName === 'BR')
token = ' ' + token + ' ';
tokens.push(token);
} else if (node.nodeType === 3 /* Node.TEXT_NODE */) {
// step 2g.
tokens.push(node.textContent || '');
}
};
tokens.push(getPseudoContent(getComputedStyle(element, '::before')));
for (let child = element.firstChild; child; child = child.nextSibling)
visit(child);
if (element.shadowRoot) {
for (let child = element.shadowRoot.firstChild; child; child = child.nextSibling)
visit(child);
}
for (const owned of getIdRefs(element, element.getAttribute('aria-owns')))
visit(owned);
tokens.push(getPseudoContent(getComputedStyle(element, '::after')));
const accessibleName = tokens.join('');
if (accessibleName.trim())
return accessibleName;
}
// step 2i.
if (!['presentation', 'none'].includes(role) || element.tagName === 'IFRAME') {
options.visitedElements.add(element);
const title = element.getAttribute('title') || '';
if (title.trim())
return title;
}
options.visitedElements.add(element);
return '';
}
export const kAriaSelectedRoles = ['gridcell', 'option', 'row', 'tab', 'rowheader', 'columnheader', 'treeitem'];
export function getAriaSelected(element: Element): boolean {
// https://www.w3.org/TR/wai-aria-1.2/#aria-selected
// https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
if (element.tagName === 'OPTION')
return (element as HTMLOptionElement).selected;
if (kAriaSelectedRoles.includes(getAriaRole(element) || ''))
return getAriaBoolean(element.getAttribute('aria-selected')) === true;
return false;
}
export const kAriaCheckedRoles = ['checkbox', 'menuitemcheckbox', 'option', 'radio', 'switch', 'menuitemradio', 'treeitem'];
export function getAriaChecked(element: Element): boolean | 'mixed' {
const result = getAriaCheckedStrict(element);
return result === 'error' ? false : result;
}
export function getAriaCheckedStrict(element: Element): boolean | 'mixed' | 'error' {
// https://www.w3.org/TR/wai-aria-1.2/#aria-checked
// https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
if (element.tagName === 'INPUT' && (element as HTMLInputElement).indeterminate)
return 'mixed';
if (element.tagName === 'INPUT' && ['checkbox', 'radio'].includes((element as HTMLInputElement).type))
return (element as HTMLInputElement).checked;
if (kAriaCheckedRoles.includes(getAriaRole(element) || '')) {
const checked = element.getAttribute('aria-checked');
if (checked === 'true')
return true;
if (checked === 'mixed')
return 'mixed';
return false;
}
return 'error';
}
export const kAriaPressedRoles = ['button'];
export function getAriaPressed(element: Element): boolean | 'mixed' {
// https://www.w3.org/TR/wai-aria-1.2/#aria-pressed
if (kAriaPressedRoles.includes(getAriaRole(element) || '')) {
const pressed = element.getAttribute('aria-pressed');
if (pressed === 'true')
return true;
if (pressed === 'mixed')
return 'mixed';
}
return false;
}
export const kAriaExpandedRoles = ['application', 'button', 'checkbox', 'combobox', 'gridcell', 'link', 'listbox', 'menuitem', 'row', 'rowheader', 'tab', 'treeitem', 'columnheader', 'menuitemcheckbox', 'menuitemradio', 'rowheader', 'switch'];
export function getAriaExpanded(element: Element): boolean {
// https://www.w3.org/TR/wai-aria-1.2/#aria-expanded
// https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
if (element.tagName === 'DETAILS')
return (element as HTMLDetailsElement).open;
if (kAriaExpandedRoles.includes(getAriaRole(element) || ''))
return getAriaBoolean(element.getAttribute('aria-expanded')) === true;
return false;
}
export const kAriaLevelRoles = ['heading', 'listitem', 'row', 'treeitem'];
export function getAriaLevel(element: Element): number {
// https://www.w3.org/TR/wai-aria-1.2/#aria-level
// https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
const native = { 'H1': 1, 'H2': 2, 'H3': 3, 'H4': 4, 'H5': 5, 'H6': 6 }[element.tagName];
if (native)
return native;
if (kAriaLevelRoles.includes(getAriaRole(element) || '')) {
const attr = element.getAttribute('aria-level');
const value = attr === null ? Number.NaN : Number(attr);
if (Number.isInteger(value) && value >= 1)
return value;
}
return 0;
}
export const kAriaDisabledRoles = ['application', 'button', 'composite', 'gridcell', 'group', 'input', 'link', 'menuitem', 'scrollbar', 'separator', 'tab', 'checkbox', 'columnheader', 'combobox', 'grid', 'listbox', 'menu', 'menubar', 'menuitemcheckbox', 'menuitemradio', 'option', 'radio', 'radiogroup', 'row', 'rowheader', 'searchbox', 'select', 'slider', 'spinbutton', 'switch', 'tablist', 'textbox', 'toolbar', 'tree', 'treegrid', 'treeitem'];
export function getAriaDisabled(element: Element): boolean {
// https://www.w3.org/TR/wai-aria-1.2/#aria-disabled
// https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
// Note that aria-disabled applies to all descendants, so we look up the hierarchy.
const isNativeFormControl = ['BUTTON', 'INPUT', 'SELECT', 'TEXTAREA', 'OPTION', 'OPTGROUP'].includes(element.tagName);
if (isNativeFormControl && (element.hasAttribute('disabled') || belongsToDisabledFieldSet(element)))
return true;
return hasExplicitAriaDisabled(element);
}
function belongsToDisabledFieldSet(element: Element | null): boolean {
if (!element)
return false;
if (element.tagName === 'FIELDSET' && element.hasAttribute('disabled'))
return true;
// fieldset does not work across shadow boundaries.
return belongsToDisabledFieldSet(element.parentElement);
}
function hasExplicitAriaDisabled(element: Element | undefined): boolean {
if (!element)
return false;
if (kAriaDisabledRoles.includes(getAriaRole(element) || '')) {
const attribute = (element.getAttribute('aria-disabled') || '').toLowerCase();
if (attribute === 'true')
return true;
if (attribute === 'false')
return false;
}
// aria-disabled works across shadow boundaries.
return hasExplicitAriaDisabled(parentElementOrShadowHost(element));
}
| packages/playwright-core/src/server/injected/roleUtils.ts | 1 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.9983940720558167,
0.1372433453798294,
0.00016504577070008963,
0.0004051544819958508,
0.3160966634750366
] |
{
"id": 1,
"code_window": [
"}\n",
"\n",
"export const kAriaExpandedRoles = ['application', 'button', 'checkbox', 'combobox', 'gridcell', 'link', 'listbox', 'menuitem', 'row', 'rowheader', 'tab', 'treeitem', 'columnheader', 'menuitemcheckbox', 'menuitemradio', 'rowheader', 'switch'];\n",
"export function getAriaExpanded(element: Element): boolean {\n",
" // https://www.w3.org/TR/wai-aria-1.2/#aria-expanded\n",
" // https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings\n",
" if (element.tagName === 'DETAILS')\n",
" return (element as HTMLDetailsElement).open;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export function getAriaExpanded(element: Element): boolean | 'none' {\n"
],
"file_path": "packages/playwright-core/src/server/injected/roleUtils.ts",
"type": "replace",
"edit_start_line_idx": 672
} | # playwright-webkit
This package contains the [WebKit](https://www.webkit.org/) flavor of the [Playwright](http://github.com/microsoft/playwright) library. If you want to write end-to-end tests, we recommend [@playwright/test](https://playwright.dev/docs/intro).
| packages/playwright-webkit/README.md | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00016642363334540278,
0.00016642363334540278,
0.00016642363334540278,
0.00016642363334540278,
0
] |
{
"id": 1,
"code_window": [
"}\n",
"\n",
"export const kAriaExpandedRoles = ['application', 'button', 'checkbox', 'combobox', 'gridcell', 'link', 'listbox', 'menuitem', 'row', 'rowheader', 'tab', 'treeitem', 'columnheader', 'menuitemcheckbox', 'menuitemradio', 'rowheader', 'switch'];\n",
"export function getAriaExpanded(element: Element): boolean {\n",
" // https://www.w3.org/TR/wai-aria-1.2/#aria-expanded\n",
" // https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings\n",
" if (element.tagName === 'DETAILS')\n",
" return (element as HTMLDetailsElement).open;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export function getAriaExpanded(element: Element): boolean | 'none' {\n"
],
"file_path": "packages/playwright-core/src/server/injected/roleUtils.ts",
"type": "replace",
"edit_start_line_idx": 672
} | ---
id: library
title: "Library"
---
Playwright Library provides unified APIs for launching and interacting with browsers, while Playwright Test provides all this plus a fully managed end-to-end Test Runner and experience.
Under most circumstances, for end-to-end testing, you'll want to use `@playwright/test` (Playwright Test), and not `playwright` (Playwright Library) directly. To get started with Playwright Test, follow the [Getting Started Guide](./intro.md).
## When Should Playwright Library Be Used Directly?
- Creating an integration for a third party test runner. For example, third-party runner plugins listed [here](./test-runners.md) are built on top of the Playwright Library.
- Automation and scraping.
## Differences when using library
### Library Example
The following is an example of using the Playwright Library directly to launch Chromium, go to a page, and check its title:
```js tab=js-ts
import { chromium, devices } from 'playwright';
import assert from 'node:assert';
(async () => {
// Setup
const browser = await chromium.launch();
const context = await browser.newContext(devices['iPhone 11']);
const page = await context.newPage();
// The actual interesting bit
await context.route('**.jpg', route => route.abort());
await page.goto('https://example.com/');
assert(await page.title() === 'Example Domain'); // 👎 not a Web First assertion
// Teardown
await context.close();
await browser.close();
})()
```
```js tab=js-js
const assert = require('node:assert');
const { chromium, devices } = require('playwright');
(async () => {
// Setup
const browser = await chromium.launch();
const context = await browser.newContext(devices['iPhone 11']);
const page = await context.newPage();
// The actual interesting bit
await context.route('**.jpg', route => route.abort());
await page.goto('https://example.com/');
assert(await page.title() === 'Example Domain'); // 👎 not a Web First assertion
// Teardown
await context.close();
await browser.close();
})()
```
Run it with `node my-script.js`.
### Test Example
A test to achieve similar behavior, would look like:
```js tab=js-ts
import { expect, test, devices } from '@playwright/test';
test.use(devices['iPhone 11']);
test('should be titled', async ({ page, context }) => {
await context.route('**.jpg', route => route.abort());
await page.goto('https://example.com/');
await expect(page).toHaveTitle('Example');
});
```
```js tab=js-js
const { expect, test, devices } = require('@playwright/test');
test.use(devices['iPhone 11']);
test('should be titled', async ({ page, context }) => {
await context.route('**.jpg', route => route.abort());
await page.goto('https://example.com/');
await expect(page).toHaveTitle('Example');
});
```
Run it with `npx playwright test`.
### Key Differences
The key differences to note are as follows:
| | Library | Test |
| - | - | - |
| Installation | `npm install playwright` | `npm init playwright@latest` - note `install` vs. `init` |
| Install browsers | Chromium, Firefox, WebKit are installed by default | `npx playwright install` or `npx playwright install chromium` for a single one |
| `import`/`require` name | `playwright` | `@playwright/test` |
| Initialization | Explicitly need to: <ol><li>Pick a browser to use, e.g. `chromium`</li><li>Launch browser with [`method: BrowserType.launch`]</li><li>Create a context with [`method: Browser.newContext`], <em>and</em> pass any context options explcitly, e.g. `devices['iPhone 11']`</li><li>Create a page with [`method: BrowserContext.newPage`]</li></ol> | An isolated `page` and `context` are provided to each test out-of the box, along with other [built-in fixtures](./test-fixtures.md#built-in-fixtures). No explicit creation. If referenced by the test in it's arguments, the Test Runner will create them for the test. (i.e. lazy-initialization) |
| Assertions | No built-in Web-First Assertions | [Web-First assertions](./test-assertions.md) like: <ul><li>[`method: PageAssertions.toHaveTitle`]</li><li>[`method: PageAssertions.toHaveScreenshot#1`]</li></ul> which auto-wait and retry for the condition to be met.|
| Cleanup | Explicitly need to: <ol><li>Close context with [`method: BrowserContext.close`]</li><li>Close browser with [`method: Browser.close`]</li></ol> | No explicit close of [built-in fixtures](./test-fixtures.md#built-in-fixtures); the Test Runner will take care of it.
| Running | When using the Library, you run the code as a node script, possibly with some compilation first. | When using the Test Runner, you use the `npx playwright test` command. Along with your [config](./test-configuration.md), the Test Runner handles any compilation and choosing what to run and how to run it. |
In addition to the above, Playwright Test, as a full-featured Test Runner, includes:
- [Configuration Matrix and Projects](./test-configuration.md): In the above example, in the Playwright Library version, if we wanted to run with a different device or browser, we'd have to modify the script and plumb the information through. With Playwright Test, we can just specify the [matrix of configurations](./test-configuration.md) in one place, and it will create run the one test under each of these configurations.
- [Parallelization](./test-parallel.md)
- [Web-First Assertions](./test-assertions.md)
- [Reporting](./test-reporters.md)
- [Retries](./test-retries.md)
- [Easily Enabled Tracing](./test-configuration.md#record-test-trace)
- and more…
## Usage
Use npm or Yarn to install Playwright library in your Node.js project. See [system requirements](./troubleshooting.md#system-requirements).
```bash
npm i -D playwright
```
This single command downloads the Playwright NPM package and browser binaries for Chromium, Firefox and WebKit. To modify this behavior see [managing browsers](./browsers.md#managing-browser-binaries).
Once installed, you can `require` Playwright in a Node.js script, and launch any of the 3 browsers (`chromium`, `firefox` and `webkit`).
```js
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
// Create pages, interact with UI elements, assert values
await browser.close();
})();
```
Playwright APIs are asynchronous and return Promise objects. Our code examples use [the async/await pattern](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await) to ease readability. The code is wrapped in an unnamed async arrow function which is invoking itself.
```js
(async () => { // Start of async arrow function
// Function code
// ...
})(); // End of the function and () to invoke itself
```
## First script
In our first script, we will navigate to `whatsmyuseragent.org` and take a screenshot in WebKit.
```js
const { webkit } = require('playwright');
(async () => {
const browser = await webkit.launch();
const page = await browser.newPage();
await page.goto('http://whatsmyuseragent.org/');
await page.screenshot({ path: `example.png` });
await browser.close();
})();
```
By default, Playwright runs the browsers in headless mode. To see the browser UI, pass the `headless: false` flag while launching the browser. You can also use `slowMo` to slow down execution. Learn more in the debugging tools [section](./debug.md).
```js
firefox.launch({ headless: false, slowMo: 50 });
```
## Record scripts
[Command line tools](./cli.md) can be used to record user interactions and generate JavaScript code.
```bash
npx playwright codegen wikipedia.org
```
## TypeScript support
Playwright includes built-in support for TypeScript. Type definitions will be imported automatically. It is recommended to use type-checking to improve the IDE experience.
### In JavaScript
Add the following to the top of your JavaScript file to get type-checking in VS Code or WebStorm.
```js
//@ts-check
// ...
```
Alternatively, you can use JSDoc to set types for variables.
```js
/** @type {import('playwright').Page} */
let page;
```
### In TypeScript
TypeScript support will work out-of-the-box. Types can also be imported explicitly.
```js
let page: import('playwright').Page;
```
| docs/src/library-js.md | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00017318707250524312,
0.00016762292943894863,
0.00015853112563490868,
0.00016794858674984425,
0.000003672114644359681
] |
{
"id": 1,
"code_window": [
"}\n",
"\n",
"export const kAriaExpandedRoles = ['application', 'button', 'checkbox', 'combobox', 'gridcell', 'link', 'listbox', 'menuitem', 'row', 'rowheader', 'tab', 'treeitem', 'columnheader', 'menuitemcheckbox', 'menuitemradio', 'rowheader', 'switch'];\n",
"export function getAriaExpanded(element: Element): boolean {\n",
" // https://www.w3.org/TR/wai-aria-1.2/#aria-expanded\n",
" // https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings\n",
" if (element.tagName === 'DETAILS')\n",
" return (element as HTMLDetailsElement).open;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export function getAriaExpanded(element: Element): boolean | 'none' {\n"
],
"file_path": "packages/playwright-core/src/server/injected/roleUtils.ts",
"type": "replace",
"edit_start_line_idx": 672
} | name: Cherry-pick into release branch
on:
workflow_dispatch:
inputs:
version:
type: string
description: Version number, e.g. 1.25
required: true
commit_hashes:
type: string
description: Comma-separated list of commit hashes to cherry-pick
required: true
jobs:
roll:
runs-on: ubuntu-22.04
steps:
- name: Validate input version number
run: |
VERSION="${{ github.event.inputs.version }}"
if ! [[ "$VERSION" =~ ^[0-9]+\.[0-9]+$ ]]; then
echo "Version is not a two digit semver version"
exit 1
fi
- uses: actions/checkout@v3
with:
ref: release-${{ github.event.inputs.version }}
fetch-depth: 0
- name: Cherry-pick commits
id: cherry-pick
run: |
git config --global user.name github-actions
git config --global user.email 41898282+github-actions[bot]@users.noreply.github.com
for COMMIT_HASH in $(echo "${{ github.event.inputs.commit_hashes }}" | tr "," "\n"); do
git cherry-pick --no-commit "$COMMIT_HASH"
COMMIT_MESSAGE="$(git show -s --format=%B $COMMIT_HASH | head -n 1)"
COMMIT_MESSAGE=$(node -e '
const match = /^(.*) (\(#\d+\))$/.exec(process.argv[1]);
if (!match) {
console.log(process.argv[1]);
process.exit(0);
}
console.log(`chery-pick${match[2]}: ${match[1]}`);
' "$COMMIT_MESSAGE")
git commit -m "$COMMIT_MESSAGE"
done
LAST_COMMIT_MESSAGE=$(git show -s --format=%B)
echo "::set-output name=PR_TITLE::$LAST_COMMIT_MESSAGE"
- name: Prepare branch
id: prepare-branch
run: |
BRANCH_NAME="cherry-pick-${{ github.event.inputs.version }}-$(date +%Y-%m-%d-%H-%M-%S)"
echo "::set-output name=BRANCH_NAME::$BRANCH_NAME"
git checkout -b "$BRANCH_NAME"
git push origin $BRANCH_NAME
- name: Create Pull Request
uses: actions/github-script@v6
with:
github-token: ${{ secrets.REPOSITORY_DISPATCH_PERSONAL_ACCESS_TOKEN }}
script: |
const readableCommitHashesList = '${{ github.event.inputs.commit_hashes }}'.split(',').map(hash => `- ${hash}`).join('\n');
const response = await github.rest.pulls.create({
owner: 'microsoft',
repo: 'playwright',
head: 'microsoft:${{ steps.prepare-branch.outputs.BRANCH_NAME }}',
base: 'release-${{ github.event.inputs.version }}',
title: '${{ steps.cherry-pick.outputs.PR_TITLE }}',
body: `This PR cherry-picks the following commits:\n\n${readableCommitHashesList}`,
});
await github.rest.issues.addLabels({
owner: 'microsoft',
repo: 'playwright',
issue_number: response.data.number,
labels: ['CQ1'],
});
| .github/workflows/cherry_pick_into_release_branch.yml | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00017325843509752303,
0.0001707992923911661,
0.00016664847498759627,
0.00017164068412967026,
0.0000020101140307815513
] |
{
"id": 2,
"code_window": [
" // https://www.w3.org/TR/wai-aria-1.2/#aria-expanded\n",
" // https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings\n",
" if (element.tagName === 'DETAILS')\n",
" return (element as HTMLDetailsElement).open;\n",
" if (kAriaExpandedRoles.includes(getAriaRole(element) || ''))\n",
" return getAriaBoolean(element.getAttribute('aria-expanded')) === true;\n",
" return false;\n",
"}\n",
"\n",
"export const kAriaLevelRoles = ['heading', 'listitem', 'row', 'treeitem'];\n",
"export function getAriaLevel(element: Element): number {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (kAriaExpandedRoles.includes(getAriaRole(element) || '')) {\n",
" const expanded = element.getAttribute('aria-expanded');\n",
" if (expanded === null)\n",
" return 'none';\n",
" if (expanded === 'true')\n",
" return true;\n",
" return false;\n",
" }\n",
" return 'none';\n"
],
"file_path": "packages/playwright-core/src/server/injected/roleUtils.ts",
"type": "replace",
"edit_start_line_idx": 677
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { SelectorEngine, SelectorRoot } from './selectorEngine';
import { matchesAttributePart } from './selectorUtils';
import { getAriaChecked, getAriaDisabled, getAriaExpanded, getAriaLevel, getAriaPressed, getAriaRole, getAriaSelected, getElementAccessibleName, isElementHiddenForAria, kAriaCheckedRoles, kAriaExpandedRoles, kAriaLevelRoles, kAriaPressedRoles, kAriaSelectedRoles } from './roleUtils';
import { parseAttributeSelector, type AttributeSelectorPart, type AttributeSelectorOperator } from '../isomorphic/selectorParser';
const kSupportedAttributes = ['selected', 'checked', 'pressed', 'expanded', 'level', 'disabled', 'name', 'include-hidden'];
kSupportedAttributes.sort();
function validateSupportedRole(attr: string, roles: string[], role: string) {
if (!roles.includes(role))
throw new Error(`"${attr}" attribute is only supported for roles: ${roles.slice().sort().map(role => `"${role}"`).join(', ')}`);
}
function validateSupportedValues(attr: AttributeSelectorPart, values: any[]) {
if (attr.op !== '<truthy>' && !values.includes(attr.value))
throw new Error(`"${attr.name}" must be one of ${values.map(v => JSON.stringify(v)).join(', ')}`);
}
function validateSupportedOp(attr: AttributeSelectorPart, ops: AttributeSelectorOperator[]) {
if (!ops.includes(attr.op))
throw new Error(`"${attr.name}" does not support "${attr.op}" matcher`);
}
function validateAttributes(attrs: AttributeSelectorPart[], role: string) {
for (const attr of attrs) {
switch (attr.name) {
case 'checked': {
validateSupportedRole(attr.name, kAriaCheckedRoles, role);
validateSupportedValues(attr, [true, false, 'mixed']);
validateSupportedOp(attr, ['<truthy>', '=']);
if (attr.op === '<truthy>') {
// Do not match "mixed" in "option[checked]".
attr.op = '=';
attr.value = true;
}
break;
}
case 'pressed': {
validateSupportedRole(attr.name, kAriaPressedRoles, role);
validateSupportedValues(attr, [true, false, 'mixed']);
validateSupportedOp(attr, ['<truthy>', '=']);
if (attr.op === '<truthy>') {
// Do not match "mixed" in "button[pressed]".
attr.op = '=';
attr.value = true;
}
break;
}
case 'selected': {
validateSupportedRole(attr.name, kAriaSelectedRoles, role);
validateSupportedValues(attr, [true, false]);
validateSupportedOp(attr, ['<truthy>', '=']);
break;
}
case 'expanded': {
validateSupportedRole(attr.name, kAriaExpandedRoles, role);
validateSupportedValues(attr, [true, false]);
validateSupportedOp(attr, ['<truthy>', '=']);
break;
}
case 'level': {
validateSupportedRole(attr.name, kAriaLevelRoles, role);
// Level is a number, convert it from string.
if (typeof attr.value === 'string')
attr.value = +attr.value;
if (attr.op !== '=' || typeof attr.value !== 'number' || Number.isNaN(attr.value))
throw new Error(`"level" attribute must be compared to a number`);
break;
}
case 'disabled': {
validateSupportedValues(attr, [true, false]);
validateSupportedOp(attr, ['<truthy>', '=']);
break;
}
case 'name': {
if (attr.op === '<truthy>')
throw new Error(`"name" attribute must have a value`);
if (typeof attr.value !== 'string' && !(attr.value instanceof RegExp))
throw new Error(`"name" attribute must be a string or a regular expression`);
break;
}
case 'include-hidden': {
validateSupportedValues(attr, [true, false]);
validateSupportedOp(attr, ['<truthy>', '=']);
break;
}
default: {
throw new Error(`Unknown attribute "${attr.name}", must be one of ${kSupportedAttributes.map(a => `"${a}"`).join(', ')}.`);
}
}
}
}
export function createRoleEngine(internal: boolean): SelectorEngine {
const queryAll = (scope: SelectorRoot, selector: string): Element[] => {
const parsed = parseAttributeSelector(selector, true);
const role = parsed.name.toLowerCase();
if (!role)
throw new Error(`Role must not be empty`);
validateAttributes(parsed.attributes, role);
const hiddenCache = new Map<Element, boolean>();
const result: Element[] = [];
const match = (element: Element) => {
if (getAriaRole(element) !== role)
return;
let includeHidden = false; // By default, hidden elements are excluded.
let nameAttr: AttributeSelectorPart | undefined;
for (const attr of parsed.attributes) {
if (attr.name === 'include-hidden') {
includeHidden = attr.op === '<truthy>' || !!attr.value;
continue;
}
if (attr.name === 'name') {
nameAttr = attr;
continue;
}
let actual;
switch (attr.name) {
case 'selected': actual = getAriaSelected(element); break;
case 'checked': actual = getAriaChecked(element); break;
case 'pressed': actual = getAriaPressed(element); break;
case 'expanded': actual = getAriaExpanded(element); break;
case 'level': actual = getAriaLevel(element); break;
case 'disabled': actual = getAriaDisabled(element); break;
}
if (!matchesAttributePart(actual, attr))
return;
}
if (!includeHidden) {
const isHidden = isElementHiddenForAria(element, hiddenCache);
if (isHidden)
return;
}
if (nameAttr !== undefined) {
// Always normalize whitespace in the accessible name.
const accessibleName = getElementAccessibleName(element, includeHidden, hiddenCache).trim().replace(/\s+/g, ' ');
if (typeof nameAttr.value === 'string')
nameAttr.value = nameAttr.value.trim().replace(/\s+/g, ' ');
// internal:role assumes that [name="foo"i] also means substring.
if (internal && !nameAttr.caseSensitive && nameAttr.op === '=')
nameAttr.op = '*=';
if (!matchesAttributePart(accessibleName, nameAttr))
return;
}
result.push(element);
};
const query = (root: Element | ShadowRoot | Document) => {
const shadows: ShadowRoot[] = [];
if ((root as Element).shadowRoot)
shadows.push((root as Element).shadowRoot!);
for (const element of root.querySelectorAll('*')) {
match(element);
if (element.shadowRoot)
shadows.push(element.shadowRoot);
}
shadows.forEach(query);
};
query(scope);
return result;
};
return { queryAll };
}
| packages/playwright-core/src/server/injected/roleSelectorEngine.ts | 1 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.9986472725868225,
0.10638780146837234,
0.00016662116104271263,
0.0001835190923884511,
0.3060015141963959
] |
{
"id": 2,
"code_window": [
" // https://www.w3.org/TR/wai-aria-1.2/#aria-expanded\n",
" // https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings\n",
" if (element.tagName === 'DETAILS')\n",
" return (element as HTMLDetailsElement).open;\n",
" if (kAriaExpandedRoles.includes(getAriaRole(element) || ''))\n",
" return getAriaBoolean(element.getAttribute('aria-expanded')) === true;\n",
" return false;\n",
"}\n",
"\n",
"export const kAriaLevelRoles = ['heading', 'listitem', 'row', 'treeitem'];\n",
"export function getAriaLevel(element: Element): number {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (kAriaExpandedRoles.includes(getAriaRole(element) || '')) {\n",
" const expanded = element.getAttribute('aria-expanded');\n",
" if (expanded === null)\n",
" return 'none';\n",
" if (expanded === 'true')\n",
" return true;\n",
" return false;\n",
" }\n",
" return 'none';\n"
],
"file_path": "packages/playwright-core/src/server/injected/roleUtils.ts",
"type": "replace",
"edit_start_line_idx": 677
} | <template>
<div>
<header>
<slot name="header" />
</header>
<main>
<slot name="main" />
</main>
<footer>
<slot name="footer" />
</footer>
</div>
</template>
| examples/components-vue/src/components/NamedSlots.vue | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00017272036348003894,
0.00017224866314791143,
0.00017177697736769915,
0.00017224866314791143,
4.716930561698973e-7
] |
{
"id": 2,
"code_window": [
" // https://www.w3.org/TR/wai-aria-1.2/#aria-expanded\n",
" // https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings\n",
" if (element.tagName === 'DETAILS')\n",
" return (element as HTMLDetailsElement).open;\n",
" if (kAriaExpandedRoles.includes(getAriaRole(element) || ''))\n",
" return getAriaBoolean(element.getAttribute('aria-expanded')) === true;\n",
" return false;\n",
"}\n",
"\n",
"export const kAriaLevelRoles = ['heading', 'listitem', 'row', 'treeitem'];\n",
"export function getAriaLevel(element: Element): number {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (kAriaExpandedRoles.includes(getAriaRole(element) || '')) {\n",
" const expanded = element.getAttribute('aria-expanded');\n",
" if (expanded === null)\n",
" return 'none';\n",
" if (expanded === 'true')\n",
" return true;\n",
" return false;\n",
" }\n",
" return 'none';\n"
],
"file_path": "packages/playwright-core/src/server/injected/roleUtils.ts",
"type": "replace",
"edit_start_line_idx": 677
} | import { test, expect } from '@playwright/experimental-ct-vue'
import Counter from './Counter.vue'
test.use({ viewport: { width: 500, height: 500 } })
test('should work', async ({ mount }) => {
const values = []
const component = await mount(<Counter v-on:changed={counter => values.push(counter)}></Counter>)
await component.click()
expect(values).toEqual([1])
await component.click()
expect(values).toEqual([1, 2])
await component.click()
expect(values).toEqual([1, 2, 3])
})
| examples/components-vue/src/components/Counter.spec.tsx | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.000176327841472812,
0.00017546879826113582,
0.0001746097404975444,
0.00017546879826113582,
8.590504876337945e-7
] |
{
"id": 2,
"code_window": [
" // https://www.w3.org/TR/wai-aria-1.2/#aria-expanded\n",
" // https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings\n",
" if (element.tagName === 'DETAILS')\n",
" return (element as HTMLDetailsElement).open;\n",
" if (kAriaExpandedRoles.includes(getAriaRole(element) || ''))\n",
" return getAriaBoolean(element.getAttribute('aria-expanded')) === true;\n",
" return false;\n",
"}\n",
"\n",
"export const kAriaLevelRoles = ['heading', 'listitem', 'row', 'treeitem'];\n",
"export function getAriaLevel(element: Element): number {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (kAriaExpandedRoles.includes(getAriaRole(element) || '')) {\n",
" const expanded = element.getAttribute('aria-expanded');\n",
" if (expanded === null)\n",
" return 'none';\n",
" if (expanded === 'true')\n",
" return true;\n",
" return false;\n",
" }\n",
" return 'none';\n"
],
"file_path": "packages/playwright-core/src/server/injected/roleUtils.ts",
"type": "replace",
"edit_start_line_idx": 677
} | ---
id: test-configuration
title: "Configuration"
---
Playwright Test provides options to configure the default `browser`, `context` and `page` fixtures. For example there are options for `headless`, `viewport` and `ignoreHTTPSErrors`. You can also record a video or a trace for the test or capture a screenshot at the end.
There are plenty of testing options like `timeout` or `testDir` that configure how your tests are collected and executed.
You can specify any options globally in the configuration file, and most of them locally in a test file.
See the full list of [test options][TestOptions] and all [configuration properties][TestConfig].
## Global configuration
Create a `playwright.config.js` (or `playwright.config.ts`) and specify options in the [`property: TestConfig.use`] section.
```js tab=js-js
// @ts-check
/** @type {import('@playwright/test').PlaywrightTestConfig} */
const config = {
use: {
headless: false,
viewport: { width: 1280, height: 720 },
ignoreHTTPSErrors: true,
video: 'on-first-retry',
},
};
module.exports = config;
```
```js tab=js-ts
import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
use: {
headless: false,
viewport: { width: 1280, height: 720 },
ignoreHTTPSErrors: true,
video: 'on-first-retry',
},
};
export default config;
```
Now run tests as usual, Playwright Test will pick up the configuration file automatically.
```bash
npx playwright test
```
If you put your configuration file in a different place, pass it with `--config` option.
```bash
npx playwright test --config=tests/my.config.js
```
## Local configuration
You can override some options for a file or describe block.
```js tab=js-js
// example.spec.js
const { test, expect } = require('@playwright/test');
// Run tests in this file with portrait-like viewport.
test.use({ viewport: { width: 600, height: 900 } });
test('my portrait test', async ({ page }) => {
// ...
});
```
```js tab=js-ts
// example.spec.ts
import { test, expect } from '@playwright/test';
// Run tests in this file with portrait-like viewport.
test.use({ viewport: { width: 600, height: 900 } });
test('my portrait test', async ({ page }) => {
// ...
});
```
The same works inside describe.
```js tab=js-js
// example.spec.js
const { test, expect } = require('@playwright/test');
test.describe('locale block', () => {
// Run tests in this describe block with portrait-like viewport.
test.use({ viewport: { width: 600, height: 900 } });
test('my portrait test', async ({ page }) => {
// ...
});
});
```
```js tab=js-ts
// example.spec.ts
import { test, expect } from '@playwright/test';
test.describe('locale block', () => {
// Run tests in this describe block with portrait-like viewport.
test.use({ viewport: { width: 600, height: 900 } });
test('my portrait test', async ({ page }) => {
// ...
});
});
```
## Basic options
Normally you would start with emulating a device, for example Desktop Chromium. See our [Emulation](./emulation.md) guide to learn more.
Here are some of the commonly used options for various scenarios. You usually set them globally in the [configuration file](#global-configuration).
- `actionTimeout` - Timeout for each Playwright action in milliseconds. Defaults to `0` (no timeout). Learn more about [various timeouts](./test-timeouts.md).
- `baseURL` - Base URL used for all pages in the context. Allows navigating by using just the path, for example `page.goto('/settings')`.
- `browserName` - Name of the browser that will run the tests, one of `chromium`, `firefox`, or `webkit`.
- `bypassCSP` - Toggles bypassing Content-Security-Policy. Useful when CSP includes the production origin.
- `channel` - Browser channel to use. [Learn more](./browsers.md) about different browsers and channels.
- `headless` - Whether to run the browser in headless mode.
- `viewport` - Viewport used for all pages in the context.
- `storageState` - Populates context with given storage state. Useful for easy authentication, [learn more](./auth.md).
- `colorScheme` - Emulates `'prefers-colors-scheme'` media feature, supported values are `'light'`, `'dark'`, `'no-preference'`.
- `geolocation` - Context geolocation.
- `locale` - [Emulates](./emulation.md) the user locale, for example `en-GB`, `de-DE`, etc.
- `permissions` - A list of permissions to grant to all pages in the context.
- `timezoneId` - Changes the timezone of the context.
```js tab=js-js
// @ts-check
/** @type {import('@playwright/test').PlaywrightTestConfig} */
const config = {
use: {
baseURL: 'http://localhost:3000',
browserName: 'firefox',
headless: true,
},
};
module.exports = config;
```
```js tab=js-ts
import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
use: {
baseURL: 'http://localhost:3000',
browserName: 'firefox',
headless: true,
},
};
export default config;
```
## Multiple browsers
Playwright Test supports multiple "projects" that can run your tests in multiple browsers and configurations. Here is an example that runs every test in Chromium, Firefox and WebKit, by creating a project for each.
```js tab=js-js
// playwright.config.js
// @ts-check
const { devices } = require('@playwright/test');
/** @type {import('@playwright/test').PlaywrightTestConfig} */
const config = {
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
],
};
module.exports = config;
```
```js tab=js-ts
// playwright.config.ts
import { type PlaywrightTestConfig, devices } from '@playwright/test';
const config: PlaywrightTestConfig = {
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
],
};
export default config;
```
You can specify [different options][TestProject] for each project, for example set specific command-line arguments for Chromium.
Playwright Test will run all projects by default.
```bash
npx playwright test
Running 5 tests using 5 workers
✓ [chromium] › example.spec.ts:3:1 › basic test (2s)
✓ [firefox] › example.spec.ts:3:1 › basic test (2s)
✓ [webkit] › example.spec.ts:3:1 › basic test (2s)
```
Use `--project` command line option to run a single project.
```bash
npx playwright test --project=firefox
Running 1 test using 1 worker
✓ [firefox] › example.spec.ts:3:1 › basic test (2s)
```
## Network
Available options to configure networking:
- `acceptDownloads` - Whether to automatically download all the attachments, defaults to `true`. [Learn more](./downloads.md) about working with downloads.
- `extraHTTPHeaders` - An object containing additional HTTP headers to be sent with every request. All header values must be strings.
- `httpCredentials` - Credentials for [HTTP authentication](./network.md#http-authentication).
- `ignoreHTTPSErrors` - Whether to ignore HTTPS errors during navigation.
- `offline` - Whether to emulate network being offline.
- `proxy` - [Proxy settings](./network.md#http-proxy) used for all pages in the test.
### Network mocking
You don't have to configure anything to mock network requests. Just define a custom [Route] that mocks network for a browser context.
```js tab=js-js
// example.spec.js
const { test, expect } = require('@playwright/test');
test.beforeEach(async ({ context }) => {
// Block any css requests for each test in this file.
await context.route(/.css/, route => route.abort());
});
test('loads page without css', async ({ page }) => {
await page.goto('https://playwright.dev');
// ... test goes here
});
```
```js tab=js-ts
// example.spec.ts
import { test, expect } from '@playwright/test';
test.beforeEach(async ({ context }) => {
// Block any css requests for each test in this file.
await context.route(/.css/, route => route.abort());
});
test('loads page without css', async ({ page }) => {
await page.goto('https://playwright.dev');
// ... test goes here
});
```
Alternatively, you can use [`method: Page.route`] to mock network in a single test.
```js tab=js-js
// example.spec.js
const { test, expect } = require('@playwright/test');
test('loads page without images', async ({ page }) => {
// Block png and jpeg images.
await page.route(/(png|jpeg)$/, route => route.abort());
await page.goto('https://playwright.dev');
// ... test goes here
});
```
```js tab=js-ts
// example.spec.ts
import { test, expect } from '@playwright/test';
test('loads page without images', async ({ page }) => {
// Block png and jpeg images.
await page.route(/(png|jpeg)$/, route => route.abort());
await page.goto('https://playwright.dev');
// ... test goes here
});
```
## Automatic screenshots
You can make Playwright Test capture screenshots for you - control it with the `screenshot` option. By default screenshots are off.
- `'off'` - Do not capture screenshots.
- `'on'` - Capture screenshot after each test.
- `'only-on-failure'` - Capture screenshot after each test failure.
Screenshots will appear in the test output directory, typically `test-results`.
```js tab=js-js
// @ts-check
/** @type {import('@playwright/test').PlaywrightTestConfig} */
const config = {
use: {
screenshot: 'only-on-failure',
},
};
module.exports = config;
```
```js tab=js-ts
import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
use: {
screenshot: 'only-on-failure',
},
};
export default config;
```
## Record video
Playwright Test can record videos for your tests, controlled by the `video` option. By default videos are off.
- `'off'` - Do not record video.
- `'on'` - Record video for each test.
- `'retain-on-failure'` - Record video for each test, but remove all videos from successful test runs.
- `'on-first-retry'` - Record video only when retrying a test for the first time.
Video files will appear in the test output directory, typically `test-results`. See [`property: TestOptions.video`] for advanced video configuration.
```js tab=js-js
// @ts-check
/** @type {import('@playwright/test').PlaywrightTestConfig} */
const config = {
use: {
video: 'on-first-retry',
},
};
module.exports = config;
```
```js tab=js-ts
import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
use: {
video: 'on-first-retry',
},
};
export default config;
```
## Record test trace
Playwright Test can produce test traces while running the tests. Later on, you can view the trace and get detailed information about Playwright execution by opening [Trace Viewer](./trace-viewer.md). By default tracing is off, controlled by the `trace` option.
- `'off'` - Do not record trace.
- `'on'` - Record trace for each test.
- `'retain-on-failure'` - Record trace for each test, but remove it from successful test runs.
- `'on-first-retry'` - Record trace only when retrying a test for the first time.
Trace files will appear in the test output directory, typically `test-results`. See [`property: TestOptions.trace`] for advanced configuration.
```js tab=js-js
// @ts-check
/** @type {import('@playwright/test').PlaywrightTestConfig} */
const config = {
use: {
trace: 'retain-on-failure',
},
};
module.exports = config;
```
```js tab=js-ts
import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
use: {
trace: 'retain-on-failure',
},
};
export default config;
```
## More browser and context options
Any options accepted by [`method: BrowserType.launch`] or [`method: Browser.newContext`] can be put into `launchOptions` or `contextOptions` respectively in the `use` section. Take a look at the [full list of available options][TestOptions].
```js tab=js-js
// @ts-check
/** @type {import('@playwright/test').PlaywrightTestConfig} */
const config = {
use: {
launchOptions: {
slowMo: 50,
},
},
};
module.exports = config;
```
```js tab=js-ts
import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
use: {
launchOptions: {
slowMo: 50,
},
},
};
export default config;
```
However, most common ones like `headless` or `viewport` are available directly in the `use` section - see [basic options](#basic-options), [emulation](#emulation) or [network](#network).
## Explicit Context Creation and Option Inheritance
If using the built-in `browser` fixture, calling [`method: Browser.newContext`] will create a context with options inherted from the config:
```js tab=js-ts
// playwright.config.ts
import type { PlaywrightTestConfig } from "@playwright/test";
const config: PlaywrightTestConfig = {
use: {
userAgent: 'some custom ua',
viewport: { width: 100, height: 100 },
},
};
export default config;
```
```js tab=js-js
// @ts-check
// example.spec.js
/** @type {import('@playwright/test').PlaywrightTestConfig} */
const config = {
use: {
userAgent: 'some custom ua',
viewport: { width: 100, height: 100 },
},
};
module.exports = config;
```
An example test illustrating the initial context options are set:
```js tab=js-ts
// example.spec.ts
import { test, expect } from "@playwright/test";
test('should inherit use options on context when using built-in browser fixture', async ({
browser,
}) => {
const context = await browser.newContext();
const page = await context.newPage();
expect(await page.evaluate(() => navigator.userAgent)).toBe('some custom ua');
expect(await page.evaluate(() => window.innerWidth)).toBe(100);
await context.close();
});
```
```js tab=js-js
// @ts-check
// example.spec.ts
const { test, expect } = require("@playwright/test");
test('should inherit use options on context when using built-in browser fixture', async ({
browser,
}) => {
const context = await browser.newContext();
const page = await context.newPage();
expect(await page.evaluate(() => navigator.userAgent)).toBe('some custom ua');
expect(await page.evaluate(() => window.innerWidth)).toBe(100);
await context.close();
});
```
## Testing options
In addition to configuring [Browser] or [BrowserContext], videos or screenshots, Playwright Test has many options to configure how your tests are run. Below are the most common ones, see [TestConfig] for the full list.
- `forbidOnly`: Whether to exit with an error if any tests are marked as `test.only`. Useful on CI.
- `globalSetup`: Path to the global setup file. This file will be required and run before all the tests. It must export a single function.
- `globalTeardown`: Path to the global teardown file. This file will be required and run after all the tests. It must export a single function.
- `retries`: The maximum number of retry attempts per test.
- `testDir`: Directory with the test files.
- `testIdAttribute`: Set a custom data attribute for your [`method: Page.getByTestId`] locators.
- `testIgnore`: Glob patterns or regular expressions that should be ignored when looking for the test files. For example, `'**/test-assets'`.
- `testMatch`: Glob patterns or regular expressions that match test files. For example, `'**/todo-tests/*.spec.ts'`. By default, Playwright Test runs `.*(test|spec)\.(js|ts|mjs)` files.
- `timeout`: Time in milliseconds given to each test. Learn more about [various timeouts](./test-timeouts.md).
- `webServer: { command: string, port?: number, url?: string, ignoreHTTPSErrors?: boolean, timeout?: number, reuseExistingServer?: boolean, cwd?: string, env?: object }` - Launch a process and wait that it's ready before the tests will start. See [launch web server](./test-advanced.md#launching-a-development-web-server-during-the-tests) configuration for examples.
- `workers`: The maximum number of concurrent worker processes to use for parallelizing tests. Can also be set as percentage of logical CPU cores, e.g. `'50%'.`
You can specify these options in the configuration file. Note that testing options are **top-level**, do not put them into the `use` section.
```js tab=js-js
// playwright.config.js
// @ts-check
/** @type {import('@playwright/test').PlaywrightTestConfig} */
const config = {
// Look for test files in the "tests" directory, relative to this configuration file
testDir: 'tests',
// change the default data-testid to a custom attribute
testIdAttribute: 'data-pw'
// Each test is given 30 seconds
timeout: 30000,
// Forbid test.only on CI
forbidOnly: !!process.env.CI,
// Two retries for each test
retries: 2,
// Limit the number of workers on CI, use default locally
workers: process.env.CI ? 2 : undefined,
use: {
// Configure browser and context here
},
};
module.exports = config;
```
```js tab=js-ts
// playwright.config.ts
import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
// Look for test files in the "tests" directory, relative to this configuration file
testDir: 'tests',
// Each test is given 30 seconds
timeout: 30000,
// Forbid test.only on CI
forbidOnly: !!process.env.CI,
// Two retries for each test
retries: 2,
// Limit the number of workers on CI, use default locally
workers: process.env.CI ? 2 : undefined,
use: {
// Configure browser and context here
},
};
export default config;
```
| docs/src/test-configuration-js.md | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00017715276044327766,
0.00017247140931431204,
0.00016118543862830848,
0.00017276483413297683,
0.0000032261598335026065
] |
{
"id": 3,
"code_window": [
"\n",
"test('should support expanded', async ({ page }) => {\n",
" await page.setContent(`\n",
" <button>Hi</button>\n",
" <button aria-expanded=\"true\">Hello</button>\n",
" <button aria-expanded=\"false\">Bye</button>\n",
" `);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" <div role=\"treeitem\">Hi</div>\n",
" <div role=\"treeitem\" aria-expanded=\"true\">Hello</div>\n",
" <div role=\"treeitem\" aria-expanded=\"false\">Bye</div>\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 171
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { closestCrossShadow, enclosingShadowRootOrDocument, parentElementOrShadowHost } from './domUtils';
function hasExplicitAccessibleName(e: Element) {
return e.hasAttribute('aria-label') || e.hasAttribute('aria-labelledby');
}
// https://www.w3.org/TR/wai-aria-practices/examples/landmarks/HTML5.html
const kAncestorPreventingLandmark = 'article:not([role]), aside:not([role]), main:not([role]), nav:not([role]), section:not([role]), [role=article], [role=complementary], [role=main], [role=navigation], [role=region]';
// https://www.w3.org/TR/wai-aria-1.2/#global_states
const kGlobalAriaAttributes = [
'aria-atomic',
'aria-busy',
'aria-controls',
'aria-current',
'aria-describedby',
'aria-details',
'aria-disabled',
'aria-dropeffect',
'aria-errormessage',
'aria-flowto',
'aria-grabbed',
'aria-haspopup',
'aria-hidden',
'aria-invalid',
'aria-keyshortcuts',
'aria-label',
'aria-labelledby',
'aria-live',
'aria-owns',
'aria-relevant',
'aria-roledescription',
];
function hasGlobalAriaAttribute(e: Element) {
return kGlobalAriaAttributes.some(a => e.hasAttribute(a));
}
// https://w3c.github.io/html-aam/#html-element-role-mappings
const kImplicitRoleByTagName: { [tagName: string]: (e: Element) => string | null } = {
'A': (e: Element) => {
return e.hasAttribute('href') ? 'link' : null;
},
'AREA': (e: Element) => {
return e.hasAttribute('href') ? 'link' : null;
},
'ARTICLE': () => 'article',
'ASIDE': () => 'complementary',
'BLOCKQUOTE': () => 'blockquote',
'BUTTON': () => 'button',
'CAPTION': () => 'caption',
'CODE': () => 'code',
'DATALIST': () => 'listbox',
'DD': () => 'definition',
'DEL': () => 'deletion',
'DETAILS': () => 'group',
'DFN': () => 'term',
'DIALOG': () => 'dialog',
'DT': () => 'term',
'EM': () => 'emphasis',
'FIELDSET': () => 'group',
'FIGURE': () => 'figure',
'FOOTER': (e: Element) => closestCrossShadow(e, kAncestorPreventingLandmark) ? null : 'contentinfo',
'FORM': (e: Element) => hasExplicitAccessibleName(e) ? 'form' : null,
'H1': () => 'heading',
'H2': () => 'heading',
'H3': () => 'heading',
'H4': () => 'heading',
'H5': () => 'heading',
'H6': () => 'heading',
'HEADER': (e: Element) => closestCrossShadow(e, kAncestorPreventingLandmark) ? null : 'banner',
'HR': () => 'separator',
'HTML': () => 'document',
'IMG': (e: Element) => (e.getAttribute('alt') === '') && !hasGlobalAriaAttribute(e) && Number.isNaN(Number(String(e.getAttribute('tabindex')))) ? 'presentation' : 'img',
'INPUT': (e: Element) => {
const type = (e as HTMLInputElement).type.toLowerCase();
if (type === 'search')
return e.hasAttribute('list') ? 'combobox' : 'searchbox';
if (['email', 'tel', 'text', 'url', ''].includes(type)) {
// https://html.spec.whatwg.org/multipage/input.html#concept-input-list
const list = getIdRefs(e, e.getAttribute('list'))[0];
return (list && list.tagName === 'DATALIST') ? 'combobox' : 'textbox';
}
if (type === 'hidden')
return '';
return {
'button': 'button',
'checkbox': 'checkbox',
'image': 'button',
'number': 'spinbutton',
'radio': 'radio',
'range': 'slider',
'reset': 'button',
'submit': 'button',
}[type] || 'textbox';
},
'INS': () => 'insertion',
'LI': () => 'listitem',
'MAIN': () => 'main',
'MARK': () => 'mark',
'MATH': () => 'math',
'MENU': () => 'list',
'METER': () => 'meter',
'NAV': () => 'navigation',
'OL': () => 'list',
'OPTGROUP': () => 'group',
'OPTION': () => 'option',
'OUTPUT': () => 'status',
'P': () => 'paragraph',
'PROGRESS': () => 'progressbar',
'SECTION': (e: Element) => hasExplicitAccessibleName(e) ? 'region' : null,
'SELECT': (e: Element) => e.hasAttribute('multiple') || (e as HTMLSelectElement).size > 1 ? 'listbox' : 'combobox',
'STRONG': () => 'strong',
'SUB': () => 'subscript',
'SUP': () => 'superscript',
'TABLE': () => 'table',
'TBODY': () => 'rowgroup',
'TD': (e: Element) => {
const table = closestCrossShadow(e, 'table');
const role = table ? getExplicitAriaRole(table) : '';
return (role === 'grid' || role === 'treegrid') ? 'gridcell' : 'cell';
},
'TEXTAREA': () => 'textbox',
'TFOOT': () => 'rowgroup',
'TH': (e: Element) => {
if (e.getAttribute('scope') === 'col')
return 'columnheader';
if (e.getAttribute('scope') === 'row')
return 'rowheader';
const table = closestCrossShadow(e, 'table');
const role = table ? getExplicitAriaRole(table) : '';
return (role === 'grid' || role === 'treegrid') ? 'gridcell' : 'cell';
},
'THEAD': () => 'rowgroup',
'TIME': () => 'time',
'TR': () => 'row',
'UL': () => 'list',
};
const kPresentationInheritanceParents: { [tagName: string]: string[] } = {
'DD': ['DL', 'DIV'],
'DIV': ['DL'],
'DT': ['DL', 'DIV'],
'LI': ['OL', 'UL'],
'TBODY': ['TABLE'],
'TD': ['TR'],
'TFOOT': ['TABLE'],
'TH': ['TR'],
'THEAD': ['TABLE'],
'TR': ['THEAD', 'TBODY', 'TFOOT', 'TABLE'],
};
function getImplicitAriaRole(element: Element): string | null {
const implicitRole = kImplicitRoleByTagName[element.tagName]?.(element) || '';
if (!implicitRole)
return null;
// Inherit presentation role when required.
// https://www.w3.org/TR/wai-aria-1.2/#conflict_resolution_presentation_none
let ancestor: Element | null = element;
while (ancestor) {
const parent = parentElementOrShadowHost(ancestor);
const parents = kPresentationInheritanceParents[ancestor.tagName];
if (!parents || !parent || !parents.includes(parent.tagName))
break;
const parentExplicitRole = getExplicitAriaRole(parent);
if ((parentExplicitRole === 'none' || parentExplicitRole === 'presentation') && !hasPresentationConflictResolution(parent))
return parentExplicitRole;
ancestor = parent;
}
return implicitRole;
}
// https://www.w3.org/TR/wai-aria-1.2/#role_definitions
const allRoles = [
'alert', 'alertdialog', 'application', 'article', 'banner', 'blockquote', 'button', 'caption', 'cell', 'checkbox', 'code', 'columnheader', 'combobox', 'command',
'complementary', 'composite', 'contentinfo', 'definition', 'deletion', 'dialog', 'directory', 'document', 'emphasis', 'feed', 'figure', 'form', 'generic', 'grid',
'gridcell', 'group', 'heading', 'img', 'input', 'insertion', 'landmark', 'link', 'list', 'listbox', 'listitem', 'log', 'main', 'marquee', 'math', 'meter', 'menu',
'menubar', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'navigation', 'none', 'note', 'option', 'paragraph', 'presentation', 'progressbar', 'radio', 'radiogroup',
'range', 'region', 'roletype', 'row', 'rowgroup', 'rowheader', 'scrollbar', 'search', 'searchbox', 'section', 'sectionhead', 'select', 'separator', 'slider',
'spinbutton', 'status', 'strong', 'structure', 'subscript', 'superscript', 'switch', 'tab', 'table', 'tablist', 'tabpanel', 'term', 'textbox', 'time', 'timer',
'toolbar', 'tooltip', 'tree', 'treegrid', 'treeitem', 'widget', 'window'
];
// https://www.w3.org/TR/wai-aria-1.2/#abstract_roles
const abstractRoles = ['command', 'composite', 'input', 'landmark', 'range', 'roletype', 'section', 'sectionhead', 'select', 'structure', 'widget', 'window'];
const validRoles = allRoles.filter(role => !abstractRoles.includes(role));
function getExplicitAriaRole(element: Element): string | null {
// https://www.w3.org/TR/wai-aria-1.2/#document-handling_author-errors_roles
const roles = (element.getAttribute('role') || '').split(' ').map(role => role.trim());
return roles.find(role => validRoles.includes(role)) || null;
}
function hasPresentationConflictResolution(element: Element) {
// https://www.w3.org/TR/wai-aria-1.2/#conflict_resolution_presentation_none
// TODO: this should include "|| focusable" check.
return !hasGlobalAriaAttribute(element);
}
export function getAriaRole(element: Element): string | null {
const explicitRole = getExplicitAriaRole(element);
if (!explicitRole)
return getImplicitAriaRole(element);
if ((explicitRole === 'none' || explicitRole === 'presentation') && hasPresentationConflictResolution(element))
return getImplicitAriaRole(element);
return explicitRole;
}
function getAriaBoolean(attr: string | null) {
return attr === null ? undefined : attr.toLowerCase() === 'true';
}
function getComputedStyle(element: Element, pseudo?: string): CSSStyleDeclaration | undefined {
return element.ownerDocument && element.ownerDocument.defaultView ? element.ownerDocument.defaultView.getComputedStyle(element, pseudo) : undefined;
}
// https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion, but including "none" and "presentation" roles
// https://www.w3.org/TR/wai-aria-1.2/#aria-hidden
export function isElementHiddenForAria(element: Element, cache: Map<Element, boolean>): boolean {
if (['STYLE', 'SCRIPT', 'NOSCRIPT', 'TEMPLATE'].includes(element.tagName))
return true;
const style: CSSStyleDeclaration | undefined = getComputedStyle(element);
if (!style || style.visibility === 'hidden')
return true;
return belongsToDisplayNoneOrAriaHidden(element, cache);
}
function belongsToDisplayNoneOrAriaHidden(element: Element, cache: Map<Element, boolean>): boolean {
if (!cache.has(element)) {
const style = getComputedStyle(element);
let hidden = !style || style.display === 'none' || getAriaBoolean(element.getAttribute('aria-hidden')) === true;
if (!hidden) {
const parent = parentElementOrShadowHost(element);
if (parent)
hidden = hidden || belongsToDisplayNoneOrAriaHidden(parent, cache);
}
cache.set(element, hidden);
}
return cache.get(element)!;
}
function getIdRefs(element: Element, ref: string | null): Element[] {
if (!ref)
return [];
const root = enclosingShadowRootOrDocument(element);
if (!root)
return [];
try {
const ids = ref.split(' ').filter(id => !!id);
const set = new Set<Element>();
for (const id of ids) {
// https://www.w3.org/TR/wai-aria-1.2/#mapping_additional_relations_error_processing
// "If more than one element has the same ID, the user agent SHOULD use the first element found with the given ID"
const firstElement = root.querySelector('#' + CSS.escape(id));
if (firstElement)
set.add(firstElement);
}
return [...set];
} catch (e) {
return [];
}
}
function normalizeAccessbileName(s: string): string {
// "Flat string" at https://w3c.github.io/accname/#terminology
return s.replace(/\r\n/g, '\n').replace(/\u00A0/g, ' ').replace(/\s\s+/g, ' ').trim();
}
function queryInAriaOwned(element: Element, selector: string): Element[] {
const result = [...element.querySelectorAll(selector)];
for (const owned of getIdRefs(element, element.getAttribute('aria-owns'))) {
if (owned.matches(selector))
result.push(owned);
result.push(...owned.querySelectorAll(selector));
}
return result;
}
function getPseudoContent(pseudoStyle: CSSStyleDeclaration | undefined) {
if (!pseudoStyle)
return '';
const content = pseudoStyle.getPropertyValue('content');
if ((content[0] === '\'' && content[content.length - 1] === '\'') ||
(content[0] === '"' && content[content.length - 1] === '"')) {
const unquoted = content.substring(1, content.length - 1);
// SPEC DIFFERENCE.
// Spec says "CSS textual content, without a space", but we account for display
// to pass "name_file-label-inline-block-styles-manual.html"
const display = pseudoStyle.getPropertyValue('display') || 'inline';
if (display !== 'inline')
return ' ' + unquoted + ' ';
return unquoted;
}
return '';
}
export function getElementAccessibleName(element: Element, includeHidden: boolean, hiddenCache: Map<Element, boolean>): string {
// https://w3c.github.io/accname/#computation-steps
// step 1.
// https://w3c.github.io/aria/#namefromprohibited
const elementProhibitsNaming = ['caption', 'code', 'definition', 'deletion', 'emphasis', 'generic', 'insertion', 'mark', 'paragraph', 'presentation', 'strong', 'subscript', 'suggestion', 'superscript', 'term', 'time'].includes(getAriaRole(element) || '');
if (elementProhibitsNaming)
return '';
// step 2.
const accessibleName = normalizeAccessbileName(getElementAccessibleNameInternal(element, {
includeHidden,
hiddenCache,
visitedElements: new Set(),
embeddedInLabelledBy: 'none',
embeddedInLabel: 'none',
embeddedInTextAlternativeElement: false,
embeddedInTargetElement: 'self',
}));
return accessibleName;
}
type AccessibleNameOptions = {
includeHidden: boolean,
hiddenCache: Map<Element, boolean>,
visitedElements: Set<Element>,
embeddedInLabelledBy: 'none' | 'self' | 'descendant',
embeddedInLabel: 'none' | 'self' | 'descendant',
embeddedInTextAlternativeElement: boolean,
embeddedInTargetElement: 'none' | 'self' | 'descendant',
};
function getElementAccessibleNameInternal(element: Element, options: AccessibleNameOptions): string {
if (options.visitedElements.has(element))
return '';
const childOptions: AccessibleNameOptions = {
...options,
embeddedInLabel: options.embeddedInLabel === 'self' ? 'descendant' : options.embeddedInLabel,
embeddedInLabelledBy: options.embeddedInLabelledBy === 'self' ? 'descendant' : options.embeddedInLabelledBy,
embeddedInTargetElement: options.embeddedInTargetElement === 'self' ? 'descendant' : options.embeddedInTargetElement,
};
// step 2a.
if (!options.includeHidden && options.embeddedInLabelledBy !== 'self' && isElementHiddenForAria(element, options.hiddenCache)) {
options.visitedElements.add(element);
return '';
}
// step 2b.
if (options.embeddedInLabelledBy === 'none') {
const refs = getIdRefs(element, element.getAttribute('aria-labelledby'));
const accessibleName = refs.map(ref => getElementAccessibleNameInternal(ref, {
...options,
embeddedInLabelledBy: 'self',
embeddedInTargetElement: 'none',
embeddedInLabel: 'none',
embeddedInTextAlternativeElement: false,
})).join(' ');
if (accessibleName)
return accessibleName;
}
const role = getAriaRole(element) || '';
// step 2c.
if (options.embeddedInLabel !== 'none' || options.embeddedInLabelledBy !== 'none') {
const isOwnLabel = [...(element as (HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement)).labels || []].includes(element as any);
const isOwnLabelledBy = getIdRefs(element, element.getAttribute('aria-labelledby')).includes(element);
if (!isOwnLabel && !isOwnLabelledBy) {
if (role === 'textbox') {
options.visitedElements.add(element);
if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA')
return (element as HTMLInputElement | HTMLTextAreaElement).value;
return element.textContent || '';
}
if (['combobox', 'listbox'].includes(role)) {
options.visitedElements.add(element);
let selectedOptions: Element[];
if (element.tagName === 'SELECT') {
selectedOptions = [...(element as HTMLSelectElement).selectedOptions];
if (!selectedOptions.length && (element as HTMLSelectElement).options.length)
selectedOptions.push((element as HTMLSelectElement).options[0]);
} else {
const listbox = role === 'combobox' ? queryInAriaOwned(element, '*').find(e => getAriaRole(e) === 'listbox') : element;
selectedOptions = listbox ? queryInAriaOwned(listbox, '[aria-selected="true"]').filter(e => getAriaRole(e) === 'option') : [];
}
return selectedOptions.map(option => getElementAccessibleNameInternal(option, childOptions)).join(' ');
}
if (['progressbar', 'scrollbar', 'slider', 'spinbutton', 'meter'].includes(role)) {
options.visitedElements.add(element);
if (element.hasAttribute('aria-valuetext'))
return element.getAttribute('aria-valuetext') || '';
if (element.hasAttribute('aria-valuenow'))
return element.getAttribute('aria-valuenow') || '';
return element.getAttribute('value') || '';
}
if (['menu'].includes(role)) {
// https://github.com/w3c/accname/issues/67#issuecomment-553196887
options.visitedElements.add(element);
return '';
}
}
}
// step 2d.
const ariaLabel = element.getAttribute('aria-label') || '';
if (ariaLabel.trim()) {
options.visitedElements.add(element);
return ariaLabel;
}
// step 2e.
if (!['presentation', 'none'].includes(role)) {
// https://w3c.github.io/html-aam/#input-type-button-input-type-submit-and-input-type-reset
if (element.tagName === 'INPUT' && ['button', 'submit', 'reset'].includes((element as HTMLInputElement).type)) {
options.visitedElements.add(element);
const value = (element as HTMLInputElement).value || '';
if (value.trim())
return value;
if ((element as HTMLInputElement).type === 'submit')
return 'Submit';
if ((element as HTMLInputElement).type === 'reset')
return 'Reset';
const title = element.getAttribute('title') || '';
return title;
}
// https://w3c.github.io/html-aam/#input-type-image
if (element.tagName === 'INPUT' && (element as HTMLInputElement).type === 'image') {
options.visitedElements.add(element);
const alt = element.getAttribute('alt') || '';
if (alt.trim())
return alt;
// SPEC DIFFERENCE.
// Spec does not mention "label" elements, but we account for labels
// to pass "name_test_case_616-manual.html"
const labels = (element as HTMLInputElement).labels || [];
if (labels.length) {
return [...labels].map(label => getElementAccessibleNameInternal(label, {
...options,
embeddedInLabel: 'self',
embeddedInTextAlternativeElement: false,
embeddedInLabelledBy: 'none',
embeddedInTargetElement: 'none',
})).filter(accessibleName => !!accessibleName).join(' ');
}
const title = element.getAttribute('title') || '';
if (title.trim())
return title;
// SPEC DIFFERENCE.
// Spec says return localized "Submit Query", but browsers and axe-core insist on "Sumbit".
return 'Submit';
}
// https://w3c.github.io/html-aam/#input-type-text-input-type-password-input-type-search-input-type-tel-input-type-url-and-textarea-element
// https://w3c.github.io/html-aam/#other-form-elements
// For "other form elements", we count select and any other input.
if (element.tagName === 'TEXTAREA' || element.tagName === 'SELECT' || element.tagName === 'INPUT') {
options.visitedElements.add(element);
const labels = (element as (HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement)).labels || [];
if (labels.length) {
return [...labels].map(label => getElementAccessibleNameInternal(label, {
...options,
embeddedInLabel: 'self',
embeddedInTextAlternativeElement: false,
embeddedInLabelledBy: 'none',
embeddedInTargetElement: 'none',
})).filter(accessibleName => !!accessibleName).join(' ');
}
const usePlaceholder = (element.tagName === 'INPUT' && ['text', 'password', 'search', 'tel', 'email', 'url'].includes((element as HTMLInputElement).type)) || element.tagName === 'TEXTAREA';
const placeholder = element.getAttribute('placeholder') || '';
const title = element.getAttribute('title') || '';
if (!usePlaceholder || title)
return title;
return placeholder;
}
// https://w3c.github.io/html-aam/#fieldset-and-legend-elements
if (element.tagName === 'FIELDSET') {
options.visitedElements.add(element);
for (let child = element.firstElementChild; child; child = child.nextElementSibling) {
if (child.tagName === 'LEGEND') {
return getElementAccessibleNameInternal(child, {
...childOptions,
embeddedInTextAlternativeElement: true,
});
}
}
const title = element.getAttribute('title') || '';
return title;
}
// https://w3c.github.io/html-aam/#figure-and-figcaption-elements
if (element.tagName === 'FIGURE') {
options.visitedElements.add(element);
for (let child = element.firstElementChild; child; child = child.nextElementSibling) {
if (child.tagName === 'FIGCAPTION') {
return getElementAccessibleNameInternal(child, {
...childOptions,
embeddedInTextAlternativeElement: true,
});
}
}
const title = element.getAttribute('title') || '';
return title;
}
// https://w3c.github.io/html-aam/#img-element
if (element.tagName === 'IMG') {
options.visitedElements.add(element);
const alt = element.getAttribute('alt') || '';
if (alt.trim())
return alt;
const title = element.getAttribute('title') || '';
return title;
}
// https://w3c.github.io/html-aam/#table-element
if (element.tagName === 'TABLE') {
options.visitedElements.add(element);
for (let child = element.firstElementChild; child; child = child.nextElementSibling) {
if (child.tagName === 'CAPTION') {
return getElementAccessibleNameInternal(child, {
...childOptions,
embeddedInTextAlternativeElement: true,
});
}
}
// SPEC DIFFERENCE.
// Spec does not say a word about <table summary="...">, but all browsers actually support it.
const summary = element.getAttribute('summary') || '';
if (summary)
return summary;
// SPEC DIFFERENCE.
// Spec says "if the table element has a title attribute, then use that attribute".
// We ignore title to pass "name_from_content-manual.html".
}
// https://w3c.github.io/html-aam/#area-element
if (element.tagName === 'AREA') {
options.visitedElements.add(element);
const alt = element.getAttribute('alt') || '';
if (alt.trim())
return alt;
const title = element.getAttribute('title') || '';
return title;
}
// https://www.w3.org/TR/svg-aam-1.0/
if (element.tagName === 'SVG' && (element as SVGElement).ownerSVGElement) {
options.visitedElements.add(element);
for (let child = element.firstElementChild; child; child = child.nextElementSibling) {
if (child.tagName === 'TITLE' && (element as SVGElement).ownerSVGElement) {
return getElementAccessibleNameInternal(child, {
...childOptions,
embeddedInTextAlternativeElement: true,
});
}
}
}
}
// step 2f + step 2h.
// https://w3c.github.io/aria/#namefromcontent
const allowsNameFromContent = ['button', 'cell', 'checkbox', 'columnheader', 'gridcell', 'heading', 'link', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'radio', 'row', 'rowheader', 'switch', 'tab', 'tooltip', 'treeitem'].includes(role);
if (allowsNameFromContent || options.embeddedInLabelledBy !== 'none' || options.embeddedInLabel !== 'none' || options.embeddedInTextAlternativeElement || options.embeddedInTargetElement === 'descendant') {
options.visitedElements.add(element);
const tokens: string[] = [];
const visit = (node: Node) => {
if (node.nodeType === 1 /* Node.ELEMENT_NODE */) {
const display = getComputedStyle(node as Element)?.getPropertyValue('display') || 'inline';
let token = getElementAccessibleNameInternal(node as Element, childOptions);
// SPEC DIFFERENCE.
// Spec says "append the result to the accumulated text", assuming "with space".
// However, multiple tests insist that inline elements do not add a space.
// Additionally, <br> insists on a space anyway, see "name_file-label-inline-block-elements-manual.html"
if (display !== 'inline' || node.nodeName === 'BR')
token = ' ' + token + ' ';
tokens.push(token);
} else if (node.nodeType === 3 /* Node.TEXT_NODE */) {
// step 2g.
tokens.push(node.textContent || '');
}
};
tokens.push(getPseudoContent(getComputedStyle(element, '::before')));
for (let child = element.firstChild; child; child = child.nextSibling)
visit(child);
if (element.shadowRoot) {
for (let child = element.shadowRoot.firstChild; child; child = child.nextSibling)
visit(child);
}
for (const owned of getIdRefs(element, element.getAttribute('aria-owns')))
visit(owned);
tokens.push(getPseudoContent(getComputedStyle(element, '::after')));
const accessibleName = tokens.join('');
if (accessibleName.trim())
return accessibleName;
}
// step 2i.
if (!['presentation', 'none'].includes(role) || element.tagName === 'IFRAME') {
options.visitedElements.add(element);
const title = element.getAttribute('title') || '';
if (title.trim())
return title;
}
options.visitedElements.add(element);
return '';
}
export const kAriaSelectedRoles = ['gridcell', 'option', 'row', 'tab', 'rowheader', 'columnheader', 'treeitem'];
export function getAriaSelected(element: Element): boolean {
// https://www.w3.org/TR/wai-aria-1.2/#aria-selected
// https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
if (element.tagName === 'OPTION')
return (element as HTMLOptionElement).selected;
if (kAriaSelectedRoles.includes(getAriaRole(element) || ''))
return getAriaBoolean(element.getAttribute('aria-selected')) === true;
return false;
}
export const kAriaCheckedRoles = ['checkbox', 'menuitemcheckbox', 'option', 'radio', 'switch', 'menuitemradio', 'treeitem'];
export function getAriaChecked(element: Element): boolean | 'mixed' {
const result = getAriaCheckedStrict(element);
return result === 'error' ? false : result;
}
export function getAriaCheckedStrict(element: Element): boolean | 'mixed' | 'error' {
// https://www.w3.org/TR/wai-aria-1.2/#aria-checked
// https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
if (element.tagName === 'INPUT' && (element as HTMLInputElement).indeterminate)
return 'mixed';
if (element.tagName === 'INPUT' && ['checkbox', 'radio'].includes((element as HTMLInputElement).type))
return (element as HTMLInputElement).checked;
if (kAriaCheckedRoles.includes(getAriaRole(element) || '')) {
const checked = element.getAttribute('aria-checked');
if (checked === 'true')
return true;
if (checked === 'mixed')
return 'mixed';
return false;
}
return 'error';
}
export const kAriaPressedRoles = ['button'];
export function getAriaPressed(element: Element): boolean | 'mixed' {
// https://www.w3.org/TR/wai-aria-1.2/#aria-pressed
if (kAriaPressedRoles.includes(getAriaRole(element) || '')) {
const pressed = element.getAttribute('aria-pressed');
if (pressed === 'true')
return true;
if (pressed === 'mixed')
return 'mixed';
}
return false;
}
export const kAriaExpandedRoles = ['application', 'button', 'checkbox', 'combobox', 'gridcell', 'link', 'listbox', 'menuitem', 'row', 'rowheader', 'tab', 'treeitem', 'columnheader', 'menuitemcheckbox', 'menuitemradio', 'rowheader', 'switch'];
export function getAriaExpanded(element: Element): boolean {
// https://www.w3.org/TR/wai-aria-1.2/#aria-expanded
// https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
if (element.tagName === 'DETAILS')
return (element as HTMLDetailsElement).open;
if (kAriaExpandedRoles.includes(getAriaRole(element) || ''))
return getAriaBoolean(element.getAttribute('aria-expanded')) === true;
return false;
}
export const kAriaLevelRoles = ['heading', 'listitem', 'row', 'treeitem'];
export function getAriaLevel(element: Element): number {
// https://www.w3.org/TR/wai-aria-1.2/#aria-level
// https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
const native = { 'H1': 1, 'H2': 2, 'H3': 3, 'H4': 4, 'H5': 5, 'H6': 6 }[element.tagName];
if (native)
return native;
if (kAriaLevelRoles.includes(getAriaRole(element) || '')) {
const attr = element.getAttribute('aria-level');
const value = attr === null ? Number.NaN : Number(attr);
if (Number.isInteger(value) && value >= 1)
return value;
}
return 0;
}
export const kAriaDisabledRoles = ['application', 'button', 'composite', 'gridcell', 'group', 'input', 'link', 'menuitem', 'scrollbar', 'separator', 'tab', 'checkbox', 'columnheader', 'combobox', 'grid', 'listbox', 'menu', 'menubar', 'menuitemcheckbox', 'menuitemradio', 'option', 'radio', 'radiogroup', 'row', 'rowheader', 'searchbox', 'select', 'slider', 'spinbutton', 'switch', 'tablist', 'textbox', 'toolbar', 'tree', 'treegrid', 'treeitem'];
export function getAriaDisabled(element: Element): boolean {
// https://www.w3.org/TR/wai-aria-1.2/#aria-disabled
// https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
// Note that aria-disabled applies to all descendants, so we look up the hierarchy.
const isNativeFormControl = ['BUTTON', 'INPUT', 'SELECT', 'TEXTAREA', 'OPTION', 'OPTGROUP'].includes(element.tagName);
if (isNativeFormControl && (element.hasAttribute('disabled') || belongsToDisabledFieldSet(element)))
return true;
return hasExplicitAriaDisabled(element);
}
function belongsToDisabledFieldSet(element: Element | null): boolean {
if (!element)
return false;
if (element.tagName === 'FIELDSET' && element.hasAttribute('disabled'))
return true;
// fieldset does not work across shadow boundaries.
return belongsToDisabledFieldSet(element.parentElement);
}
function hasExplicitAriaDisabled(element: Element | undefined): boolean {
if (!element)
return false;
if (kAriaDisabledRoles.includes(getAriaRole(element) || '')) {
const attribute = (element.getAttribute('aria-disabled') || '').toLowerCase();
if (attribute === 'true')
return true;
if (attribute === 'false')
return false;
}
// aria-disabled works across shadow boundaries.
return hasExplicitAriaDisabled(parentElementOrShadowHost(element));
}
| packages/playwright-core/src/server/injected/roleUtils.ts | 1 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.0009251883020624518,
0.00018256083421874791,
0.00016255247464869171,
0.00017149107588920742,
0.00008724277722649276
] |
{
"id": 3,
"code_window": [
"\n",
"test('should support expanded', async ({ page }) => {\n",
" await page.setContent(`\n",
" <button>Hi</button>\n",
" <button aria-expanded=\"true\">Hello</button>\n",
" <button aria-expanded=\"false\">Bye</button>\n",
" `);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" <div role=\"treeitem\">Hi</div>\n",
" <div role=\"treeitem\" aria-expanded=\"true\">Hello</div>\n",
" <div role=\"treeitem\" aria-expanded=\"false\">Bye</div>\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 171
} | // Any comment. You must start the file with a single-line comment!
pref("general.config.filename", "playwright.cfg");
pref("general.config.obscure_value", 0);
| browser_patches/firefox/preferences/00-playwright-prefs.js | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00017354663577862084,
0.00017354663577862084,
0.00017354663577862084,
0.00017354663577862084,
0
] |
{
"id": 3,
"code_window": [
"\n",
"test('should support expanded', async ({ page }) => {\n",
" await page.setContent(`\n",
" <button>Hi</button>\n",
" <button aria-expanded=\"true\">Hello</button>\n",
" <button aria-expanded=\"false\">Bye</button>\n",
" `);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" <div role=\"treeitem\">Hi</div>\n",
" <div role=\"treeitem\" aria-expanded=\"true\">Hello</div>\n",
" <div role=\"treeitem\" aria-expanded=\"false\">Bye</div>\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 171
} | /**
* Copyright 2018 Google Inc. All rights reserved.
* Modifications copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { test as it, expect } from './pageTest';
it('should work @smoke', async ({ page, server }) => {
await page.setContent('<html><body><div class="tweet"><div class="like">100</div><div class="retweets">10</div></div></body></html>');
const tweet = page.locator('.tweet .like');
const content = await tweet.evaluate(node => (node as HTMLElement).innerText);
expect(content).toBe('100');
});
it('should retrieve content from subtree', async ({ page, server }) => {
const htmlContent = '<div class="a">not-a-child-div</div><div id="myId"><div class="a">a-child-div</div></div>';
await page.setContent(htmlContent);
const elementHandle = page.locator('#myId .a');
const content = await elementHandle.evaluate(node => (node as HTMLElement).innerText);
expect(content).toBe('a-child-div');
});
it('should work for all', async ({ page, server }) => {
await page.setContent('<html><body><div class="tweet"><div class="like">100</div><div class="like">10</div></div></body></html>');
const tweet = page.locator('.tweet .like');
const content = await tweet.evaluateAll(nodes => nodes.map(n => (n as HTMLElement).innerText));
expect(content).toEqual(['100', '10']);
});
it('should retrieve content from subtree for all', async ({ page, server }) => {
const htmlContent = '<div class="a">not-a-child-div</div><div id="myId"><div class="a">a1-child-div</div><div class="a">a2-child-div</div></div>';
await page.setContent(htmlContent);
const element = page.locator('#myId .a');
const content = await element.evaluateAll(nodes => nodes.map(n => (n as HTMLElement).innerText));
expect(content).toEqual(['a1-child-div', 'a2-child-div']);
});
it('should not throw in case of missing selector for all', async ({ page, server }) => {
const htmlContent = '<div class="a">not-a-child-div</div><div id="myId"></div>';
await page.setContent(htmlContent);
const element = page.locator('#myId .a');
const nodesLength = await element.evaluateAll(nodes => nodes.length);
expect(nodesLength).toBe(0);
});
| tests/page/locator-evaluate.spec.ts | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.0004964186227880418,
0.000292958808131516,
0.00016354717081412673,
0.0002549507189542055,
0.00012208726548124105
] |
{
"id": 3,
"code_window": [
"\n",
"test('should support expanded', async ({ page }) => {\n",
" await page.setContent(`\n",
" <button>Hi</button>\n",
" <button aria-expanded=\"true\">Hello</button>\n",
" <button aria-expanded=\"false\">Bye</button>\n",
" `);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" <div role=\"treeitem\">Hi</div>\n",
" <div role=\"treeitem\" aria-expanded=\"true\">Hello</div>\n",
" <div role=\"treeitem\" aria-expanded=\"false\">Bye</div>\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 171
} | # class: FormData
* since: v1.18
* langs: java, csharp
The [FormData] is used create form data that is sent via [APIRequestContext].
```java
import com.microsoft.playwright.options.FormData;
...
FormData form = FormData.create()
.set("firstName", "John")
.set("lastName", "Doe")
.set("age", 30);
page.request().post("http://localhost/submit", RequestOptions.create().setForm(form));
```
## method: FormData.create
* since: v1.18
* langs: java
- returns: <[FormData]>
Creates new instance of [FormData].
## method: FormData.set
* since: v1.18
- returns: <[FormData]>
Sets a field on the form. File values can be passed either as `Path` or as `FilePayload`.
### param: FormData.set.name
* since: v1.18
- `name` <[string]>
Field name.
### param: FormData.set.value
* since: v1.18
- `value` <[string]|[boolean]|[int]|[Path]|[Object]>
- `name` <[string]> File name
- `mimeType` <[string]> File type
- `buffer` <[Buffer]> File content
Field value.
### param: FormData.set.value
* since: v1.18
* langs: csharp
- `value` <[string]|[boolean]|[int]|[Object]>
- `name` <[string]> File name
- `mimeType` <[string]> File type
- `buffer` <[Buffer]> File content
Field value.
| docs/src/api/class-formdata.md | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.000171999228768982,
0.00016879189934115857,
0.00016558328934479505,
0.00016889955441001803,
0.0000025113261017395416
] |
{
"id": 4,
"code_window": [
" `);\n",
" expect(await page.locator(`role=button[expanded]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<button aria-expanded=\"true\">Hello</button>`,\n",
" ]);\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\n",
" expect(await page.locator('role=treeitem').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\">Hi</div>`,\n",
" `<div role=\"treeitem\" aria-expanded=\"true\">Hello</div>`,\n",
" `<div role=\"treeitem\" aria-expanded=\"false\">Bye</div>`,\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 175
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { closestCrossShadow, enclosingShadowRootOrDocument, parentElementOrShadowHost } from './domUtils';
function hasExplicitAccessibleName(e: Element) {
return e.hasAttribute('aria-label') || e.hasAttribute('aria-labelledby');
}
// https://www.w3.org/TR/wai-aria-practices/examples/landmarks/HTML5.html
const kAncestorPreventingLandmark = 'article:not([role]), aside:not([role]), main:not([role]), nav:not([role]), section:not([role]), [role=article], [role=complementary], [role=main], [role=navigation], [role=region]';
// https://www.w3.org/TR/wai-aria-1.2/#global_states
const kGlobalAriaAttributes = [
'aria-atomic',
'aria-busy',
'aria-controls',
'aria-current',
'aria-describedby',
'aria-details',
'aria-disabled',
'aria-dropeffect',
'aria-errormessage',
'aria-flowto',
'aria-grabbed',
'aria-haspopup',
'aria-hidden',
'aria-invalid',
'aria-keyshortcuts',
'aria-label',
'aria-labelledby',
'aria-live',
'aria-owns',
'aria-relevant',
'aria-roledescription',
];
function hasGlobalAriaAttribute(e: Element) {
return kGlobalAriaAttributes.some(a => e.hasAttribute(a));
}
// https://w3c.github.io/html-aam/#html-element-role-mappings
const kImplicitRoleByTagName: { [tagName: string]: (e: Element) => string | null } = {
'A': (e: Element) => {
return e.hasAttribute('href') ? 'link' : null;
},
'AREA': (e: Element) => {
return e.hasAttribute('href') ? 'link' : null;
},
'ARTICLE': () => 'article',
'ASIDE': () => 'complementary',
'BLOCKQUOTE': () => 'blockquote',
'BUTTON': () => 'button',
'CAPTION': () => 'caption',
'CODE': () => 'code',
'DATALIST': () => 'listbox',
'DD': () => 'definition',
'DEL': () => 'deletion',
'DETAILS': () => 'group',
'DFN': () => 'term',
'DIALOG': () => 'dialog',
'DT': () => 'term',
'EM': () => 'emphasis',
'FIELDSET': () => 'group',
'FIGURE': () => 'figure',
'FOOTER': (e: Element) => closestCrossShadow(e, kAncestorPreventingLandmark) ? null : 'contentinfo',
'FORM': (e: Element) => hasExplicitAccessibleName(e) ? 'form' : null,
'H1': () => 'heading',
'H2': () => 'heading',
'H3': () => 'heading',
'H4': () => 'heading',
'H5': () => 'heading',
'H6': () => 'heading',
'HEADER': (e: Element) => closestCrossShadow(e, kAncestorPreventingLandmark) ? null : 'banner',
'HR': () => 'separator',
'HTML': () => 'document',
'IMG': (e: Element) => (e.getAttribute('alt') === '') && !hasGlobalAriaAttribute(e) && Number.isNaN(Number(String(e.getAttribute('tabindex')))) ? 'presentation' : 'img',
'INPUT': (e: Element) => {
const type = (e as HTMLInputElement).type.toLowerCase();
if (type === 'search')
return e.hasAttribute('list') ? 'combobox' : 'searchbox';
if (['email', 'tel', 'text', 'url', ''].includes(type)) {
// https://html.spec.whatwg.org/multipage/input.html#concept-input-list
const list = getIdRefs(e, e.getAttribute('list'))[0];
return (list && list.tagName === 'DATALIST') ? 'combobox' : 'textbox';
}
if (type === 'hidden')
return '';
return {
'button': 'button',
'checkbox': 'checkbox',
'image': 'button',
'number': 'spinbutton',
'radio': 'radio',
'range': 'slider',
'reset': 'button',
'submit': 'button',
}[type] || 'textbox';
},
'INS': () => 'insertion',
'LI': () => 'listitem',
'MAIN': () => 'main',
'MARK': () => 'mark',
'MATH': () => 'math',
'MENU': () => 'list',
'METER': () => 'meter',
'NAV': () => 'navigation',
'OL': () => 'list',
'OPTGROUP': () => 'group',
'OPTION': () => 'option',
'OUTPUT': () => 'status',
'P': () => 'paragraph',
'PROGRESS': () => 'progressbar',
'SECTION': (e: Element) => hasExplicitAccessibleName(e) ? 'region' : null,
'SELECT': (e: Element) => e.hasAttribute('multiple') || (e as HTMLSelectElement).size > 1 ? 'listbox' : 'combobox',
'STRONG': () => 'strong',
'SUB': () => 'subscript',
'SUP': () => 'superscript',
'TABLE': () => 'table',
'TBODY': () => 'rowgroup',
'TD': (e: Element) => {
const table = closestCrossShadow(e, 'table');
const role = table ? getExplicitAriaRole(table) : '';
return (role === 'grid' || role === 'treegrid') ? 'gridcell' : 'cell';
},
'TEXTAREA': () => 'textbox',
'TFOOT': () => 'rowgroup',
'TH': (e: Element) => {
if (e.getAttribute('scope') === 'col')
return 'columnheader';
if (e.getAttribute('scope') === 'row')
return 'rowheader';
const table = closestCrossShadow(e, 'table');
const role = table ? getExplicitAriaRole(table) : '';
return (role === 'grid' || role === 'treegrid') ? 'gridcell' : 'cell';
},
'THEAD': () => 'rowgroup',
'TIME': () => 'time',
'TR': () => 'row',
'UL': () => 'list',
};
const kPresentationInheritanceParents: { [tagName: string]: string[] } = {
'DD': ['DL', 'DIV'],
'DIV': ['DL'],
'DT': ['DL', 'DIV'],
'LI': ['OL', 'UL'],
'TBODY': ['TABLE'],
'TD': ['TR'],
'TFOOT': ['TABLE'],
'TH': ['TR'],
'THEAD': ['TABLE'],
'TR': ['THEAD', 'TBODY', 'TFOOT', 'TABLE'],
};
function getImplicitAriaRole(element: Element): string | null {
const implicitRole = kImplicitRoleByTagName[element.tagName]?.(element) || '';
if (!implicitRole)
return null;
// Inherit presentation role when required.
// https://www.w3.org/TR/wai-aria-1.2/#conflict_resolution_presentation_none
let ancestor: Element | null = element;
while (ancestor) {
const parent = parentElementOrShadowHost(ancestor);
const parents = kPresentationInheritanceParents[ancestor.tagName];
if (!parents || !parent || !parents.includes(parent.tagName))
break;
const parentExplicitRole = getExplicitAriaRole(parent);
if ((parentExplicitRole === 'none' || parentExplicitRole === 'presentation') && !hasPresentationConflictResolution(parent))
return parentExplicitRole;
ancestor = parent;
}
return implicitRole;
}
// https://www.w3.org/TR/wai-aria-1.2/#role_definitions
const allRoles = [
'alert', 'alertdialog', 'application', 'article', 'banner', 'blockquote', 'button', 'caption', 'cell', 'checkbox', 'code', 'columnheader', 'combobox', 'command',
'complementary', 'composite', 'contentinfo', 'definition', 'deletion', 'dialog', 'directory', 'document', 'emphasis', 'feed', 'figure', 'form', 'generic', 'grid',
'gridcell', 'group', 'heading', 'img', 'input', 'insertion', 'landmark', 'link', 'list', 'listbox', 'listitem', 'log', 'main', 'marquee', 'math', 'meter', 'menu',
'menubar', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'navigation', 'none', 'note', 'option', 'paragraph', 'presentation', 'progressbar', 'radio', 'radiogroup',
'range', 'region', 'roletype', 'row', 'rowgroup', 'rowheader', 'scrollbar', 'search', 'searchbox', 'section', 'sectionhead', 'select', 'separator', 'slider',
'spinbutton', 'status', 'strong', 'structure', 'subscript', 'superscript', 'switch', 'tab', 'table', 'tablist', 'tabpanel', 'term', 'textbox', 'time', 'timer',
'toolbar', 'tooltip', 'tree', 'treegrid', 'treeitem', 'widget', 'window'
];
// https://www.w3.org/TR/wai-aria-1.2/#abstract_roles
const abstractRoles = ['command', 'composite', 'input', 'landmark', 'range', 'roletype', 'section', 'sectionhead', 'select', 'structure', 'widget', 'window'];
const validRoles = allRoles.filter(role => !abstractRoles.includes(role));
function getExplicitAriaRole(element: Element): string | null {
// https://www.w3.org/TR/wai-aria-1.2/#document-handling_author-errors_roles
const roles = (element.getAttribute('role') || '').split(' ').map(role => role.trim());
return roles.find(role => validRoles.includes(role)) || null;
}
function hasPresentationConflictResolution(element: Element) {
// https://www.w3.org/TR/wai-aria-1.2/#conflict_resolution_presentation_none
// TODO: this should include "|| focusable" check.
return !hasGlobalAriaAttribute(element);
}
export function getAriaRole(element: Element): string | null {
const explicitRole = getExplicitAriaRole(element);
if (!explicitRole)
return getImplicitAriaRole(element);
if ((explicitRole === 'none' || explicitRole === 'presentation') && hasPresentationConflictResolution(element))
return getImplicitAriaRole(element);
return explicitRole;
}
function getAriaBoolean(attr: string | null) {
return attr === null ? undefined : attr.toLowerCase() === 'true';
}
function getComputedStyle(element: Element, pseudo?: string): CSSStyleDeclaration | undefined {
return element.ownerDocument && element.ownerDocument.defaultView ? element.ownerDocument.defaultView.getComputedStyle(element, pseudo) : undefined;
}
// https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion, but including "none" and "presentation" roles
// https://www.w3.org/TR/wai-aria-1.2/#aria-hidden
export function isElementHiddenForAria(element: Element, cache: Map<Element, boolean>): boolean {
if (['STYLE', 'SCRIPT', 'NOSCRIPT', 'TEMPLATE'].includes(element.tagName))
return true;
const style: CSSStyleDeclaration | undefined = getComputedStyle(element);
if (!style || style.visibility === 'hidden')
return true;
return belongsToDisplayNoneOrAriaHidden(element, cache);
}
function belongsToDisplayNoneOrAriaHidden(element: Element, cache: Map<Element, boolean>): boolean {
if (!cache.has(element)) {
const style = getComputedStyle(element);
let hidden = !style || style.display === 'none' || getAriaBoolean(element.getAttribute('aria-hidden')) === true;
if (!hidden) {
const parent = parentElementOrShadowHost(element);
if (parent)
hidden = hidden || belongsToDisplayNoneOrAriaHidden(parent, cache);
}
cache.set(element, hidden);
}
return cache.get(element)!;
}
function getIdRefs(element: Element, ref: string | null): Element[] {
if (!ref)
return [];
const root = enclosingShadowRootOrDocument(element);
if (!root)
return [];
try {
const ids = ref.split(' ').filter(id => !!id);
const set = new Set<Element>();
for (const id of ids) {
// https://www.w3.org/TR/wai-aria-1.2/#mapping_additional_relations_error_processing
// "If more than one element has the same ID, the user agent SHOULD use the first element found with the given ID"
const firstElement = root.querySelector('#' + CSS.escape(id));
if (firstElement)
set.add(firstElement);
}
return [...set];
} catch (e) {
return [];
}
}
function normalizeAccessbileName(s: string): string {
// "Flat string" at https://w3c.github.io/accname/#terminology
return s.replace(/\r\n/g, '\n').replace(/\u00A0/g, ' ').replace(/\s\s+/g, ' ').trim();
}
function queryInAriaOwned(element: Element, selector: string): Element[] {
const result = [...element.querySelectorAll(selector)];
for (const owned of getIdRefs(element, element.getAttribute('aria-owns'))) {
if (owned.matches(selector))
result.push(owned);
result.push(...owned.querySelectorAll(selector));
}
return result;
}
function getPseudoContent(pseudoStyle: CSSStyleDeclaration | undefined) {
if (!pseudoStyle)
return '';
const content = pseudoStyle.getPropertyValue('content');
if ((content[0] === '\'' && content[content.length - 1] === '\'') ||
(content[0] === '"' && content[content.length - 1] === '"')) {
const unquoted = content.substring(1, content.length - 1);
// SPEC DIFFERENCE.
// Spec says "CSS textual content, without a space", but we account for display
// to pass "name_file-label-inline-block-styles-manual.html"
const display = pseudoStyle.getPropertyValue('display') || 'inline';
if (display !== 'inline')
return ' ' + unquoted + ' ';
return unquoted;
}
return '';
}
export function getElementAccessibleName(element: Element, includeHidden: boolean, hiddenCache: Map<Element, boolean>): string {
// https://w3c.github.io/accname/#computation-steps
// step 1.
// https://w3c.github.io/aria/#namefromprohibited
const elementProhibitsNaming = ['caption', 'code', 'definition', 'deletion', 'emphasis', 'generic', 'insertion', 'mark', 'paragraph', 'presentation', 'strong', 'subscript', 'suggestion', 'superscript', 'term', 'time'].includes(getAriaRole(element) || '');
if (elementProhibitsNaming)
return '';
// step 2.
const accessibleName = normalizeAccessbileName(getElementAccessibleNameInternal(element, {
includeHidden,
hiddenCache,
visitedElements: new Set(),
embeddedInLabelledBy: 'none',
embeddedInLabel: 'none',
embeddedInTextAlternativeElement: false,
embeddedInTargetElement: 'self',
}));
return accessibleName;
}
type AccessibleNameOptions = {
includeHidden: boolean,
hiddenCache: Map<Element, boolean>,
visitedElements: Set<Element>,
embeddedInLabelledBy: 'none' | 'self' | 'descendant',
embeddedInLabel: 'none' | 'self' | 'descendant',
embeddedInTextAlternativeElement: boolean,
embeddedInTargetElement: 'none' | 'self' | 'descendant',
};
function getElementAccessibleNameInternal(element: Element, options: AccessibleNameOptions): string {
if (options.visitedElements.has(element))
return '';
const childOptions: AccessibleNameOptions = {
...options,
embeddedInLabel: options.embeddedInLabel === 'self' ? 'descendant' : options.embeddedInLabel,
embeddedInLabelledBy: options.embeddedInLabelledBy === 'self' ? 'descendant' : options.embeddedInLabelledBy,
embeddedInTargetElement: options.embeddedInTargetElement === 'self' ? 'descendant' : options.embeddedInTargetElement,
};
// step 2a.
if (!options.includeHidden && options.embeddedInLabelledBy !== 'self' && isElementHiddenForAria(element, options.hiddenCache)) {
options.visitedElements.add(element);
return '';
}
// step 2b.
if (options.embeddedInLabelledBy === 'none') {
const refs = getIdRefs(element, element.getAttribute('aria-labelledby'));
const accessibleName = refs.map(ref => getElementAccessibleNameInternal(ref, {
...options,
embeddedInLabelledBy: 'self',
embeddedInTargetElement: 'none',
embeddedInLabel: 'none',
embeddedInTextAlternativeElement: false,
})).join(' ');
if (accessibleName)
return accessibleName;
}
const role = getAriaRole(element) || '';
// step 2c.
if (options.embeddedInLabel !== 'none' || options.embeddedInLabelledBy !== 'none') {
const isOwnLabel = [...(element as (HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement)).labels || []].includes(element as any);
const isOwnLabelledBy = getIdRefs(element, element.getAttribute('aria-labelledby')).includes(element);
if (!isOwnLabel && !isOwnLabelledBy) {
if (role === 'textbox') {
options.visitedElements.add(element);
if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA')
return (element as HTMLInputElement | HTMLTextAreaElement).value;
return element.textContent || '';
}
if (['combobox', 'listbox'].includes(role)) {
options.visitedElements.add(element);
let selectedOptions: Element[];
if (element.tagName === 'SELECT') {
selectedOptions = [...(element as HTMLSelectElement).selectedOptions];
if (!selectedOptions.length && (element as HTMLSelectElement).options.length)
selectedOptions.push((element as HTMLSelectElement).options[0]);
} else {
const listbox = role === 'combobox' ? queryInAriaOwned(element, '*').find(e => getAriaRole(e) === 'listbox') : element;
selectedOptions = listbox ? queryInAriaOwned(listbox, '[aria-selected="true"]').filter(e => getAriaRole(e) === 'option') : [];
}
return selectedOptions.map(option => getElementAccessibleNameInternal(option, childOptions)).join(' ');
}
if (['progressbar', 'scrollbar', 'slider', 'spinbutton', 'meter'].includes(role)) {
options.visitedElements.add(element);
if (element.hasAttribute('aria-valuetext'))
return element.getAttribute('aria-valuetext') || '';
if (element.hasAttribute('aria-valuenow'))
return element.getAttribute('aria-valuenow') || '';
return element.getAttribute('value') || '';
}
if (['menu'].includes(role)) {
// https://github.com/w3c/accname/issues/67#issuecomment-553196887
options.visitedElements.add(element);
return '';
}
}
}
// step 2d.
const ariaLabel = element.getAttribute('aria-label') || '';
if (ariaLabel.trim()) {
options.visitedElements.add(element);
return ariaLabel;
}
// step 2e.
if (!['presentation', 'none'].includes(role)) {
// https://w3c.github.io/html-aam/#input-type-button-input-type-submit-and-input-type-reset
if (element.tagName === 'INPUT' && ['button', 'submit', 'reset'].includes((element as HTMLInputElement).type)) {
options.visitedElements.add(element);
const value = (element as HTMLInputElement).value || '';
if (value.trim())
return value;
if ((element as HTMLInputElement).type === 'submit')
return 'Submit';
if ((element as HTMLInputElement).type === 'reset')
return 'Reset';
const title = element.getAttribute('title') || '';
return title;
}
// https://w3c.github.io/html-aam/#input-type-image
if (element.tagName === 'INPUT' && (element as HTMLInputElement).type === 'image') {
options.visitedElements.add(element);
const alt = element.getAttribute('alt') || '';
if (alt.trim())
return alt;
// SPEC DIFFERENCE.
// Spec does not mention "label" elements, but we account for labels
// to pass "name_test_case_616-manual.html"
const labels = (element as HTMLInputElement).labels || [];
if (labels.length) {
return [...labels].map(label => getElementAccessibleNameInternal(label, {
...options,
embeddedInLabel: 'self',
embeddedInTextAlternativeElement: false,
embeddedInLabelledBy: 'none',
embeddedInTargetElement: 'none',
})).filter(accessibleName => !!accessibleName).join(' ');
}
const title = element.getAttribute('title') || '';
if (title.trim())
return title;
// SPEC DIFFERENCE.
// Spec says return localized "Submit Query", but browsers and axe-core insist on "Sumbit".
return 'Submit';
}
// https://w3c.github.io/html-aam/#input-type-text-input-type-password-input-type-search-input-type-tel-input-type-url-and-textarea-element
// https://w3c.github.io/html-aam/#other-form-elements
// For "other form elements", we count select and any other input.
if (element.tagName === 'TEXTAREA' || element.tagName === 'SELECT' || element.tagName === 'INPUT') {
options.visitedElements.add(element);
const labels = (element as (HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement)).labels || [];
if (labels.length) {
return [...labels].map(label => getElementAccessibleNameInternal(label, {
...options,
embeddedInLabel: 'self',
embeddedInTextAlternativeElement: false,
embeddedInLabelledBy: 'none',
embeddedInTargetElement: 'none',
})).filter(accessibleName => !!accessibleName).join(' ');
}
const usePlaceholder = (element.tagName === 'INPUT' && ['text', 'password', 'search', 'tel', 'email', 'url'].includes((element as HTMLInputElement).type)) || element.tagName === 'TEXTAREA';
const placeholder = element.getAttribute('placeholder') || '';
const title = element.getAttribute('title') || '';
if (!usePlaceholder || title)
return title;
return placeholder;
}
// https://w3c.github.io/html-aam/#fieldset-and-legend-elements
if (element.tagName === 'FIELDSET') {
options.visitedElements.add(element);
for (let child = element.firstElementChild; child; child = child.nextElementSibling) {
if (child.tagName === 'LEGEND') {
return getElementAccessibleNameInternal(child, {
...childOptions,
embeddedInTextAlternativeElement: true,
});
}
}
const title = element.getAttribute('title') || '';
return title;
}
// https://w3c.github.io/html-aam/#figure-and-figcaption-elements
if (element.tagName === 'FIGURE') {
options.visitedElements.add(element);
for (let child = element.firstElementChild; child; child = child.nextElementSibling) {
if (child.tagName === 'FIGCAPTION') {
return getElementAccessibleNameInternal(child, {
...childOptions,
embeddedInTextAlternativeElement: true,
});
}
}
const title = element.getAttribute('title') || '';
return title;
}
// https://w3c.github.io/html-aam/#img-element
if (element.tagName === 'IMG') {
options.visitedElements.add(element);
const alt = element.getAttribute('alt') || '';
if (alt.trim())
return alt;
const title = element.getAttribute('title') || '';
return title;
}
// https://w3c.github.io/html-aam/#table-element
if (element.tagName === 'TABLE') {
options.visitedElements.add(element);
for (let child = element.firstElementChild; child; child = child.nextElementSibling) {
if (child.tagName === 'CAPTION') {
return getElementAccessibleNameInternal(child, {
...childOptions,
embeddedInTextAlternativeElement: true,
});
}
}
// SPEC DIFFERENCE.
// Spec does not say a word about <table summary="...">, but all browsers actually support it.
const summary = element.getAttribute('summary') || '';
if (summary)
return summary;
// SPEC DIFFERENCE.
// Spec says "if the table element has a title attribute, then use that attribute".
// We ignore title to pass "name_from_content-manual.html".
}
// https://w3c.github.io/html-aam/#area-element
if (element.tagName === 'AREA') {
options.visitedElements.add(element);
const alt = element.getAttribute('alt') || '';
if (alt.trim())
return alt;
const title = element.getAttribute('title') || '';
return title;
}
// https://www.w3.org/TR/svg-aam-1.0/
if (element.tagName === 'SVG' && (element as SVGElement).ownerSVGElement) {
options.visitedElements.add(element);
for (let child = element.firstElementChild; child; child = child.nextElementSibling) {
if (child.tagName === 'TITLE' && (element as SVGElement).ownerSVGElement) {
return getElementAccessibleNameInternal(child, {
...childOptions,
embeddedInTextAlternativeElement: true,
});
}
}
}
}
// step 2f + step 2h.
// https://w3c.github.io/aria/#namefromcontent
const allowsNameFromContent = ['button', 'cell', 'checkbox', 'columnheader', 'gridcell', 'heading', 'link', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'radio', 'row', 'rowheader', 'switch', 'tab', 'tooltip', 'treeitem'].includes(role);
if (allowsNameFromContent || options.embeddedInLabelledBy !== 'none' || options.embeddedInLabel !== 'none' || options.embeddedInTextAlternativeElement || options.embeddedInTargetElement === 'descendant') {
options.visitedElements.add(element);
const tokens: string[] = [];
const visit = (node: Node) => {
if (node.nodeType === 1 /* Node.ELEMENT_NODE */) {
const display = getComputedStyle(node as Element)?.getPropertyValue('display') || 'inline';
let token = getElementAccessibleNameInternal(node as Element, childOptions);
// SPEC DIFFERENCE.
// Spec says "append the result to the accumulated text", assuming "with space".
// However, multiple tests insist that inline elements do not add a space.
// Additionally, <br> insists on a space anyway, see "name_file-label-inline-block-elements-manual.html"
if (display !== 'inline' || node.nodeName === 'BR')
token = ' ' + token + ' ';
tokens.push(token);
} else if (node.nodeType === 3 /* Node.TEXT_NODE */) {
// step 2g.
tokens.push(node.textContent || '');
}
};
tokens.push(getPseudoContent(getComputedStyle(element, '::before')));
for (let child = element.firstChild; child; child = child.nextSibling)
visit(child);
if (element.shadowRoot) {
for (let child = element.shadowRoot.firstChild; child; child = child.nextSibling)
visit(child);
}
for (const owned of getIdRefs(element, element.getAttribute('aria-owns')))
visit(owned);
tokens.push(getPseudoContent(getComputedStyle(element, '::after')));
const accessibleName = tokens.join('');
if (accessibleName.trim())
return accessibleName;
}
// step 2i.
if (!['presentation', 'none'].includes(role) || element.tagName === 'IFRAME') {
options.visitedElements.add(element);
const title = element.getAttribute('title') || '';
if (title.trim())
return title;
}
options.visitedElements.add(element);
return '';
}
export const kAriaSelectedRoles = ['gridcell', 'option', 'row', 'tab', 'rowheader', 'columnheader', 'treeitem'];
export function getAriaSelected(element: Element): boolean {
// https://www.w3.org/TR/wai-aria-1.2/#aria-selected
// https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
if (element.tagName === 'OPTION')
return (element as HTMLOptionElement).selected;
if (kAriaSelectedRoles.includes(getAriaRole(element) || ''))
return getAriaBoolean(element.getAttribute('aria-selected')) === true;
return false;
}
export const kAriaCheckedRoles = ['checkbox', 'menuitemcheckbox', 'option', 'radio', 'switch', 'menuitemradio', 'treeitem'];
export function getAriaChecked(element: Element): boolean | 'mixed' {
const result = getAriaCheckedStrict(element);
return result === 'error' ? false : result;
}
export function getAriaCheckedStrict(element: Element): boolean | 'mixed' | 'error' {
// https://www.w3.org/TR/wai-aria-1.2/#aria-checked
// https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
if (element.tagName === 'INPUT' && (element as HTMLInputElement).indeterminate)
return 'mixed';
if (element.tagName === 'INPUT' && ['checkbox', 'radio'].includes((element as HTMLInputElement).type))
return (element as HTMLInputElement).checked;
if (kAriaCheckedRoles.includes(getAriaRole(element) || '')) {
const checked = element.getAttribute('aria-checked');
if (checked === 'true')
return true;
if (checked === 'mixed')
return 'mixed';
return false;
}
return 'error';
}
export const kAriaPressedRoles = ['button'];
export function getAriaPressed(element: Element): boolean | 'mixed' {
// https://www.w3.org/TR/wai-aria-1.2/#aria-pressed
if (kAriaPressedRoles.includes(getAriaRole(element) || '')) {
const pressed = element.getAttribute('aria-pressed');
if (pressed === 'true')
return true;
if (pressed === 'mixed')
return 'mixed';
}
return false;
}
export const kAriaExpandedRoles = ['application', 'button', 'checkbox', 'combobox', 'gridcell', 'link', 'listbox', 'menuitem', 'row', 'rowheader', 'tab', 'treeitem', 'columnheader', 'menuitemcheckbox', 'menuitemradio', 'rowheader', 'switch'];
export function getAriaExpanded(element: Element): boolean {
// https://www.w3.org/TR/wai-aria-1.2/#aria-expanded
// https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
if (element.tagName === 'DETAILS')
return (element as HTMLDetailsElement).open;
if (kAriaExpandedRoles.includes(getAriaRole(element) || ''))
return getAriaBoolean(element.getAttribute('aria-expanded')) === true;
return false;
}
export const kAriaLevelRoles = ['heading', 'listitem', 'row', 'treeitem'];
export function getAriaLevel(element: Element): number {
// https://www.w3.org/TR/wai-aria-1.2/#aria-level
// https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
const native = { 'H1': 1, 'H2': 2, 'H3': 3, 'H4': 4, 'H5': 5, 'H6': 6 }[element.tagName];
if (native)
return native;
if (kAriaLevelRoles.includes(getAriaRole(element) || '')) {
const attr = element.getAttribute('aria-level');
const value = attr === null ? Number.NaN : Number(attr);
if (Number.isInteger(value) && value >= 1)
return value;
}
return 0;
}
export const kAriaDisabledRoles = ['application', 'button', 'composite', 'gridcell', 'group', 'input', 'link', 'menuitem', 'scrollbar', 'separator', 'tab', 'checkbox', 'columnheader', 'combobox', 'grid', 'listbox', 'menu', 'menubar', 'menuitemcheckbox', 'menuitemradio', 'option', 'radio', 'radiogroup', 'row', 'rowheader', 'searchbox', 'select', 'slider', 'spinbutton', 'switch', 'tablist', 'textbox', 'toolbar', 'tree', 'treegrid', 'treeitem'];
export function getAriaDisabled(element: Element): boolean {
// https://www.w3.org/TR/wai-aria-1.2/#aria-disabled
// https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
// Note that aria-disabled applies to all descendants, so we look up the hierarchy.
const isNativeFormControl = ['BUTTON', 'INPUT', 'SELECT', 'TEXTAREA', 'OPTION', 'OPTGROUP'].includes(element.tagName);
if (isNativeFormControl && (element.hasAttribute('disabled') || belongsToDisabledFieldSet(element)))
return true;
return hasExplicitAriaDisabled(element);
}
function belongsToDisabledFieldSet(element: Element | null): boolean {
if (!element)
return false;
if (element.tagName === 'FIELDSET' && element.hasAttribute('disabled'))
return true;
// fieldset does not work across shadow boundaries.
return belongsToDisabledFieldSet(element.parentElement);
}
function hasExplicitAriaDisabled(element: Element | undefined): boolean {
if (!element)
return false;
if (kAriaDisabledRoles.includes(getAriaRole(element) || '')) {
const attribute = (element.getAttribute('aria-disabled') || '').toLowerCase();
if (attribute === 'true')
return true;
if (attribute === 'false')
return false;
}
// aria-disabled works across shadow boundaries.
return hasExplicitAriaDisabled(parentElementOrShadowHost(element));
}
| packages/playwright-core/src/server/injected/roleUtils.ts | 1 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.0021395953372120857,
0.00020323805802036077,
0.00016269684419967234,
0.00017014022159855813,
0.00022877240553498268
] |
{
"id": 4,
"code_window": [
" `);\n",
" expect(await page.locator(`role=button[expanded]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<button aria-expanded=\"true\">Hello</button>`,\n",
" ]);\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\n",
" expect(await page.locator('role=treeitem').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\">Hi</div>`,\n",
" `<div role=\"treeitem\" aria-expanded=\"true\">Hello</div>`,\n",
" `<div role=\"treeitem\" aria-expanded=\"false\">Bye</div>`,\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 175
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import expectLibrary from 'expect';
export const expect = expectLibrary;
export {
INVERTED_COLOR,
RECEIVED_COLOR,
printReceived,
} from 'jest-matcher-utils';
| packages/playwright-test/bundles/expect/src/expectBundleImpl.ts | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00029737583827227354,
0.000228207660256885,
0.00017474632477387786,
0.00021250081772450358,
0.000051280461775604635
] |
{
"id": 4,
"code_window": [
" `);\n",
" expect(await page.locator(`role=button[expanded]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<button aria-expanded=\"true\">Hello</button>`,\n",
" ]);\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\n",
" expect(await page.locator('role=treeitem').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\">Hi</div>`,\n",
" `<div role=\"treeitem\" aria-expanded=\"true\">Hello</div>`,\n",
" `<div role=\"treeitem\" aria-expanded=\"false\">Bye</div>`,\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 175
} | <style>
html { background-image: url(image1x.jpg); }
@media(-webkit-min-device-pixel-ratio: 1.5) {
html { background-image: url(image2x.jpg); }
}
</style>
| tests/assets/highdpi.html | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00016338117711711675,
0.00016338117711711675,
0.00016338117711711675,
0.00016338117711711675,
0
] |
{
"id": 4,
"code_window": [
" `);\n",
" expect(await page.locator(`role=button[expanded]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<button aria-expanded=\"true\">Hello</button>`,\n",
" ]);\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\n",
" expect(await page.locator('role=treeitem').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\">Hi</div>`,\n",
" `<div role=\"treeitem\" aria-expanded=\"true\">Hello</div>`,\n",
" `<div role=\"treeitem\" aria-expanded=\"false\">Bye</div>`,\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 175
} | **/*
!README.md
!LICENSE
!register.d.ts
!register.mjs
!registerSource.mjs
!index.d.ts
!index.js
!hooks.d.ts
!hooks.mjs
| packages/playwright-ct-vue2/.npmignore | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00017323200881946832,
0.0001723423192743212,
0.0001714526442810893,
0.0001723423192743212,
8.896822691895068e-7
] |
{
"id": 5,
"code_window": [
" ]);\n",
" expect(await page.locator(`role=button[expanded=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<button aria-expanded=\"true\">Hello</button>`,\n",
" ]);\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" expect(await page.getByRole('treeitem').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\">Hi</div>`,\n",
" `<div role=\"treeitem\" aria-expanded=\"true\">Hello</div>`,\n",
" `<div role=\"treeitem\" aria-expanded=\"false\">Bye</div>`,\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 178
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { SelectorEngine, SelectorRoot } from './selectorEngine';
import { matchesAttributePart } from './selectorUtils';
import { getAriaChecked, getAriaDisabled, getAriaExpanded, getAriaLevel, getAriaPressed, getAriaRole, getAriaSelected, getElementAccessibleName, isElementHiddenForAria, kAriaCheckedRoles, kAriaExpandedRoles, kAriaLevelRoles, kAriaPressedRoles, kAriaSelectedRoles } from './roleUtils';
import { parseAttributeSelector, type AttributeSelectorPart, type AttributeSelectorOperator } from '../isomorphic/selectorParser';
const kSupportedAttributes = ['selected', 'checked', 'pressed', 'expanded', 'level', 'disabled', 'name', 'include-hidden'];
kSupportedAttributes.sort();
function validateSupportedRole(attr: string, roles: string[], role: string) {
if (!roles.includes(role))
throw new Error(`"${attr}" attribute is only supported for roles: ${roles.slice().sort().map(role => `"${role}"`).join(', ')}`);
}
function validateSupportedValues(attr: AttributeSelectorPart, values: any[]) {
if (attr.op !== '<truthy>' && !values.includes(attr.value))
throw new Error(`"${attr.name}" must be one of ${values.map(v => JSON.stringify(v)).join(', ')}`);
}
function validateSupportedOp(attr: AttributeSelectorPart, ops: AttributeSelectorOperator[]) {
if (!ops.includes(attr.op))
throw new Error(`"${attr.name}" does not support "${attr.op}" matcher`);
}
function validateAttributes(attrs: AttributeSelectorPart[], role: string) {
for (const attr of attrs) {
switch (attr.name) {
case 'checked': {
validateSupportedRole(attr.name, kAriaCheckedRoles, role);
validateSupportedValues(attr, [true, false, 'mixed']);
validateSupportedOp(attr, ['<truthy>', '=']);
if (attr.op === '<truthy>') {
// Do not match "mixed" in "option[checked]".
attr.op = '=';
attr.value = true;
}
break;
}
case 'pressed': {
validateSupportedRole(attr.name, kAriaPressedRoles, role);
validateSupportedValues(attr, [true, false, 'mixed']);
validateSupportedOp(attr, ['<truthy>', '=']);
if (attr.op === '<truthy>') {
// Do not match "mixed" in "button[pressed]".
attr.op = '=';
attr.value = true;
}
break;
}
case 'selected': {
validateSupportedRole(attr.name, kAriaSelectedRoles, role);
validateSupportedValues(attr, [true, false]);
validateSupportedOp(attr, ['<truthy>', '=']);
break;
}
case 'expanded': {
validateSupportedRole(attr.name, kAriaExpandedRoles, role);
validateSupportedValues(attr, [true, false]);
validateSupportedOp(attr, ['<truthy>', '=']);
break;
}
case 'level': {
validateSupportedRole(attr.name, kAriaLevelRoles, role);
// Level is a number, convert it from string.
if (typeof attr.value === 'string')
attr.value = +attr.value;
if (attr.op !== '=' || typeof attr.value !== 'number' || Number.isNaN(attr.value))
throw new Error(`"level" attribute must be compared to a number`);
break;
}
case 'disabled': {
validateSupportedValues(attr, [true, false]);
validateSupportedOp(attr, ['<truthy>', '=']);
break;
}
case 'name': {
if (attr.op === '<truthy>')
throw new Error(`"name" attribute must have a value`);
if (typeof attr.value !== 'string' && !(attr.value instanceof RegExp))
throw new Error(`"name" attribute must be a string or a regular expression`);
break;
}
case 'include-hidden': {
validateSupportedValues(attr, [true, false]);
validateSupportedOp(attr, ['<truthy>', '=']);
break;
}
default: {
throw new Error(`Unknown attribute "${attr.name}", must be one of ${kSupportedAttributes.map(a => `"${a}"`).join(', ')}.`);
}
}
}
}
export function createRoleEngine(internal: boolean): SelectorEngine {
const queryAll = (scope: SelectorRoot, selector: string): Element[] => {
const parsed = parseAttributeSelector(selector, true);
const role = parsed.name.toLowerCase();
if (!role)
throw new Error(`Role must not be empty`);
validateAttributes(parsed.attributes, role);
const hiddenCache = new Map<Element, boolean>();
const result: Element[] = [];
const match = (element: Element) => {
if (getAriaRole(element) !== role)
return;
let includeHidden = false; // By default, hidden elements are excluded.
let nameAttr: AttributeSelectorPart | undefined;
for (const attr of parsed.attributes) {
if (attr.name === 'include-hidden') {
includeHidden = attr.op === '<truthy>' || !!attr.value;
continue;
}
if (attr.name === 'name') {
nameAttr = attr;
continue;
}
let actual;
switch (attr.name) {
case 'selected': actual = getAriaSelected(element); break;
case 'checked': actual = getAriaChecked(element); break;
case 'pressed': actual = getAriaPressed(element); break;
case 'expanded': actual = getAriaExpanded(element); break;
case 'level': actual = getAriaLevel(element); break;
case 'disabled': actual = getAriaDisabled(element); break;
}
if (!matchesAttributePart(actual, attr))
return;
}
if (!includeHidden) {
const isHidden = isElementHiddenForAria(element, hiddenCache);
if (isHidden)
return;
}
if (nameAttr !== undefined) {
// Always normalize whitespace in the accessible name.
const accessibleName = getElementAccessibleName(element, includeHidden, hiddenCache).trim().replace(/\s+/g, ' ');
if (typeof nameAttr.value === 'string')
nameAttr.value = nameAttr.value.trim().replace(/\s+/g, ' ');
// internal:role assumes that [name="foo"i] also means substring.
if (internal && !nameAttr.caseSensitive && nameAttr.op === '=')
nameAttr.op = '*=';
if (!matchesAttributePart(accessibleName, nameAttr))
return;
}
result.push(element);
};
const query = (root: Element | ShadowRoot | Document) => {
const shadows: ShadowRoot[] = [];
if ((root as Element).shadowRoot)
shadows.push((root as Element).shadowRoot!);
for (const element of root.querySelectorAll('*')) {
match(element);
if (element.shadowRoot)
shadows.push(element.shadowRoot);
}
shadows.forEach(query);
};
query(scope);
return result;
};
return { queryAll };
}
| packages/playwright-core/src/server/injected/roleSelectorEngine.ts | 1 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00019889447139576077,
0.00017119682161137462,
0.00016363484610337764,
0.00017002812819555402,
0.000007433499831677182
] |
{
"id": 5,
"code_window": [
" ]);\n",
" expect(await page.locator(`role=button[expanded=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<button aria-expanded=\"true\">Hello</button>`,\n",
" ]);\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" expect(await page.getByRole('treeitem').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\">Hi</div>`,\n",
" `<div role=\"treeitem\" aria-expanded=\"true\">Hello</div>`,\n",
" `<div role=\"treeitem\" aria-expanded=\"false\">Bye</div>`,\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 178
} | <script>
setTimeout(() => {
const iter = window.localStorage.iter || '';
window.localStorage.iter = iter + 'a';
if (iter.length === 10)
return;
window.location.href = window.location.href.replace('loop1', 'loop2');
}, 1);
</script>>
| tests/assets/redirectloop1.html | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00017110510088969022,
0.00017110510088969022,
0.00017110510088969022,
0.00017110510088969022,
0
] |
{
"id": 5,
"code_window": [
" ]);\n",
" expect(await page.locator(`role=button[expanded=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<button aria-expanded=\"true\">Hello</button>`,\n",
" ]);\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" expect(await page.getByRole('treeitem').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\">Hi</div>`,\n",
" `<div role=\"treeitem\" aria-expanded=\"true\">Hello</div>`,\n",
" `<div role=\"treeitem\" aria-expanded=\"false\">Bye</div>`,\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 178
} | /**
* Copyright 2017 Google Inc. All rights reserved.
* Modifications copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { playwrightTest as it, expect } from '../config/browserTest';
import fs from 'fs';
import path from 'path';
it('should support hasTouch option', async ({ server, launchPersistent }) => {
const { page } = await launchPersistent({ hasTouch: true });
await page.goto(server.PREFIX + '/mobile.html');
expect(await page.evaluate(() => 'ontouchstart' in window)).toBe(true);
});
it('should work in persistent context', async ({ server, launchPersistent, browserName }) => {
it.skip(browserName === 'firefox', 'Firefox does not support mobile');
const { page } = await launchPersistent({ viewport: { width: 320, height: 480 }, isMobile: true });
await page.goto(server.PREFIX + '/empty.html');
expect(await page.evaluate(() => window.innerWidth)).toBe(980);
});
it('should support colorScheme option', async ({ launchPersistent }) => {
const { page } = await launchPersistent({ colorScheme: 'dark' });
expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches)).toBe(false);
expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches)).toBe(true);
});
it('should support reducedMotion option', async ({ launchPersistent }) => {
const { page } = await launchPersistent({ reducedMotion: 'reduce' });
expect(await page.evaluate(() => matchMedia('(prefers-reduced-motion: reduce)').matches)).toBe(true);
expect(await page.evaluate(() => matchMedia('(prefers-reduced-motion: no-preference)').matches)).toBe(false);
});
it('should support forcedColors option', async ({ launchPersistent, browserName }) => {
const { page } = await launchPersistent({ forcedColors: 'active' });
expect(await page.evaluate(() => matchMedia('(forced-colors: active)').matches)).toBe(true);
expect(await page.evaluate(() => matchMedia('(forced-colors: none)').matches)).toBe(false);
});
it('should support timezoneId option', async ({ launchPersistent, browserName }) => {
const { page } = await launchPersistent({ locale: 'en-US', timezoneId: 'America/Jamaica' });
expect(await page.evaluate(() => new Date(1479579154987).toString())).toBe('Sat Nov 19 2016 13:12:34 GMT-0500 (Eastern Standard Time)');
});
it('should support locale option', async ({ launchPersistent }) => {
const { page } = await launchPersistent({ locale: 'fr-FR' });
expect(await page.evaluate(() => navigator.language)).toBe('fr-FR');
});
it('should support geolocation and permissions options', async ({ server, launchPersistent }) => {
const { page } = await launchPersistent({ geolocation: { longitude: 10, latitude: 10 }, permissions: ['geolocation'] });
await page.goto(server.EMPTY_PAGE);
const geolocation = await page.evaluate(() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {
resolve({ latitude: position.coords.latitude, longitude: position.coords.longitude });
})));
expect(geolocation).toEqual({ latitude: 10, longitude: 10 });
});
it('should support ignoreHTTPSErrors option', async ({ httpsServer, launchPersistent }) => {
const { page } = await launchPersistent({ ignoreHTTPSErrors: true });
let error = null;
const response = await page.goto(httpsServer.EMPTY_PAGE).catch(e => error = e);
expect(error).toBe(null);
expect(response.ok()).toBe(true);
});
it('should support extraHTTPHeaders option', async ({ server, launchPersistent }) => {
const { page } = await launchPersistent({ extraHTTPHeaders: { foo: 'bar' } });
const [request] = await Promise.all([
server.waitForRequest('/empty.html'),
page.goto(server.EMPTY_PAGE),
]);
expect(request.headers['foo']).toBe('bar');
});
it('should accept userDataDir', async ({ createUserDataDir, browserType }) => {
const userDataDir = await createUserDataDir();
const context = await browserType.launchPersistentContext(userDataDir);
expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);
await context.close();
expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);
});
it('should restore state from userDataDir', async ({ browserType, server, createUserDataDir, isMac, browserName }) => {
it.fixme(browserName === 'firefox', 'https://github.com/microsoft/playwright/issues/12632');
it.slow();
const userDataDir = await createUserDataDir();
const browserContext = await browserType.launchPersistentContext(userDataDir);
const page = await browserContext.newPage();
await page.goto(server.EMPTY_PAGE);
await page.evaluate(() => localStorage.hey = 'hello');
await browserContext.close();
const browserContext2 = await browserType.launchPersistentContext(userDataDir);
const page2 = await browserContext2.newPage();
await page2.goto(server.EMPTY_PAGE);
expect(await page2.evaluate(() => localStorage.hey)).toBe('hello');
await browserContext2.close();
const userDataDir2 = await createUserDataDir();
const browserContext3 = await browserType.launchPersistentContext(userDataDir2);
const page3 = await browserContext3.newPage();
await page3.goto(server.EMPTY_PAGE);
expect(await page3.evaluate(() => localStorage.hey)).not.toBe('hello');
await browserContext3.close();
});
it('should create userDataDir if it does not exist', async ({ createUserDataDir, browserType }) => {
const userDataDir = path.join(await createUserDataDir(), 'nonexisting');
const context = await browserType.launchPersistentContext(userDataDir);
await context.close();
expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);
});
it('should have default URL when launching browser', async ({ launchPersistent }) => {
const { context } = await launchPersistent();
const urls = context.pages().map(page => page.url());
expect(urls).toEqual(['about:blank']);
});
it('should throw if page argument is passed', async ({ browserType, server, createUserDataDir, browserName }) => {
it.skip(browserName === 'firefox');
const options = { args: [server.EMPTY_PAGE] };
const error = await browserType.launchPersistentContext(await createUserDataDir(), options).catch(e => e);
expect(error.message).toContain('can not specify page');
});
it('should have passed URL when launching with ignoreDefaultArgs: true', async ({ browserType, server, createUserDataDir, toImpl, mode, browserName }) => {
it.skip(mode !== 'default');
const userDataDir = await createUserDataDir();
const args = toImpl(browserType)._defaultArgs((browserType as any)._defaultLaunchOptions, 'persistent', userDataDir, 0).filter(a => a !== 'about:blank');
const options = {
args: browserName === 'firefox' ? [...args, '-new-tab', server.EMPTY_PAGE] : [...args, server.EMPTY_PAGE],
ignoreDefaultArgs: true,
};
const browserContext = await browserType.launchPersistentContext(userDataDir, options);
if (!browserContext.pages().length)
await browserContext.waitForEvent('page');
await browserContext.pages()[0].waitForLoadState();
const gotUrls = browserContext.pages().map(page => page.url());
expect(gotUrls).toEqual([server.EMPTY_PAGE]);
await browserContext.close();
});
it('should handle timeout', async ({ browserType, createUserDataDir, mode }) => {
it.skip(mode !== 'default');
const options: any = { timeout: 5000, __testHookBeforeCreateBrowser: () => new Promise(f => setTimeout(f, 6000)) };
const error = await browserType.launchPersistentContext(await createUserDataDir(), options).catch(e => e);
expect(error.message).toContain(`browserType.launchPersistentContext: Timeout 5000ms exceeded.`);
});
it('should handle exception', async ({ browserType, createUserDataDir, mode }) => {
it.skip(mode !== 'default');
const e = new Error('Dummy');
const options: any = { __testHookBeforeCreateBrowser: () => { throw e; } };
const error = await browserType.launchPersistentContext(await createUserDataDir(), options).catch(e => e);
expect(error.message).toContain('Dummy');
});
it('should fire close event for a persistent context', async ({ launchPersistent }) => {
const { context } = await launchPersistent();
let closed = false;
context.on('close', () => closed = true);
await context.close();
expect(closed).toBe(true);
});
it('coverage should work', async ({ server, launchPersistent, browserName }) => {
it.skip(browserName !== 'chromium');
const { page } = await launchPersistent();
await page.coverage.startJSCoverage();
await page.goto(server.PREFIX + '/jscoverage/simple.html', { waitUntil: 'load' });
const coverage = await page.coverage.stopJSCoverage();
expect(coverage.length).toBe(1);
expect(coverage[0].url).toContain('/jscoverage/simple.html');
expect(coverage[0].functions.find(f => f.functionName === 'foo').ranges[0].count).toEqual(1);
});
it('should respect selectors', async ({ playwright, launchPersistent }) => {
const { page } = await launchPersistent();
const defaultContextCSS = () => ({
query(root, selector) {
return root.querySelector(selector);
},
queryAll(root: HTMLElement, selector: string) {
return Array.from(root.querySelectorAll(selector));
}
});
await playwright.selectors.register('defaultContextCSS', defaultContextCSS);
await page.setContent(`<div>hello</div>`);
expect(await page.innerHTML('css=div')).toBe('hello');
expect(await page.innerHTML('defaultContextCSS=div')).toBe('hello');
});
it('should connect to a browser with the default page', async ({ browserType, createUserDataDir, mode }) => {
it.skip(mode !== 'default');
const options: any = { __testHookOnConnectToBrowser: () => new Promise(f => setTimeout(f, 3000)) };
const context = await browserType.launchPersistentContext(await createUserDataDir(), options);
expect(context.pages().length).toBe(1);
await context.close();
});
it('should support har option', async ({ launchPersistent, asset }) => {
const path = asset('har-fulfill.har');
const { page } = await launchPersistent();
await page.routeFromHAR(path);
await page.goto('http://no.playwright/');
// HAR contains a redirect for the script that should be followed automatically.
expect(await page.evaluate('window.value')).toBe('foo');
// HAR contains a POST for the css file that should not be used.
await expect(page.locator('body')).toHaveCSS('background-color', 'rgb(255, 0, 0)');
});
| tests/library/defaultbrowsercontext-2.spec.ts | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.002805033465847373,
0.0007108606514520943,
0.00016603893891442567,
0.00018840038683265448,
0.0007890271954238415
] |
{
"id": 5,
"code_window": [
" ]);\n",
" expect(await page.locator(`role=button[expanded=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<button aria-expanded=\"true\">Hello</button>`,\n",
" ]);\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" expect(await page.getByRole('treeitem').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\">Hi</div>`,\n",
" `<div role=\"treeitem\" aria-expanded=\"true\">Hello</div>`,\n",
" `<div role=\"treeitem\" aria-expanded=\"false\">Bye</div>`,\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 178
} | /* eslint-disable notice/notice */
/**
* In this script, we will login and run a few tests that use GitHub API.
*
* Steps summary
* 1. Create a new repo.
* 2. Run tests that programmatically create new issues.
* 3. Delete the repo.
*/
import { test, expect } from '@playwright/test';
const user = process.env.GITHUB_USER;
const repo = 'Test-Repo-1';
test.use({
baseURL: 'https://api.github.com',
extraHTTPHeaders: {
'Accept': 'application/vnd.github.v3+json',
// Add authorization token to all requests.
'Authorization': `token ${process.env.API_TOKEN}`,
}
});
test.beforeAll(async ({ request }) => {
// Create repo
const response = await request.post('/user/repos', {
data: {
name: repo
}
});
expect(response.ok()).toBeTruthy();
});
test.afterAll(async ({ request }) => {
// Delete repo
const response = await request.delete(`/repos/${user}/${repo}`);
expect(response.ok()).toBeTruthy();
});
test('should create bug report', async ({ request }) => {
const newIssue = await request.post(`/repos/${user}/${repo}/issues`, {
data: {
title: '[Bug] report 1',
body: 'Bug description',
}
});
expect(newIssue.ok()).toBeTruthy();
const issues = await request.get(`/repos/${user}/${repo}/issues`);
expect(issues.ok()).toBeTruthy();
expect(await issues.json()).toContainEqual(expect.objectContaining({
title: '[Bug] report 1',
body: 'Bug description'
}));
});
test('should create feature request', async ({ request }) => {
const newIssue = await request.post(`/repos/${user}/${repo}/issues`, {
data: {
title: '[Feature] request 1',
body: 'Feature description',
}
});
expect(newIssue.ok()).toBeTruthy();
const issues = await request.get(`/repos/${user}/${repo}/issues`);
expect(issues.ok()).toBeTruthy();
expect(await issues.json()).toContainEqual(expect.objectContaining({
title: '[Feature] request 1',
body: 'Feature description'
}));
});
| examples/github-api/tests/test-api.spec.ts | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00017638619465287775,
0.0001713996462058276,
0.000167073609190993,
0.00017122465942520648,
0.000002491648046998307
] |
{
"id": 6,
"code_window": [
" ]);\n",
" expect(await page.getByRole('button', { expanded: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<button aria-expanded=\"true\">Hello</button>`,\n",
" ]);\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\n",
" expect(await page.locator(`role=treeitem[expanded]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\" aria-expanded=\"true\">Hello</div>`,\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 181
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { test, expect } from './pageTest';
test('should detect roles', async ({ page }) => {
await page.setContent(`
<button>Hello</button>
<select multiple="" size="2"></select>
<select></select>
<h3>Heading</h3>
<details><summary>Hello</summary></details>
<div role="dialog">I am a dialog</div>
`);
expect(await page.locator(`role=button`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hello</button>`,
]);
expect(await page.locator(`role=listbox`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<select multiple="" size="2"></select>`,
]);
expect(await page.locator(`role=combobox`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<select></select>`,
]);
expect(await page.locator(`role=heading`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<h3>Heading</h3>`,
]);
expect(await page.locator(`role=group`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<details><summary>Hello</summary></details>`,
]);
expect(await page.locator(`role=dialog`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="dialog">I am a dialog</div>`,
]);
expect(await page.locator(`role=menuitem`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
]);
expect(await page.getByRole('menuitem').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
]);
});
test('should support selected', async ({ page }) => {
await page.setContent(`
<select>
<option>Hi</option>
<option selected>Hello</option>
</select>
<div>
<div role="option" aria-selected="true">Hi</div>
<div role="option" aria-selected="false">Hello</div>
</div>
`);
expect(await page.locator(`role=option[selected]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<option selected="">Hello</option>`,
`<div role="option" aria-selected="true">Hi</div>`,
]);
expect(await page.locator(`role=option[selected=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<option selected="">Hello</option>`,
`<div role="option" aria-selected="true">Hi</div>`,
]);
expect(await page.getByRole('option', { selected: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<option selected="">Hello</option>`,
`<div role="option" aria-selected="true">Hi</div>`,
]);
expect(await page.locator(`role=option[selected=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<option>Hi</option>`,
`<div role="option" aria-selected="false">Hello</div>`,
]);
expect(await page.getByRole('option', { selected: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<option>Hi</option>`,
`<div role="option" aria-selected="false">Hello</div>`,
]);
});
test('should support checked', async ({ page }) => {
await page.setContent(`
<input type=checkbox>
<input type=checkbox checked>
<input type=checkbox indeterminate>
<div role=checkbox aria-checked="true">Hi</div>
<div role=checkbox aria-checked="false">Hello</div>
<div role=checkbox>Unknown</div>
`);
await page.$eval('[indeterminate]', input => (input as HTMLInputElement).indeterminate = true);
expect(await page.locator(`role=checkbox[checked]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox" checked="">`,
`<div role="checkbox" aria-checked="true">Hi</div>`,
]);
expect(await page.locator(`role=checkbox[checked=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox" checked="">`,
`<div role="checkbox" aria-checked="true">Hi</div>`,
]);
expect(await page.getByRole('checkbox', { checked: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox" checked="">`,
`<div role="checkbox" aria-checked="true">Hi</div>`,
]);
expect(await page.locator(`role=checkbox[checked=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox">`,
`<div role="checkbox" aria-checked="false">Hello</div>`,
`<div role="checkbox">Unknown</div>`,
]);
expect(await page.getByRole('checkbox', { checked: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox">`,
`<div role="checkbox" aria-checked="false">Hello</div>`,
`<div role="checkbox">Unknown</div>`,
]);
expect(await page.locator(`role=checkbox[checked="mixed"]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox" indeterminate="">`,
]);
expect(await page.locator(`role=checkbox`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox">`,
`<input type="checkbox" checked="">`,
`<input type="checkbox" indeterminate="">`,
`<div role="checkbox" aria-checked="true">Hi</div>`,
`<div role="checkbox" aria-checked="false">Hello</div>`,
`<div role="checkbox">Unknown</div>`,
]);
});
test('should support pressed', async ({ page }) => {
await page.setContent(`
<button>Hi</button>
<button aria-pressed="true">Hello</button>
<button aria-pressed="false">Bye</button>
<button aria-pressed="mixed">Mixed</button>
`);
expect(await page.locator(`role=button[pressed]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-pressed="true">Hello</button>`,
]);
expect(await page.locator(`role=button[pressed=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-pressed="true">Hello</button>`,
]);
expect(await page.getByRole('button', { pressed: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-pressed="true">Hello</button>`,
]);
expect(await page.locator(`role=button[pressed=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-pressed="false">Bye</button>`,
]);
expect(await page.getByRole('button', { pressed: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-pressed="false">Bye</button>`,
]);
expect(await page.locator(`role=button[pressed="mixed"]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-pressed="mixed">Mixed</button>`,
]);
expect(await page.locator(`role=button`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-pressed="true">Hello</button>`,
`<button aria-pressed="false">Bye</button>`,
`<button aria-pressed="mixed">Mixed</button>`,
]);
});
test('should support expanded', async ({ page }) => {
await page.setContent(`
<button>Hi</button>
<button aria-expanded="true">Hello</button>
<button aria-expanded="false">Bye</button>
`);
expect(await page.locator(`role=button[expanded]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-expanded="true">Hello</button>`,
]);
expect(await page.locator(`role=button[expanded=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-expanded="true">Hello</button>`,
]);
expect(await page.getByRole('button', { expanded: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-expanded="true">Hello</button>`,
]);
expect(await page.locator(`role=button[expanded=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-expanded="false">Bye</button>`,
]);
expect(await page.getByRole('button', { expanded: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-expanded="false">Bye</button>`,
]);
});
test('should support disabled', async ({ page }) => {
await page.setContent(`
<button>Hi</button>
<button disabled>Bye</button>
<button aria-disabled="true">Hello</button>
<button aria-disabled="false">Oh</button>
<fieldset disabled>
<button>Yay</button>
</fieldset>
`);
expect(await page.locator(`role=button[disabled]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button disabled="">Bye</button>`,
`<button aria-disabled="true">Hello</button>`,
`<button>Yay</button>`,
]);
expect(await page.locator(`role=button[disabled=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button disabled="">Bye</button>`,
`<button aria-disabled="true">Hello</button>`,
`<button>Yay</button>`,
]);
expect(await page.getByRole('button', { disabled: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button disabled="">Bye</button>`,
`<button aria-disabled="true">Hello</button>`,
`<button>Yay</button>`,
]);
expect(await page.locator(`role=button[disabled=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-disabled="false">Oh</button>`,
]);
expect(await page.getByRole('button', { disabled: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-disabled="false">Oh</button>`,
]);
});
test('should support level', async ({ page }) => {
await page.setContent(`
<h1>Hello</h1>
<h3>Hi</h3>
<div role="heading" aria-level="5">Bye</div>
`);
expect(await page.locator(`role=heading[level=1]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<h1>Hello</h1>`,
]);
expect(await page.getByRole('heading', { level: 1 }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<h1>Hello</h1>`,
]);
expect(await page.locator(`role=heading[level=3]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<h3>Hi</h3>`,
]);
expect(await page.getByRole('heading', { level: 3 }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<h3>Hi</h3>`,
]);
expect(await page.locator(`role=heading[level=5]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="heading" aria-level="5">Bye</div>`,
]);
});
test('should filter hidden, unless explicitly asked for', async ({ page }) => {
await page.setContent(`
<button>Hi</button>
<button hidden>Hello</button>
<button aria-hidden="true">Yay</button>
<button aria-hidden="false">Nay</button>
<button style="visibility:hidden">Bye</button>
<div style="visibility:hidden">
<button>Oh</button>
</div>
<div style="visibility:hidden">
<button style="visibility:visible">Still here</button>
</div>
<button style="display:none">Never</button>
<div id=host1></div>
<div id=host2 style="display:none"></div>
<script>
function addButton(host, text) {
const root = host.attachShadow({ mode: 'open' });
const button = document.createElement('button');
button.textContent = text;
root.appendChild(button);
}
addButton(document.getElementById('host1'), 'Shadow1');
addButton(document.getElementById('host2'), 'Shadow2');
</script>
`);
expect(await page.locator(`role=button`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-hidden="false">Nay</button>`,
`<button style="visibility:visible">Still here</button>`,
`<button>Shadow1</button>`,
]);
expect(await page.locator(`role=button[include-hidden]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button hidden="">Hello</button>`,
`<button aria-hidden="true">Yay</button>`,
`<button aria-hidden="false">Nay</button>`,
`<button style="visibility:hidden">Bye</button>`,
`<button>Oh</button>`,
`<button style="visibility:visible">Still here</button>`,
`<button style="display:none">Never</button>`,
`<button>Shadow1</button>`,
`<button>Shadow2</button>`,
]);
expect(await page.locator(`role=button[include-hidden=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button hidden="">Hello</button>`,
`<button aria-hidden="true">Yay</button>`,
`<button aria-hidden="false">Nay</button>`,
`<button style="visibility:hidden">Bye</button>`,
`<button>Oh</button>`,
`<button style="visibility:visible">Still here</button>`,
`<button style="display:none">Never</button>`,
`<button>Shadow1</button>`,
`<button>Shadow2</button>`,
]);
expect(await page.locator(`role=button[include-hidden=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-hidden="false">Nay</button>`,
`<button style="visibility:visible">Still here</button>`,
`<button>Shadow1</button>`,
]);
});
test('should support name', async ({ page }) => {
await page.setContent(`
<div role="button" aria-label=" Hello "></div>
<div role="button" aria-label="Hallo"></div>
<div role="button" aria-label="Hello" aria-hidden="true"></div>
<div role="button" aria-label="123" aria-hidden="true"></div>
<div role="button" aria-label='foo"bar' aria-hidden="true"></div>
`);
expect(await page.locator(`role=button[name="Hello"]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
]);
expect(await page.locator(`role=button[name=" \n Hello "]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
]);
expect(await page.getByRole('button', { name: 'Hello' }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
]);
expect(await page.locator(`role=button[name*="all"]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label="Hallo"></div>`,
]);
expect(await page.locator(`role=button[name=/^H[ae]llo$/]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hallo"></div>`,
]);
expect(await page.getByRole('button', { name: /^H[ae]llo$/ }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hallo"></div>`,
]);
expect(await page.locator(`role=button[name=/h.*o/i]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hallo"></div>`,
]);
expect(await page.getByRole('button', { name: /h.*o/i }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hallo"></div>`,
]);
expect(await page.locator(`role=button[name="Hello"][include-hidden]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hello" aria-hidden="true"></div>`,
]);
expect(await page.getByRole('button', { name: 'Hello', includeHidden: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hello" aria-hidden="true"></div>`,
]);
expect(await page.getByRole('button', { name: 'hello', includeHidden: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hello" aria-hidden="true"></div>`,
]);
expect(await page.locator(`role=button[name=Hello]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
]);
expect(await page.locator(`role=button[name=123][include-hidden]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label="123" aria-hidden="true"></div>`,
]);
expect(await page.getByRole('button', { name: '123', includeHidden: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label="123" aria-hidden="true"></div>`,
]);
});
test('errors', async ({ page }) => {
const e0 = await page.$('role=[bar]').catch(e => e);
expect(e0.message).toContain(`Role must not be empty`);
const e1 = await page.$('role=foo[sElected]').catch(e => e);
expect(e1.message).toContain(`Unknown attribute "sElected", must be one of "checked", "disabled", "expanded", "include-hidden", "level", "name", "pressed", "selected"`);
const e2 = await page.$('role=foo[bar . qux=true]').catch(e => e);
expect(e2.message).toContain(`Unknown attribute "bar.qux"`);
const e3 = await page.$('role=heading[level="bar"]').catch(e => e);
expect(e3.message).toContain(`"level" attribute must be compared to a number`);
const e4 = await page.$('role=checkbox[checked="bar"]').catch(e => e);
expect(e4.message).toContain(`"checked" must be one of true, false, "mixed"`);
const e5 = await page.$('role=checkbox[checked~=true]').catch(e => e);
expect(e5.message).toContain(`cannot use ~= in attribute with non-string matching value`);
const e6 = await page.$('role=button[level=3]').catch(e => e);
expect(e6.message).toContain(`"level" attribute is only supported for roles: "heading", "listitem", "row", "treeitem"`);
const e7 = await page.$('role=button[name]').catch(e => e);
expect(e7.message).toContain(`"name" attribute must have a value`);
});
| tests/page/selectors-role.spec.ts | 1 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.9641361236572266,
0.18877209722995758,
0.00016642901755403727,
0.00717034051194787,
0.3020729124546051
] |
{
"id": 6,
"code_window": [
" ]);\n",
" expect(await page.getByRole('button', { expanded: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<button aria-expanded=\"true\">Hello</button>`,\n",
" ]);\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\n",
" expect(await page.locator(`role=treeitem[expanded]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\" aria-expanded=\"true\">Hello</div>`,\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 181
} | /**
* Copyright 2018 Google Inc. All rights reserved.
* Modifications copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { browserTest as it, expect } from '../config/browserTest';
it('BrowserContext.Events.Request', async ({ context, server }) => {
const page = await context.newPage();
const requests = [];
context.on('request', request => requests.push(request));
await page.goto(server.EMPTY_PAGE);
await page.setContent('<a target=_blank rel=noopener href="/one-style.html">yo</a>');
const [page1] = await Promise.all([
context.waitForEvent('page'),
page.click('a'),
]);
await page1.waitForLoadState();
const urls = requests.map(r => r.url());
expect(urls).toEqual([
server.EMPTY_PAGE,
`${server.PREFIX}/one-style.html`,
`${server.PREFIX}/one-style.css`
]);
});
it('BrowserContext.Events.Response', async ({ context, server }) => {
const page = await context.newPage();
const responses = [];
context.on('response', response => responses.push(response));
await page.goto(server.EMPTY_PAGE);
await page.setContent('<a target=_blank rel=noopener href="/one-style.html">yo</a>');
const [page1] = await Promise.all([
context.waitForEvent('page'),
page.click('a'),
]);
await page1.waitForLoadState();
const urls = responses.map(r => r.url());
expect(urls).toEqual([
server.EMPTY_PAGE,
`${server.PREFIX}/one-style.html`,
`${server.PREFIX}/one-style.css`
]);
});
it('BrowserContext.Events.RequestFailed', async ({ context, server }) => {
server.setRoute('/one-style.css', (_, res) => {
res.setHeader('Content-Type', 'text/css');
res.connection.destroy();
});
const page = await context.newPage();
const failedRequests = [];
context.on('requestfailed', request => failedRequests.push(request));
await page.goto(server.PREFIX + '/one-style.html');
expect(failedRequests.length).toBe(1);
expect(failedRequests[0].url()).toContain('one-style.css');
expect(await failedRequests[0].response()).toBe(null);
expect(failedRequests[0].resourceType()).toBe('stylesheet');
expect(failedRequests[0].frame()).toBeTruthy();
});
it('BrowserContext.Events.RequestFinished', async ({ context, server }) => {
const page = await context.newPage();
const [response] = await Promise.all([
page.goto(server.EMPTY_PAGE),
context.waitForEvent('requestfinished')
]);
const request = response.request();
expect(request.url()).toBe(server.EMPTY_PAGE);
expect(await request.response()).toBeTruthy();
expect(request.frame() === page.mainFrame()).toBe(true);
expect(request.frame().url()).toBe(server.EMPTY_PAGE);
expect(request.failure()).toBe(null);
});
it('should fire events in proper order', async ({ context, server }) => {
const page = await context.newPage();
const events = [];
context.on('request', () => events.push('request'));
context.on('response', () => events.push('response'));
context.on('requestfinished', () => events.push('requestfinished'));
await Promise.all([
page.goto(server.EMPTY_PAGE),
context.waitForEvent('requestfinished')
]);
expect(events).toEqual([
'request',
'response',
'requestfinished',
]);
});
it('should not fire events for favicon or favicon redirects', async ({ context, page, server, browserName, channel, headless }) => {
it.skip(headless && browserName !== 'firefox', 'headless browsers, except firefox, do not request favicons');
it.skip(!headless && browserName === 'webkit' && !channel, 'headed webkit does not have a favicon feature');
const favicon = `/no-cache/favicon.ico`;
const hashedFaviconUrl = `/favicon-hashed.ico`;
const imagePath = `/fakeimage.png`;
const pagePath = `/page.html`;
server.setRedirect(favicon, hashedFaviconUrl);
server.setRoute(pagePath, (_, res) => {
res.end(`
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="icon" type="image/svg+xml" href="${favicon}">
<title>SVG Favicon Test</title>
</head>
<body>
<img src="${imagePath}" alt="my fake image">
</body>
</html>
`);
});
const events = [];
context.on('request', req => events.push(req.url()));
context.on('response', res => events.push(res.url()));
context.on('requestfinished', req => events.push(req.url()));
await Promise.all([
server.waitForRequest(favicon),
server.waitForRequest(hashedFaviconUrl),
page.goto(server.PREFIX + '/page.html'),
]);
expect(events).toEqual(expect.arrayContaining([expect.stringContaining(pagePath)]));
expect(events).toEqual(expect.arrayContaining([expect.stringContaining(imagePath)]));
expect(events).not.toEqual(expect.arrayContaining([expect.stringContaining(favicon)]));
expect(events).not.toEqual(expect.arrayContaining([expect.stringContaining(hashedFaviconUrl)]));
});
| tests/library/browsercontext-network-event.spec.ts | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.0017823659582063556,
0.0004994678893126547,
0.00016414851415902376,
0.00017469700833316892,
0.0005465152789838612
] |
{
"id": 6,
"code_window": [
" ]);\n",
" expect(await page.getByRole('button', { expanded: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<button aria-expanded=\"true\">Hello</button>`,\n",
" ]);\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\n",
" expect(await page.locator(`role=treeitem[expanded]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\" aria-expanded=\"true\">Hello</div>`,\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 181
} | <!DOCTYPE HTML>
<style>
div {
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 100px;
background-color: red;
}
</style>
<div></div>
<script>
document.querySelector('div').animate(
[
{ transform: 'rotate(0deg)' },
{ transform: 'rotate(360deg)' }
], {
duration: 3000,
iterations: Infinity
}
);
</script>
| tests/assets/web-animation.html | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00017341064813081175,
0.00017071620095521212,
0.00016932659491430968,
0.00016941138892434537,
0.0000019055694338021567
] |
{
"id": 6,
"code_window": [
" ]);\n",
" expect(await page.getByRole('button', { expanded: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<button aria-expanded=\"true\">Hello</button>`,\n",
" ]);\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\n",
" expect(await page.locator(`role=treeitem[expanded]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\" aria-expanded=\"true\">Hello</div>`,\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 181
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { createGuid } from 'playwright-core/lib/utils';
import { spawnAsync } from 'playwright-core/lib/utils/spawnAsync';
import type { TestRunnerPlugin } from './';
import type { FullConfig } from '../../types/testReporter';
const GIT_OPERATIONS_TIMEOUT_MS = 1500;
export const gitCommitInfo = (options?: GitCommitInfoPluginOptions): TestRunnerPlugin => {
return {
name: 'playwright:git-commit-info',
setup: async (config: FullConfig, configDir: string) => {
const info = {
...linksFromEnv(),
...options?.info ? options.info : await gitStatusFromCLI(options?.directory || configDir),
timestamp: Date.now(),
};
// Normalize dates
const timestamp = info['revision.timestamp'];
if (timestamp instanceof Date)
info['revision.timestamp'] = timestamp.getTime();
config.metadata = config.metadata || {};
Object.assign(config.metadata, info);
},
};
};
export interface GitCommitInfoPluginOptions {
directory?: string;
info?: Info;
}
export interface Info {
'revision.id'?: string;
'revision.author'?: string;
'revision.email'?: string;
'revision.subject'?: string;
'revision.timestamp'?: number | Date;
'revision.link'?: string;
'ci.link'?: string;
}
const linksFromEnv = (): Pick<Info, 'revision.link' | 'ci.link'> => {
const out: { 'revision.link'?: string; 'ci.link'?: string; } = {};
// Jenkins: https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables
if (process.env.BUILD_URL)
out['ci.link'] = process.env.BUILD_URL;
// GitLab: https://docs.gitlab.com/ee/ci/variables/predefined_variables.html
if (process.env.CI_PROJECT_URL && process.env.CI_COMMIT_SHA)
out['revision.link'] = `${process.env.CI_PROJECT_URL}/-/commit/${process.env.CI_COMMIT_SHA}`;
if (process.env.CI_JOB_URL)
out['ci.link'] = process.env.CI_JOB_URL;
// GitHub: https://docs.github.com/en/actions/learn-github-actions/environment-variables#default-environment-variables
if (process.env.GITHUB_SERVER_URL && process.env.GITHUB_REPOSITORY && process.env.GITHUB_SHA)
out['revision.link'] = `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/commit/${process.env.GITHUB_SHA}`;
if (process.env.GITHUB_SERVER_URL && process.env.GITHUB_REPOSITORY && process.env.GITHUB_RUN_ID)
out['ci.link'] = `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`;
return out;
};
export const gitStatusFromCLI = async (gitDir: string): Promise<Info | undefined> => {
const separator = `:${createGuid().slice(0, 4)}:`;
const { code, stdout } = await spawnAsync(
'git',
['show', '-s', `--format=%H${separator}%s${separator}%an${separator}%ae${separator}%ct`, 'HEAD'],
{ stdio: 'pipe', cwd: gitDir, timeout: GIT_OPERATIONS_TIMEOUT_MS }
);
if (code)
return;
const showOutput = stdout.trim();
const [id, subject, author, email, rawTimestamp] = showOutput.split(separator);
let timestamp: number = Number.parseInt(rawTimestamp, 10);
timestamp = Number.isInteger(timestamp) ? timestamp * 1000 : 0;
return {
'revision.id': id,
'revision.author': author,
'revision.email': email,
'revision.subject': subject,
'revision.timestamp': timestamp,
};
};
| packages/playwright-test/src/plugins/gitCommitInfoPlugin.ts | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00017693467088975012,
0.00017372504225932062,
0.0001698576525086537,
0.00017407431732863188,
0.0000022908752725925297
] |
{
"id": 7,
"code_window": [
" ]);\n",
" expect(await page.locator(`role=button[expanded=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<button>Hi</button>`,\n",
" `<button aria-expanded=\"false\">Bye</button>`,\n",
" ]);\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" expect(await page.locator(`role=treeitem[expanded=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\" aria-expanded=\"true\">Hello</div>`,\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 184
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { test, expect } from './pageTest';
test('should detect roles', async ({ page }) => {
await page.setContent(`
<button>Hello</button>
<select multiple="" size="2"></select>
<select></select>
<h3>Heading</h3>
<details><summary>Hello</summary></details>
<div role="dialog">I am a dialog</div>
`);
expect(await page.locator(`role=button`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hello</button>`,
]);
expect(await page.locator(`role=listbox`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<select multiple="" size="2"></select>`,
]);
expect(await page.locator(`role=combobox`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<select></select>`,
]);
expect(await page.locator(`role=heading`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<h3>Heading</h3>`,
]);
expect(await page.locator(`role=group`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<details><summary>Hello</summary></details>`,
]);
expect(await page.locator(`role=dialog`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="dialog">I am a dialog</div>`,
]);
expect(await page.locator(`role=menuitem`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
]);
expect(await page.getByRole('menuitem').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
]);
});
test('should support selected', async ({ page }) => {
await page.setContent(`
<select>
<option>Hi</option>
<option selected>Hello</option>
</select>
<div>
<div role="option" aria-selected="true">Hi</div>
<div role="option" aria-selected="false">Hello</div>
</div>
`);
expect(await page.locator(`role=option[selected]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<option selected="">Hello</option>`,
`<div role="option" aria-selected="true">Hi</div>`,
]);
expect(await page.locator(`role=option[selected=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<option selected="">Hello</option>`,
`<div role="option" aria-selected="true">Hi</div>`,
]);
expect(await page.getByRole('option', { selected: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<option selected="">Hello</option>`,
`<div role="option" aria-selected="true">Hi</div>`,
]);
expect(await page.locator(`role=option[selected=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<option>Hi</option>`,
`<div role="option" aria-selected="false">Hello</div>`,
]);
expect(await page.getByRole('option', { selected: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<option>Hi</option>`,
`<div role="option" aria-selected="false">Hello</div>`,
]);
});
test('should support checked', async ({ page }) => {
await page.setContent(`
<input type=checkbox>
<input type=checkbox checked>
<input type=checkbox indeterminate>
<div role=checkbox aria-checked="true">Hi</div>
<div role=checkbox aria-checked="false">Hello</div>
<div role=checkbox>Unknown</div>
`);
await page.$eval('[indeterminate]', input => (input as HTMLInputElement).indeterminate = true);
expect(await page.locator(`role=checkbox[checked]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox" checked="">`,
`<div role="checkbox" aria-checked="true">Hi</div>`,
]);
expect(await page.locator(`role=checkbox[checked=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox" checked="">`,
`<div role="checkbox" aria-checked="true">Hi</div>`,
]);
expect(await page.getByRole('checkbox', { checked: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox" checked="">`,
`<div role="checkbox" aria-checked="true">Hi</div>`,
]);
expect(await page.locator(`role=checkbox[checked=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox">`,
`<div role="checkbox" aria-checked="false">Hello</div>`,
`<div role="checkbox">Unknown</div>`,
]);
expect(await page.getByRole('checkbox', { checked: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox">`,
`<div role="checkbox" aria-checked="false">Hello</div>`,
`<div role="checkbox">Unknown</div>`,
]);
expect(await page.locator(`role=checkbox[checked="mixed"]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox" indeterminate="">`,
]);
expect(await page.locator(`role=checkbox`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox">`,
`<input type="checkbox" checked="">`,
`<input type="checkbox" indeterminate="">`,
`<div role="checkbox" aria-checked="true">Hi</div>`,
`<div role="checkbox" aria-checked="false">Hello</div>`,
`<div role="checkbox">Unknown</div>`,
]);
});
test('should support pressed', async ({ page }) => {
await page.setContent(`
<button>Hi</button>
<button aria-pressed="true">Hello</button>
<button aria-pressed="false">Bye</button>
<button aria-pressed="mixed">Mixed</button>
`);
expect(await page.locator(`role=button[pressed]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-pressed="true">Hello</button>`,
]);
expect(await page.locator(`role=button[pressed=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-pressed="true">Hello</button>`,
]);
expect(await page.getByRole('button', { pressed: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-pressed="true">Hello</button>`,
]);
expect(await page.locator(`role=button[pressed=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-pressed="false">Bye</button>`,
]);
expect(await page.getByRole('button', { pressed: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-pressed="false">Bye</button>`,
]);
expect(await page.locator(`role=button[pressed="mixed"]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-pressed="mixed">Mixed</button>`,
]);
expect(await page.locator(`role=button`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-pressed="true">Hello</button>`,
`<button aria-pressed="false">Bye</button>`,
`<button aria-pressed="mixed">Mixed</button>`,
]);
});
test('should support expanded', async ({ page }) => {
await page.setContent(`
<button>Hi</button>
<button aria-expanded="true">Hello</button>
<button aria-expanded="false">Bye</button>
`);
expect(await page.locator(`role=button[expanded]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-expanded="true">Hello</button>`,
]);
expect(await page.locator(`role=button[expanded=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-expanded="true">Hello</button>`,
]);
expect(await page.getByRole('button', { expanded: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-expanded="true">Hello</button>`,
]);
expect(await page.locator(`role=button[expanded=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-expanded="false">Bye</button>`,
]);
expect(await page.getByRole('button', { expanded: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-expanded="false">Bye</button>`,
]);
});
test('should support disabled', async ({ page }) => {
await page.setContent(`
<button>Hi</button>
<button disabled>Bye</button>
<button aria-disabled="true">Hello</button>
<button aria-disabled="false">Oh</button>
<fieldset disabled>
<button>Yay</button>
</fieldset>
`);
expect(await page.locator(`role=button[disabled]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button disabled="">Bye</button>`,
`<button aria-disabled="true">Hello</button>`,
`<button>Yay</button>`,
]);
expect(await page.locator(`role=button[disabled=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button disabled="">Bye</button>`,
`<button aria-disabled="true">Hello</button>`,
`<button>Yay</button>`,
]);
expect(await page.getByRole('button', { disabled: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button disabled="">Bye</button>`,
`<button aria-disabled="true">Hello</button>`,
`<button>Yay</button>`,
]);
expect(await page.locator(`role=button[disabled=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-disabled="false">Oh</button>`,
]);
expect(await page.getByRole('button', { disabled: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-disabled="false">Oh</button>`,
]);
});
test('should support level', async ({ page }) => {
await page.setContent(`
<h1>Hello</h1>
<h3>Hi</h3>
<div role="heading" aria-level="5">Bye</div>
`);
expect(await page.locator(`role=heading[level=1]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<h1>Hello</h1>`,
]);
expect(await page.getByRole('heading', { level: 1 }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<h1>Hello</h1>`,
]);
expect(await page.locator(`role=heading[level=3]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<h3>Hi</h3>`,
]);
expect(await page.getByRole('heading', { level: 3 }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<h3>Hi</h3>`,
]);
expect(await page.locator(`role=heading[level=5]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="heading" aria-level="5">Bye</div>`,
]);
});
test('should filter hidden, unless explicitly asked for', async ({ page }) => {
await page.setContent(`
<button>Hi</button>
<button hidden>Hello</button>
<button aria-hidden="true">Yay</button>
<button aria-hidden="false">Nay</button>
<button style="visibility:hidden">Bye</button>
<div style="visibility:hidden">
<button>Oh</button>
</div>
<div style="visibility:hidden">
<button style="visibility:visible">Still here</button>
</div>
<button style="display:none">Never</button>
<div id=host1></div>
<div id=host2 style="display:none"></div>
<script>
function addButton(host, text) {
const root = host.attachShadow({ mode: 'open' });
const button = document.createElement('button');
button.textContent = text;
root.appendChild(button);
}
addButton(document.getElementById('host1'), 'Shadow1');
addButton(document.getElementById('host2'), 'Shadow2');
</script>
`);
expect(await page.locator(`role=button`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-hidden="false">Nay</button>`,
`<button style="visibility:visible">Still here</button>`,
`<button>Shadow1</button>`,
]);
expect(await page.locator(`role=button[include-hidden]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button hidden="">Hello</button>`,
`<button aria-hidden="true">Yay</button>`,
`<button aria-hidden="false">Nay</button>`,
`<button style="visibility:hidden">Bye</button>`,
`<button>Oh</button>`,
`<button style="visibility:visible">Still here</button>`,
`<button style="display:none">Never</button>`,
`<button>Shadow1</button>`,
`<button>Shadow2</button>`,
]);
expect(await page.locator(`role=button[include-hidden=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button hidden="">Hello</button>`,
`<button aria-hidden="true">Yay</button>`,
`<button aria-hidden="false">Nay</button>`,
`<button style="visibility:hidden">Bye</button>`,
`<button>Oh</button>`,
`<button style="visibility:visible">Still here</button>`,
`<button style="display:none">Never</button>`,
`<button>Shadow1</button>`,
`<button>Shadow2</button>`,
]);
expect(await page.locator(`role=button[include-hidden=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-hidden="false">Nay</button>`,
`<button style="visibility:visible">Still here</button>`,
`<button>Shadow1</button>`,
]);
});
test('should support name', async ({ page }) => {
await page.setContent(`
<div role="button" aria-label=" Hello "></div>
<div role="button" aria-label="Hallo"></div>
<div role="button" aria-label="Hello" aria-hidden="true"></div>
<div role="button" aria-label="123" aria-hidden="true"></div>
<div role="button" aria-label='foo"bar' aria-hidden="true"></div>
`);
expect(await page.locator(`role=button[name="Hello"]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
]);
expect(await page.locator(`role=button[name=" \n Hello "]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
]);
expect(await page.getByRole('button', { name: 'Hello' }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
]);
expect(await page.locator(`role=button[name*="all"]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label="Hallo"></div>`,
]);
expect(await page.locator(`role=button[name=/^H[ae]llo$/]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hallo"></div>`,
]);
expect(await page.getByRole('button', { name: /^H[ae]llo$/ }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hallo"></div>`,
]);
expect(await page.locator(`role=button[name=/h.*o/i]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hallo"></div>`,
]);
expect(await page.getByRole('button', { name: /h.*o/i }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hallo"></div>`,
]);
expect(await page.locator(`role=button[name="Hello"][include-hidden]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hello" aria-hidden="true"></div>`,
]);
expect(await page.getByRole('button', { name: 'Hello', includeHidden: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hello" aria-hidden="true"></div>`,
]);
expect(await page.getByRole('button', { name: 'hello', includeHidden: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hello" aria-hidden="true"></div>`,
]);
expect(await page.locator(`role=button[name=Hello]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
]);
expect(await page.locator(`role=button[name=123][include-hidden]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label="123" aria-hidden="true"></div>`,
]);
expect(await page.getByRole('button', { name: '123', includeHidden: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label="123" aria-hidden="true"></div>`,
]);
});
test('errors', async ({ page }) => {
const e0 = await page.$('role=[bar]').catch(e => e);
expect(e0.message).toContain(`Role must not be empty`);
const e1 = await page.$('role=foo[sElected]').catch(e => e);
expect(e1.message).toContain(`Unknown attribute "sElected", must be one of "checked", "disabled", "expanded", "include-hidden", "level", "name", "pressed", "selected"`);
const e2 = await page.$('role=foo[bar . qux=true]').catch(e => e);
expect(e2.message).toContain(`Unknown attribute "bar.qux"`);
const e3 = await page.$('role=heading[level="bar"]').catch(e => e);
expect(e3.message).toContain(`"level" attribute must be compared to a number`);
const e4 = await page.$('role=checkbox[checked="bar"]').catch(e => e);
expect(e4.message).toContain(`"checked" must be one of true, false, "mixed"`);
const e5 = await page.$('role=checkbox[checked~=true]').catch(e => e);
expect(e5.message).toContain(`cannot use ~= in attribute with non-string matching value`);
const e6 = await page.$('role=button[level=3]').catch(e => e);
expect(e6.message).toContain(`"level" attribute is only supported for roles: "heading", "listitem", "row", "treeitem"`);
const e7 = await page.$('role=button[name]').catch(e => e);
expect(e7.message).toContain(`"name" attribute must have a value`);
});
| tests/page/selectors-role.spec.ts | 1 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.9944581985473633,
0.09534318000078201,
0.00016968572163023055,
0.006476897280663252,
0.2323644757270813
] |
{
"id": 7,
"code_window": [
" ]);\n",
" expect(await page.locator(`role=button[expanded=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<button>Hi</button>`,\n",
" `<button aria-expanded=\"false\">Bye</button>`,\n",
" ]);\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" expect(await page.locator(`role=treeitem[expanded=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\" aria-expanded=\"true\">Hello</div>`,\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 184
} | {
"name": "playwright-firefox",
"version": "1.0.0",
"description": "A high-level API to automate web browsers",
"repository": "github:Microsoft/playwright",
"license": "Apache-2.0"
} | .github/dummy-package-files-for-dependents-analytics/playwright-firefox/package.json | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.0001710949873086065,
0.0001710949873086065,
0.0001710949873086065,
0.0001710949873086065,
0
] |
{
"id": 7,
"code_window": [
" ]);\n",
" expect(await page.locator(`role=button[expanded=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<button>Hi</button>`,\n",
" `<button aria-expanded=\"false\">Bye</button>`,\n",
" ]);\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" expect(await page.locator(`role=treeitem[expanded=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\" aria-expanded=\"true\">Hello</div>`,\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 184
} | /**
* Copyright 2018 Google Inc. All rights reserved.
* Modifications copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { test as it, expect } from './pageTest';
import type { Route } from 'playwright-core';
it('should pick up ongoing navigation', async ({ page, server }) => {
let response = null;
server.setRoute('/one-style.css', (req, res) => response = res);
await Promise.all([
server.waitForRequest('/one-style.css'),
page.goto(server.PREFIX + '/one-style.html', { waitUntil: 'domcontentloaded' }),
]);
const waitPromise = page.waitForLoadState();
response.statusCode = 404;
response.end('Not found');
await waitPromise;
});
it('should respect timeout', async ({ page, server }) => {
server.setRoute('/one-style.css', (req, res) => void 0);
await page.goto(server.PREFIX + '/one-style.html', { waitUntil: 'domcontentloaded' });
const error = await page.waitForLoadState('load', { timeout: 1 }).catch(e => e);
expect(error.message).toContain('page.waitForLoadState: Timeout 1ms exceeded.');
expect(error.stack.split('\n')[1]).toContain(__filename);
});
it('should resolve immediately if loaded', async ({ page, server }) => {
await page.goto(server.PREFIX + '/one-style.html');
await page.waitForLoadState();
});
it('should throw for bad state', async ({ page, server }) => {
await page.goto(server.PREFIX + '/one-style.html');
// @ts-expect-error 'bad' is not a valid load state
const error = await page.waitForLoadState('bad').catch(e => e);
expect(error.message).toContain(`state: expected one of (load|domcontentloaded|networkidle|commit)`);
});
it('should resolve immediately if load state matches', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
server.setRoute('/one-style.css', (req, res) => void 0);
await page.goto(server.PREFIX + '/one-style.html', { waitUntil: 'domcontentloaded' });
await page.waitForLoadState('domcontentloaded');
});
it('should work with pages that have loaded before being connected to', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => window['_popup'] = window.open(document.location.href)),
]);
// The url is about:blank in FF.
// expect(popup.url()).toBe(server.EMPTY_PAGE);
await popup.waitForLoadState();
expect(popup.url()).toBe(server.EMPTY_PAGE);
});
it('should wait for load state of empty url popup', async ({ page, browserName }) => {
const [popup, readyState] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => {
const popup = window.open('');
return popup.document.readyState;
}),
]);
await popup.waitForLoadState();
expect(readyState).toBe(browserName === 'firefox' ? 'uninitialized' : 'complete');
expect(await popup.evaluate(() => document.readyState)).toBe(browserName === 'firefox' ? 'uninitialized' : 'complete');
});
it('should wait for load state of about:blank popup ', async ({ page }) => {
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => window.open('about:blank') && 1),
]);
await popup.waitForLoadState();
expect(await popup.evaluate(() => document.readyState)).toBe('complete');
});
it('should wait for load state of about:blank popup with noopener ', async ({ page }) => {
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(() => window.open('about:blank', null, 'noopener') && 1),
]);
await popup.waitForLoadState();
expect(await popup.evaluate(() => document.readyState)).toBe('complete');
});
it('should wait for load state of popup with network url ', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(url => window.open(url) && 1, server.EMPTY_PAGE),
]);
await popup.waitForLoadState();
expect(await popup.evaluate(() => document.readyState)).toBe('complete');
});
it('should wait for load state of popup with network url and noopener ', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.evaluate(url => window.open(url, null, 'noopener') && 1, server.EMPTY_PAGE),
]);
await popup.waitForLoadState();
expect(await popup.evaluate(() => document.readyState)).toBe('complete');
});
it('should work with clicking target=_blank', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
await page.setContent('<a target=_blank rel="opener" href="/one-style.html">yo</a>');
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.click('a'),
]);
await popup.waitForLoadState();
expect(await popup.evaluate(() => document.readyState)).toBe('complete');
});
it('should wait for load state of newPage', async ({ page, isElectron }) => {
it.fixme(isElectron, 'BrowserContext.newPage does not work in Electron');
const [newPage] = await Promise.all([
page.context().waitForEvent('page'),
page.context().newPage(),
]);
await newPage.waitForLoadState();
expect(await newPage.evaluate(() => document.readyState)).toBe('complete');
});
it('should resolve after popup load', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
// Stall the 'load' by delaying css.
let cssResponse;
server.setRoute('/one-style.css', (req, res) => cssResponse = res);
const [popup] = await Promise.all([
page.waitForEvent('popup'),
server.waitForRequest('/one-style.css'),
page.evaluate(url => window['popup'] = window.open(url), server.PREFIX + '/one-style.html'),
]);
let resolved = false;
const loadSatePromise = popup.waitForLoadState().then(() => resolved = true);
// Round trips!
for (let i = 0; i < 5; i++)
await page.evaluate('window');
expect(resolved).toBe(false);
cssResponse.end('');
await loadSatePromise;
expect(resolved).toBe(true);
expect(popup.url()).toBe(server.PREFIX + '/one-style.html');
});
it('should work for frame', async ({ page, server }) => {
await page.goto(server.PREFIX + '/frames/one-frame.html');
const frame = page.frames()[1];
const requestPromise = new Promise<Route>(resolve => page.route(server.PREFIX + '/one-style.css', resolve));
await frame.goto(server.PREFIX + '/one-style.html', { waitUntil: 'domcontentloaded' });
const request = await requestPromise;
let resolved = false;
const loadPromise = frame.waitForLoadState().then(() => resolved = true);
// give the promise a chance to resolve, even though it shouldn't
await page.evaluate('1');
expect(resolved).toBe(false);
request.continue();
await loadPromise;
});
it('should work with javascript: iframe', async ({ page, server, browserName }) => {
it.fixme(browserName === 'firefox', 'no load event');
await page.goto(server.EMPTY_PAGE);
await page.setContent(`<iframe src="javascript:false"></iframe>`, { waitUntil: 'commit' });
await page.waitForLoadState('domcontentloaded');
await page.waitForLoadState('load');
await page.waitForLoadState('networkidle');
});
it('should work with broken data-url iframe', async ({ page, server }) => {
await page.goto(server.EMPTY_PAGE);
await page.setContent(`<iframe src="data:text/html"></iframe>`, { waitUntil: 'commit' });
await page.waitForLoadState('domcontentloaded');
await page.waitForLoadState('load');
await page.waitForLoadState('networkidle');
});
it('should work with broken blob-url iframe', async ({ page, server, browserName }) => {
it.fixme(browserName === 'chromium', 'no load event');
it.fixme(browserName === 'firefox', 'no load event');
await page.goto(server.EMPTY_PAGE);
await page.setContent(`<iframe src="blob:"></iframe>`, { waitUntil: 'commit' });
await page.waitForLoadState('domcontentloaded');
await page.waitForLoadState('load');
await page.waitForLoadState('networkidle');
});
| tests/page/page-wait-for-load-state.spec.ts | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.0001887709804577753,
0.00017094009672291577,
0.00016278529074043036,
0.0001679378910921514,
0.0000071448212111135945
] |
{
"id": 7,
"code_window": [
" ]);\n",
" expect(await page.locator(`role=button[expanded=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<button>Hi</button>`,\n",
" `<button aria-expanded=\"false\">Bye</button>`,\n",
" ]);\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" expect(await page.locator(`role=treeitem[expanded=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\" aria-expanded=\"true\">Hello</div>`,\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 184
} | <!--
Copyright (c) Microsoft Corporation.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/png" sizes="32x32" href="/icon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/icon-16x16.png">
<link rel="manifest" href="/manifest.webmanifest">
<title>Playwright Inspector</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/index.tsx"></script>
</body>
</html>
| packages/recorder/index.html | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.0001775650744093582,
0.00017462100367993116,
0.00017155484238173813,
0.00017468204896431416,
0.000002506987357264734
] |
{
"id": 8,
"code_window": [
" ]);\n",
" expect(await page.getByRole('button', { expanded: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<button>Hi</button>`,\n",
" `<button aria-expanded=\"false\">Bye</button>`,\n",
" ]);\n",
"});\n",
"\n",
"test('should support disabled', async ({ page }) => {\n",
" await page.setContent(`\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(await page.getByRole('treeitem', { expanded: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\" aria-expanded=\"true\">Hello</div>`,\n",
" ]);\n",
"\n",
" expect(await page.locator(`role=treeitem[expanded=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\" aria-expanded=\"false\">Bye</div>`,\n",
" ]);\n",
" expect(await page.getByRole('treeitem', { expanded: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\" aria-expanded=\"false\">Bye</div>`,\n",
" ]);\n",
"\n",
" // Workaround for expanded=\"none\".\n",
" expect(await page.locator(`[role=treeitem]:not([aria-expanded])`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\">Hi</div>`,\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 188
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { SelectorEngine, SelectorRoot } from './selectorEngine';
import { matchesAttributePart } from './selectorUtils';
import { getAriaChecked, getAriaDisabled, getAriaExpanded, getAriaLevel, getAriaPressed, getAriaRole, getAriaSelected, getElementAccessibleName, isElementHiddenForAria, kAriaCheckedRoles, kAriaExpandedRoles, kAriaLevelRoles, kAriaPressedRoles, kAriaSelectedRoles } from './roleUtils';
import { parseAttributeSelector, type AttributeSelectorPart, type AttributeSelectorOperator } from '../isomorphic/selectorParser';
const kSupportedAttributes = ['selected', 'checked', 'pressed', 'expanded', 'level', 'disabled', 'name', 'include-hidden'];
kSupportedAttributes.sort();
function validateSupportedRole(attr: string, roles: string[], role: string) {
if (!roles.includes(role))
throw new Error(`"${attr}" attribute is only supported for roles: ${roles.slice().sort().map(role => `"${role}"`).join(', ')}`);
}
function validateSupportedValues(attr: AttributeSelectorPart, values: any[]) {
if (attr.op !== '<truthy>' && !values.includes(attr.value))
throw new Error(`"${attr.name}" must be one of ${values.map(v => JSON.stringify(v)).join(', ')}`);
}
function validateSupportedOp(attr: AttributeSelectorPart, ops: AttributeSelectorOperator[]) {
if (!ops.includes(attr.op))
throw new Error(`"${attr.name}" does not support "${attr.op}" matcher`);
}
function validateAttributes(attrs: AttributeSelectorPart[], role: string) {
for (const attr of attrs) {
switch (attr.name) {
case 'checked': {
validateSupportedRole(attr.name, kAriaCheckedRoles, role);
validateSupportedValues(attr, [true, false, 'mixed']);
validateSupportedOp(attr, ['<truthy>', '=']);
if (attr.op === '<truthy>') {
// Do not match "mixed" in "option[checked]".
attr.op = '=';
attr.value = true;
}
break;
}
case 'pressed': {
validateSupportedRole(attr.name, kAriaPressedRoles, role);
validateSupportedValues(attr, [true, false, 'mixed']);
validateSupportedOp(attr, ['<truthy>', '=']);
if (attr.op === '<truthy>') {
// Do not match "mixed" in "button[pressed]".
attr.op = '=';
attr.value = true;
}
break;
}
case 'selected': {
validateSupportedRole(attr.name, kAriaSelectedRoles, role);
validateSupportedValues(attr, [true, false]);
validateSupportedOp(attr, ['<truthy>', '=']);
break;
}
case 'expanded': {
validateSupportedRole(attr.name, kAriaExpandedRoles, role);
validateSupportedValues(attr, [true, false]);
validateSupportedOp(attr, ['<truthy>', '=']);
break;
}
case 'level': {
validateSupportedRole(attr.name, kAriaLevelRoles, role);
// Level is a number, convert it from string.
if (typeof attr.value === 'string')
attr.value = +attr.value;
if (attr.op !== '=' || typeof attr.value !== 'number' || Number.isNaN(attr.value))
throw new Error(`"level" attribute must be compared to a number`);
break;
}
case 'disabled': {
validateSupportedValues(attr, [true, false]);
validateSupportedOp(attr, ['<truthy>', '=']);
break;
}
case 'name': {
if (attr.op === '<truthy>')
throw new Error(`"name" attribute must have a value`);
if (typeof attr.value !== 'string' && !(attr.value instanceof RegExp))
throw new Error(`"name" attribute must be a string or a regular expression`);
break;
}
case 'include-hidden': {
validateSupportedValues(attr, [true, false]);
validateSupportedOp(attr, ['<truthy>', '=']);
break;
}
default: {
throw new Error(`Unknown attribute "${attr.name}", must be one of ${kSupportedAttributes.map(a => `"${a}"`).join(', ')}.`);
}
}
}
}
export function createRoleEngine(internal: boolean): SelectorEngine {
const queryAll = (scope: SelectorRoot, selector: string): Element[] => {
const parsed = parseAttributeSelector(selector, true);
const role = parsed.name.toLowerCase();
if (!role)
throw new Error(`Role must not be empty`);
validateAttributes(parsed.attributes, role);
const hiddenCache = new Map<Element, boolean>();
const result: Element[] = [];
const match = (element: Element) => {
if (getAriaRole(element) !== role)
return;
let includeHidden = false; // By default, hidden elements are excluded.
let nameAttr: AttributeSelectorPart | undefined;
for (const attr of parsed.attributes) {
if (attr.name === 'include-hidden') {
includeHidden = attr.op === '<truthy>' || !!attr.value;
continue;
}
if (attr.name === 'name') {
nameAttr = attr;
continue;
}
let actual;
switch (attr.name) {
case 'selected': actual = getAriaSelected(element); break;
case 'checked': actual = getAriaChecked(element); break;
case 'pressed': actual = getAriaPressed(element); break;
case 'expanded': actual = getAriaExpanded(element); break;
case 'level': actual = getAriaLevel(element); break;
case 'disabled': actual = getAriaDisabled(element); break;
}
if (!matchesAttributePart(actual, attr))
return;
}
if (!includeHidden) {
const isHidden = isElementHiddenForAria(element, hiddenCache);
if (isHidden)
return;
}
if (nameAttr !== undefined) {
// Always normalize whitespace in the accessible name.
const accessibleName = getElementAccessibleName(element, includeHidden, hiddenCache).trim().replace(/\s+/g, ' ');
if (typeof nameAttr.value === 'string')
nameAttr.value = nameAttr.value.trim().replace(/\s+/g, ' ');
// internal:role assumes that [name="foo"i] also means substring.
if (internal && !nameAttr.caseSensitive && nameAttr.op === '=')
nameAttr.op = '*=';
if (!matchesAttributePart(accessibleName, nameAttr))
return;
}
result.push(element);
};
const query = (root: Element | ShadowRoot | Document) => {
const shadows: ShadowRoot[] = [];
if ((root as Element).shadowRoot)
shadows.push((root as Element).shadowRoot!);
for (const element of root.querySelectorAll('*')) {
match(element);
if (element.shadowRoot)
shadows.push(element.shadowRoot);
}
shadows.forEach(query);
};
query(scope);
return result;
};
return { queryAll };
}
| packages/playwright-core/src/server/injected/roleSelectorEngine.ts | 1 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.000452364154625684,
0.00020979582041036338,
0.0001644964941078797,
0.00017393426969647408,
0.00007272170478245243
] |
{
"id": 8,
"code_window": [
" ]);\n",
" expect(await page.getByRole('button', { expanded: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<button>Hi</button>`,\n",
" `<button aria-expanded=\"false\">Bye</button>`,\n",
" ]);\n",
"});\n",
"\n",
"test('should support disabled', async ({ page }) => {\n",
" await page.setContent(`\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(await page.getByRole('treeitem', { expanded: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\" aria-expanded=\"true\">Hello</div>`,\n",
" ]);\n",
"\n",
" expect(await page.locator(`role=treeitem[expanded=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\" aria-expanded=\"false\">Bye</div>`,\n",
" ]);\n",
" expect(await page.getByRole('treeitem', { expanded: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\" aria-expanded=\"false\">Bye</div>`,\n",
" ]);\n",
"\n",
" // Workaround for expanded=\"none\".\n",
" expect(await page.locator(`[role=treeitem]:not([aria-expanded])`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\">Hi</div>`,\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 188
} | {
"extends": "@vue/tsconfig/tsconfig.web.json",
"include": ["src/**/*", "src/**/*.vue"],
"exclude": ["src/**/*.spec.*/*"],
"compilerOptions": {
"composite": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}
| tests/components/ct-vue-cli/tsconfig.app.json | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00017487617151346058,
0.00017134274821728468,
0.00016780932492110878,
0.00017134274821728468,
0.000003533423296175897
] |
{
"id": 8,
"code_window": [
" ]);\n",
" expect(await page.getByRole('button', { expanded: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<button>Hi</button>`,\n",
" `<button aria-expanded=\"false\">Bye</button>`,\n",
" ]);\n",
"});\n",
"\n",
"test('should support disabled', async ({ page }) => {\n",
" await page.setContent(`\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(await page.getByRole('treeitem', { expanded: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\" aria-expanded=\"true\">Hello</div>`,\n",
" ]);\n",
"\n",
" expect(await page.locator(`role=treeitem[expanded=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\" aria-expanded=\"false\">Bye</div>`,\n",
" ]);\n",
" expect(await page.getByRole('treeitem', { expanded: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\" aria-expanded=\"false\">Bye</div>`,\n",
" ]);\n",
"\n",
" // Workaround for expanded=\"none\".\n",
" expect(await page.locator(`[role=treeitem]:not([aria-expanded])`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\">Hi</div>`,\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 188
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import '../src/common.css';
import '../src/theme.ts';
import '../src/third_party/vscode/codicon.css';
| packages/web/playwright/index.ts | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.0001765497581800446,
0.0001759688020683825,
0.0001753878459567204,
0.0001759688020683825,
5.809561116620898e-7
] |
{
"id": 8,
"code_window": [
" ]);\n",
" expect(await page.getByRole('button', { expanded: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<button>Hi</button>`,\n",
" `<button aria-expanded=\"false\">Bye</button>`,\n",
" ]);\n",
"});\n",
"\n",
"test('should support disabled', async ({ page }) => {\n",
" await page.setContent(`\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(await page.getByRole('treeitem', { expanded: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\" aria-expanded=\"true\">Hello</div>`,\n",
" ]);\n",
"\n",
" expect(await page.locator(`role=treeitem[expanded=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\" aria-expanded=\"false\">Bye</div>`,\n",
" ]);\n",
" expect(await page.getByRole('treeitem', { expanded: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\" aria-expanded=\"false\">Bye</div>`,\n",
" ]);\n",
"\n",
" // Workaround for expanded=\"none\".\n",
" expect(await page.locator(`[role=treeitem]:not([aria-expanded])`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([\n",
" `<div role=\"treeitem\">Hi</div>`,\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "replace",
"edit_start_line_idx": 188
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import childProcess from 'child_process';
import http from 'http';
import path from 'path';
import type net from 'net';
import { contextTest, expect } from '../config/browserTest';
import type { Page, Browser } from 'playwright-core';
class OutOfProcessPlaywrightServer {
private _driverProcess: childProcess.ChildProcess;
private _receivedPortPromise: Promise<string>;
constructor(port: number, proxyPort: number) {
this._driverProcess = childProcess.fork(path.join(__dirname, '..', '..', 'packages', 'playwright-core', 'lib', 'cli', 'cli.js'), ['run-server', '--port', port.toString()], {
stdio: 'pipe',
detached: true,
env: {
...process.env
}
});
this._driverProcess.unref();
this._receivedPortPromise = new Promise<string>((resolve, reject) => {
this._driverProcess.stdout.on('data', (data: Buffer) => {
const prefix = 'Listening on ';
const line = data.toString();
if (line.startsWith(prefix))
resolve(line.substr(prefix.length));
});
this._driverProcess.stderr.on('data', (data: Buffer) => {
console.log(data.toString());
});
this._driverProcess.on('exit', () => reject());
});
}
async kill() {
const waitForExit = new Promise<void>(resolve => this._driverProcess.on('exit', () => resolve()));
this._driverProcess.kill('SIGKILL');
await waitForExit;
}
public async wsEndpoint(): Promise<string> {
return await this._receivedPortPromise;
}
}
const it = contextTest.extend<{ pageFactory: (redirectPortForTest?: number) => Promise<Page> }>({
pageFactory: async ({ browserType, browserName, channel }, run, testInfo) => {
const playwrightServers: OutOfProcessPlaywrightServer[] = [];
const browsers: Browser[] = [];
await run(async (redirectPortForTest?: number): Promise<Page> => {
const server = new OutOfProcessPlaywrightServer(0, 3200 + testInfo.workerIndex);
playwrightServers.push(server);
const browser = await browserType.connect({
wsEndpoint: await server.wsEndpoint() + '?proxy=*&browser=' + browserName,
headers: { 'x-playwright-launch-options': JSON.stringify({ channel }) },
__testHookRedirectPortForwarding: redirectPortForTest,
} as any);
browsers.push(browser);
return await browser.newPage();
});
for (const playwrightServer of playwrightServers)
await playwrightServer.kill();
await Promise.all(browsers.map(async browser => {
if (browser.isConnected())
await new Promise(f => browser.once('disconnected', f));
}));
},
});
it.fixme(({ platform, browserName }) => browserName === 'webkit' && platform === 'win32');
it.skip(({ mode }) => mode !== 'default');
async function startTestServer() {
const server = http.createServer((req: http.IncomingMessage, res: http.ServerResponse) => {
res.end('<html><body>from-retargeted-server</body></html>');
});
await new Promise<void>(resolve => server.listen(0, resolve));
return {
testServerPort: (server.address() as net.AddressInfo).port,
stopTestServer: () => server.close()
};
}
it('should forward non-forwarded requests', async ({ pageFactory, server }) => {
let reachedOriginalTarget = false;
server.setRoute('/foo.html', async (req, res) => {
reachedOriginalTarget = true;
res.end('<html><body>original-target</body></html>');
});
const page = await pageFactory();
await page.goto(server.PREFIX + '/foo.html');
expect(await page.content()).toContain('original-target');
expect(reachedOriginalTarget).toBe(true);
});
it('should proxy localhost requests @smoke', async ({ pageFactory, server, browserName, platform }, workerInfo) => {
it.skip(browserName === 'webkit' && platform === 'darwin');
const { testServerPort, stopTestServer } = await startTestServer();
let reachedOriginalTarget = false;
server.setRoute('/foo.html', async (req, res) => {
reachedOriginalTarget = true;
res.end('<html><body></body></html>');
});
const examplePort = 20_000 + workerInfo.workerIndex * 3;
const page = await pageFactory(testServerPort);
await page.goto(`http://127.0.0.1:${examplePort}/foo.html`);
expect(await page.content()).toContain('from-retargeted-server');
expect(reachedOriginalTarget).toBe(false);
stopTestServer();
});
it('should proxy localhost requests from fetch api', async ({ pageFactory, server, browserName, platform }, workerInfo) => {
it.skip(browserName === 'webkit' && platform === 'darwin');
const { testServerPort, stopTestServer } = await startTestServer();
let reachedOriginalTarget = false;
server.setRoute('/foo.html', async (req, res) => {
reachedOriginalTarget = true;
res.end('<html><body></body></html>');
});
const examplePort = 20_000 + workerInfo.workerIndex * 3;
const page = await pageFactory(testServerPort);
const response = await page.request.get(`http://127.0.0.1:${examplePort}/foo.html`);
expect(response.status()).toBe(200);
expect(await response.text()).toContain('from-retargeted-server');
expect(reachedOriginalTarget).toBe(false);
stopTestServer();
});
it('should proxy local.playwright requests', async ({ pageFactory, server, browserName }, workerInfo) => {
const { testServerPort, stopTestServer } = await startTestServer();
let reachedOriginalTarget = false;
server.setRoute('/foo.html', async (req, res) => {
reachedOriginalTarget = true;
res.end('<html><body></body></html>');
});
const examplePort = 20_000 + workerInfo.workerIndex * 3;
const page = await pageFactory(testServerPort);
await page.goto(`http://local.playwright:${examplePort}/foo.html`);
expect(await page.content()).toContain('from-retargeted-server');
expect(reachedOriginalTarget).toBe(false);
stopTestServer();
});
it('should lead to the error page for forwarded requests when the connection is refused', async ({ pageFactory, browserName }, workerInfo) => {
const examplePort = 20_000 + workerInfo.workerIndex * 3;
const page = await pageFactory();
const error = await page.goto(`http://127.0.0.1:${examplePort}`).catch(e => e);
if (browserName === 'chromium')
expect(error.message).toContain('net::ERR_SOCKS_CONNECTION_FAILED at http://127.0.0.1:20');
else if (browserName === 'webkit')
expect(error.message).toBeTruthy();
else if (browserName === 'firefox')
expect(error.message.includes('NS_ERROR_NET_RESET') || error.message.includes('NS_ERROR_CONNECTION_REFUSED')).toBe(true);
});
| tests/library/port-forwarding-server.spec.ts | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.0025024916976690292,
0.0006557113956660032,
0.00016532029258087277,
0.0001747600472299382,
0.0008046033908613026
] |
{
"id": 9,
"code_window": [
" expect(e6.message).toContain(`\"level\" attribute is only supported for roles: \"heading\", \"listitem\", \"row\", \"treeitem\"`);\n",
"\n",
" const e7 = await page.$('role=button[name]').catch(e => e);\n",
" expect(e7.message).toContain(`\"name\" attribute must have a value`);\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
" const e8 = await page.$('role=treeitem[expanded=\"none\"]').catch(e => e);\n",
" expect(e8.message).toContain(`\"expanded\" must be one of true, false`);\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "add",
"edit_start_line_idx": 405
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { test, expect } from './pageTest';
test('should detect roles', async ({ page }) => {
await page.setContent(`
<button>Hello</button>
<select multiple="" size="2"></select>
<select></select>
<h3>Heading</h3>
<details><summary>Hello</summary></details>
<div role="dialog">I am a dialog</div>
`);
expect(await page.locator(`role=button`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hello</button>`,
]);
expect(await page.locator(`role=listbox`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<select multiple="" size="2"></select>`,
]);
expect(await page.locator(`role=combobox`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<select></select>`,
]);
expect(await page.locator(`role=heading`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<h3>Heading</h3>`,
]);
expect(await page.locator(`role=group`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<details><summary>Hello</summary></details>`,
]);
expect(await page.locator(`role=dialog`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="dialog">I am a dialog</div>`,
]);
expect(await page.locator(`role=menuitem`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
]);
expect(await page.getByRole('menuitem').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
]);
});
test('should support selected', async ({ page }) => {
await page.setContent(`
<select>
<option>Hi</option>
<option selected>Hello</option>
</select>
<div>
<div role="option" aria-selected="true">Hi</div>
<div role="option" aria-selected="false">Hello</div>
</div>
`);
expect(await page.locator(`role=option[selected]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<option selected="">Hello</option>`,
`<div role="option" aria-selected="true">Hi</div>`,
]);
expect(await page.locator(`role=option[selected=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<option selected="">Hello</option>`,
`<div role="option" aria-selected="true">Hi</div>`,
]);
expect(await page.getByRole('option', { selected: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<option selected="">Hello</option>`,
`<div role="option" aria-selected="true">Hi</div>`,
]);
expect(await page.locator(`role=option[selected=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<option>Hi</option>`,
`<div role="option" aria-selected="false">Hello</div>`,
]);
expect(await page.getByRole('option', { selected: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<option>Hi</option>`,
`<div role="option" aria-selected="false">Hello</div>`,
]);
});
test('should support checked', async ({ page }) => {
await page.setContent(`
<input type=checkbox>
<input type=checkbox checked>
<input type=checkbox indeterminate>
<div role=checkbox aria-checked="true">Hi</div>
<div role=checkbox aria-checked="false">Hello</div>
<div role=checkbox>Unknown</div>
`);
await page.$eval('[indeterminate]', input => (input as HTMLInputElement).indeterminate = true);
expect(await page.locator(`role=checkbox[checked]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox" checked="">`,
`<div role="checkbox" aria-checked="true">Hi</div>`,
]);
expect(await page.locator(`role=checkbox[checked=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox" checked="">`,
`<div role="checkbox" aria-checked="true">Hi</div>`,
]);
expect(await page.getByRole('checkbox', { checked: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox" checked="">`,
`<div role="checkbox" aria-checked="true">Hi</div>`,
]);
expect(await page.locator(`role=checkbox[checked=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox">`,
`<div role="checkbox" aria-checked="false">Hello</div>`,
`<div role="checkbox">Unknown</div>`,
]);
expect(await page.getByRole('checkbox', { checked: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox">`,
`<div role="checkbox" aria-checked="false">Hello</div>`,
`<div role="checkbox">Unknown</div>`,
]);
expect(await page.locator(`role=checkbox[checked="mixed"]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox" indeterminate="">`,
]);
expect(await page.locator(`role=checkbox`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<input type="checkbox">`,
`<input type="checkbox" checked="">`,
`<input type="checkbox" indeterminate="">`,
`<div role="checkbox" aria-checked="true">Hi</div>`,
`<div role="checkbox" aria-checked="false">Hello</div>`,
`<div role="checkbox">Unknown</div>`,
]);
});
test('should support pressed', async ({ page }) => {
await page.setContent(`
<button>Hi</button>
<button aria-pressed="true">Hello</button>
<button aria-pressed="false">Bye</button>
<button aria-pressed="mixed">Mixed</button>
`);
expect(await page.locator(`role=button[pressed]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-pressed="true">Hello</button>`,
]);
expect(await page.locator(`role=button[pressed=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-pressed="true">Hello</button>`,
]);
expect(await page.getByRole('button', { pressed: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-pressed="true">Hello</button>`,
]);
expect(await page.locator(`role=button[pressed=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-pressed="false">Bye</button>`,
]);
expect(await page.getByRole('button', { pressed: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-pressed="false">Bye</button>`,
]);
expect(await page.locator(`role=button[pressed="mixed"]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-pressed="mixed">Mixed</button>`,
]);
expect(await page.locator(`role=button`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-pressed="true">Hello</button>`,
`<button aria-pressed="false">Bye</button>`,
`<button aria-pressed="mixed">Mixed</button>`,
]);
});
test('should support expanded', async ({ page }) => {
await page.setContent(`
<button>Hi</button>
<button aria-expanded="true">Hello</button>
<button aria-expanded="false">Bye</button>
`);
expect(await page.locator(`role=button[expanded]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-expanded="true">Hello</button>`,
]);
expect(await page.locator(`role=button[expanded=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-expanded="true">Hello</button>`,
]);
expect(await page.getByRole('button', { expanded: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button aria-expanded="true">Hello</button>`,
]);
expect(await page.locator(`role=button[expanded=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-expanded="false">Bye</button>`,
]);
expect(await page.getByRole('button', { expanded: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-expanded="false">Bye</button>`,
]);
});
test('should support disabled', async ({ page }) => {
await page.setContent(`
<button>Hi</button>
<button disabled>Bye</button>
<button aria-disabled="true">Hello</button>
<button aria-disabled="false">Oh</button>
<fieldset disabled>
<button>Yay</button>
</fieldset>
`);
expect(await page.locator(`role=button[disabled]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button disabled="">Bye</button>`,
`<button aria-disabled="true">Hello</button>`,
`<button>Yay</button>`,
]);
expect(await page.locator(`role=button[disabled=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button disabled="">Bye</button>`,
`<button aria-disabled="true">Hello</button>`,
`<button>Yay</button>`,
]);
expect(await page.getByRole('button', { disabled: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button disabled="">Bye</button>`,
`<button aria-disabled="true">Hello</button>`,
`<button>Yay</button>`,
]);
expect(await page.locator(`role=button[disabled=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-disabled="false">Oh</button>`,
]);
expect(await page.getByRole('button', { disabled: false }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-disabled="false">Oh</button>`,
]);
});
test('should support level', async ({ page }) => {
await page.setContent(`
<h1>Hello</h1>
<h3>Hi</h3>
<div role="heading" aria-level="5">Bye</div>
`);
expect(await page.locator(`role=heading[level=1]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<h1>Hello</h1>`,
]);
expect(await page.getByRole('heading', { level: 1 }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<h1>Hello</h1>`,
]);
expect(await page.locator(`role=heading[level=3]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<h3>Hi</h3>`,
]);
expect(await page.getByRole('heading', { level: 3 }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<h3>Hi</h3>`,
]);
expect(await page.locator(`role=heading[level=5]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="heading" aria-level="5">Bye</div>`,
]);
});
test('should filter hidden, unless explicitly asked for', async ({ page }) => {
await page.setContent(`
<button>Hi</button>
<button hidden>Hello</button>
<button aria-hidden="true">Yay</button>
<button aria-hidden="false">Nay</button>
<button style="visibility:hidden">Bye</button>
<div style="visibility:hidden">
<button>Oh</button>
</div>
<div style="visibility:hidden">
<button style="visibility:visible">Still here</button>
</div>
<button style="display:none">Never</button>
<div id=host1></div>
<div id=host2 style="display:none"></div>
<script>
function addButton(host, text) {
const root = host.attachShadow({ mode: 'open' });
const button = document.createElement('button');
button.textContent = text;
root.appendChild(button);
}
addButton(document.getElementById('host1'), 'Shadow1');
addButton(document.getElementById('host2'), 'Shadow2');
</script>
`);
expect(await page.locator(`role=button`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-hidden="false">Nay</button>`,
`<button style="visibility:visible">Still here</button>`,
`<button>Shadow1</button>`,
]);
expect(await page.locator(`role=button[include-hidden]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button hidden="">Hello</button>`,
`<button aria-hidden="true">Yay</button>`,
`<button aria-hidden="false">Nay</button>`,
`<button style="visibility:hidden">Bye</button>`,
`<button>Oh</button>`,
`<button style="visibility:visible">Still here</button>`,
`<button style="display:none">Never</button>`,
`<button>Shadow1</button>`,
`<button>Shadow2</button>`,
]);
expect(await page.locator(`role=button[include-hidden=true]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button hidden="">Hello</button>`,
`<button aria-hidden="true">Yay</button>`,
`<button aria-hidden="false">Nay</button>`,
`<button style="visibility:hidden">Bye</button>`,
`<button>Oh</button>`,
`<button style="visibility:visible">Still here</button>`,
`<button style="display:none">Never</button>`,
`<button>Shadow1</button>`,
`<button>Shadow2</button>`,
]);
expect(await page.locator(`role=button[include-hidden=false]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<button>Hi</button>`,
`<button aria-hidden="false">Nay</button>`,
`<button style="visibility:visible">Still here</button>`,
`<button>Shadow1</button>`,
]);
});
test('should support name', async ({ page }) => {
await page.setContent(`
<div role="button" aria-label=" Hello "></div>
<div role="button" aria-label="Hallo"></div>
<div role="button" aria-label="Hello" aria-hidden="true"></div>
<div role="button" aria-label="123" aria-hidden="true"></div>
<div role="button" aria-label='foo"bar' aria-hidden="true"></div>
`);
expect(await page.locator(`role=button[name="Hello"]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
]);
expect(await page.locator(`role=button[name=" \n Hello "]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
]);
expect(await page.getByRole('button', { name: 'Hello' }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
]);
expect(await page.locator(`role=button[name*="all"]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label="Hallo"></div>`,
]);
expect(await page.locator(`role=button[name=/^H[ae]llo$/]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hallo"></div>`,
]);
expect(await page.getByRole('button', { name: /^H[ae]llo$/ }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hallo"></div>`,
]);
expect(await page.locator(`role=button[name=/h.*o/i]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hallo"></div>`,
]);
expect(await page.getByRole('button', { name: /h.*o/i }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hallo"></div>`,
]);
expect(await page.locator(`role=button[name="Hello"][include-hidden]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hello" aria-hidden="true"></div>`,
]);
expect(await page.getByRole('button', { name: 'Hello', includeHidden: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hello" aria-hidden="true"></div>`,
]);
expect(await page.getByRole('button', { name: 'hello', includeHidden: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
`<div role="button" aria-label="Hello" aria-hidden="true"></div>`,
]);
expect(await page.locator(`role=button[name=Hello]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label=" Hello "></div>`,
]);
expect(await page.locator(`role=button[name=123][include-hidden]`).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label="123" aria-hidden="true"></div>`,
]);
expect(await page.getByRole('button', { name: '123', includeHidden: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
`<div role="button" aria-label="123" aria-hidden="true"></div>`,
]);
});
test('errors', async ({ page }) => {
const e0 = await page.$('role=[bar]').catch(e => e);
expect(e0.message).toContain(`Role must not be empty`);
const e1 = await page.$('role=foo[sElected]').catch(e => e);
expect(e1.message).toContain(`Unknown attribute "sElected", must be one of "checked", "disabled", "expanded", "include-hidden", "level", "name", "pressed", "selected"`);
const e2 = await page.$('role=foo[bar . qux=true]').catch(e => e);
expect(e2.message).toContain(`Unknown attribute "bar.qux"`);
const e3 = await page.$('role=heading[level="bar"]').catch(e => e);
expect(e3.message).toContain(`"level" attribute must be compared to a number`);
const e4 = await page.$('role=checkbox[checked="bar"]').catch(e => e);
expect(e4.message).toContain(`"checked" must be one of true, false, "mixed"`);
const e5 = await page.$('role=checkbox[checked~=true]').catch(e => e);
expect(e5.message).toContain(`cannot use ~= in attribute with non-string matching value`);
const e6 = await page.$('role=button[level=3]').catch(e => e);
expect(e6.message).toContain(`"level" attribute is only supported for roles: "heading", "listitem", "row", "treeitem"`);
const e7 = await page.$('role=button[name]').catch(e => e);
expect(e7.message).toContain(`"name" attribute must have a value`);
});
| tests/page/selectors-role.spec.ts | 1 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.9984605312347412,
0.02518865466117859,
0.00016569589206483215,
0.00020696264982689172,
0.1539044976234436
] |
{
"id": 9,
"code_window": [
" expect(e6.message).toContain(`\"level\" attribute is only supported for roles: \"heading\", \"listitem\", \"row\", \"treeitem\"`);\n",
"\n",
" const e7 = await page.$('role=button[name]').catch(e => e);\n",
" expect(e7.message).toContain(`\"name\" attribute must have a value`);\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
" const e8 = await page.$('role=treeitem[expanded=\"none\"]').catch(e => e);\n",
" expect(e8.message).toContain(`\"expanded\" must be one of true, false`);\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "add",
"edit_start_line_idx": 405
} | {"version":3,"file":"static/js/787.2f3b90fa.chunk.js","mappings":"2QAAA,IAAIA,EAAEC,EAAEC,EAAEC,EAAEC,EAAE,SAASJ,EAAEC,GAAG,MAAM,CAACI,KAAKL,EAAEM,WAAM,IAASL,GAAG,EAAEA,EAAEM,MAAM,EAAEC,QAAQ,GAAGC,GAAG,MAAMC,OAAOC,KAAKC,MAAM,KAAKF,OAAOG,KAAKC,MAAM,cAAcD,KAAKE,UAAU,QAAQC,EAAE,SAAShB,EAAEC,GAAG,IAAI,GAAGgB,oBAAoBC,oBAAoBC,SAASnB,GAAG,CAAC,GAAG,gBAAgBA,KAAK,2BAA2BoB,MAAM,OAAO,IAAIlB,EAAE,IAAIe,qBAAqB,SAASjB,GAAG,OAAOA,EAAEqB,aAAaC,IAAIrB,MAAM,OAAOC,EAAEqB,QAAQ,CAACC,KAAKxB,EAAEyB,UAAS,IAAKvB,GAAG,MAAMF,MAAM0B,EAAE,SAAS1B,EAAEC,GAAG,IAAIC,EAAE,SAASA,EAAEC,GAAG,aAAaA,EAAEqB,MAAM,WAAWG,SAASC,kBAAkB5B,EAAEG,GAAGF,IAAI4B,oBAAoB,mBAAmB3B,GAAE,GAAI2B,oBAAoB,WAAW3B,GAAE,MAAO4B,iBAAiB,mBAAmB5B,GAAE,GAAI4B,iBAAiB,WAAW5B,GAAE,IAAK6B,EAAE,SAAS/B,GAAG8B,iBAAiB,YAAY,SAAS7B,GAAGA,EAAE+B,WAAWhC,EAAEC,MAAK,IAAKgC,EAAE,SAASjC,EAAEC,EAAEC,GAAG,IAAIC,EAAE,OAAO,SAASC,GAAGH,EAAEK,OAAO,IAAIF,GAAGF,KAAKD,EAAEM,MAAMN,EAAEK,OAAOH,GAAG,IAAIF,EAAEM,YAAO,IAASJ,KAAKA,EAAEF,EAAEK,MAAMN,EAAEC,OAAOiC,GAAG,EAAEC,EAAE,WAAW,MAAM,WAAWR,SAASC,gBAAgB,EAAE,KAAKQ,EAAE,WAAWV,GAAG,SAAS1B,GAAG,IAAIC,EAAED,EAAEqC,UAAUH,EAAEjC,KAAI,IAAKqC,EAAE,WAAW,OAAOJ,EAAE,IAAIA,EAAEC,IAAIC,IAAIL,GAAG,WAAWQ,YAAY,WAAWL,EAAEC,IAAIC,MAAM,OAAO,CAAKI,sBAAkB,OAAON,KAAKO,EAAE,SAASzC,EAAEC,GAAG,IAAIC,EAAEC,EAAEmC,IAAIZ,EAAEtB,EAAE,OAAO8B,EAAE,SAASlC,GAAG,2BAA2BA,EAAEK,OAAO+B,GAAGA,EAAEM,aAAa1C,EAAE2C,UAAUxC,EAAEqC,kBAAkBd,EAAEpB,MAAMN,EAAE2C,UAAUjB,EAAElB,QAAQoC,KAAK5C,GAAGE,GAAE,MAAOiC,EAAEU,OAAOC,aAAaA,YAAYC,kBAAkBD,YAAYC,iBAAiB,0BAA0B,GAAGX,EAAED,EAAE,KAAKnB,EAAE,QAAQkB,IAAIC,GAAGC,KAAKlC,EAAE+B,EAAEjC,EAAE0B,EAAEzB,GAAGkC,GAAGD,EAAEC,GAAGJ,GAAG,SAAS5B,GAAGuB,EAAEtB,EAAE,OAAOF,EAAE+B,EAAEjC,EAAE0B,EAAEzB,GAAG+C,uBAAuB,WAAWA,uBAAuB,WAAWtB,EAAEpB,MAAMwC,YAAYlC,MAAMT,EAAEkC,UAAUnC,GAAE,cAAe+C,GAAE,EAAGC,GAAG,EAAEC,EAAE,SAASnD,EAAEC,GAAGgD,IAAIR,GAAG,SAASzC,GAAGkD,EAAElD,EAAEM,SAAS2C,GAAE,GAAI,IAAI/C,EAAEC,EAAE,SAASF,GAAGiD,GAAG,GAAGlD,EAAEC,IAAIiC,EAAE9B,EAAE,MAAM,GAAG+B,EAAE,EAAEC,EAAE,GAAGE,EAAE,SAAStC,GAAG,IAAIA,EAAEoD,eAAe,CAAC,IAAInD,EAAEmC,EAAE,GAAGjC,EAAEiC,EAAEA,EAAEiB,OAAO,GAAGlB,GAAGnC,EAAE2C,UAAUxC,EAAEwC,UAAU,KAAK3C,EAAE2C,UAAU1C,EAAE0C,UAAU,KAAKR,GAAGnC,EAAEM,MAAM8B,EAAEQ,KAAK5C,KAAKmC,EAAEnC,EAAEM,MAAM8B,EAAE,CAACpC,IAAImC,EAAED,EAAE5B,QAAQ4B,EAAE5B,MAAM6B,EAAED,EAAE1B,QAAQ4B,EAAElC,OAAOiD,EAAEnC,EAAE,eAAesB,GAAGa,IAAIjD,EAAE+B,EAAE9B,EAAE+B,EAAEjC,GAAGyB,GAAG,WAAWyB,EAAEG,cAAchC,IAAIgB,GAAGpC,GAAE,MAAO6B,GAAG,WAAWI,EAAE,EAAEe,GAAG,EAAEhB,EAAE9B,EAAE,MAAM,GAAGF,EAAE+B,EAAE9B,EAAE+B,EAAEjC,QAAQsD,EAAE,CAACC,SAAQ,EAAGC,SAAQ,GAAIC,EAAE,IAAI/C,KAAKgD,EAAE,SAASxD,EAAEC,GAAGJ,IAAIA,EAAEI,EAAEH,EAAEE,EAAED,EAAE,IAAIS,KAAKiD,EAAE/B,qBAAqBgC,MAAMA,EAAE,WAAW,GAAG5D,GAAG,GAAGA,EAAEC,EAAEwD,EAAE,CAAC,IAAItD,EAAE,CAAC0D,UAAU,cAAczD,KAAKL,EAAEwB,KAAKuC,OAAO/D,EAAE+D,OAAOC,WAAWhE,EAAEgE,WAAWrB,UAAU3C,EAAEqC,UAAU4B,gBAAgBjE,EAAEqC,UAAUpC,GAAGE,EAAE+D,SAAS,SAASlE,GAAGA,EAAEI,MAAMD,EAAE,KAAKgE,EAAE,SAASnE,GAAG,GAAGA,EAAEgE,WAAW,CAAC,IAAI/D,GAAGD,EAAEqC,UAAU,KAAK,IAAI1B,KAAKmC,YAAYlC,OAAOZ,EAAEqC,UAAU,eAAerC,EAAEwB,KAAK,SAASxB,EAAEC,GAAG,IAAIC,EAAE,WAAWyD,EAAE3D,EAAEC,GAAGG,KAAKD,EAAE,WAAWC,KAAKA,EAAE,WAAWyB,oBAAoB,YAAY3B,EAAEqD,GAAG1B,oBAAoB,gBAAgB1B,EAAEoD,IAAIzB,iBAAiB,YAAY5B,EAAEqD,GAAGzB,iBAAiB,gBAAgB3B,EAAEoD,GAA9N,CAAkOtD,EAAED,GAAG2D,EAAE1D,EAAED,KAAK4D,EAAE,SAAS5D,GAAG,CAAC,YAAY,UAAU,aAAa,eAAekE,SAAS,SAASjE,GAAG,OAAOD,EAAEC,EAAEkE,EAAEZ,OAAOa,EAAE,SAASlE,EAAEgC,GAAG,IAAIC,EAAEC,EAAEE,IAAIG,EAAErC,EAAE,OAAO6C,EAAE,SAASjD,GAAGA,EAAE2C,UAAUP,EAAEI,kBAAkBC,EAAEnC,MAAMN,EAAEiE,gBAAgBjE,EAAE2C,UAAUF,EAAEjC,QAAQoC,KAAK5C,GAAGmC,GAAE,KAAMe,EAAElC,EAAE,cAAciC,GAAGd,EAAEF,EAAE/B,EAAEuC,EAAEP,GAAGgB,GAAGxB,GAAG,WAAWwB,EAAEI,cAAchC,IAAI2B,GAAGC,EAAER,gBAAe,GAAIQ,GAAGnB,GAAG,WAAW,IAAIf,EAAEyB,EAAErC,EAAE,OAAO+B,EAAEF,EAAE/B,EAAEuC,EAAEP,GAAG/B,EAAE,GAAGF,GAAG,EAAED,EAAE,KAAK4D,EAAE9B,kBAAkBd,EAAEiC,EAAE9C,EAAEyC,KAAK5B,GAAG6C,QAAQQ,EAAE,GAAGC,EAAE,SAAStE,EAAEC,GAAG,IAAIC,EAAEC,EAAEmC,IAAIJ,EAAE9B,EAAE,OAAO+B,EAAE,SAASnC,GAAG,IAAIC,EAAED,EAAE2C,UAAU1C,EAAEE,EAAEqC,kBAAkBN,EAAE5B,MAAML,EAAEiC,EAAE1B,QAAQoC,KAAK5C,GAAGE,MAAMkC,EAAEpB,EAAE,2BAA2BmB,GAAG,GAAGC,EAAE,CAAClC,EAAE+B,EAAEjC,EAAEkC,EAAEjC,GAAG,IAAIwC,EAAE,WAAW4B,EAAEnC,EAAEzB,MAAM2B,EAAEkB,cAAchC,IAAIa,GAAGC,EAAEM,aAAa2B,EAAEnC,EAAEzB,KAAI,EAAGP,GAAE,KAAM,CAAC,UAAU,SAASgE,SAAS,SAASlE,GAAG8B,iBAAiB9B,EAAEyC,EAAE,CAAC8B,MAAK,EAAGd,SAAQ,OAAQ/B,EAAEe,GAAE,GAAIV,GAAG,SAAS5B,GAAG+B,EAAE9B,EAAE,OAAOF,EAAE+B,EAAEjC,EAAEkC,EAAEjC,GAAG+C,uBAAuB,WAAWA,uBAAuB,WAAWd,EAAE5B,MAAMwC,YAAYlC,MAAMT,EAAEkC,UAAUgC,EAAEnC,EAAEzB,KAAI,EAAGP,GAAE,cAAesE,EAAE,SAASxE,GAAG,IAAIC,EAAEC,EAAEE,EAAE,QAAQH,EAAE,WAAW,IAAI,IAAIA,EAAE6C,YAAY2B,iBAAiB,cAAc,IAAI,WAAW,IAAIzE,EAAE8C,YAAY4B,OAAOzE,EAAE,CAAC6D,UAAU,aAAanB,UAAU,GAAG,IAAI,IAAIzC,KAAKF,EAAE,oBAAoBE,GAAG,WAAWA,IAAID,EAAEC,GAAGW,KAAK8D,IAAI3E,EAAEE,GAAGF,EAAE4E,gBAAgB,IAAI,OAAO3E,EAAhL,GAAqL,GAAGC,EAAEI,MAAMJ,EAAEK,MAAMN,EAAE4E,cAAc3E,EAAEI,MAAM,GAAGJ,EAAEI,MAAMwC,YAAYlC,MAAM,OAAOV,EAAEM,QAAQ,CAACP,GAAGD,EAAEE,GAAG,MAAMF,MAAM,aAAa2B,SAASmD,WAAWvC,WAAWtC,EAAE,GAAG6B,iBAAiB,QAAQ,WAAW,OAAOS,WAAWtC,EAAE","sources":["../node_modules/web-vitals/dist/web-vitals.js"],"sourcesContent":["var e,t,n,i,r=function(e,t){return{name:e,value:void 0===t?-1:t,delta:0,entries:[],id:\"v2-\".concat(Date.now(),\"-\").concat(Math.floor(8999999999999*Math.random())+1e12)}},a=function(e,t){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){if(\"first-input\"===e&&!(\"PerformanceEventTiming\"in self))return;var n=new PerformanceObserver((function(e){return e.getEntries().map(t)}));return n.observe({type:e,buffered:!0}),n}}catch(e){}},o=function(e,t){var n=function n(i){\"pagehide\"!==i.type&&\"hidden\"!==document.visibilityState||(e(i),t&&(removeEventListener(\"visibilitychange\",n,!0),removeEventListener(\"pagehide\",n,!0)))};addEventListener(\"visibilitychange\",n,!0),addEventListener(\"pagehide\",n,!0)},u=function(e){addEventListener(\"pageshow\",(function(t){t.persisted&&e(t)}),!0)},c=function(e,t,n){var i;return function(r){t.value>=0&&(r||n)&&(t.delta=t.value-(i||0),(t.delta||void 0===i)&&(i=t.value,e(t)))}},f=-1,s=function(){return\"hidden\"===document.visibilityState?0:1/0},m=function(){o((function(e){var t=e.timeStamp;f=t}),!0)},v=function(){return f<0&&(f=s(),m(),u((function(){setTimeout((function(){f=s(),m()}),0)}))),{get firstHiddenTime(){return f}}},d=function(e,t){var n,i=v(),o=r(\"FCP\"),f=function(e){\"first-contentful-paint\"===e.name&&(m&&m.disconnect(),e.startTime<i.firstHiddenTime&&(o.value=e.startTime,o.entries.push(e),n(!0)))},s=window.performance&&performance.getEntriesByName&&performance.getEntriesByName(\"first-contentful-paint\")[0],m=s?null:a(\"paint\",f);(s||m)&&(n=c(e,o,t),s&&f(s),u((function(i){o=r(\"FCP\"),n=c(e,o,t),requestAnimationFrame((function(){requestAnimationFrame((function(){o.value=performance.now()-i.timeStamp,n(!0)}))}))})))},p=!1,l=-1,h=function(e,t){p||(d((function(e){l=e.value})),p=!0);var n,i=function(t){l>-1&&e(t)},f=r(\"CLS\",0),s=0,m=[],v=function(e){if(!e.hadRecentInput){var t=m[0],i=m[m.length-1];s&&e.startTime-i.startTime<1e3&&e.startTime-t.startTime<5e3?(s+=e.value,m.push(e)):(s=e.value,m=[e]),s>f.value&&(f.value=s,f.entries=m,n())}},h=a(\"layout-shift\",v);h&&(n=c(i,f,t),o((function(){h.takeRecords().map(v),n(!0)})),u((function(){s=0,l=-1,f=r(\"CLS\",0),n=c(i,f,t)})))},T={passive:!0,capture:!0},y=new Date,g=function(i,r){e||(e=r,t=i,n=new Date,w(removeEventListener),E())},E=function(){if(t>=0&&t<n-y){var r={entryType:\"first-input\",name:e.type,target:e.target,cancelable:e.cancelable,startTime:e.timeStamp,processingStart:e.timeStamp+t};i.forEach((function(e){e(r)})),i=[]}},S=function(e){if(e.cancelable){var t=(e.timeStamp>1e12?new Date:performance.now())-e.timeStamp;\"pointerdown\"==e.type?function(e,t){var n=function(){g(e,t),r()},i=function(){r()},r=function(){removeEventListener(\"pointerup\",n,T),removeEventListener(\"pointercancel\",i,T)};addEventListener(\"pointerup\",n,T),addEventListener(\"pointercancel\",i,T)}(t,e):g(t,e)}},w=function(e){[\"mousedown\",\"keydown\",\"touchstart\",\"pointerdown\"].forEach((function(t){return e(t,S,T)}))},L=function(n,f){var s,m=v(),d=r(\"FID\"),p=function(e){e.startTime<m.firstHiddenTime&&(d.value=e.processingStart-e.startTime,d.entries.push(e),s(!0))},l=a(\"first-input\",p);s=c(n,d,f),l&&o((function(){l.takeRecords().map(p),l.disconnect()}),!0),l&&u((function(){var a;d=r(\"FID\"),s=c(n,d,f),i=[],t=-1,e=null,w(addEventListener),a=p,i.push(a),E()}))},b={},F=function(e,t){var n,i=v(),f=r(\"LCP\"),s=function(e){var t=e.startTime;t<i.firstHiddenTime&&(f.value=t,f.entries.push(e),n())},m=a(\"largest-contentful-paint\",s);if(m){n=c(e,f,t);var d=function(){b[f.id]||(m.takeRecords().map(s),m.disconnect(),b[f.id]=!0,n(!0))};[\"keydown\",\"click\"].forEach((function(e){addEventListener(e,d,{once:!0,capture:!0})})),o(d,!0),u((function(i){f=r(\"LCP\"),n=c(e,f,t),requestAnimationFrame((function(){requestAnimationFrame((function(){f.value=performance.now()-i.timeStamp,b[f.id]=!0,n(!0)}))}))}))}},P=function(e){var t,n=r(\"TTFB\");t=function(){try{var t=performance.getEntriesByType(\"navigation\")[0]||function(){var e=performance.timing,t={entryType:\"navigation\",startTime:0};for(var n in e)\"navigationStart\"!==n&&\"toJSON\"!==n&&(t[n]=Math.max(e[n]-e.navigationStart,0));return t}();if(n.value=n.delta=t.responseStart,n.value<0||n.value>performance.now())return;n.entries=[t],e(n)}catch(e){}},\"complete\"===document.readyState?setTimeout(t,0):addEventListener(\"load\",(function(){return setTimeout(t,0)}))};export{h as getCLS,d as getFCP,L as getFID,F as getLCP,P as getTTFB};\n"],"names":["e","t","n","i","r","name","value","delta","entries","id","concat","Date","now","Math","floor","random","a","PerformanceObserver","supportedEntryTypes","includes","self","getEntries","map","observe","type","buffered","o","document","visibilityState","removeEventListener","addEventListener","u","persisted","c","f","s","m","timeStamp","v","setTimeout","firstHiddenTime","d","disconnect","startTime","push","window","performance","getEntriesByName","requestAnimationFrame","p","l","h","hadRecentInput","length","takeRecords","T","passive","capture","y","g","w","E","entryType","target","cancelable","processingStart","forEach","S","L","b","F","once","P","getEntriesByType","timing","max","navigationStart","responseStart","readyState"],"sourceRoot":""} | tests/assets/stress/static/js/787.2f3b90fa.chunk.js.map | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00017252845282200724,
0.00017252845282200724,
0.00017252845282200724,
0.00017252845282200724,
0
] |
{
"id": 9,
"code_window": [
" expect(e6.message).toContain(`\"level\" attribute is only supported for roles: \"heading\", \"listitem\", \"row\", \"treeitem\"`);\n",
"\n",
" const e7 = await page.$('role=button[name]').catch(e => e);\n",
" expect(e7.message).toContain(`\"name\" attribute must have a value`);\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
" const e8 = await page.$('role=treeitem[expanded=\"none\"]').catch(e => e);\n",
" expect(e8.message).toContain(`\"expanded\" must be one of true, false`);\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "add",
"edit_start_line_idx": 405
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { test, expect, stripAnsi } from './playwright-test-fixtures';
test('should respect path resolver', async ({ runInlineTest }) => {
test.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/11656' });
const result = await runInlineTest({
'playwright.config.ts': `
export default {
projects: [{name: 'foo'}],
};
`,
'tsconfig.json': `{
"compilerOptions": {
"target": "ES2019",
"module": "commonjs",
"lib": ["esnext", "dom", "DOM.Iterable"],
"baseUrl": ".",
"paths": {
"util/*": ["./foo/bar/util/*"],
"util2/*": ["./foo/bar/util/*"],
"util3": ["./does-not-exist", "./foo/bar/util/b"],
},
},
}`,
'a.test.ts': `
import { foo } from 'util/b';
const { test } = pwt;
test('test', ({}, testInfo) => {
expect(testInfo.project.name).toBe(foo);
});
`,
'b.test.ts': `
import { foo } from 'util2/b';
const { test } = pwt;
test('test', ({}, testInfo) => {
expect(testInfo.project.name).toBe(foo);
});
`,
'c.test.ts': `
import { foo } from 'util3';
const { test } = pwt;
test('test', ({}, testInfo) => {
expect(testInfo.project.name).toBe(foo);
});
`,
'foo/bar/util/b.ts': `
export const foo: string = 'foo';
`,
'helper.ts': `
export { foo } from 'util3';
`,
'dir/tsconfig.json': `{
"compilerOptions": {
"target": "ES2019",
"module": "commonjs",
"lib": ["esnext", "dom", "DOM.Iterable"],
"baseUrl": ".",
"paths": {
"parent-util/*": ["../foo/bar/util/*"],
},
},
}`,
'dir/inner.spec.ts': `
// This import should pick up <root>/dir/tsconfig
import { foo } from 'parent-util/b';
// This import should pick up <root>/tsconfig through the helper
import { foo as foo2 } from '../helper';
const { test } = pwt;
test('test', ({}, testInfo) => {
expect(testInfo.project.name).toBe(foo);
expect(testInfo.project.name).toBe(foo2);
});
`,
});
expect(result.passed).toBe(4);
expect(result.exitCode).toBe(0);
expect(result.output).not.toContain(`Could not`);
});
test('should respect baseurl', async ({ runInlineTest }) => {
const result = await runInlineTest({
'playwright.config.ts': `
export default {
projects: [{name: 'foo'}],
};
`,
'tsconfig.json': `{
"compilerOptions": {
"target": "ES2019",
"module": "commonjs",
"lib": ["esnext", "dom", "DOM.Iterable"],
"baseUrl": "./foo",
"paths": {
"util/*": ["./bar/util/*"],
"util2": ["./bar/util/b"],
},
},
}`,
'a.test.ts': `
import { foo } from 'util/b';
const { test } = pwt;
test('test', ({}, testInfo) => {
expect(testInfo.project.name).toBe(foo);
});
`,
'b.test.ts': `
import { foo } from 'util2';
const { test } = pwt;
test('test', ({}, testInfo) => {
expect(testInfo.project.name).toBe(foo);
});
`,
'foo/bar/util/b.ts': `
export const foo: string = 'foo';
`,
});
expect(result.passed).toBe(2);
expect(result.exitCode).toBe(0);
});
test('should respect baseurl w/o paths', async ({ runInlineTest }) => {
const result = await runInlineTest({
'foo/bar/util/b.ts': `
export const foo = 42;
`,
'dir2/tsconfig.json': `{
"compilerOptions": {
"target": "ES2019",
"module": "commonjs",
"lib": ["esnext", "dom", "DOM.Iterable"],
"baseUrl": "..",
},
}`,
'dir2/inner.spec.ts': `
// This import should pick up ../foo/bar/util/b due to baseUrl.
import { foo } from 'foo/bar/util/b';
const { test } = pwt;
test('test', ({}, testInfo) => {
expect(foo).toBe(42);
});
`,
});
expect(result.exitCode).toBe(0);
expect(result.passed).toBe(1);
expect(result.output).not.toContain(`Could not`);
});
test('should respect complex path resolver', async ({ runInlineTest }) => {
const result = await runInlineTest({
'playwright.config.ts': `
export default {
projects: [{name: 'foo'}],
};
`,
'tsconfig.json': `{
"compilerOptions": {
"target": "ES2019",
"module": "commonjs",
"lib": ["esnext", "dom", "DOM.Iterable"],
"baseUrl": ".",
"paths": {
"prefix-*": ["./prefix-*/bar"],
"prefix-*-suffix": ["./prefix-*-suffix/bar"],
"*-suffix": ["./*-suffix/bar"],
"no-star": ["./no-star-foo"],
"longest-*": ["./this-is-not-the-longest-prefix"],
"longest-pre*": ["./this-is-the-longest-prefix"],
"*bar": ["./*bar"],
"*[bar]": ["*foo"],
},
},
}`,
'a.spec.ts': `
import { foo } from 'prefix-matchedstar';
const { test } = pwt;
test('test', ({}, testInfo) => {
expect(testInfo.project.name).toBe(foo);
});
`,
'prefix-matchedstar/bar/index.ts': `
export const foo: string = 'foo';
`,
'b.spec.ts': `
import { foo } from 'prefix-matchedstar-suffix';
const { test } = pwt;
test('test', ({}, testInfo) => {
expect(testInfo.project.name).toBe(foo);
});
`,
'prefix-matchedstar-suffix/bar.ts': `
export const foo: string = 'foo';
`,
'c.spec.ts': `
import { foo } from 'matchedstar-suffix';
const { test } = pwt;
test('test', ({}, testInfo) => {
expect(testInfo.project.name).toBe(foo);
});
`,
'matchedstar-suffix/bar.ts': `
export const foo: string = 'foo';
`,
'd.spec.ts': `
import { foo } from 'no-star';
const { test } = pwt;
test('test', ({}, testInfo) => {
expect(testInfo.project.name).toBe(foo);
});
`,
'./no-star-foo.ts': `
export const foo: string = 'foo';
`,
'e.spec.ts': `
import { foo } from 'longest-prefix';
const { test } = pwt;
test('test', ({}, testInfo) => {
expect(testInfo.project.name).toBe(foo);
});
`,
'./this-is-the-longest-prefix.ts': `
// this module should be resolved as it matches by a longer prefix
export const foo: string = 'foo';
`,
'./this-is-not-the-longest-prefix.ts': `
// This module should't be resolved as it matches by a shorter prefix
export const bar: string = 'bar';
`,
'f.spec.ts': `
import { foo } from 'barfoobar';
const { test } = pwt;
test('test', ({}, testInfo) => {
expect(testInfo.project.name).toBe(foo);
});
`,
'barfoobar.ts': `
export const foo: string = 'foo';
`,
'g.spec.ts': `
import { foo } from 'foo/[bar]';
const { test } = pwt;
test('test', ({}, testInfo) => {
expect(testInfo.project.name).toBe(foo);
});
`,
'foo/foo.ts': `
export const foo: string = 'foo';
`,
});
expect(result.passed).toBe(7);
expect(result.exitCode).toBe(0);
expect(result.output).not.toContain(`Could not`);
});
test('should not use baseurl for relative imports', async ({ runInlineTest }) => {
test.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/15891' });
const result = await runInlineTest({
'frontend/tsconfig.json': `{
"compilerOptions": {
"baseUrl": "src",
},
}`,
'frontend/playwright/utils.ts': `
export const foo = 42;
`,
'frontend/playwright/tests/forms_cms_standard.spec.ts': `
// This relative import should not use baseUrl
import { foo } from '../utils';
const { test } = pwt;
test('test', ({}, testInfo) => {
expect(foo).toBe(42);
});
`,
});
expect(result.exitCode).toBe(0);
expect(result.passed).toBe(1);
expect(result.output).not.toContain(`Could not`);
});
test('should not use baseurl for relative imports when dir with same name exists', async ({ runInlineTest }) => {
test.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/15891' });
const result = await runInlineTest({
'frontend/tsconfig.json': `{
"compilerOptions": {
"baseUrl": "src",
},
}`,
'frontend/src/utils/foo.js': `
export const foo = -1;
`,
'frontend/src/index.js': `
export const index = -1;
`,
'frontend/src/.bar.js': `
export const bar = 42;
`,
'frontend/playwright/tests/utils.ts': `
export const foo = 42;
`,
'frontend/playwright/tests/index.js': `
export const index = 42;
`,
'frontend/playwright/tests/forms_cms_standard.spec.ts': `
// These relative imports should not use baseUrl
import { foo } from './utils';
import { index } from '.';
// This absolute import should use baseUrl
import { bar } from '.bar';
const { test } = pwt;
test('test', ({}, testInfo) => {
expect(foo).toBe(42);
expect(index).toBe(42);
expect(bar).toBe(42);
});
`,
});
expect(result.exitCode).toBe(0);
expect(result.passed).toBe(1);
expect(result.output).not.toContain(`Could not`);
expect(result.output).not.toContain(`Cannot`);
});
test('should respect path resolver for JS files when allowJs', async ({ runInlineTest }) => {
const result = await runInlineTest({
'playwright.config.ts': `export default { projects: [{name: 'foo'}], };`,
'tsconfig.json': `{
"compilerOptions": {
"allowJs": true,
"baseUrl": ".",
"paths": {
"util/*": ["./foo/bar/util/*"],
},
},
}`,
'a.test.js': `
const { foo } = require('util/b');
const { test } = pwt;
test('test', ({}, testInfo) => {
expect(testInfo.project.name).toBe(foo);
});
`,
'foo/bar/util/b.ts': `
module.exports = { foo: 'foo' };
`,
});
expect(result.passed).toBe(1);
expect(result.exitCode).toBe(0);
});
test('should not respect path resolver for JS files w/o allowJS', async ({ runInlineTest }) => {
const result = await runInlineTest({
'playwright.config.ts': `export default { projects: [{name: 'foo'}], };`,
'tsconfig.json': `{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"util/*": ["./foo/bar/util/*"],
},
},
}`,
'a.test.js': `
const { foo } = require('util/b');
const { test } = pwt;
test('test', ({}, testInfo) => {
expect(testInfo.project.name).toBe(foo);
});
`,
'foo/bar/util/b.ts': `
module.exports = { foo: 'foo' };
`,
});
expect(stripAnsi(result.output)).toContain('Cannot find module \'util/b\'');
expect(result.exitCode).toBe(1);
});
| tests/playwright-test/resolver.spec.ts | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00018004447338171303,
0.0001765233464539051,
0.0001667549804551527,
0.0001770887611201033,
0.000002356483719267999
] |
{
"id": 9,
"code_window": [
" expect(e6.message).toContain(`\"level\" attribute is only supported for roles: \"heading\", \"listitem\", \"row\", \"treeitem\"`);\n",
"\n",
" const e7 = await page.$('role=button[name]').catch(e => e);\n",
" expect(e7.message).toContain(`\"name\" attribute must have a value`);\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
" const e8 = await page.$('role=treeitem[expanded=\"none\"]').catch(e => e);\n",
" expect(e8.message).toContain(`\"expanded\" must be one of true, false`);\n"
],
"file_path": "tests/page/selectors-role.spec.ts",
"type": "add",
"edit_start_line_idx": 405
} | /**
* Copyright 2018 Google Inc. All rights reserved.
* Modifications copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { browserTest as it, expect } from '../config/browserTest';
import { attachFrame } from '../config/utils';
it('should work', async ({ browser, server }) => {
{
const context = await browser.newContext();
const page = await context.newPage();
expect(await page.evaluate(() => navigator.userAgent)).toContain('Mozilla');
await context.close();
}
{
const context = await browser.newContext({ userAgent: 'foobar' });
const page = await context.newPage();
const [request] = await Promise.all([
server.waitForRequest('/empty.html'),
page.goto(server.EMPTY_PAGE),
]);
expect(request.headers['user-agent']).toBe('foobar');
await context.close();
}
});
it('should work for subframes', async ({ browser, server }) => {
{
const context = await browser.newContext();
const page = await context.newPage();
expect(await page.evaluate(() => navigator.userAgent)).toContain('Mozilla');
await context.close();
}
{
const context = await browser.newContext({ userAgent: 'foobar' });
const page = await context.newPage();
const [request] = await Promise.all([
server.waitForRequest('/empty.html'),
attachFrame(page, 'frame1', server.EMPTY_PAGE),
]);
expect(request.headers['user-agent']).toBe('foobar');
await context.close();
}
});
it('should emulate device user-agent', async ({ browser, server, playwright }) => {
{
const context = await browser.newContext();
const page = await context.newPage();
await page.goto(server.PREFIX + '/mobile.html');
expect(await page.evaluate(() => navigator.userAgent)).not.toContain('iPhone');
await context.close();
}
{
const context = await browser.newContext({ userAgent: playwright.devices['iPhone 6'].userAgent });
const page = await context.newPage();
await page.goto(server.PREFIX + '/mobile.html');
expect(await page.evaluate(() => navigator.userAgent)).toContain('iPhone');
await context.close();
}
});
it('should make a copy of default options', async ({ browser, server }) => {
const options = { userAgent: 'foobar' };
const context = await browser.newContext(options);
options.userAgent = 'wrong';
const page = await context.newPage();
const [request] = await Promise.all([
server.waitForRequest('/empty.html'),
page.goto(server.EMPTY_PAGE),
]);
expect(request.headers['user-agent']).toBe('foobar');
await context.close();
});
| tests/library/browsercontext-user-agent.spec.ts | 0 | https://github.com/microsoft/playwright/commit/8ad3bc7ff3a0fc0d134eaab7a9a6eead13f59c5b | [
0.00043306281440891325,
0.00022340200666803867,
0.00016545939433854073,
0.0001770880917320028,
0.00008481355325784534
] |
{
"id": 0,
"code_window": [
" \"compilerOptions\": {\n",
" \"rootDir\": \"./src\",\n",
" \"outDir\": \"./build\",\n",
" \"declarationMap\": true,\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "packages/core/helper-plugin/tsconfig.build.json",
"type": "replace",
"edit_start_line_idx": 7
} | {
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "dist",
"noEmit": false,
"declarationMap": true,
},
"include": ["src"],
"exclude": ["node_modules", "**/__tests__/**"]
}
| packages/core/strapi/tsconfig.build.json | 1 | https://github.com/strapi/strapi/commit/eb0cebb965521ebc77eb3af75ceb457310c34bfb | [
0.0003150624397676438,
0.0002468729508109391,
0.00017868346185423434,
0.0002468729508109391,
0.00006818948895670474
] |
{
"id": 0,
"code_window": [
" \"compilerOptions\": {\n",
" \"rootDir\": \"./src\",\n",
" \"outDir\": \"./build\",\n",
" \"declarationMap\": true,\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "packages/core/helper-plugin/tsconfig.build.json",
"type": "replace",
"edit_start_line_idx": 7
} | import React from 'react';
import { lightTheme, ThemeProvider } from '@strapi/design-system';
import { render as renderTL } from '@testing-library/react';
import en from '../../../translations/en.json';
import { ImageAssetCard } from '../ImageAssetCard';
jest.mock('../../../utils', () => ({
...jest.requireActual('../../../utils'),
getTrad: (x) => x,
}));
jest.mock('react-intl', () => ({
useIntl: () => ({ formatMessage: jest.fn(({ id }) => en[id]) }),
}));
describe('ImageAssetCard', () => {
it('snapshots the component', () => {
const { container } = renderTL(
<ThemeProvider theme={lightTheme}>
<ImageAssetCard
alt=""
name="hello.png"
extension="png"
height={40}
width={40}
thumbnail="http://somewhere.com/hello.png"
selected={false}
onSelect={jest.fn()}
onEdit={jest.fn()}
/>
</ThemeProvider>
);
expect(container).toMatchInlineSnapshot(`
.c17 {
border: 0;
-webkit-clip: rect(0 0 0 0);
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
.c24 {
font-size: 0.75rem;
line-height: 1.33;
font-weight: 600;
color: #32324d;
}
.c25 {
font-size: 0.75rem;
line-height: 1.33;
color: #666687;
}
.c33 {
font-weight: 600;
font-size: 0.6875rem;
line-height: 1.45;
text-transform: uppercase;
color: #666687;
}
.c0 {
background: #ffffff;
border-radius: 4px;
border-style: solid;
border-width: 1px;
border-color: #eaeaef;
box-shadow: 0px 1px 4px rgba(33,33,52,0.1);
height: 100%;
}
.c2 {
position: relative;
}
.c5 {
position: start;
}
.c10 {
position: end;
}
.c14 {
background: #ffffff;
padding: 8px;
border-radius: 4px;
border-color: #dcdce4;
border: 1px solid #dcdce4;
cursor: pointer;
}
.c20 {
padding-top: 8px;
padding-right: 12px;
padding-bottom: 8px;
padding-left: 12px;
}
.c23 {
padding-top: 4px;
}
.c27 {
padding-top: 4px;
-webkit-box-flex: 1;
-webkit-flex-grow: 1;
-ms-flex-positive: 1;
flex-grow: 1;
}
.c29 {
background: #eaeaef;
padding-right: 8px;
padding-left: 8px;
min-width: 20px;
}
.c3 {
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
}
.c6 {
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
}
.c21 {
-webkit-align-items: flex-start;
-webkit-box-align: flex-start;
-ms-flex-align: flex-start;
align-items: flex-start;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
}
.c30 {
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
display: -webkit-inline-box;
display: -webkit-inline-flex;
display: -ms-inline-flexbox;
display: inline-flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
}
.c31 {
border-radius: 4px;
height: 1.5rem;
}
.c15 {
position: relative;
outline: none;
}
.c15 > svg {
height: 12px;
width: 12px;
}
.c15 > svg > g,
.c15 > svg path {
fill: #ffffff;
}
.c15[aria-disabled='true'] {
pointer-events: none;
}
.c15:after {
-webkit-transition-property: all;
transition-property: all;
-webkit-transition-duration: 0.2s;
transition-duration: 0.2s;
border-radius: 8px;
content: '';
position: absolute;
top: -4px;
bottom: -4px;
left: -4px;
right: -4px;
border: 2px solid transparent;
}
.c15:focus-visible {
outline: none;
}
.c15:focus-visible:after {
border-radius: 8px;
content: '';
position: absolute;
top: -5px;
bottom: -5px;
left: -5px;
right: -5px;
border: 2px solid #4945ff;
}
.c9 {
height: 18px;
min-width: 18px;
margin: 0;
border-radius: 4px;
border: 1px solid #c0c0cf;
-webkit-appearance: none;
background-color: #ffffff;
cursor: pointer;
}
.c9:checked {
background-color: #4945ff;
border: 1px solid #4945ff;
}
.c9:checked:after {
content: '';
display: block;
position: relative;
background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAiIGhlaWdodD0iOCIgdmlld0JveD0iMCAwIDEwIDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CiAgPHBhdGgKICAgIGQ9Ik04LjU1MzIzIDAuMzk2OTczQzguNjMxMzUgMC4zMTYzNTUgOC43NjA1MSAwLjMxNTgxMSA4LjgzOTMxIDAuMzk1NzY4TDkuODYyNTYgMS40MzQwN0M5LjkzODkzIDEuNTExNTcgOS45MzkzNSAxLjYzNTkgOS44NjM0OSAxLjcxMzlMNC4wNjQwMSA3LjY3NzI0QzMuOTg1OSA3Ljc1NzU1IDMuODU3MDcgNy43NTgwNSAzLjc3ODM0IDcuNjc4MzRMMC4xMzg2NiAzLjk5MzMzQzAuMDYxNzc5OCAzLjkxNTQ5IDAuMDYxNzEwMiAzLjc5MDMyIDAuMTM4NTA0IDMuNzEyNEwxLjE2MjEzIDIuNjczNzJDMS4yNDAzOCAyLjU5NDMyIDEuMzY4NDMgMi41OTQyMiAxLjQ0NjggMi42NzM0OEwzLjkyMTc0IDUuMTc2NDdMOC41NTMyMyAwLjM5Njk3M1oiCiAgICBmaWxsPSJ3aGl0ZSIKICAvPgo8L3N2Zz4=) no-repeat no-repeat center center;
width: 10px;
height: 10px;
left: 50%;
top: 50%;
-webkit-transform: translateX(-50%) translateY(-50%);
-ms-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
}
.c9:checked:disabled:after {
background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAiIGhlaWdodD0iOCIgdmlld0JveD0iMCAwIDEwIDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CiAgPHBhdGgKICAgIGQ9Ik04LjU1MzIzIDAuMzk2OTczQzguNjMxMzUgMC4zMTYzNTUgOC43NjA1MSAwLjMxNTgxMSA4LjgzOTMxIDAuMzk1NzY4TDkuODYyNTYgMS40MzQwN0M5LjkzODkzIDEuNTExNTcgOS45MzkzNSAxLjYzNTkgOS44NjM0OSAxLjcxMzlMNC4wNjQwMSA3LjY3NzI0QzMuOTg1OSA3Ljc1NzU1IDMuODU3MDcgNy43NTgwNSAzLjc3ODM0IDcuNjc4MzRMMC4xMzg2NiAzLjk5MzMzQzAuMDYxNzc5OCAzLjkxNTQ5IDAuMDYxNzEwMiAzLjc5MDMyIDAuMTM4NTA0IDMuNzEyNEwxLjE2MjEzIDIuNjczNzJDMS4yNDAzOCAyLjU5NDMyIDEuMzY4NDMgMi41OTQyMiAxLjQ0NjggMi42NzM0OEwzLjkyMTc0IDUuMTc2NDdMOC41NTMyMyAwLjM5Njk3M1oiCiAgICBmaWxsPSIjOEU4RUE5IgogIC8+Cjwvc3ZnPg==) no-repeat no-repeat center center;
}
.c9:disabled {
background-color: #dcdce4;
border: 1px solid #c0c0cf;
}
.c9:indeterminate {
background-color: #4945ff;
border: 1px solid #4945ff;
}
.c9:indeterminate:after {
content: '';
display: block;
position: relative;
color: white;
height: 2px;
width: 10px;
background-color: #ffffff;
left: 50%;
top: 50%;
-webkit-transform: translateX(-50%) translateY(-50%);
-ms-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
}
.c9:indeterminate:disabled {
background-color: #dcdce4;
border: 1px solid #c0c0cf;
}
.c9:indeterminate:disabled:after {
background-color: #8e8ea9;
}
.c7 > * {
margin-left: 0;
margin-right: 0;
}
.c7 > * + * {
margin-left: 8px;
}
.c8 {
position: absolute;
top: 12px;
left: 12px;
}
.c12 {
position: absolute;
top: 12px;
right: 12px;
}
.c19 {
margin: 0;
padding: 0;
max-height: 100%;
max-width: 100%;
object-fit: contain;
}
.c18 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
height: 10.25rem;
width: 100%;
background: repeating-conic-gradient(#f6f6f9 0% 25%,transparent 0% 50%) 50% / 20px 20px;
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
.c28 {
margin-left: auto;
-webkit-flex-shrink: 0;
-ms-flex-negative: 0;
flex-shrink: 0;
}
.c32 {
margin-left: 4px;
}
.c22 {
word-break: break-all;
}
.c4 {
border-bottom: 1px solid #eaeaef;
}
.c16 {
border-color: #dcdce4;
height: 2rem;
width: 2rem;
}
.c16 svg g,
.c16 svg path {
fill: #8e8ea9;
}
.c16:hover svg g,
.c16:focus svg g,
.c16:hover svg path,
.c16:focus svg path {
fill: #666687;
}
.c16[aria-disabled='true'] svg path {
fill: #666687;
}
.c26 {
text-transform: uppercase;
}
.c13 {
opacity: 0;
}
.c13:focus-within {
opacity: 1;
}
.c1 {
cursor: pointer;
}
.c1:hover .c11 {
opacity: 1;
}
<div>
<article
aria-labelledby=":r0:-title"
class="c0 c1"
role="button"
tabindex="-1"
>
<div
class="c2 c3 c4"
>
<div>
<div
class="c5 c6 c7 c8"
>
<div
class=""
>
<input
aria-labelledby=":r0:-title"
class="c9"
type="checkbox"
/>
</div>
</div>
</div>
<div
class="c10 c6 c7 c11 c12 c13"
>
<span>
<button
aria-disabled="false"
aria-labelledby=":r1:"
class="c14 c3 c15 c16"
tabindex="0"
type="button"
>
<span
class="c17"
>
Edit
</span>
<svg
aria-hidden="true"
fill="none"
focusable="false"
height="1rem"
viewBox="0 0 24 24"
width="1rem"
xmlns="http://www.w3.org/2000/svg"
>
<path
clip-rule="evenodd"
d="M23.604 3.514c.528.528.528 1.36 0 1.887l-2.622 2.607-4.99-4.99L18.6.396a1.322 1.322 0 0 1 1.887 0l3.118 3.118ZM0 24v-4.99l14.2-14.2 4.99 4.99L4.99 24H0Z"
fill="#212134"
fill-rule="evenodd"
/>
</svg>
</button>
</span>
</div>
<div
class="c18"
>
<img
alt=""
aria-hidden="true"
class="c19"
src="http://somewhere.com/hello.png"
/>
</div>
</div>
<div
class="c20"
>
<div
class="c21"
>
<div
class="c22"
>
<div
class="c23"
>
<h2
class="c24"
id=":r0:-title"
>
hello.png
</h2>
</div>
<div
class="c25"
>
<span
class="c26"
>
png
</span>
- 40✕40
</div>
</div>
<div
class="c27 c6"
>
<div
class="c28"
>
<div
class="c29 c30 c31 c32"
>
<span
class="c33"
>
Image
</span>
</div>
</div>
</div>
</div>
</div>
</article>
<div
class="c17"
>
<p
aria-live="polite"
aria-relevant="all"
id="live-region-log"
role="log"
/>
<p
aria-live="polite"
aria-relevant="all"
id="live-region-status"
role="status"
/>
<p
aria-live="assertive"
aria-relevant="all"
id="live-region-alert"
role="alert"
/>
</div>
</div>
`);
});
});
| packages/core/upload/admin/src/components/AssetCard/tests/ImageAssetCard.test.js | 0 | https://github.com/strapi/strapi/commit/eb0cebb965521ebc77eb3af75ceb457310c34bfb | [
0.001671153586357832,
0.00020758714526891708,
0.00016857412992976606,
0.00017196100088767707,
0.00020817539189010859
] |
{
"id": 0,
"code_window": [
" \"compilerOptions\": {\n",
" \"rootDir\": \"./src\",\n",
" \"outDir\": \"./build\",\n",
" \"declarationMap\": true,\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "packages/core/helper-plugin/tsconfig.build.json",
"type": "replace",
"edit_start_line_idx": 7
} | 'use strict';
const { createCoreRouter } = require('@strapi/strapi').factories;
module.exports = createCoreRouter('api::like.like');
| examples/getstarted/src/api/like/routes/like.js | 0 | https://github.com/strapi/strapi/commit/eb0cebb965521ebc77eb3af75ceb457310c34bfb | [
0.00016776339907664806,
0.00016776339907664806,
0.00016776339907664806,
0.00016776339907664806,
0
] |
{
"id": 0,
"code_window": [
" \"compilerOptions\": {\n",
" \"rootDir\": \"./src\",\n",
" \"outDir\": \"./build\",\n",
" \"declarationMap\": true,\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "packages/core/helper-plugin/tsconfig.build.json",
"type": "replace",
"edit_start_line_idx": 7
} | import * as locales from '../services/locales';
import * as permissions from '../services/permissions';
import * as contentTypes from '../services/content-types';
import * as metrics from '../services/metrics';
import * as entityServiceDecorator from '../services/entity-service-decorator';
import * as coreAPI from '../services/core-api';
import * as ISOLocales from '../services/iso-locales';
import * as localizations from '../services/localizations';
type S = {
permissions: typeof permissions;
metrics: typeof metrics;
locales: typeof locales;
localizations: typeof localizations;
['iso-locales']: typeof ISOLocales;
['content-types']: typeof contentTypes;
['entity-service-decorator']: typeof entityServiceDecorator;
['core-api']: typeof coreAPI;
};
export function getService<T extends keyof S>(name: T): ReturnType<S[T]>;
| packages/plugins/i18n/server/utils/index.d.ts | 0 | https://github.com/strapi/strapi/commit/eb0cebb965521ebc77eb3af75ceb457310c34bfb | [
0.0001740698207868263,
0.0001734486868372187,
0.00017311872215941548,
0.0001731575175654143,
4.394935047002946e-7
] |
{
"id": 1,
"code_window": [
" \"extends\": \"./tsconfig.json\",\n",
" \"compilerOptions\": {\n",
" \"outDir\": \"dist\",\n",
" \"noEmit\": false,\n",
" \"declarationMap\": true,\n",
" },\n",
" \"include\": [\"src\"],\n",
" \"exclude\": [\"node_modules\", \"**/__tests__/**\"]\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/core/strapi/tsconfig.build.json",
"type": "replace",
"edit_start_line_idx": 5
} | {
"extends": "./tsconfig.json",
"include": ["declarations", "src"],
"exclude": ["**/*.test.tsx", "**/*.test.ts"],
"compilerOptions": {
"rootDir": "./src",
"outDir": "./build",
"declarationMap": true,
}
}
| packages/core/helper-plugin/tsconfig.build.json | 1 | https://github.com/strapi/strapi/commit/eb0cebb965521ebc77eb3af75ceb457310c34bfb | [
0.01074636448174715,
0.005459173116832972,
0.00017198150453623384,
0.005459173116832972,
0.005287191830575466
] |
{
"id": 1,
"code_window": [
" \"extends\": \"./tsconfig.json\",\n",
" \"compilerOptions\": {\n",
" \"outDir\": \"dist\",\n",
" \"noEmit\": false,\n",
" \"declarationMap\": true,\n",
" },\n",
" \"include\": [\"src\"],\n",
" \"exclude\": [\"node_modules\", \"**/__tests__/**\"]\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/core/strapi/tsconfig.build.json",
"type": "replace",
"edit_start_line_idx": 5
} | import { Flex, FlexProps, Typography } from '@strapi/design-system';
import styled from 'styled-components';
export interface ContentBoxProps {
title?: string;
subtitle?: string;
icon?: FlexProps['children'];
iconBackground?: FlexProps['background'];
endAction?: FlexProps['children'];
titleEllipsis?: boolean;
}
const IconWrapper = styled(Flex)`
margin-right: ${({ theme }) => theme.spaces[6]};
svg {
width: ${32 / 16}rem;
height: ${32 / 16}rem;
}
`;
const TypographyWordBreak = styled(Typography)`
word-break: break-all;
`;
const ContentBox = ({
title,
subtitle,
icon,
iconBackground,
endAction,
titleEllipsis = false,
}: ContentBoxProps) => {
if (title && title.length > 70 && titleEllipsis) {
title = `${title.substring(0, 70)}...`;
}
return (
<Flex shadow="tableShadow" hasRadius padding={6} background="neutral0">
<IconWrapper background={iconBackground} hasRadius padding={3}>
{icon}
</IconWrapper>
<Flex direction="column" alignItems="stretch" gap={endAction ? 0 : 1}>
<Flex>
<TypographyWordBreak fontWeight="semiBold" variant="pi">
{title}
</TypographyWordBreak>
{endAction}
</Flex>
<Typography textColor="neutral600">{subtitle}</Typography>
</Flex>
</Flex>
);
};
export { ContentBox };
| packages/core/helper-plugin/src/components/ContentBox.tsx | 0 | https://github.com/strapi/strapi/commit/eb0cebb965521ebc77eb3af75ceb457310c34bfb | [
0.0001752320386003703,
0.00017284054774791002,
0.0001678749395068735,
0.0001733832759782672,
0.0000024075723104033386
] |
{
"id": 1,
"code_window": [
" \"extends\": \"./tsconfig.json\",\n",
" \"compilerOptions\": {\n",
" \"outDir\": \"dist\",\n",
" \"noEmit\": false,\n",
" \"declarationMap\": true,\n",
" },\n",
" \"include\": [\"src\"],\n",
" \"exclude\": [\"node_modules\", \"**/__tests__/**\"]\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/core/strapi/tsconfig.build.json",
"type": "replace",
"edit_start_line_idx": 5
} | import * as React from 'react';
import { Alert, AlertVariant, Flex } from '@strapi/design-system';
import { Link } from '@strapi/design-system/v2';
import { MessageDescriptor, useIntl } from 'react-intl';
import { useCallbackRef } from '../hooks/useCallbackRef';
import { TranslationMessage } from '../types';
/**
* TODO: realistically a lot of this logic is isolated to the `core/admin` package.
* However, we want to expose the `useNotification` hook to the plugins.
*
* Therefore, in V5 we should move this logic back to the `core/admin` package & export
* the hook from that package and re-export here. For now, let's keep it all together
* because it's easier to diagnose and we're not using a million refs because we don't
* understand what's going on.
*/
export interface NotificationLink {
label: string | MessageDescriptor;
target?: string;
url: string;
}
export interface NotificationConfig {
blockTransition?: boolean;
link?: NotificationLink;
message?: string | TranslationMessage;
onClose?: () => void;
timeout?: number;
title?: string | TranslationMessage;
type?: 'info' | 'warning' | 'softWarning' | 'success';
}
/* -------------------------------------------------------------------------------------------------
* Context
* -----------------------------------------------------------------------------------------------*/
export interface NotificationsContextValue {
/**
* Toggles a notification, wrapped in `useCallback` for a stable identity.
*/
toggleNotification: (config: NotificationConfig) => void;
}
const NotificationsContext = React.createContext<NotificationsContextValue | null>(null);
/* -------------------------------------------------------------------------------------------------
* Provider
* -----------------------------------------------------------------------------------------------*/
export interface NotificationsProviderProps {
children: React.ReactNode;
}
export interface Notification extends NotificationConfig {
id: number;
}
const NotificationsProvider = ({ children }: NotificationsProviderProps) => {
const notificationIdRef = React.useRef(0);
const [notifications, setNotifications] = React.useState<Notification[]>([]);
const toggleNotification = React.useCallback(
({ type, message, link, timeout, blockTransition, onClose, title }: NotificationConfig) => {
setNotifications((s) => [
...s,
{
id: notificationIdRef.current++,
type,
message,
link,
timeout,
blockTransition,
onClose,
title,
},
]);
},
[]
);
const clearNotification = React.useCallback((id: number) => {
setNotifications((s) => s.filter((n) => n.id !== id));
}, []);
const value = React.useMemo(() => ({ toggleNotification }), [toggleNotification]);
return (
<NotificationsContext.Provider value={value}>
<Flex
left="50%"
// @ts-expect-error - TODO: We need to find a way to accept custom sizes on DS or refactor this
marginLeft="-250px"
position="fixed"
direction="column"
alignItems="stretch"
gap={2}
top={`${46 / 16}rem`}
width={`${500 / 16}rem`}
zIndex={10}
>
{notifications.map((notification) => {
return (
<Notification
key={notification.id}
{...notification}
clearNotification={clearNotification}
/>
);
})}
</Flex>
{children}
</NotificationsContext.Provider>
);
};
export interface NotificationProps extends Notification {
clearNotification: (id: number) => void;
}
const Notification = ({
clearNotification,
blockTransition = false,
id,
link,
message = {
id: 'notification.success.saved',
defaultMessage: 'Saved',
},
onClose,
timeout = 2500,
title = 'success',
type,
}: NotificationProps) => {
const { formatMessage } = useIntl();
/**
* Chances are `onClose` won't be classed as stabilised,
* so we use `useCallbackRef` to avoid make it stable.
*/
const onCloseCallback = useCallbackRef(onClose);
const handleClose = React.useCallback(() => {
onCloseCallback();
clearNotification(id);
}, [clearNotification, id, onCloseCallback]);
// eslint-disable-next-line consistent-return
React.useEffect(() => {
if (!blockTransition) {
const timeoutReference = setTimeout(() => {
handleClose();
}, timeout);
return () => {
clearTimeout(timeoutReference);
};
}
}, [blockTransition, handleClose, timeout]);
let variant: AlertVariant;
let alertTitle: string;
if (type === 'info') {
variant = 'default';
alertTitle = formatMessage({
id: 'notification.default.title',
defaultMessage: 'Information:',
});
} else if (type === 'warning') {
// TODO: type should be renamed to danger in the future, but it might introduce changes if done now
variant = 'danger';
alertTitle = formatMessage({
id: 'notification.warning.title',
defaultMessage: 'Warning:',
});
} else if (type === 'softWarning') {
// TODO: type should be renamed to just warning in the future
variant = 'warning';
alertTitle = formatMessage({
id: 'notification.warning.title',
defaultMessage: 'Warning:',
});
} else {
variant = 'success';
alertTitle = formatMessage({
id: 'notification.success.title',
defaultMessage: 'Success:',
});
}
if (title) {
alertTitle =
typeof title === 'string'
? title
: formatMessage(
{
id: title.id,
defaultMessage: title.defaultMessage ?? title.id,
},
title.values
);
}
return (
<Alert
action={
link ? (
<Link href={link.url} isExternal>
{formatMessage({
id: typeof link.label === 'object' ? link.label.id : link.label,
defaultMessage:
typeof link.label === 'object'
? link.label.defaultMessage ?? link.label.id
: link.label,
})}
</Link>
) : undefined
}
onClose={handleClose}
closeLabel={formatMessage({
id: 'global.close',
defaultMessage: 'Close',
})}
title={alertTitle}
variant={variant}
>
{formatMessage(
{
id: typeof message === 'object' ? message.id : message,
defaultMessage:
typeof message === 'object' ? message.defaultMessage ?? message.id : message,
},
typeof message === 'object' ? message.values : undefined
)}
</Alert>
);
};
/* -------------------------------------------------------------------------------------------------
* Hook
* -----------------------------------------------------------------------------------------------*/
/**
* @preserve
* @description Returns an object to interact with the notification
* system. The callbacks are wrapped in `useCallback` for a stable
* identity.
*
* @example
* ```tsx
* import { useNotification } from '@strapi/helper-plugin';
*
* const MyComponent = () => {
* const { toggleNotification } = useNotification();
*
* return <button onClick={() => toggleNotification({ message: 'Hello world!' })}>Click me</button>;
*/
const useNotification = () => React.useContext(NotificationsContext)?.toggleNotification;
export { NotificationsContext, NotificationsProvider, useNotification };
| packages/core/helper-plugin/src/features/Notifications.tsx | 0 | https://github.com/strapi/strapi/commit/eb0cebb965521ebc77eb3af75ceb457310c34bfb | [
0.00017428805585950613,
0.0001708152994979173,
0.00016360940935555845,
0.00017127780301962048,
0.000002518641622373252
] |
{
"id": 1,
"code_window": [
" \"extends\": \"./tsconfig.json\",\n",
" \"compilerOptions\": {\n",
" \"outDir\": \"dist\",\n",
" \"noEmit\": false,\n",
" \"declarationMap\": true,\n",
" },\n",
" \"include\": [\"src\"],\n",
" \"exclude\": [\"node_modules\", \"**/__tests__/**\"]\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/core/strapi/tsconfig.build.json",
"type": "replace",
"edit_start_line_idx": 5
} | 'use strict';
jest.mock('@strapi/strapi/dist/utils/ee', () => {
const eeModule = () => false;
Object.assign(eeModule, {
default: {
features: {
isEnabled() {
return false;
},
list() {
return [];
},
},
},
});
return eeModule;
});
const adminController = require('../admin');
describe('Admin Controller', () => {
describe('init', () => {
beforeAll(() => {
global.strapi = {
config: {
get: jest.fn(() => 'foo'),
},
admin: {
services: {
user: {
exists: jest.fn(() => true),
},
'project-settings': {
getProjectSettings: jest.fn(() => ({ menuLogo: null, authLogo: null })),
},
},
},
};
});
test('Returns the uuid and if the app has admins', async () => {
const result = await adminController.init();
expect(global.strapi.config.get).toHaveBeenCalledWith('uuid', false);
expect(global.strapi.config.get).toHaveBeenCalledWith(
'packageJsonStrapi.telemetryDisabled',
null
);
expect(global.strapi.admin.services.user.exists).toHaveBeenCalled();
expect(result.data).toBeDefined();
expect(result.data).toStrictEqual({
uuid: 'foo',
hasAdmin: true,
menuLogo: null,
authLogo: null,
});
});
});
describe('information', () => {
beforeAll(() => {
global.strapi = {
config: {
get: jest.fn(
(key, value) =>
({
autoReload: undefined,
'info.strapi': '1.0.0',
'info.dependencies': {
dependency: '1.0.0',
},
uuid: 'testuuid',
environment: 'development',
}[key] || value)
),
},
EE: true,
};
});
test('Returns application information', async () => {
const result = await adminController.information();
expect(global.strapi.config.get.mock.calls).toEqual([
['environment'],
['autoReload', false],
['info.strapi', null],
['info.dependencies', {}],
['uuid', null],
]);
expect(result.data).toBeDefined();
expect(result.data).toMatchObject({
currentEnvironment: 'development',
autoReload: false,
strapiVersion: '1.0.0',
projectId: 'testuuid',
dependencies: {
dependency: '1.0.0',
},
nodeVersion: process.version,
communityEdition: false,
});
});
});
});
| packages/core/admin/server/controllers/__tests__/admin.test.js | 0 | https://github.com/strapi/strapi/commit/eb0cebb965521ebc77eb3af75ceb457310c34bfb | [
0.00017617155390325934,
0.00017053248302545398,
0.00016533433517906815,
0.00016926784883253276,
0.00000303346450891695
] |
{
"id": 2,
"code_window": [
" \"extends\": \"./tsconfig.json\",\n",
" \"compilerOptions\": {\n",
" \"outDir\": \"dist\",\n",
" \"noEmit\": false,\n",
" \"emitDeclarationOnly\": true,\n",
" \"declarationMap\": true,\n",
" },\n",
" \"include\": [\"src\"],\n",
" \"exclude\": [\"node_modules\", \"**/__tests__/**\"]\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/core/types/tsconfig.build.json",
"type": "replace",
"edit_start_line_idx": 6
} | {
"extends": "./tsconfig.json",
"include": ["declarations", "src"],
"exclude": ["**/*.test.tsx", "**/*.test.ts"],
"compilerOptions": {
"rootDir": "./src",
"outDir": "./build",
"declarationMap": true,
}
}
| packages/core/helper-plugin/tsconfig.build.json | 1 | https://github.com/strapi/strapi/commit/eb0cebb965521ebc77eb3af75ceb457310c34bfb | [
0.02145574614405632,
0.010813630186021328,
0.00017151428619399667,
0.010813630186021328,
0.010642115958034992
] |
{
"id": 2,
"code_window": [
" \"extends\": \"./tsconfig.json\",\n",
" \"compilerOptions\": {\n",
" \"outDir\": \"dist\",\n",
" \"noEmit\": false,\n",
" \"emitDeclarationOnly\": true,\n",
" \"declarationMap\": true,\n",
" },\n",
" \"include\": [\"src\"],\n",
" \"exclude\": [\"node_modules\", \"**/__tests__/**\"]\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/core/types/tsconfig.build.json",
"type": "replace",
"edit_start_line_idx": 6
} | ############################
# OS X
############################
.DS_Store
.AppleDouble
.LSOverride
Icon
.Spotlight-V100
.Trashes
._*
############################
# Linux
############################
*~
############################
# Windows
############################
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
*.cab
*.msi
*.msm
*.msp
############################
# Packages
############################
*.7z
*.csv
*.dat
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
*.com
*.class
*.dll
*.exe
*.o
*.seed
*.so
*.swo
*.swp
*.swn
*.swm
*.out
*.pid
############################
# Logs and databases
############################
*.log
*.sql
############################
# Misc.
############################
*#
ssl
.editorconfig
.gitattributes
.idea
nbproject
############################
# Node.js
############################
lib-cov
lcov.info
pids
logs
results
node_modules
.node_history
############################
# Tests
############################
test
tests
__tests__
jest.config.js
coverage
| packages/core/email/.npmignore | 0 | https://github.com/strapi/strapi/commit/eb0cebb965521ebc77eb3af75ceb457310c34bfb | [
0.0002972596266772598,
0.0001927980047184974,
0.00016359241271857172,
0.00016792130190879107,
0.00005065489676780999
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.