hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
listlengths
5
5
{ "id": 6, "code_window": [ " return await installDependenciesWindows(targets);\n", " if (os.platform() === 'linux')\n", " return await installDependenciesLinux(targets);\n", " }\n", "\n", " async install(executablesToInstall?: Executable[]) {\n", " const executables = this._addRequirementsAndDedupe(executablesToInstall);\n", " await fs.promises.mkdir(registryDirectory, { recursive: true });\n", " const lockfilePath = path.join(registryDirectory, '__dirlock');\n", " const releaseLock = await lockfile.lock(registryDirectory, {\n", " retries: {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " async install(executablesToInstall: Executable[]) {\n" ], "file_path": "src/utils/registry.ts", "type": "replace", "edit_start_line_idx": 530 }
/* 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. */ .network-request { white-space: nowrap; display: flex; align-items: center; padding: 0 3px; background: #fdfcfc; width: 100%; flex: none; outline: none; } .network-request.selected, .network-request:hover { border-color: var(--inactive-focus-ring); } .network-request.selected:focus { border-color: var(--orange); } .network-request-title { height: 28px; display: flex; align-items: center; flex: 1; } .network-request-title-status, .network-request-title-method { padding-right: 5px; } .network-request-title-status.status-failure { background-color: var(--red); color: var(--white); } .network-request-title-status.status-neutral { background-color: var(--white); } .network-request-title-url { overflow: hidden; text-overflow: ellipsis; flex: 1; } .network-request-details { width: 100%; user-select: text; } .network-request-details-url { white-space: normal; word-wrap: break-word; } .network-request-headers { white-space: pre; overflow: hidden; } .network-request-body { white-space: pre; overflow: scroll; background-color: var(--network-content-bg); border: black 1px solid; max-height: 500px; } .network-request-response-body { white-space: pre; overflow: scroll; background-color: var(--network-content-bg); border: black 1px solid; max-height: 500px; } .network-request-details-header { margin: 3px 0; font-weight: bold; }
src/web/traceViewer/ui/networkResourceDetails.css
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.00017827062401920557, 0.0001739397703204304, 0.0001702588051557541, 0.00017326943634543568, 0.0000024007638330658665 ]
{ "id": 6, "code_window": [ " return await installDependenciesWindows(targets);\n", " if (os.platform() === 'linux')\n", " return await installDependenciesLinux(targets);\n", " }\n", "\n", " async install(executablesToInstall?: Executable[]) {\n", " const executables = this._addRequirementsAndDedupe(executablesToInstall);\n", " await fs.promises.mkdir(registryDirectory, { recursive: true });\n", " const lockfilePath = path.join(registryDirectory, '__dirlock');\n", " const releaseLock = await lockfile.lock(registryDirectory, {\n", " retries: {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " async install(executablesToInstall: Executable[]) {\n" ], "file_path": "src/utils/registry.ts", "type": "replace", "edit_start_line_idx": 530 }
/** * Copyright 2017 Google Inc. All rights reserved. * * 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. */ // @ts-check const md = require('../markdown'); /** @typedef {import('../markdown').MarkdownNode} MarkdownNode */ /** * @typedef {{ * name: string, * args: ParsedType | null, * retType: ParsedType | null, * template: ParsedType | null, * union: ParsedType | null, * unionName?: string, * next: ParsedType | null, * }} ParsedType */ /** * @typedef {{ * only?: string[], * aliases?: Object<string, string>, * types?: Object<string, Documentation.Type>, * overrides?: Object<string, Documentation.Member>, * }} Langs */ /** * @typedef {function({ * clazz?: Documentation.Class, * member?: Documentation.Member, * param?: string, * option?: string * }): string} Renderer */ class Documentation { /** * @param {!Array<!Documentation.Class>} classesArray */ constructor(classesArray) { this.classesArray = classesArray; /** @type {!Map<string, !Documentation.Class>} */ this.classes = new Map(); this.index(); } /** * @param {!Documentation} documentation * @return {!Documentation} */ mergeWith(documentation) { return new Documentation([...this.classesArray, ...documentation.classesArray]); } /** * @param {string[]} errors */ copyDocsFromSuperclasses(errors) { for (const [name, clazz] of this.classes.entries()) { clazz.validateOrder(errors, clazz); if (!clazz.extends || ['EventEmitter', 'Error', 'Exception', 'RuntimeException'].includes(clazz.extends)) continue; const superClass = this.classes.get(clazz.extends); if (!superClass) { errors.push(`Undefined superclass: ${superClass} in ${name}`); continue; } for (const memberName of clazz.members.keys()) { if (superClass.members.has(memberName)) errors.push(`Member documentation overrides base: ${name}.${memberName} over ${clazz.extends}.${memberName}`); } clazz.membersArray = [...clazz.membersArray, ...superClass.membersArray.map(c => c.clone())]; clazz.index(); } } /** * @param {string} lang */ filterForLanguage(lang) { const classesArray = []; for (const clazz of this.classesArray) { if (clazz.langs.only && !clazz.langs.only.includes(lang)) continue; clazz.filterForLanguage(lang); classesArray.push(clazz); } this.classesArray = classesArray; this.index(); } index() { for (const cls of this.classesArray) { this.classes.set(cls.name, cls); cls.index(); } } /** * @param {Renderer} linkRenderer */ setLinkRenderer(linkRenderer) { // @type {Map<string, Documentation.Class>} const classesMap = new Map(); const membersMap = new Map(); for (const clazz of this.classesArray) { classesMap.set(clazz.name, clazz); for (const member of clazz.membersArray) membersMap.set(`${member.kind}: ${clazz.name}.${member.name}`, member); } /** * @param {Documentation.Class|Documentation.Member|null} classOrMember * @param {MarkdownNode[]} nodes */ this._patchLinks = (classOrMember, nodes) => patchLinks(classOrMember, nodes, classesMap, membersMap, linkRenderer); for (const clazz of this.classesArray) clazz.visit(item => this._patchLinks(item, item.spec)); } /** * @param {MarkdownNode[]} nodes */ renderLinksInText(nodes) { this._patchLinks(null, nodes); } generateSourceCodeComments() { for (const clazz of this.classesArray) clazz.visit(item => item.comment = generateSourceCodeComment(item.spec)); } } Documentation.Class = class { /** * @param {Langs} langs * @param {string} name * @param {!Array<!Documentation.Member>} membersArray * @param {?string=} extendsName * @param {MarkdownNode[]=} spec */ constructor(langs, name, membersArray, extendsName = null, spec = undefined) { this.langs = langs; this.name = name; this.membersArray = membersArray; this.spec = spec; this.extends = extendsName; this.comment = ''; this.index(); const match = name.match(/(JS|CDP|[A-Z])(.*)/); this.varName = match[1].toLowerCase() + match[2]; } index() { /** @type {!Map<string, !Documentation.Member>} */ this.members = new Map(); /** @type {!Map<string, !Documentation.Member>} */ this.properties = new Map(); /** @type {!Array<!Documentation.Member>} */ this.propertiesArray = []; /** @type {!Map<string, !Documentation.Member>} */ this.methods = new Map(); /** @type {!Array<!Documentation.Member>} */ this.methodsArray = []; /** @type {!Map<string, !Documentation.Member>} */ this.events = new Map(); /** @type {!Array<!Documentation.Member>} */ this.eventsArray = []; for (const member of this.membersArray) { this.members.set(member.name, member); if (member.kind === 'method') { this.methods.set(member.name, member); this.methodsArray.push(member); } else if (member.kind === 'property') { this.properties.set(member.name, member); this.propertiesArray.push(member); } else if (member.kind === 'event') { this.events.set(member.name, member); this.eventsArray.push(member); } member.clazz = this; member.index(); } } /** * @param {string} lang */ filterForLanguage(lang) { const membersArray = []; for (const member of this.membersArray) { if (member.langs.only && !member.langs.only.includes(lang)) continue; member.filterForLanguage(lang); membersArray.push(member); } this.membersArray = membersArray; } validateOrder(errors, cls) { const members = this.membersArray; // Events should go first. let eventIndex = 0; for (; eventIndex < members.length && members[eventIndex].kind === 'event'; ++eventIndex); for (; eventIndex < members.length && members[eventIndex].kind !== 'event'; ++eventIndex); if (eventIndex < members.length) errors.push(`Events should go first. Event '${members[eventIndex].name}' in class ${cls.name} breaks order`); // Constructor should be right after events and before all other members. const constructorIndex = members.findIndex(member => member.kind === 'method' && member.name === 'constructor'); if (constructorIndex > 0 && members[constructorIndex - 1].kind !== 'event') errors.push(`Constructor of ${cls.name} should go before other methods`); // Events should be sorted alphabetically. for (let i = 0; i < members.length - 1; ++i) { const member1 = this.membersArray[i]; const member2 = this.membersArray[i + 1]; if (member1.kind !== 'event' || member2.kind !== 'event') continue; if (member1.name.localeCompare(member2.name, 'en', { sensitivity: 'base' }) > 0) errors.push(`Event '${member1.name}' in class ${this.name} breaks alphabetic ordering of events`); } // All other members should be sorted alphabetically. for (let i = 0; i < members.length - 1; ++i) { const member1 = this.membersArray[i]; const member2 = this.membersArray[i + 1]; if (member1.kind === 'event' || member2.kind === 'event') continue; if (member1.kind === 'method' && member1.name === 'constructor') continue; if (member1.name.replace(/^\$+/, '$').localeCompare(member2.name.replace(/^\$+/, '$'), 'en', { sensitivity: 'base' }) > 0) { let memberName1 = `${this.name}.${member1.name}`; if (member1.kind === 'method') memberName1 += '()'; let memberName2 = `${this.name}.${member2.name}`; if (member2.kind === 'method') memberName2 += '()'; errors.push(`Bad alphabetic ordering of ${this.name} members: ${memberName1} should go after ${memberName2}`); } } } /** * @param {function(Documentation.Member|Documentation.Class): void} visitor */ visit(visitor) { visitor(this); for (const p of this.propertiesArray) p.visit(visitor); for (const m of this.methodsArray) m.visit(visitor); for (const e of this.eventsArray) e.visit(visitor); } }; Documentation.Member = class { /** * @param {string} kind * @param {Langs} langs * @param {string} name * @param {?Documentation.Type} type * @param {!Array<!Documentation.Member>} argsArray * @param {MarkdownNode[]=} spec * @param {boolean=} required * @param {string[]=} templates */ constructor(kind, langs, name, type, argsArray, spec = undefined, required = true, templates = []) { this.kind = kind; this.langs = langs; this.name = name; this.type = type; this.spec = spec; this.argsArray = argsArray; this.required = required; this.comment = ''; /** @type {!Map<string, !Documentation.Member>} */ this.args = new Map(); this.index(); /** @type {!Documentation.Class} */ this.clazz = null; /** @type {Documentation.Member=} */ this.enclosingMethod = undefined; this.deprecated = false; if (spec) { md.visitAll(spec, node => { if (node.text && node.text.includes('**DEPRECATED**')) this.deprecated = true; }); }; this.async = false; this.alias = name; this.overloadIndex = 0; if (name.includes('#')) { const match = name.match(/(.*)#(.*)/); this.alias = match[1]; this.overloadIndex = (+match[2]) - 1; } /** * Param is true and option false * @type {Boolean} */ this.paramOrOption = null; } index() { this.args = new Map(); if (this.kind === 'method') this.enclosingMethod = this; for (const arg of this.argsArray) { this.args.set(arg.name, arg); arg.enclosingMethod = this; if (arg.name === 'options') { arg.type.properties.sort((p1, p2) => p1.name.localeCompare(p2.name)); arg.type.properties.forEach(p => p.enclosingMethod = this); } } } /** * @param {string} lang */ filterForLanguage(lang) { if (this.langs.aliases && this.langs.aliases[lang]) this.alias = this.langs.aliases[lang]; if (this.langs.types && this.langs.types[lang]) this.type = this.langs.types[lang]; this.type.filterForLanguage(lang); const argsArray = []; for (const arg of this.argsArray) { if (arg.langs.only && !arg.langs.only.includes(lang)) continue; const overriddenArg = (arg.langs.overrides && arg.langs.overrides[lang]) || arg; overriddenArg.filterForLanguage(lang); if (overriddenArg.name === 'options' && !overriddenArg.type.properties.length) continue; argsArray.push(overriddenArg); } this.argsArray = argsArray; } clone() { const result = new Documentation.Member(this.kind, this.langs, this.name, this.type, this.argsArray, this.spec, this.required); result.async = this.async; result.paramOrOption = this.paramOrOption; return result; } /** * @param {Langs} langs * @param {string} name * @param {!Array<!Documentation.Member>} argsArray * @param {?Documentation.Type} returnType * @param {MarkdownNode[]=} spec * @return {!Documentation.Member} */ static createMethod(langs, name, argsArray, returnType, spec) { return new Documentation.Member('method', langs, name, returnType, argsArray, spec); } /** * @param {!Langs} langs * @param {!string} name * @param {!Documentation.Type} type * @param {!MarkdownNode[]=} spec * @param {boolean=} required * @return {!Documentation.Member} */ static createProperty(langs, name, type, spec, required) { return new Documentation.Member('property', langs, name, type, [], spec, required); } /** * @param {Langs} langs * @param {string} name * @param {?Documentation.Type=} type * @param {MarkdownNode[]=} spec * @return {!Documentation.Member} */ static createEvent(langs, name, type = null, spec) { return new Documentation.Member('event', langs, name, type, [], spec); } /** * @param {function(Documentation.Member|Documentation.Class): void} visitor */ visit(visitor) { visitor(this); if (this.type) this.type.visit(visitor); for (const arg of this.argsArray) arg.visit(visitor); } }; Documentation.Type = class { /** * @param {string} expression * @param {!Array<!Documentation.Member>=} properties * @return {Documentation.Type} */ static parse(expression, properties = []) { expression = expression.replace(/\\\(/g, '(').replace(/\\\)/g, ')'); const type = Documentation.Type.fromParsedType(parseTypeExpression(expression)); type.expression = expression; if (type.name === 'number') throw new Error('Number types should be either int or float, not number in: ' + expression); if (!properties.length) return type; const types = []; type._collectAllTypes(types); let success = false; for (const t of types) { if (t.name === 'Object') { t.properties = properties; success = true; } } if (!success) throw new Error('Nested properties given, but there are no objects in type expression: ' + expression); return type; } /** * @param {ParsedType} parsedType * @return {Documentation.Type} */ static fromParsedType(parsedType, inUnion = false) { if (!inUnion && parsedType.union) { const type = new Documentation.Type(parsedType.unionName || ''); type.union = []; for (let t = parsedType; t; t = t.union) { const nestedUnion = !!t.unionName && t !== parsedType; type.union.push(Documentation.Type.fromParsedType(t, !nestedUnion)); if (nestedUnion) break; } return type; } if (parsedType.args) { const type = new Documentation.Type('function'); type.args = []; for (let t = parsedType.args; t; t = t.next) type.args.push(Documentation.Type.fromParsedType(t)); type.returnType = parsedType.retType ? Documentation.Type.fromParsedType(parsedType.retType) : null; return type; } if (parsedType.template) { const type = new Documentation.Type(parsedType.name); type.templates = []; for (let t = parsedType.template; t; t = t.next) type.templates.push(Documentation.Type.fromParsedType(t)); return type; } return new Documentation.Type(parsedType.name); } /** * @param {string} name * @param {!Array<!Documentation.Member>=} properties */ constructor(name, properties) { this.name = name.replace(/^\[/, '').replace(/\]$/, ''); this.properties = this.name === 'Object' ? properties : undefined; /** @type {Documentation.Type[]} | undefined */ this.union; /** @type {Documentation.Type[]} | undefined */ this.args; /** @type {Documentation.Type} | undefined */ this.returnType; /** @type {Documentation.Type[]} | undefined */ this.templates; /** @type {string | undefined } */ this.expression; } visit(visitor) { const types = []; this._collectAllTypes(types); for (const type of types) { for (const p of type.properties || []) p.visit(visitor); } } /** * @returns {Documentation.Member[]} */ deepProperties() { const types = []; this._collectAllTypes(types); for (const type of types) { if (type.properties && type.properties.length) return type.properties; } return []; } /** * @returns {Documentation.Member[]} */ sortedProperties() { if (!this.properties) return this.properties; const sortedProperties = [...this.properties]; sortedProperties.sort((p1, p2) => p1.name.localeCompare(p2.name)); return sortedProperties; } /** * @param {string} lang */ filterForLanguage(lang) { if (!this.properties) return; const properties = []; for (const prop of this.properties) { if (prop.langs.only && !prop.langs.only.includes(lang)) continue; prop.filterForLanguage(lang); properties.push(prop); } this.properties = properties; } /** * @param {Documentation.Type[]} result */ _collectAllTypes(result) { result.push(this); for (const t of this.union || []) t._collectAllTypes(result); for (const t of this.args || []) t._collectAllTypes(result); for (const t of this.templates || []) t._collectAllTypes(result); if (this.returnType) this.returnType._collectAllTypes(result); } }; /** * @param {ParsedType} type * @returns {boolean} */ function isStringUnion(type) { if (!type.union) return false; while (type) { if (!type.name.startsWith('"') || !type.name.endsWith('"')) return false; type = type.union; } return true; } /** * @param {string} type * @returns {ParsedType} */ function parseTypeExpression(type) { type = type.trim(); let name = type; let next = null; let template = null; let args = null; let retType = null; let firstTypeLength = type.length; for (let i = 0; i < type.length; i++) { if (type[i] === '<') { name = type.substring(0, i); const matching = matchingBracket(type.substring(i), '<', '>'); template = parseTypeExpression(type.substring(i + 1, i + matching - 1)); firstTypeLength = i + matching; break; } if (type[i] === '(') { name = type.substring(0, i); const matching = matchingBracket(type.substring(i), '(', ')'); args = parseTypeExpression(type.substring(i + 1, i + matching - 1)); i = i + matching; if (type[i] === ':') { retType = parseTypeExpression(type.substring(i + 1)); next = retType.next; retType.next = null; break; } } if (type[i] === '|' || type[i] === ',') { name = type.substring(0, i); firstTypeLength = i; break; } } let union = null; if (type[firstTypeLength] === '|') union = parseTypeExpression(type.substring(firstTypeLength + 1)); else if (type[firstTypeLength] === ',') next = parseTypeExpression(type.substring(firstTypeLength + 1)); if (template && !template.unionName && isStringUnion(template)) { template.unionName = name; return template; } return { name, args, retType, template, union, next }; } /** * @param {string} str * @param {any} open * @param {any} close */ function matchingBracket(str, open, close) { let count = 1; let i = 1; for (; i < str.length && count; i++) { if (str[i] === open) count++; else if (str[i] === close) count--; } return i; } /** * @param {Documentation.Class|Documentation.Member|null} classOrMember * @param {MarkdownNode[]} spec * @param {Map<string, Documentation.Class>} classesMap * @param {Map<string, Documentation.Member>} membersMap * @param {Renderer} linkRenderer */ function patchLinks(classOrMember, spec, classesMap, membersMap, linkRenderer) { if (!spec) return; md.visitAll(spec, node => { if (!node.text) return; node.text = node.text.replace(/\[`(\w+): ([^\]]+)`\]/g, (match, p1, p2) => { if (['event', 'method', 'property'].includes(p1)) { const memberName = p1 + ': ' + p2; const member = membersMap.get(memberName); if (!member) throw new Error('Undefined member references: ' + match); return linkRenderer({ member }) || match; } if (p1 === 'param') { let alias = p2; if (classOrMember) { // param/option reference can only be in method or same method parameter comments. // @ts-ignore const method = classOrMember.enclosingMethod; const param = method.argsArray.find(a => a.name === p2); if (!param) throw new Error(`Referenced parameter ${match} not found in the parent method ${method.name} `); alias = param.alias; } return linkRenderer({ param: alias }) || match; } if (p1 === 'option') return linkRenderer({ option: p2 }) || match; throw new Error(`Undefined link prefix, expected event|method|property|param|option, got: ` + match); }); node.text = node.text.replace(/\[([\w]+)\]/g, (match, p1) => { const clazz = classesMap.get(p1); if (clazz) return linkRenderer({ clazz }) || match; return match; }); }); } /** * @param {MarkdownNode[]} spec */ function generateSourceCodeComment(spec) { const comments = (spec || []).filter(n => !n.type.startsWith('h') && (n.type !== 'li' || n.liType !== 'default')).map(c => md.clone(c)); md.visitAll(comments, node => { if (node.liType === 'bullet') node.liType = 'default'; if (node.type === 'note') { node.type = 'text'; node.text = '> NOTE: ' + node.text; } }); return md.render(comments, 120); } module.exports = Documentation;
utils/doclint/documentation.js
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.00017844255489762872, 0.00017458594811614603, 0.00016918007167987525, 0.0001747170026646927, 0.0000020219897578499513 ]
{ "id": 7, "code_window": [ " }\n", "}\n", "\n", "export async function installDefaultBrowsersForNpmInstall() {\n", " // PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD should have a value of 0 or 1\n", " if (getAsBooleanFromENV('PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD')) {\n", " logPolitely('Skipping browsers download because `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` env variable is set');\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const defaultBrowserNames = registry.defaultExecutables().map(e => e.name);\n", " return installBrowsersForNpmInstall(defaultBrowserNames);\n", "}\n", "\n", "export async function installBrowsersForNpmInstall(browsers: string[]) {\n" ], "file_path": "src/utils/registry.ts", "type": "add", "edit_start_line_idx": 705 }
#!/usr/bin/env node /** * 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 no-console */ import fs from 'fs'; import os from 'os'; import path from 'path'; import program from 'commander'; import { runDriver, runServer, printApiJson, launchBrowserServer } from './driver'; import { showTraceViewer } from '../server/trace/viewer/traceViewer'; import * as playwright from '../..'; import { BrowserContext } from '../client/browserContext'; import { Browser } from '../client/browser'; import { Page } from '../client/page'; import { BrowserType } from '../client/browserType'; import { BrowserContextOptions, LaunchOptions } from '../client/types'; import { spawn } from 'child_process'; import { registry, Executable } from '../utils/registry'; import { launchGridAgent } from '../grid/gridAgent'; import { launchGridServer } from '../grid/gridServer'; const packageJSON = require('../../package.json'); program .version('Version ' + packageJSON.version) .name(process.env.PW_CLI_NAME || 'npx playwright'); commandWithOpenOptions('open [url]', 'open page in browser specified via -b, --browser', []) .action(function(url, command) { open(command, url, language()).catch(logErrorAndExit); }) .on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ open'); console.log(' $ open -b webkit https://example.com'); }); commandWithOpenOptions('codegen [url]', 'open page and generate code for user actions', [ ['-o, --output <file name>', 'saves the generated script to a file'], ['--target <language>', `language to generate, one of javascript, test, python, python-async, csharp`, language()], ]).action(function(url, command) { codegen(command, url, command.target, command.output).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ codegen'); console.log(' $ codegen --target=python'); console.log(' $ codegen -b webkit https://example.com'); }); program .command('debug <app> [args...]', { hidden: true }) .description('run command in debug mode: disable timeout, open inspector') .allowUnknownOption(true) .action(function(app, args) { spawn(app, args, { env: { ...process.env, PWDEBUG: '1' }, stdio: 'inherit' }); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ debug node test.js'); console.log(' $ debug npm run test'); }); function suggestedBrowsersToInstall() { return registry.executables().filter(e => e.installType !== 'none' && e.type !== 'tool').map(e => e.name).join(', '); } function checkBrowsersToInstall(args: string[]): Executable[] { const faultyArguments: string[] = []; const executables: Executable[] = []; for (const arg of args) { const executable = registry.findExecutable(arg); if (!executable || executable.installType === 'none') faultyArguments.push(arg); else executables.push(executable); } if (faultyArguments.length) { console.log(`Invalid installation targets: ${faultyArguments.map(name => `'${name}'`).join(', ')}. Expecting one of: ${suggestedBrowsersToInstall()}`); process.exit(1); } return executables; } program .command('install [browser...]') .description('ensure browsers necessary for this version of Playwright are installed') .option('--with-deps', 'install system dependencies for browsers') .action(async function(args: string[], command: program.Command) { try { if (!args.length) { if (command.opts().withDeps) await registry.installDeps(); await registry.install(); } else { const executables = checkBrowsersToInstall(args); if (command.opts().withDeps) await registry.installDeps(executables); await registry.install(executables); } } catch (e) { console.log(`Failed to install browsers\n${e}`); process.exit(1); } }).on('--help', function() { console.log(``); console.log(`Examples:`); console.log(` - $ install`); console.log(` Install default browsers.`); console.log(``); console.log(` - $ install chrome firefox`); console.log(` Install custom browsers, supports ${suggestedBrowsersToInstall()}.`); }); program .command('install-deps [browser...]') .description('install dependencies necessary to run browsers (will ask for sudo permissions)') .action(async function(args: string[]) { try { if (!args.length) await registry.installDeps(); else await registry.installDeps(checkBrowsersToInstall(args)); } catch (e) { console.log(`Failed to install browser dependencies\n${e}`); process.exit(1); } }).on('--help', function() { console.log(``); console.log(`Examples:`); console.log(` - $ install-deps`); console.log(` Install dependencies for default browsers.`); console.log(``); console.log(` - $ install-deps chrome firefox`); console.log(` Install dependencies for specific browsers, supports ${suggestedBrowsersToInstall()}.`); }); const browsers = [ { alias: 'cr', name: 'Chromium', type: 'chromium' }, { alias: 'ff', name: 'Firefox', type: 'firefox' }, { alias: 'wk', name: 'WebKit', type: 'webkit' }, ]; for (const {alias, name, type} of browsers) { commandWithOpenOptions(`${alias} [url]`, `open page in ${name}`, []) .action(function(url, command) { open({ ...command, browser: type }, url, command.target).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(` $ ${alias} https://example.com`); }); } commandWithOpenOptions('screenshot <url> <filename>', 'capture a page screenshot', [ ['--wait-for-selector <selector>', 'wait for selector before taking a screenshot'], ['--wait-for-timeout <timeout>', 'wait for timeout in milliseconds before taking a screenshot'], ['--full-page', 'whether to take a full page screenshot (entire scrollable area)'], ]).action(function(url, filename, command) { screenshot(command, command, url, filename).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ screenshot -b webkit https://example.com example.png'); }); commandWithOpenOptions('pdf <url> <filename>', 'save page as pdf', [ ['--wait-for-selector <selector>', 'wait for given selector before saving as pdf'], ['--wait-for-timeout <timeout>', 'wait for given timeout in milliseconds before saving as pdf'], ]).action(function(url, filename, command) { pdf(command, command, url, filename).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ pdf https://example.com example.pdf'); }); program .command('experimental-grid-server', { hidden: true }) .option('--port <port>', 'grid port; defaults to 3333') .option('--agent-factory <factory>', 'path to grid agent factory or npm package') .option('--auth-token <authToken>', 'optional authentication token') .action(function(options) { launchGridServer(options.agentFactory, options.port || 3333, options.authToken); }); program .command('experimental-grid-agent', { hidden: true }) .requiredOption('--agent-id <agentId>', 'agent ID') .requiredOption('--grid-url <gridURL>', 'grid URL') .action(function(options) { launchGridAgent(options.agentId, options.gridUrl); }); program .command('show-trace [trace]') .option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium') .description('Show trace viewer') .action(function(trace, command) { if (command.browser === 'cr') command.browser = 'chromium'; if (command.browser === 'ff') command.browser = 'firefox'; if (command.browser === 'wk') command.browser = 'webkit'; showTraceViewer(trace, command.browser).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ show-trace trace/directory'); }); if (!process.env.PW_CLI_TARGET_LANG) { let playwrightTestPackagePath = null; try { const isLocal = packageJSON.name === '@playwright/test' || process.env.PWTEST_CLI_ALLOW_TEST_COMMAND; if (isLocal) { playwrightTestPackagePath = '../test/cli'; } else { playwrightTestPackagePath = require.resolve('@playwright/test/lib/test/cli', { paths: [__dirname, process.cwd()] }); } } catch {} if (playwrightTestPackagePath) { require(playwrightTestPackagePath).addTestCommand(program); } else { const command = program.command('test').allowUnknownOption(true); command.description('Run tests with Playwright Test. Available in @playwright/test package.'); command.action(async (args, opts) => { console.error('Please install @playwright/test package to use Playwright Test.'); console.error(' npm install -D @playwright/test'); process.exit(1); }); } } if (process.argv[2] === 'run-driver') runDriver(); else if (process.argv[2] === 'run-server') runServer(process.argv[3] ? +process.argv[3] : undefined).catch(logErrorAndExit); else if (process.argv[2] === 'print-api-json') printApiJson(); else if (process.argv[2] === 'launch-server') launchBrowserServer(process.argv[3], process.argv[4]).catch(logErrorAndExit); else program.parse(process.argv); type Options = { browser: string; channel?: string; colorScheme?: string; device?: string; geolocation?: string; ignoreHttpsErrors?: boolean; lang?: string; loadStorage?: string; proxyServer?: string; saveStorage?: string; saveTrace?: string; timeout: string; timezone?: string; viewportSize?: string; userAgent?: string; }; type CaptureOptions = { waitForSelector?: string; waitForTimeout?: string; fullPage: boolean; }; async function launchContext(options: Options, headless: boolean, executablePath?: string): Promise<{ browser: Browser, browserName: string, launchOptions: LaunchOptions, contextOptions: BrowserContextOptions, context: BrowserContext }> { validateOptions(options); const browserType = lookupBrowserType(options); const launchOptions: LaunchOptions = { headless, executablePath }; if (options.channel) launchOptions.channel = options.channel as any; const contextOptions: BrowserContextOptions = // Copy the device descriptor since we have to compare and modify the options. options.device ? { ...playwright.devices[options.device] } : {}; // In headful mode, use host device scale factor for things to look nice. // In headless, keep things the way it works in Playwright by default. // Assume high-dpi on MacOS. TODO: this is not perfect. if (!headless) contextOptions.deviceScaleFactor = os.platform() === 'darwin' ? 2 : 1; // Work around the WebKit GTK scrolling issue. if (browserType.name() === 'webkit' && process.platform === 'linux') { delete contextOptions.hasTouch; delete contextOptions.isMobile; } if (contextOptions.isMobile && browserType.name() === 'firefox') contextOptions.isMobile = undefined; contextOptions.acceptDownloads = true; // Proxy if (options.proxyServer) { launchOptions.proxy = { server: options.proxyServer }; } const browser = await browserType.launch(launchOptions); // Viewport size if (options.viewportSize) { try { const [ width, height ] = options.viewportSize.split(',').map(n => parseInt(n, 10)); contextOptions.viewport = { width, height }; } catch (e) { console.log('Invalid window size format: use "width, height", for example --window-size=800,600'); process.exit(0); } } // Geolocation if (options.geolocation) { try { const [latitude, longitude] = options.geolocation.split(',').map(n => parseFloat(n.trim())); contextOptions.geolocation = { latitude, longitude }; } catch (e) { console.log('Invalid geolocation format: user lat, long, for example --geolocation="37.819722,-122.478611"'); process.exit(0); } contextOptions.permissions = ['geolocation']; } // User agent if (options.userAgent) contextOptions.userAgent = options.userAgent; // Lang if (options.lang) contextOptions.locale = options.lang; // Color scheme if (options.colorScheme) contextOptions.colorScheme = options.colorScheme as 'dark' | 'light'; // Timezone if (options.timezone) contextOptions.timezoneId = options.timezone; // Storage if (options.loadStorage) contextOptions.storageState = options.loadStorage; if (options.ignoreHttpsErrors) contextOptions.ignoreHTTPSErrors = true; // Close app when the last window closes. const context = await browser.newContext(contextOptions); let closingBrowser = false; async function closeBrowser() { // We can come here multiple times. For example, saving storage creates // a temporary page and we call closeBrowser again when that page closes. if (closingBrowser) return; closingBrowser = true; if (options.saveTrace) await context.tracing.stop({ path: options.saveTrace }); if (options.saveStorage) await context.storageState({ path: options.saveStorage }).catch(e => null); await browser.close(); } context.on('page', page => { page.on('dialog', () => {}); // Prevent dialogs from being automatically dismissed. page.on('close', () => { const hasPage = browser.contexts().some(context => context.pages().length > 0); if (hasPage) return; // Avoid the error when the last page is closed because the browser has been closed. closeBrowser().catch(e => null); }); }); if (options.timeout) { context.setDefaultTimeout(parseInt(options.timeout, 10)); context.setDefaultNavigationTimeout(parseInt(options.timeout, 10)); } if (options.saveTrace) await context.tracing.start({ screenshots: true, snapshots: true }); // Omit options that we add automatically for presentation purpose. delete launchOptions.headless; delete launchOptions.executablePath; delete contextOptions.deviceScaleFactor; delete contextOptions.acceptDownloads; return { browser, browserName: browserType.name(), context, contextOptions, launchOptions }; } async function openPage(context: BrowserContext, url: string | undefined): Promise<Page> { const page = await context.newPage(); if (url) { if (fs.existsSync(url)) url = 'file://' + path.resolve(url); else if (!url.startsWith('http') && !url.startsWith('file://') && !url.startsWith('about:') && !url.startsWith('data:')) url = 'http://' + url; await page.goto(url); } return page; } async function open(options: Options, url: string | undefined, language: string) { const { context, launchOptions, contextOptions } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH); await context._enableRecorder({ language, launchOptions, contextOptions, device: options.device, saveStorage: options.saveStorage, }); await openPage(context, url); if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close())); } async function codegen(options: Options, url: string | undefined, language: string, outputFile?: string) { const { context, launchOptions, contextOptions } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH); await context._enableRecorder({ language, launchOptions, contextOptions, device: options.device, saveStorage: options.saveStorage, startRecording: true, outputFile: outputFile ? path.resolve(outputFile) : undefined }); await openPage(context, url); if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close())); } async function waitForPage(page: Page, captureOptions: CaptureOptions) { if (captureOptions.waitForSelector) { console.log(`Waiting for selector ${captureOptions.waitForSelector}...`); await page.waitForSelector(captureOptions.waitForSelector); } if (captureOptions.waitForTimeout) { console.log(`Waiting for timeout ${captureOptions.waitForTimeout}...`); await page.waitForTimeout(parseInt(captureOptions.waitForTimeout, 10)); } } async function screenshot(options: Options, captureOptions: CaptureOptions, url: string, path: string) { const { browser, context } = await launchContext(options, true); console.log('Navigating to ' + url); const page = await openPage(context, url); await waitForPage(page, captureOptions); console.log('Capturing screenshot into ' + path); await page.screenshot({ path, fullPage: !!captureOptions.fullPage }); await browser.close(); } async function pdf(options: Options, captureOptions: CaptureOptions, url: string, path: string) { if (options.browser !== 'chromium') { console.error('PDF creation is only working with Chromium'); process.exit(1); } const { browser, context } = await launchContext({ ...options, browser: 'chromium' }, true); console.log('Navigating to ' + url); const page = await openPage(context, url); await waitForPage(page, captureOptions); console.log('Saving as pdf into ' + path); await page.pdf!({ path }); await browser.close(); } function lookupBrowserType(options: Options): BrowserType { let name = options.browser; if (options.device) { const device = playwright.devices[options.device]; name = device.defaultBrowserType; } let browserType: any; switch (name) { case 'chromium': browserType = playwright.chromium; break; case 'webkit': browserType = playwright.webkit; break; case 'firefox': browserType = playwright.firefox; break; case 'cr': browserType = playwright.chromium; break; case 'wk': browserType = playwright.webkit; break; case 'ff': browserType = playwright.firefox; break; } if (browserType) return browserType; program.help(); } function validateOptions(options: Options) { if (options.device && !(options.device in playwright.devices)) { console.log(`Device descriptor not found: '${options.device}', available devices are:`); for (const name in playwright.devices) console.log(` "${name}"`); process.exit(0); } if (options.colorScheme && !['light', 'dark'].includes(options.colorScheme)) { console.log('Invalid color scheme, should be one of "light", "dark"'); process.exit(0); } } function logErrorAndExit(e: Error) { console.error(e); process.exit(1); } function language(): string { return process.env.PW_CLI_TARGET_LANG || 'test'; } function commandWithOpenOptions(command: string, description: string, options: any[][]): program.Command { let result = program.command(command).description(description); for (const option of options) result = result.option(option[0], ...option.slice(1)); return result .option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium') .option('--channel <channel>', 'Chromium distribution channel, "chrome", "chrome-beta", "msedge-dev", etc') .option('--color-scheme <scheme>', 'emulate preferred color scheme, "light" or "dark"') .option('--device <deviceName>', 'emulate device, for example "iPhone 11"') .option('--geolocation <coordinates>', 'specify geolocation coordinates, for example "37.819722,-122.478611"') .option('--ignore-https-errors', 'ignore https errors') .option('--load-storage <filename>', 'load context storage state from the file, previously saved with --save-storage') .option('--lang <language>', 'specify language / locale, for example "en-GB"') .option('--proxy-server <proxy>', 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"') .option('--save-storage <filename>', 'save context storage state at the end, for later use with --load-storage') .option('--save-trace <filename>', 'record a trace for the session and save it to a file') .option('--timezone <time zone>', 'time zone to emulate, for example "Europe/Rome"') .option('--timeout <timeout>', 'timeout for Playwright actions in milliseconds', '10000') .option('--user-agent <ua string>', 'specify user agent string') .option('--viewport-size <size>', 'specify browser viewport size in pixels, for example "1280, 720"'); }
src/cli/cli.ts
1
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.031989727169275284, 0.0014351371210068464, 0.00016414631681982428, 0.00017115911759901792, 0.004702341742813587 ]
{ "id": 7, "code_window": [ " }\n", "}\n", "\n", "export async function installDefaultBrowsersForNpmInstall() {\n", " // PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD should have a value of 0 or 1\n", " if (getAsBooleanFromENV('PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD')) {\n", " logPolitely('Skipping browsers download because `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` env variable is set');\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const defaultBrowserNames = registry.defaultExecutables().map(e => e.name);\n", " return installBrowsersForNpmInstall(defaultBrowserNames);\n", "}\n", "\n", "export async function installBrowsersForNpmInstall(browsers: string[]) {\n" ], "file_path": "src/utils/registry.ts", "type": "add", "edit_start_line_idx": 705 }
/** * 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', async ({page}) => { await page.setContent(`<div>yo</div><div>ya</div><div>\nye </div>`); expect(await page.$eval(`text=ya`, e => e.outerHTML)).toBe('<div>ya</div>'); expect(await page.$eval(`text="ya"`, e => e.outerHTML)).toBe('<div>ya</div>'); expect(await page.$eval(`text=/^[ay]+$/`, e => e.outerHTML)).toBe('<div>ya</div>'); expect(await page.$eval(`text=/Ya/i`, e => e.outerHTML)).toBe('<div>ya</div>'); expect(await page.$eval(`text=ye`, e => e.outerHTML)).toBe('<div>\nye </div>'); await page.setContent(`<div> ye </div><div>ye</div>`); expect(await page.$eval(`text="ye"`, e => e.outerHTML)).toBe('<div> ye </div>'); await page.setContent(`<div>yo</div><div>"ya</div><div> hello world! </div>`); expect(await page.$eval(`text="\\"ya"`, e => e.outerHTML)).toBe('<div>"ya</div>'); expect(await page.$eval(`text=/hello/`, e => e.outerHTML)).toBe('<div> hello world! </div>'); expect(await page.$eval(`text=/^\\s*heLLo/i`, e => e.outerHTML)).toBe('<div> hello world! </div>'); await page.setContent(`<div>yo<div>ya</div>hey<div>hey</div></div>`); expect(await page.$eval(`text=hey`, e => e.outerHTML)).toBe('<div>hey</div>'); expect(await page.$eval(`text=yo>>text="ya"`, e => e.outerHTML)).toBe('<div>ya</div>'); expect(await page.$eval(`text=yo>> text="ya"`, e => e.outerHTML)).toBe('<div>ya</div>'); expect(await page.$eval(`text=yo >>text='ya'`, e => e.outerHTML)).toBe('<div>ya</div>'); expect(await page.$eval(`text=yo >> text='ya'`, e => e.outerHTML)).toBe('<div>ya</div>'); expect(await page.$eval(`'yo'>>"ya"`, e => e.outerHTML)).toBe('<div>ya</div>'); expect(await page.$eval(`"yo" >> 'ya'`, e => e.outerHTML)).toBe('<div>ya</div>'); await page.setContent(`<div>yo<span id="s1"></span></div><div>yo<span id="s2"></span><span id="s3"></span></div>`); expect(await page.$$eval(`text=yo`, es => es.map(e => e.outerHTML).join('\n'))).toBe('<div>yo<span id="s1"></span></div>\n<div>yo<span id="s2"></span><span id="s3"></span></div>'); await page.setContent(`<div>'</div><div>"</div><div>\\</div><div>x</div>`); expect(await page.$eval(`text='\\''`, e => e.outerHTML)).toBe('<div>\'</div>'); expect(await page.$eval(`text='"'`, e => e.outerHTML)).toBe('<div>"</div>'); expect(await page.$eval(`text="\\""`, e => e.outerHTML)).toBe('<div>"</div>'); expect(await page.$eval(`text="'"`, e => e.outerHTML)).toBe('<div>\'</div>'); expect(await page.$eval(`text="\\x"`, e => e.outerHTML)).toBe('<div>x</div>'); expect(await page.$eval(`text='\\x'`, e => e.outerHTML)).toBe('<div>x</div>'); expect(await page.$eval(`text='\\\\'`, e => e.outerHTML)).toBe('<div>\\</div>'); expect(await page.$eval(`text="\\\\"`, e => e.outerHTML)).toBe('<div>\\</div>'); expect(await page.$eval(`text="`, e => e.outerHTML)).toBe('<div>"</div>'); expect(await page.$eval(`text='`, e => e.outerHTML)).toBe('<div>\'</div>'); expect(await page.$eval(`"x"`, e => e.outerHTML)).toBe('<div>x</div>'); expect(await page.$eval(`'x'`, e => e.outerHTML)).toBe('<div>x</div>'); let error = await page.$(`"`).catch(e => e); expect(error).toBeInstanceOf(Error); error = await page.$(`'`).catch(e => e); expect(error).toBeInstanceOf(Error); await page.setContent(`<div> ' </div><div> " </div>`); expect(await page.$eval(`text="`, e => e.outerHTML)).toBe('<div> " </div>'); expect(await page.$eval(`text='`, e => e.outerHTML)).toBe('<div> \' </div>'); await page.setContent(`<div>Hi''&gt;&gt;foo=bar</div>`); expect(await page.$eval(`text="Hi''>>foo=bar"`, e => e.outerHTML)).toBe(`<div>Hi''&gt;&gt;foo=bar</div>`); await page.setContent(`<div>Hi'"&gt;&gt;foo=bar</div>`); expect(await page.$eval(`text="Hi'\\">>foo=bar"`, e => e.outerHTML)).toBe(`<div>Hi'"&gt;&gt;foo=bar</div>`); await page.setContent(`<div>Hi&gt;&gt;<span></span></div>`); expect(await page.$eval(`text="Hi>>">>span`, e => e.outerHTML)).toBe(`<span></span>`); await page.setContent(`<div>a<br>b</div><div>a</div>`); expect(await page.$eval(`text=a`, e => e.outerHTML)).toBe('<div>a<br>b</div>'); expect(await page.$eval(`text=b`, e => e.outerHTML)).toBe('<div>a<br>b</div>'); expect(await page.$eval(`text=ab`, e => e.outerHTML)).toBe('<div>a<br>b</div>'); expect(await page.$(`text=abc`)).toBe(null); expect(await page.$$eval(`text=a`, els => els.length)).toBe(2); expect(await page.$$eval(`text=b`, els => els.length)).toBe(1); expect(await page.$$eval(`text=ab`, els => els.length)).toBe(1); expect(await page.$$eval(`text=abc`, els => els.length)).toBe(0); await page.setContent(`<div></div><span></span>`); await page.$eval('div', div => { div.appendChild(document.createTextNode('hello')); div.appendChild(document.createTextNode('world')); }); await page.$eval('span', span => { span.appendChild(document.createTextNode('hello')); span.appendChild(document.createTextNode('world')); }); expect(await page.$eval(`text=lowo`, e => e.outerHTML)).toBe('<div>helloworld</div>'); expect(await page.$$eval(`text=lowo`, els => els.map(e => e.outerHTML).join(''))).toBe('<div>helloworld</div><span>helloworld</span>'); await page.setContent(`<span>Sign&nbsp;in</span><span>Hello\n \nworld</span>`); expect(await page.$eval(`text=Sign in`, e => e.outerHTML)).toBe('<span>Sign&nbsp;in</span>'); expect((await page.$$(`text=Sign \tin`)).length).toBe(1); expect((await page.$$(`text="Sign in"`)).length).toBe(1); expect(await page.$eval(`text=lo wo`, e => e.outerHTML)).toBe('<span>Hello\n \nworld</span>'); expect(await page.$eval(`text="Hello world"`, e => e.outerHTML)).toBe('<span>Hello\n \nworld</span>'); expect(await page.$(`text="lo wo"`)).toBe(null); expect((await page.$$(`text=lo \nwo`)).length).toBe(1); expect((await page.$$(`text="lo \nwo"`)).length).toBe(0); }); it('should work with :text', async ({page}) => { await page.setContent(`<div>yo</div><div>ya</div><div>\nHELLO \n world </div>`); expect(await page.$eval(`:text("ya")`, e => e.outerHTML)).toBe('<div>ya</div>'); expect(await page.$eval(`:text-is("ya")`, e => e.outerHTML)).toBe('<div>ya</div>'); expect(await page.$eval(`:text("y")`, e => e.outerHTML)).toBe('<div>yo</div>'); expect(await page.$(`:text-is("Y")`)).toBe(null); expect(await page.$eval(`:text("hello world")`, e => e.outerHTML)).toBe('<div>\nHELLO \n world </div>'); expect(await page.$eval(`:text-is("HELLO world")`, e => e.outerHTML)).toBe('<div>\nHELLO \n world </div>'); expect(await page.$eval(`:text("lo wo")`, e => e.outerHTML)).toBe('<div>\nHELLO \n world </div>'); expect(await page.$(`:text-is("lo wo")`)).toBe(null); expect(await page.$eval(`:text-matches("^[ay]+$")`, e => e.outerHTML)).toBe('<div>ya</div>'); expect(await page.$eval(`:text-matches("y", "g")`, e => e.outerHTML)).toBe('<div>yo</div>'); expect(await page.$eval(`:text-matches("Y", "i")`, e => e.outerHTML)).toBe('<div>yo</div>'); expect(await page.$(`:text-matches("^y$")`)).toBe(null); const error1 = await page.$(`:text("foo", "bar")`).catch(e => e); expect(error1.message).toContain(`"text" engine expects a single string`); const error2 = await page.$(`:text(foo > bar)`).catch(e => e); expect(error2.message).toContain(`"text" engine expects a single string`); }); it('should work across nodes', async ({page}) => { await page.setContent(`<div id=target1>Hello<i>,</i> <span id=target2>world</span><b>!</b></div>`); expect(await page.$eval(`:text("Hello, world!")`, e => e.id)).toBe('target1'); expect(await page.$eval(`:text("Hello")`, e => e.id)).toBe('target1'); expect(await page.$eval(`:text("world")`, e => e.id)).toBe('target2'); expect(await page.$$eval(`:text("world")`, els => els.length)).toBe(1); expect(await page.$(`:text("hello world")`)).toBe(null); expect(await page.$(`div:text("world")`)).toBe(null); expect(await page.$eval(`text=Hello, world!`, e => e.id)).toBe('target1'); expect(await page.$eval(`text=Hello`, e => e.id)).toBe('target1'); expect(await page.$eval(`text=world`, e => e.id)).toBe('target2'); expect(await page.$$eval(`text=world`, els => els.length)).toBe(1); expect(await page.$(`text=hello world`)).toBe(null); expect(await page.$(`:text-is("Hello, world!")`)).toBe(null); expect(await page.$eval(`:text-is("Hello")`, e => e.id)).toBe('target1'); expect(await page.$eval(`:text-is("world")`, e => e.id)).toBe('target2'); expect(await page.$$eval(`:text-is("world")`, els => els.length)).toBe(1); expect(await page.$(`text="Hello, world!"`)).toBe(null); expect(await page.$eval(`text="Hello"`, e => e.id)).toBe('target1'); expect(await page.$eval(`text="world"`, e => e.id)).toBe('target2'); expect(await page.$$eval(`text="world"`, els => els.length)).toBe(1); expect(await page.$eval(`:text-matches(".*")`, e => e.nodeName)).toBe('I'); expect(await page.$eval(`:text-matches("world?")`, e => e.id)).toBe('target2'); expect(await page.$$eval(`:text-matches("world")`, els => els.length)).toBe(1); expect(await page.$(`div:text(".*")`)).toBe(null); expect(await page.$eval(`text=/.*/`, e => e.nodeName)).toBe('I'); expect(await page.$eval(`text=/world?/`, e => e.id)).toBe('target2'); expect(await page.$$eval(`text=/world/`, els => els.length)).toBe(1); }); it('should work with text nodes in quoted mode', async ({page}) => { await page.setContent(`<div id=target1>Hello<span id=target2>wo rld </span> Hi again </div>`); expect(await page.$eval(`text="Hello"`, e => e.id)).toBe('target1'); expect(await page.$eval(`text="Hi again"`, e => e.id)).toBe('target1'); expect(await page.$eval(`text="wo rld"`, e => e.id)).toBe('target2'); expect(await page.$(`text="Hellowo rld Hi again"`)).toBe(null); expect(await page.$(`text="Hellowo"`)).toBe(null); expect(await page.$(`text="Hellowo rld"`)).toBe(null); expect(await page.$(`text="wo rld Hi ag"`)).toBe(null); expect(await page.$(`text="again"`)).toBe(null); expect(await page.$(`text="hi again"`)).toBe(null); expect(await page.$eval(`text=hi again`, e => e.id)).toBe('target1'); }); it('should clear caches', async ({page}) => { await page.setContent(`<div id=target1>text</div><div id=target2>text</div>`); const div = await page.$('#target1'); await div.evaluate(div => div.textContent = 'text'); expect(await page.$eval(`text=text`, e => e.id)).toBe('target1'); await div.evaluate(div => div.textContent = 'foo'); expect(await page.$eval(`text=text`, e => e.id)).toBe('target2'); await div.evaluate(div => div.textContent = 'text'); expect(await page.$eval(`:text("text")`, e => e.id)).toBe('target1'); await div.evaluate(div => div.textContent = 'foo'); expect(await page.$eval(`:text("text")`, e => e.id)).toBe('target2'); await div.evaluate(div => div.textContent = 'text'); expect(await page.$$eval(`text=text`, els => els.length)).toBe(2); await div.evaluate(div => div.textContent = 'foo'); expect(await page.$$eval(`text=text`, els => els.length)).toBe(1); await div.evaluate(div => div.textContent = 'text'); expect(await page.$$eval(`:text("text")`, els => els.length)).toBe(2); await div.evaluate(div => div.textContent = 'foo'); expect(await page.$$eval(`:text("text")`, els => els.length)).toBe(1); }); it('should work with :has-text', async ({page}) => { await page.setContent(` <input id=input2> <div id=div1> <span> Find me </span> or <wrap><span id=span2>maybe me </span></wrap> <div><input id=input1></div> </div> `); expect(await page.$eval(`:has-text("find me")`, e => e.tagName)).toBe('HTML'); expect(await page.$eval(`span:has-text("find me")`, e => e.outerHTML)).toBe('<span> Find me </span>'); expect(await page.$eval(`div:has-text("find me")`, e => e.id)).toBe('div1'); expect(await page.$eval(`div:has-text("find me") input`, e => e.id)).toBe('input1'); expect(await page.$eval(`:has-text("find me") input`, e => e.id)).toBe('input2'); expect(await page.$eval(`div:has-text("find me or maybe me")`, e => e.id)).toBe('div1'); expect(await page.$(`div:has-text("find noone")`)).toBe(null); expect(await page.$$eval(`:is(div,span):has-text("maybe")`, els => els.map(e => e.id).join(';'))).toBe('div1;span2'); expect(await page.$eval(`div:has-text("find me") :has-text("maybe me")`, e => e.tagName)).toBe('WRAP'); expect(await page.$eval(`div:has-text("find me") span:has-text("maybe me")`, e => e.id)).toBe('span2'); const error1 = await page.$(`:has-text("foo", "bar")`).catch(e => e); expect(error1.message).toContain(`"has-text" engine expects a single string`); const error2 = await page.$(`:has-text(foo > bar)`).catch(e => e); expect(error2.message).toContain(`"has-text" engine expects a single string`); }); it('should work with large DOM', async ({page}) => { await page.evaluate(() => { let id = 0; const next = (tag: string) => { const e = document.createElement(tag); const eid = ++id; e.textContent = 'id' + eid; e.id = 'id' + eid; return e; }; const generate = (depth: number) => { const div = next('div'); const span1 = next('span'); const span2 = next('span'); div.appendChild(span1); div.appendChild(span2); if (depth > 0) { div.appendChild(generate(depth - 1)); div.appendChild(generate(depth - 1)); } return div; }; document.body.appendChild(generate(12)); }); const selectors = [ ':has-text("id18")', ':has-text("id12345")', ':has-text("id")', ':text("id18")', ':text("id12345")', ':text("id")', ':text-matches("id12345", "i")', 'text=id18', 'text=id12345', 'text=id', '#id18', '#id12345', '*', ]; const measure = false; for (const selector of selectors) { const time1 = Date.now(); for (let i = 0; i < (measure ? 10 : 1); i++) await page.$$eval(selector, els => els.length); if (measure) console.log(`pw("${selector}"): ` + (Date.now() - time1)); if (measure && !selector.includes('text')) { const time2 = Date.now(); for (let i = 0; i < (measure ? 10 : 1); i++) await page.evaluate(selector => document.querySelectorAll(selector).length, selector); console.log(`qs("${selector}"): ` + (Date.now() - time2)); } } }); it('should be case sensitive if quotes are specified', async ({page}) => { await page.setContent(`<div>yo</div><div>ya</div><div>\nye </div>`); expect(await page.$eval(`text=yA`, e => e.outerHTML)).toBe('<div>ya</div>'); expect(await page.$(`text="yA"`)).toBe(null); }); it('should search for a substring without quotes', async ({page}) => { await page.setContent(`<div>textwithsubstring</div>`); expect(await page.$eval(`text=with`, e => e.outerHTML)).toBe('<div>textwithsubstring</div>'); expect(await page.$(`text="with"`)).toBe(null); }); it('should skip head, script and style', async ({page}) => { await page.setContent(` <head> <title>title</title> <script>var script</script> <style>.style {}</style> </head> <body> <script>var script</script> <style>.style {}</style> <div>title script style</div> </body>`); const head = await page.$('head'); const title = await page.$('title'); const script = await page.$('body script'); const style = await page.$('body style'); for (const text of ['title', 'script', 'style']) { expect(await page.$eval(`text=${text}`, e => e.nodeName)).toBe('DIV'); expect(await page.$$eval(`text=${text}`, els => els.map(e => e.nodeName).join('|'))).toBe('DIV'); for (const root of [head, title, script, style]) { expect(await root.$(`text=${text}`)).toBe(null); expect(await root.$$eval(`text=${text}`, els => els.length)).toBe(0); } } }); it('should match input[type=button|submit]', async ({page}) => { await page.setContent(`<input type="submit" value="hello"><input type="button" value="world">`); expect(await page.$eval(`text=hello`, e => e.outerHTML)).toBe('<input type="submit" value="hello">'); expect(await page.$eval(`text=world`, e => e.outerHTML)).toBe('<input type="button" value="world">'); }); it('should work for open shadow roots', async ({page, server}) => { await page.goto(server.PREFIX + '/deep-shadow.html'); expect(await page.$eval(`text=root1`, e => e.textContent)).toBe('Hello from root1'); expect(await page.$eval(`text=root2`, e => e.textContent)).toBe('Hello from root2'); expect(await page.$eval(`text=root3`, e => e.textContent)).toBe('Hello from root3'); expect(await page.$eval(`#root1 >> text=from root3`, e => e.textContent)).toBe('Hello from root3'); expect(await page.$eval(`#target >> text=from root2`, e => e.textContent)).toBe('Hello from root2'); expect(await page.$(`text:light=root1`)).toBe(null); expect(await page.$(`text:light=root2`)).toBe(null); expect(await page.$(`text:light=root3`)).toBe(null); }); it('should prioritize light dom over shadow dom in the same parent', async ({page, server}) => { await page.evaluate(() => { const div = document.createElement('div'); document.body.appendChild(div); div.attachShadow({ mode: 'open' }); const shadowSpan = document.createElement('span'); shadowSpan.textContent = 'Hello from shadow'; div.shadowRoot.appendChild(shadowSpan); const lightSpan = document.createElement('span'); lightSpan.textContent = 'Hello from light'; div.appendChild(lightSpan); }); expect(await page.$eval(`div >> text=Hello`, e => e.textContent)).toBe('Hello from light'); }); it('should waitForSelector with distributed elements', async ({page, server}) => { const promise = page.waitForSelector(`div >> text=Hello`); await page.evaluate(() => { const div = document.createElement('div'); document.body.appendChild(div); div.attachShadow({ mode: 'open' }); const shadowSpan = document.createElement('span'); shadowSpan.textContent = 'Hello from shadow'; div.shadowRoot.appendChild(shadowSpan); div.shadowRoot.appendChild(document.createElement('slot')); const lightSpan = document.createElement('span'); lightSpan.textContent = 'Hello from light'; div.appendChild(lightSpan); }); const handle = await promise; expect(await handle.textContent()).toBe('Hello from light'); }); it('should match root after >>', async ({page, server}) => { await page.setContent('<section>test</section>'); const element = await page.$('css=section >> text=test'); expect(element).toBeTruthy(); const element2 = await page.$('text=test >> text=test'); expect(element2).toBeTruthy(); }); it('should match root after >> with *', async ({ page }) => { await page.setContent(`<button> hello world </button> <button> hellow <span> world </span> </button>`); expect(await page.$$eval('*css=button >> text=hello >> text=world', els => els.length)).toBe(2); });
tests/page/selectors-text.spec.ts
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.00017644237959757447, 0.0001733205863274634, 0.00016751115617807955, 0.00017347790708299726, 0.0000020658321773225907 ]
{ "id": 7, "code_window": [ " }\n", "}\n", "\n", "export async function installDefaultBrowsersForNpmInstall() {\n", " // PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD should have a value of 0 or 1\n", " if (getAsBooleanFromENV('PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD')) {\n", " logPolitely('Skipping browsers download because `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` env variable is set');\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const defaultBrowserNames = registry.defaultExecutables().map(e => e.name);\n", " return installBrowsersForNpmInstall(defaultBrowserNames);\n", "}\n", "\n", "export async function installBrowsersForNpmInstall(browsers: string[]) {\n" ], "file_path": "src/utils/registry.ts", "type": "add", "edit_start_line_idx": 705 }
/** * 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 { EventEmitter } from 'events'; import { assert } from '../../utils/utils'; import { ConnectionTransport, ProtocolRequest, ProtocolResponse } from '../transport'; import { Protocol } from './protocol'; import { rewriteErrorMessage } from '../../utils/stackTrace'; import { debugLogger, RecentLogsCollector } from '../../utils/debugLogger'; import { ProtocolLogger } from '../types'; import { helper } from '../helper'; import { kBrowserClosedError } from '../../utils/errors'; import { ProtocolError } from '../common/protocolError'; // WKPlaywright uses this special id to issue Browser.close command which we // should ignore. export const kBrowserCloseMessageId = -9999; // We emulate kPageProxyMessageReceived message to unify it with Browser.pageProxyCreated // and Browser.pageProxyDestroyed for easier management. export const kPageProxyMessageReceived = 'kPageProxyMessageReceived'; export type PageProxyMessageReceivedPayload = { pageProxyId: string, message: any }; export class WKConnection { private readonly _transport: ConnectionTransport; private readonly _onDisconnect: () => void; private readonly _protocolLogger: ProtocolLogger; readonly _browserLogsCollector: RecentLogsCollector; private _lastId = 0; private _closed = false; readonly browserSession: WKSession; constructor(transport: ConnectionTransport, onDisconnect: () => void, protocolLogger: ProtocolLogger, browserLogsCollector: RecentLogsCollector) { this._transport = transport; this._transport.onmessage = this._dispatchMessage.bind(this); this._transport.onclose = this._onClose.bind(this); this._onDisconnect = onDisconnect; this._protocolLogger = protocolLogger; this._browserLogsCollector = browserLogsCollector; this.browserSession = new WKSession(this, '', kBrowserClosedError, (message: any) => { this.rawSend(message); }); } nextMessageId(): number { return ++this._lastId; } rawSend(message: ProtocolRequest) { this._protocolLogger('send', message); this._transport.send(message); } private _dispatchMessage(message: ProtocolResponse) { this._protocolLogger('receive', message); if (message.id === kBrowserCloseMessageId) return; if (message.pageProxyId) { const payload: PageProxyMessageReceivedPayload = { message: message, pageProxyId: message.pageProxyId }; this.browserSession.dispatchMessage({ method: kPageProxyMessageReceived, params: payload }); return; } this.browserSession.dispatchMessage(message); } _onClose() { this._closed = true; this._transport.onmessage = undefined; this._transport.onclose = undefined; this.browserSession.dispose(true); this._onDisconnect(); } isClosed() { return this._closed; } close() { if (!this._closed) this._transport.close(); } } export class WKSession extends EventEmitter { connection: WKConnection; errorText: string; readonly sessionId: string; private _disposed = false; private readonly _rawSend: (message: any) => void; private readonly _callbacks = new Map<number, {resolve: (o: any) => void, reject: (e: ProtocolError) => void, error: ProtocolError, method: string}>(); private _crashed: boolean = false; override on: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this; override addListener: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this; override off: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this; override removeListener: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this; override once: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this; constructor(connection: WKConnection, sessionId: string, errorText: string, rawSend: (message: any) => void) { super(); this.setMaxListeners(0); this.connection = connection; this.sessionId = sessionId; this._rawSend = rawSend; this.errorText = errorText; this.on = super.on; this.off = super.removeListener; this.addListener = super.addListener; this.removeListener = super.removeListener; this.once = super.once; } async send<T extends keyof Protocol.CommandParameters>( method: T, params?: Protocol.CommandParameters[T] ): Promise<Protocol.CommandReturnValues[T]> { if (this._crashed) throw new ProtocolError(true, 'Target crashed'); if (this._disposed) throw new ProtocolError(true, `Target closed`); const id = this.connection.nextMessageId(); const messageObj = { id, method, params }; this._rawSend(messageObj); return new Promise<Protocol.CommandReturnValues[T]>((resolve, reject) => { this._callbacks.set(id, {resolve, reject, error: new ProtocolError(false), method}); }); } sendMayFail<T extends keyof Protocol.CommandParameters>(method: T, params?: Protocol.CommandParameters[T]): Promise<Protocol.CommandReturnValues[T] | void> { return this.send(method, params).catch(error => debugLogger.log('error', error)); } markAsCrashed() { this._crashed = true; } isDisposed(): boolean { return this._disposed; } dispose(disconnected: boolean) { if (disconnected) this.errorText = 'Browser closed.' + helper.formatBrowserLogs(this.connection._browserLogsCollector.recentLogs()); for (const callback of this._callbacks.values()) { callback.error.sessionClosed = true; callback.reject(rewriteErrorMessage(callback.error, this.errorText)); } this._callbacks.clear(); this._disposed = true; } dispatchMessage(object: any) { if (object.id && this._callbacks.has(object.id)) { const callback = this._callbacks.get(object.id)!; this._callbacks.delete(object.id); if (object.error) callback.reject(createProtocolError(callback.error, callback.method, object.error)); else callback.resolve(object.result); } else if (object.id && !object.error) { // Response might come after session has been disposed and rejected all callbacks. assert(this.isDisposed()); } else { Promise.resolve().then(() => this.emit(object.method, object.params)); } } } export function createProtocolError(error: ProtocolError, method: string, protocolError: { message: string; data: any; }): ProtocolError { let message = `Protocol error (${method}): ${protocolError.message}`; if ('data' in protocolError) message += ` ${JSON.stringify(protocolError.data)}`; return rewriteErrorMessage(error, message); }
src/server/webkit/wkConnection.ts
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.000183310461579822, 0.000170375409652479, 0.00016394892008975148, 0.00017023918917402625, 0.000004008570613223128 ]
{ "id": 7, "code_window": [ " }\n", "}\n", "\n", "export async function installDefaultBrowsersForNpmInstall() {\n", " // PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD should have a value of 0 or 1\n", " if (getAsBooleanFromENV('PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD')) {\n", " logPolitely('Skipping browsers download because `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` env variable is set');\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const defaultBrowserNames = registry.defaultExecutables().map(e => e.name);\n", " return installBrowsersForNpmInstall(defaultBrowserNames);\n", "}\n", "\n", "export async function installBrowsersForNpmInstall(browsers: string[]) {\n" ], "file_path": "src/utils/registry.ts", "type": "add", "edit_start_line_idx": 705 }
# class: Request Whenever the page sends a request for a network resource the following sequence of events are emitted by [Page]: * [`event: Page.request`] emitted when the request is issued by the page. * [`event: Page.response`] emitted when/if the response status and headers are received for the request. * [`event: Page.requestFinished`] emitted when the response body is downloaded and the request is complete. If request fails at some point, then instead of `'requestfinished'` event (and possibly instead of 'response' event), the [`event: Page.requestFailed`] event is emitted. :::note HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with `'requestfinished'` event. ::: If request gets a 'redirect' response, the request is successfully finished with the 'requestfinished' event, and a new request is issued to a redirected url. ## async method: Request.allHeaders - returns: <[Object]<[string], [string]>> An object with all the request HTTP headers associated with this request. The header names are lower-cased. ## method: Request.failure - returns: <[null]|[string]> The method returns `null` unless this request has failed, as reported by `requestfailed` event. Example of logging of all the failed requests: ```js page.on('requestfailed', request => { console.log(request.url() + ' ' + request.failure().errorText); }); ``` ```java page.onRequestFailed(request -> { System.out.println(request.url() + " " + request.failure()); }); ``` ```py page.on("requestfailed", lambda request: print(request.url + " " + request.failure)) ``` ```csharp page.RequestFailed += (_, request) => { Console.WriteLine(request.Failure); }; ``` ## method: Request.frame - returns: <[Frame]> Returns the [Frame] that initiated this request. ## method: Request.headers - returns: <[Object]<[string], [string]>> **DEPRECATED** Incomplete list of headers as seen by the rendering engine. Use [`method: Request.allHeaders`] instead. ## async method: Request.headersArray - returns: <[Array]<[Object]>> - `name` <[string]> Name of the header. - `value` <[string]> Value of the header. An array with all the request HTTP headers associated with this request. Unlike [`method: Request.allHeaders`], header names are NOT lower-cased. Headers with multiple entries, such as `Set-Cookie`, appear in the array multiple times. ## async method: Request.headerValue - returns: <[null]|[string]> Returns the value of the header matching the name. The name is case insensitive. ### param: Request.headerValue.name - `name` <[string]> Name of the header. ## method: Request.isNavigationRequest - returns: <[boolean]> Whether this request is driving frame's navigation. ## method: Request.method - returns: <[string]> Request's method (GET, POST, etc.) ## method: Request.postData - returns: <[null]|[string]> Request's post body, if any. ## method: Request.postDataBuffer - returns: <[null]|[Buffer]> Request's post body in a binary form, if any. ## method: Request.postDataJSON * langs: js, python - returns: <[null]|[any]> Returns parsed request's body for `form-urlencoded` and JSON as a fallback if any. When the response is `application/x-www-form-urlencoded` then a key/value object of the values will be returned. Otherwise it will be parsed as JSON. ## method: Request.redirectedFrom - returns: <[null]|[Request]> Request that was redirected by the server to this one, if any. When the server responds with a redirect, Playwright creates a new [Request] object. The two requests are connected by `redirectedFrom()` and `redirectedTo()` methods. When multiple server redirects has happened, it is possible to construct the whole redirect chain by repeatedly calling `redirectedFrom()`. For example, if the website `http://example.com` redirects to `https://example.com`: ```js const response = await page.goto('http://example.com'); console.log(response.request().redirectedFrom().url()); // 'http://example.com' ``` ```java Response response = page.navigate("http://example.com"); System.out.println(response.request().redirectedFrom().url()); // "http://example.com" ``` ```python async response = await page.goto("http://example.com") print(response.request.redirected_from.url) # "http://example.com" ``` ```python sync response = page.goto("http://example.com") print(response.request.redirected_from.url) # "http://example.com" ``` ```csharp var response = await page.GotoAsync("http://www.microsoft.com"); Console.WriteLine(response.Request.RedirectedFrom?.Url); // http://www.microsoft.com ``` If the website `https://google.com` has no redirects: ```js const response = await page.goto('https://google.com'); console.log(response.request().redirectedFrom()); // null ``` ```java Response response = page.navigate("https://google.com"); System.out.println(response.request().redirectedFrom()); // null ``` ```python async response = await page.goto("https://google.com") print(response.request.redirected_from) # None ``` ```python sync response = page.goto("https://google.com") print(response.request.redirected_from) # None ``` ```csharp var response = await page.GotoAsync("https://www.google.com"); Console.WriteLine(response.Request.RedirectedFrom?.Url); // null ``` ## method: Request.redirectedTo - returns: <[null]|[Request]> New request issued by the browser if the server responded with redirect. This method is the opposite of [`method: Request.redirectedFrom`]: ```js console.log(request.redirectedFrom().redirectedTo() === request); // true ``` ```java System.out.println(request.redirectedFrom().redirectedTo() == request); // true ``` ```py assert request.redirected_from.redirected_to == request ``` ```csharp Console.WriteLine(request.RedirectedFrom?.RedirectedTo == request); // True ``` ## method: Request.resourceType - returns: <[string]> Contains the request's resource type as it was perceived by the rendering engine. ResourceType will be one of the following: `document`, `stylesheet`, `image`, `media`, `font`, `script`, `texttrack`, `xhr`, `fetch`, `eventsource`, `websocket`, `manifest`, `other`. ## async method: Request.response - returns: <[null]|[Response]> Returns the matching [Response] object, or `null` if the response was not received due to error. ## async method: Request.sizes - returns: <[Object]> - `requestBodySize` <[int]> Size of the request body (POST data payload) in bytes. Set to 0 if there was no body. - `requestHeadersSize` <[int]> Total number of bytes from the start of the HTTP request message until (and including) the double CRLF before the body. - `responseBodySize` <[int]> Size of the received response body (encoded) in bytes. - `responseHeadersSize` <[int]> Total number of bytes from the start of the HTTP response message until (and including) the double CRLF before the body. Returns resource size information for given request. ## method: Request.timing - returns: <[Object]> - `startTime` <[float]> Request start time in milliseconds elapsed since January 1, 1970 00:00:00 UTC - `domainLookupStart` <[float]> Time immediately before the browser starts the domain name lookup for the resource. The value is given in milliseconds relative to `startTime`, -1 if not available. - `domainLookupEnd` <[float]> Time immediately after the browser starts the domain name lookup for the resource. The value is given in milliseconds relative to `startTime`, -1 if not available. - `connectStart` <[float]> Time immediately before the user agent starts establishing the connection to the server to retrieve the resource. The value is given in milliseconds relative to `startTime`, -1 if not available. - `secureConnectionStart` <[float]> Time immediately before the browser starts the handshake process to secure the current connection. The value is given in milliseconds relative to `startTime`, -1 if not available. - `connectEnd` <[float]> Time immediately before the user agent starts establishing the connection to the server to retrieve the resource. The value is given in milliseconds relative to `startTime`, -1 if not available. - `requestStart` <[float]> Time immediately before the browser starts requesting the resource from the server, cache, or local resource. The value is given in milliseconds relative to `startTime`, -1 if not available. - `responseStart` <[float]> Time immediately after the browser starts requesting the resource from the server, cache, or local resource. The value is given in milliseconds relative to `startTime`, -1 if not available. - `responseEnd` <[float]> Time immediately after the browser receives the last byte of the resource or immediately before the transport connection is closed, whichever comes first. The value is given in milliseconds relative to `startTime`, -1 if not available. Returns resource timing information for given request. Most of the timing values become available upon the response, `responseEnd` becomes available when request finishes. Find more information at [Resource Timing API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming). ```js const [request] = await Promise.all([ page.waitForEvent('requestfinished'), page.goto('http://example.com') ]); console.log(request.timing()); ``` ```java page.onRequestFinished(request -> { Timing timing = request.timing(); System.out.println(timing.responseEnd - timing.startTime); }); page.navigate("http://example.com"); ``` ```python async async with page.expect_event("requestfinished") as request_info: await page.goto("http://example.com") request = await request_info.value print(request.timing) ``` ```python sync with page.expect_event("requestfinished") as request_info: page.goto("http://example.com") request = request_info.value print(request.timing) ``` ```csharp var request = await page.RunAndWaitForRequestFinishedAsync(async () => { await page.GotoAsync("https://www.microsoft.com"); }); Console.WriteLine(request.Timing.ResponseEnd); ``` ## method: Request.url - returns: <[string]> URL of the request.
docs/src/api/class-request.md
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.002305885311216116, 0.00024289994325954467, 0.000162957061547786, 0.00016855017747730017, 0.00038992727058939636 ]
{ "id": 8, "code_window": [ " logPolitely('Skipping browsers download because `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` env variable is set');\n", " return false;\n", " }\n", " await registry.install();\n", "}\n", "\n", "export const registry = new Registry(require('../../browsers.json'));" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const executables: Executable[] = [];\n", " for (const browserName of browsers) {\n", " const executable = registry.findExecutable(browserName);\n", " if (!executable || executable.installType === 'none')\n", " throw new Error(`Cannot install ${browserName}`);\n", " executables.push(executable);\n", " }\n", "\n", " await registry.install(executables);\n" ], "file_path": "src/utils/registry.ts", "type": "replace", "edit_start_line_idx": 710 }
#!/usr/bin/env node /** * 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 no-console */ import fs from 'fs'; import os from 'os'; import path from 'path'; import program from 'commander'; import { runDriver, runServer, printApiJson, launchBrowserServer } from './driver'; import { showTraceViewer } from '../server/trace/viewer/traceViewer'; import * as playwright from '../..'; import { BrowserContext } from '../client/browserContext'; import { Browser } from '../client/browser'; import { Page } from '../client/page'; import { BrowserType } from '../client/browserType'; import { BrowserContextOptions, LaunchOptions } from '../client/types'; import { spawn } from 'child_process'; import { registry, Executable } from '../utils/registry'; import { launchGridAgent } from '../grid/gridAgent'; import { launchGridServer } from '../grid/gridServer'; const packageJSON = require('../../package.json'); program .version('Version ' + packageJSON.version) .name(process.env.PW_CLI_NAME || 'npx playwright'); commandWithOpenOptions('open [url]', 'open page in browser specified via -b, --browser', []) .action(function(url, command) { open(command, url, language()).catch(logErrorAndExit); }) .on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ open'); console.log(' $ open -b webkit https://example.com'); }); commandWithOpenOptions('codegen [url]', 'open page and generate code for user actions', [ ['-o, --output <file name>', 'saves the generated script to a file'], ['--target <language>', `language to generate, one of javascript, test, python, python-async, csharp`, language()], ]).action(function(url, command) { codegen(command, url, command.target, command.output).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ codegen'); console.log(' $ codegen --target=python'); console.log(' $ codegen -b webkit https://example.com'); }); program .command('debug <app> [args...]', { hidden: true }) .description('run command in debug mode: disable timeout, open inspector') .allowUnknownOption(true) .action(function(app, args) { spawn(app, args, { env: { ...process.env, PWDEBUG: '1' }, stdio: 'inherit' }); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ debug node test.js'); console.log(' $ debug npm run test'); }); function suggestedBrowsersToInstall() { return registry.executables().filter(e => e.installType !== 'none' && e.type !== 'tool').map(e => e.name).join(', '); } function checkBrowsersToInstall(args: string[]): Executable[] { const faultyArguments: string[] = []; const executables: Executable[] = []; for (const arg of args) { const executable = registry.findExecutable(arg); if (!executable || executable.installType === 'none') faultyArguments.push(arg); else executables.push(executable); } if (faultyArguments.length) { console.log(`Invalid installation targets: ${faultyArguments.map(name => `'${name}'`).join(', ')}. Expecting one of: ${suggestedBrowsersToInstall()}`); process.exit(1); } return executables; } program .command('install [browser...]') .description('ensure browsers necessary for this version of Playwright are installed') .option('--with-deps', 'install system dependencies for browsers') .action(async function(args: string[], command: program.Command) { try { if (!args.length) { if (command.opts().withDeps) await registry.installDeps(); await registry.install(); } else { const executables = checkBrowsersToInstall(args); if (command.opts().withDeps) await registry.installDeps(executables); await registry.install(executables); } } catch (e) { console.log(`Failed to install browsers\n${e}`); process.exit(1); } }).on('--help', function() { console.log(``); console.log(`Examples:`); console.log(` - $ install`); console.log(` Install default browsers.`); console.log(``); console.log(` - $ install chrome firefox`); console.log(` Install custom browsers, supports ${suggestedBrowsersToInstall()}.`); }); program .command('install-deps [browser...]') .description('install dependencies necessary to run browsers (will ask for sudo permissions)') .action(async function(args: string[]) { try { if (!args.length) await registry.installDeps(); else await registry.installDeps(checkBrowsersToInstall(args)); } catch (e) { console.log(`Failed to install browser dependencies\n${e}`); process.exit(1); } }).on('--help', function() { console.log(``); console.log(`Examples:`); console.log(` - $ install-deps`); console.log(` Install dependencies for default browsers.`); console.log(``); console.log(` - $ install-deps chrome firefox`); console.log(` Install dependencies for specific browsers, supports ${suggestedBrowsersToInstall()}.`); }); const browsers = [ { alias: 'cr', name: 'Chromium', type: 'chromium' }, { alias: 'ff', name: 'Firefox', type: 'firefox' }, { alias: 'wk', name: 'WebKit', type: 'webkit' }, ]; for (const {alias, name, type} of browsers) { commandWithOpenOptions(`${alias} [url]`, `open page in ${name}`, []) .action(function(url, command) { open({ ...command, browser: type }, url, command.target).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(` $ ${alias} https://example.com`); }); } commandWithOpenOptions('screenshot <url> <filename>', 'capture a page screenshot', [ ['--wait-for-selector <selector>', 'wait for selector before taking a screenshot'], ['--wait-for-timeout <timeout>', 'wait for timeout in milliseconds before taking a screenshot'], ['--full-page', 'whether to take a full page screenshot (entire scrollable area)'], ]).action(function(url, filename, command) { screenshot(command, command, url, filename).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ screenshot -b webkit https://example.com example.png'); }); commandWithOpenOptions('pdf <url> <filename>', 'save page as pdf', [ ['--wait-for-selector <selector>', 'wait for given selector before saving as pdf'], ['--wait-for-timeout <timeout>', 'wait for given timeout in milliseconds before saving as pdf'], ]).action(function(url, filename, command) { pdf(command, command, url, filename).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ pdf https://example.com example.pdf'); }); program .command('experimental-grid-server', { hidden: true }) .option('--port <port>', 'grid port; defaults to 3333') .option('--agent-factory <factory>', 'path to grid agent factory or npm package') .option('--auth-token <authToken>', 'optional authentication token') .action(function(options) { launchGridServer(options.agentFactory, options.port || 3333, options.authToken); }); program .command('experimental-grid-agent', { hidden: true }) .requiredOption('--agent-id <agentId>', 'agent ID') .requiredOption('--grid-url <gridURL>', 'grid URL') .action(function(options) { launchGridAgent(options.agentId, options.gridUrl); }); program .command('show-trace [trace]') .option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium') .description('Show trace viewer') .action(function(trace, command) { if (command.browser === 'cr') command.browser = 'chromium'; if (command.browser === 'ff') command.browser = 'firefox'; if (command.browser === 'wk') command.browser = 'webkit'; showTraceViewer(trace, command.browser).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ show-trace trace/directory'); }); if (!process.env.PW_CLI_TARGET_LANG) { let playwrightTestPackagePath = null; try { const isLocal = packageJSON.name === '@playwright/test' || process.env.PWTEST_CLI_ALLOW_TEST_COMMAND; if (isLocal) { playwrightTestPackagePath = '../test/cli'; } else { playwrightTestPackagePath = require.resolve('@playwright/test/lib/test/cli', { paths: [__dirname, process.cwd()] }); } } catch {} if (playwrightTestPackagePath) { require(playwrightTestPackagePath).addTestCommand(program); } else { const command = program.command('test').allowUnknownOption(true); command.description('Run tests with Playwright Test. Available in @playwright/test package.'); command.action(async (args, opts) => { console.error('Please install @playwright/test package to use Playwright Test.'); console.error(' npm install -D @playwright/test'); process.exit(1); }); } } if (process.argv[2] === 'run-driver') runDriver(); else if (process.argv[2] === 'run-server') runServer(process.argv[3] ? +process.argv[3] : undefined).catch(logErrorAndExit); else if (process.argv[2] === 'print-api-json') printApiJson(); else if (process.argv[2] === 'launch-server') launchBrowserServer(process.argv[3], process.argv[4]).catch(logErrorAndExit); else program.parse(process.argv); type Options = { browser: string; channel?: string; colorScheme?: string; device?: string; geolocation?: string; ignoreHttpsErrors?: boolean; lang?: string; loadStorage?: string; proxyServer?: string; saveStorage?: string; saveTrace?: string; timeout: string; timezone?: string; viewportSize?: string; userAgent?: string; }; type CaptureOptions = { waitForSelector?: string; waitForTimeout?: string; fullPage: boolean; }; async function launchContext(options: Options, headless: boolean, executablePath?: string): Promise<{ browser: Browser, browserName: string, launchOptions: LaunchOptions, contextOptions: BrowserContextOptions, context: BrowserContext }> { validateOptions(options); const browserType = lookupBrowserType(options); const launchOptions: LaunchOptions = { headless, executablePath }; if (options.channel) launchOptions.channel = options.channel as any; const contextOptions: BrowserContextOptions = // Copy the device descriptor since we have to compare and modify the options. options.device ? { ...playwright.devices[options.device] } : {}; // In headful mode, use host device scale factor for things to look nice. // In headless, keep things the way it works in Playwright by default. // Assume high-dpi on MacOS. TODO: this is not perfect. if (!headless) contextOptions.deviceScaleFactor = os.platform() === 'darwin' ? 2 : 1; // Work around the WebKit GTK scrolling issue. if (browserType.name() === 'webkit' && process.platform === 'linux') { delete contextOptions.hasTouch; delete contextOptions.isMobile; } if (contextOptions.isMobile && browserType.name() === 'firefox') contextOptions.isMobile = undefined; contextOptions.acceptDownloads = true; // Proxy if (options.proxyServer) { launchOptions.proxy = { server: options.proxyServer }; } const browser = await browserType.launch(launchOptions); // Viewport size if (options.viewportSize) { try { const [ width, height ] = options.viewportSize.split(',').map(n => parseInt(n, 10)); contextOptions.viewport = { width, height }; } catch (e) { console.log('Invalid window size format: use "width, height", for example --window-size=800,600'); process.exit(0); } } // Geolocation if (options.geolocation) { try { const [latitude, longitude] = options.geolocation.split(',').map(n => parseFloat(n.trim())); contextOptions.geolocation = { latitude, longitude }; } catch (e) { console.log('Invalid geolocation format: user lat, long, for example --geolocation="37.819722,-122.478611"'); process.exit(0); } contextOptions.permissions = ['geolocation']; } // User agent if (options.userAgent) contextOptions.userAgent = options.userAgent; // Lang if (options.lang) contextOptions.locale = options.lang; // Color scheme if (options.colorScheme) contextOptions.colorScheme = options.colorScheme as 'dark' | 'light'; // Timezone if (options.timezone) contextOptions.timezoneId = options.timezone; // Storage if (options.loadStorage) contextOptions.storageState = options.loadStorage; if (options.ignoreHttpsErrors) contextOptions.ignoreHTTPSErrors = true; // Close app when the last window closes. const context = await browser.newContext(contextOptions); let closingBrowser = false; async function closeBrowser() { // We can come here multiple times. For example, saving storage creates // a temporary page and we call closeBrowser again when that page closes. if (closingBrowser) return; closingBrowser = true; if (options.saveTrace) await context.tracing.stop({ path: options.saveTrace }); if (options.saveStorage) await context.storageState({ path: options.saveStorage }).catch(e => null); await browser.close(); } context.on('page', page => { page.on('dialog', () => {}); // Prevent dialogs from being automatically dismissed. page.on('close', () => { const hasPage = browser.contexts().some(context => context.pages().length > 0); if (hasPage) return; // Avoid the error when the last page is closed because the browser has been closed. closeBrowser().catch(e => null); }); }); if (options.timeout) { context.setDefaultTimeout(parseInt(options.timeout, 10)); context.setDefaultNavigationTimeout(parseInt(options.timeout, 10)); } if (options.saveTrace) await context.tracing.start({ screenshots: true, snapshots: true }); // Omit options that we add automatically for presentation purpose. delete launchOptions.headless; delete launchOptions.executablePath; delete contextOptions.deviceScaleFactor; delete contextOptions.acceptDownloads; return { browser, browserName: browserType.name(), context, contextOptions, launchOptions }; } async function openPage(context: BrowserContext, url: string | undefined): Promise<Page> { const page = await context.newPage(); if (url) { if (fs.existsSync(url)) url = 'file://' + path.resolve(url); else if (!url.startsWith('http') && !url.startsWith('file://') && !url.startsWith('about:') && !url.startsWith('data:')) url = 'http://' + url; await page.goto(url); } return page; } async function open(options: Options, url: string | undefined, language: string) { const { context, launchOptions, contextOptions } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH); await context._enableRecorder({ language, launchOptions, contextOptions, device: options.device, saveStorage: options.saveStorage, }); await openPage(context, url); if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close())); } async function codegen(options: Options, url: string | undefined, language: string, outputFile?: string) { const { context, launchOptions, contextOptions } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH); await context._enableRecorder({ language, launchOptions, contextOptions, device: options.device, saveStorage: options.saveStorage, startRecording: true, outputFile: outputFile ? path.resolve(outputFile) : undefined }); await openPage(context, url); if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close())); } async function waitForPage(page: Page, captureOptions: CaptureOptions) { if (captureOptions.waitForSelector) { console.log(`Waiting for selector ${captureOptions.waitForSelector}...`); await page.waitForSelector(captureOptions.waitForSelector); } if (captureOptions.waitForTimeout) { console.log(`Waiting for timeout ${captureOptions.waitForTimeout}...`); await page.waitForTimeout(parseInt(captureOptions.waitForTimeout, 10)); } } async function screenshot(options: Options, captureOptions: CaptureOptions, url: string, path: string) { const { browser, context } = await launchContext(options, true); console.log('Navigating to ' + url); const page = await openPage(context, url); await waitForPage(page, captureOptions); console.log('Capturing screenshot into ' + path); await page.screenshot({ path, fullPage: !!captureOptions.fullPage }); await browser.close(); } async function pdf(options: Options, captureOptions: CaptureOptions, url: string, path: string) { if (options.browser !== 'chromium') { console.error('PDF creation is only working with Chromium'); process.exit(1); } const { browser, context } = await launchContext({ ...options, browser: 'chromium' }, true); console.log('Navigating to ' + url); const page = await openPage(context, url); await waitForPage(page, captureOptions); console.log('Saving as pdf into ' + path); await page.pdf!({ path }); await browser.close(); } function lookupBrowserType(options: Options): BrowserType { let name = options.browser; if (options.device) { const device = playwright.devices[options.device]; name = device.defaultBrowserType; } let browserType: any; switch (name) { case 'chromium': browserType = playwright.chromium; break; case 'webkit': browserType = playwright.webkit; break; case 'firefox': browserType = playwright.firefox; break; case 'cr': browserType = playwright.chromium; break; case 'wk': browserType = playwright.webkit; break; case 'ff': browserType = playwright.firefox; break; } if (browserType) return browserType; program.help(); } function validateOptions(options: Options) { if (options.device && !(options.device in playwright.devices)) { console.log(`Device descriptor not found: '${options.device}', available devices are:`); for (const name in playwright.devices) console.log(` "${name}"`); process.exit(0); } if (options.colorScheme && !['light', 'dark'].includes(options.colorScheme)) { console.log('Invalid color scheme, should be one of "light", "dark"'); process.exit(0); } } function logErrorAndExit(e: Error) { console.error(e); process.exit(1); } function language(): string { return process.env.PW_CLI_TARGET_LANG || 'test'; } function commandWithOpenOptions(command: string, description: string, options: any[][]): program.Command { let result = program.command(command).description(description); for (const option of options) result = result.option(option[0], ...option.slice(1)); return result .option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium') .option('--channel <channel>', 'Chromium distribution channel, "chrome", "chrome-beta", "msedge-dev", etc') .option('--color-scheme <scheme>', 'emulate preferred color scheme, "light" or "dark"') .option('--device <deviceName>', 'emulate device, for example "iPhone 11"') .option('--geolocation <coordinates>', 'specify geolocation coordinates, for example "37.819722,-122.478611"') .option('--ignore-https-errors', 'ignore https errors') .option('--load-storage <filename>', 'load context storage state from the file, previously saved with --save-storage') .option('--lang <language>', 'specify language / locale, for example "en-GB"') .option('--proxy-server <proxy>', 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"') .option('--save-storage <filename>', 'save context storage state at the end, for later use with --load-storage') .option('--save-trace <filename>', 'record a trace for the session and save it to a file') .option('--timezone <time zone>', 'time zone to emulate, for example "Europe/Rome"') .option('--timeout <timeout>', 'timeout for Playwright actions in milliseconds', '10000') .option('--user-agent <ua string>', 'specify user agent string') .option('--viewport-size <size>', 'specify browser viewport size in pixels, for example "1280, 720"'); }
src/cli/cli.ts
1
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.9722830057144165, 0.06333913654088974, 0.0001625602162675932, 0.00017192952509503812, 0.23308750987052917 ]
{ "id": 8, "code_window": [ " logPolitely('Skipping browsers download because `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` env variable is set');\n", " return false;\n", " }\n", " await registry.install();\n", "}\n", "\n", "export const registry = new Registry(require('../../browsers.json'));" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const executables: Executable[] = [];\n", " for (const browserName of browsers) {\n", " const executable = registry.findExecutable(browserName);\n", " if (!executable || executable.installType === 'none')\n", " throw new Error(`Cannot install ${browserName}`);\n", " executables.push(executable);\n", " }\n", "\n", " await registry.install(executables);\n" ], "file_path": "src/utils/registry.ts", "type": "replace", "edit_start_line_idx": 710 }
1292 Changed: [email protected] Fri 10 Sep 2021 17:25:22 CEST
browser_patches/firefox-beta/BUILD_NUMBER
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.00016642473929096013, 0.00016642473929096013, 0.00016642473929096013, 0.00016642473929096013, 0 ]
{ "id": 8, "code_window": [ " logPolitely('Skipping browsers download because `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` env variable is set');\n", " return false;\n", " }\n", " await registry.install();\n", "}\n", "\n", "export const registry = new Registry(require('../../browsers.json'));" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const executables: Executable[] = [];\n", " for (const browserName of browsers) {\n", " const executable = registry.findExecutable(browserName);\n", " if (!executable || executable.installType === 'none')\n", " throw new Error(`Cannot install ${browserName}`);\n", " executables.push(executable);\n", " }\n", "\n", " await registry.install(executables);\n" ], "file_path": "src/utils/registry.ts", "type": "replace", "edit_start_line_idx": 710 }
See building instructions at [`//browser_patches/winldd/README.md`](../browser_patches/winldd/README.md)
bin/README.md
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.00016782675811555237, 0.00016782675811555237, 0.00016782675811555237, 0.00016782675811555237, 0 ]
{ "id": 8, "code_window": [ " logPolitely('Skipping browsers download because `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` env variable is set');\n", " return false;\n", " }\n", " await registry.install();\n", "}\n", "\n", "export const registry = new Registry(require('../../browsers.json'));" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const executables: Executable[] = [];\n", " for (const browserName of browsers) {\n", " const executable = registry.findExecutable(browserName);\n", " if (!executable || executable.installType === 'none')\n", " throw new Error(`Cannot install ${browserName}`);\n", " executables.push(executable);\n", " }\n", "\n", " await registry.install(executables);\n" ], "file_path": "src/utils/registry.ts", "type": "replace", "edit_start_line_idx": 710 }
/** * 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.describe('mobile viewport', () => { it.skip(({ browserName }) => browserName === 'firefox'); it('should support mobile emulation', async ({playwright, browser, server}) => { const iPhone = playwright.devices['iPhone 6']; const context = await browser.newContext({ ...iPhone }); const page = await context.newPage(); await page.goto(server.PREFIX + '/mobile.html'); expect(await page.evaluate(() => window.innerWidth)).toBe(375); await page.setViewportSize({width: 400, height: 300}); expect(await page.evaluate(() => window.innerWidth)).toBe(400); await context.close(); }); it('should support touch emulation', async ({playwright, browser, server}) => { const iPhone = playwright.devices['iPhone 6']; const context = await browser.newContext({ ...iPhone }); const page = await context.newPage(); await page.goto(server.PREFIX + '/mobile.html'); expect(await page.evaluate(() => 'ontouchstart' in window)).toBe(true); expect(await page.evaluate(dispatchTouch)).toBe('Received touch'); await context.close(); function dispatchTouch() { let fulfill; const promise = new Promise(x => fulfill = x); window.ontouchstart = function(e) { fulfill('Received touch'); }; window.dispatchEvent(new Event('touchstart')); fulfill('Did not receive touch'); return promise; } }); it('should be detectable by Modernizr', async ({playwright, browser, server}) => { const iPhone = playwright.devices['iPhone 6']; const context = await browser.newContext({ ...iPhone }); const page = await context.newPage(); await page.goto(server.PREFIX + '/detect-touch.html'); expect(await page.evaluate(() => document.body.textContent.trim())).toBe('YES'); await context.close(); }); it('should detect touch when applying viewport with touches', async ({browser, server}) => { const context = await browser.newContext({ viewport: { width: 800, height: 600 }, hasTouch: true }); const page = await context.newPage(); await page.goto(server.EMPTY_PAGE); await page.addScriptTag({url: server.PREFIX + '/modernizr.js'}); expect(await page.evaluate(() => window['Modernizr'].touchevents)).toBe(true); await context.close(); }); it('should support landscape emulation', async ({playwright, browser, server}) => { const iPhone = playwright.devices['iPhone 6']; const iPhoneLandscape = playwright.devices['iPhone 6 landscape']; const context1 = await browser.newContext({ ...iPhone }); const page1 = await context1.newPage(); await page1.goto(server.PREFIX + '/mobile.html'); expect(await page1.evaluate(() => matchMedia('(orientation: landscape)').matches)).toBe(false); const context2 = await browser.newContext({ ...iPhoneLandscape }); const page2 = await context2.newPage(); expect(await page2.evaluate(() => matchMedia('(orientation: landscape)').matches)).toBe(true); await context1.close(); await context2.close(); }); it('should support window.orientation emulation', async ({browser, server}) => { const context = await browser.newContext({ viewport: { width: 300, height: 400 }, isMobile: true }); const page = await context.newPage(); await page.goto(server.PREFIX + '/mobile.html'); expect(await page.evaluate(() => window.orientation)).toBe(0); await page.setViewportSize({width: 400, height: 300}); expect(await page.evaluate(() => window.orientation)).toBe(90); await context.close(); }); it('should fire orientationchange event', async ({browser, server}) => { const context = await browser.newContext({ viewport: { width: 300, height: 400 }, isMobile: true }); const page = await context.newPage(); await page.goto(server.PREFIX + '/mobile.html'); await page.evaluate(() => { let counter = 0; window.addEventListener('orientationchange', () => console.log(++counter)); }); const event1 = page.waitForEvent('console'); await page.setViewportSize({width: 400, height: 300}); expect((await event1).text()).toBe('1'); const event2 = page.waitForEvent('console'); await page.setViewportSize({width: 300, height: 400}); expect((await event2).text()).toBe('2'); await context.close(); }); it('default mobile viewports to 980 width', async ({browser, server}) => { const context = await browser.newContext({ viewport: {width: 320, height: 480 }, isMobile: true }); const page = await context.newPage(); await page.goto(server.PREFIX + '/empty.html'); expect(await page.evaluate(() => window.innerWidth)).toBe(980); await context.close(); }); it('respect meta viewport tag', async ({browser, server}) => { const context = await browser.newContext({ viewport: {width: 320, height: 480 }, isMobile: true }); const page = await context.newPage(); await page.goto(server.PREFIX + '/mobile.html'); expect(await page.evaluate(() => window.innerWidth)).toBe(320); await context.close(); }); it('should emulate the hover media feature', async ({playwright, browser}) => { const iPhone = playwright.devices['iPhone 6']; const mobilepage = await browser.newPage({ ...iPhone }); expect(await mobilepage.evaluate(() => matchMedia('(hover: hover)').matches)).toBe(false); expect(await mobilepage.evaluate(() => matchMedia('(hover: none)').matches)).toBe(true); expect(await mobilepage.evaluate(() => matchMedia('(any-hover: hover)').matches)).toBe(false); expect(await mobilepage.evaluate(() => matchMedia('(any-hover: none)').matches)).toBe(true); expect(await mobilepage.evaluate(() => matchMedia('(pointer: coarse)').matches)).toBe(true); expect(await mobilepage.evaluate(() => matchMedia('(pointer: fine)').matches)).toBe(false); expect(await mobilepage.evaluate(() => matchMedia('(any-pointer: coarse)').matches)).toBe(true); expect(await mobilepage.evaluate(() => matchMedia('(any-pointer: fine)').matches)).toBe(false); await mobilepage.close(); const desktopPage = await browser.newPage(); expect(await desktopPage.evaluate(() => matchMedia('(hover: none)').matches)).toBe(false); expect(await desktopPage.evaluate(() => matchMedia('(hover: hover)').matches)).toBe(true); expect(await desktopPage.evaluate(() => matchMedia('(any-hover: none)').matches)).toBe(false); expect(await desktopPage.evaluate(() => matchMedia('(any-hover: hover)').matches)).toBe(true); expect(await desktopPage.evaluate(() => matchMedia('(pointer: coarse)').matches)).toBe(false); expect(await desktopPage.evaluate(() => matchMedia('(pointer: fine)').matches)).toBe(true); expect(await desktopPage.evaluate(() => matchMedia('(any-pointer: coarse)').matches)).toBe(false); expect(await desktopPage.evaluate(() => matchMedia('(any-pointer: fine)').matches)).toBe(true); await desktopPage.close(); }); it('mouse should work with mobile viewports and cross process navigations', async ({browser, server, browserName}) => { // @see https://crbug.com/929806 const context = await browser.newContext({ viewport: {width: 360, height: 640}, isMobile: true }); const page = await context.newPage(); await page.goto(server.EMPTY_PAGE); await page.goto(server.CROSS_PROCESS_PREFIX + '/mobile.html'); await page.evaluate(() => { document.addEventListener('click', event => { window['result'] = {x: event.clientX, y: event.clientY}; }); }); await page.mouse.click(30, 40); expect(await page.evaluate('result')).toEqual({x: 30, y: 40}); await context.close(); }); });
tests/browsercontext-viewport-mobile.spec.ts
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.00017603336891625077, 0.0001734150282572955, 0.0001688096090219915, 0.00017402955563738942, 0.0000020555582977976883 ]
{ "id": 1, "code_window": [ "\t\tconst handleClickOrTouch = (e: MouseEvent | GestureEvent, preserveFocus: boolean): void => {\n", "\t\t\ttab.blur(); // prevent flicker of focus outline on tab until editor got focus\n", "\n", "\t\t\tif (e instanceof MouseEvent && e.button !== 0) {\n", "\t\t\t\tif (e.button === 1) {\n", "\t\t\t\t\te.preventDefault(); // required to prevent auto-scrolling (https://github.com/microsoft/vscode/issues/16690)\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (e instanceof MouseEvent && (e.button !== 0 /* middle/right mouse button */ || (isMacintosh && e.ctrlKey /* macOS context menu */))) {\n" ], "file_path": "src/vs/workbench/browser/parts/editor/tabsTitleControl.ts", "type": "replace", "edit_start_line_idx": 693 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/editorgroupview'; import { EditorGroupModel, IEditorOpenOptions, IGroupModelChangeEvent, ISerializedEditorGroupModel, isGroupEditorCloseEvent, isGroupEditorOpenEvent, isSerializedEditorGroupModel } from 'vs/workbench/common/editor/editorGroupModel'; import { GroupIdentifier, CloseDirection, IEditorCloseEvent, IEditorPane, SaveReason, IEditorPartOptionsChangeEvent, EditorsOrder, IVisibleEditorPane, EditorResourceAccessor, EditorInputCapabilities, IUntypedEditorInput, DEFAULT_EDITOR_ASSOCIATION, SideBySideEditor, EditorCloseContext, IEditorWillMoveEvent, IEditorWillOpenEvent, IMatchEditorOptions, GroupModelChangeKind, IActiveEditorChangeEvent, IFindEditorOptions } from 'vs/workbench/common/editor'; import { ActiveEditorGroupLockedContext, ActiveEditorDirtyContext, EditorGroupEditorsCountContext, ActiveEditorStickyContext, ActiveEditorPinnedContext, ActiveEditorLastInGroupContext, ActiveEditorFirstInGroupContext } from 'vs/workbench/common/contextkeys'; import { EditorInput } from 'vs/workbench/common/editor/editorInput'; import { SideBySideEditorInput } from 'vs/workbench/common/editor/sideBySideEditorInput'; import { Emitter, Relay } from 'vs/base/common/event'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { Dimension, trackFocus, addDisposableListener, EventType, EventHelper, findParentWithClass, clearNode, isAncestor, asCSSUrl, IDomNodePagePosition } from 'vs/base/browser/dom'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { IThemeService, registerThemingParticipant, Themable } from 'vs/platform/theme/common/themeService'; import { editorBackground, contrastBorder } from 'vs/platform/theme/common/colorRegistry'; import { EDITOR_GROUP_HEADER_TABS_BACKGROUND, EDITOR_GROUP_HEADER_NO_TABS_BACKGROUND, EDITOR_GROUP_EMPTY_BACKGROUND, EDITOR_GROUP_FOCUSED_EMPTY_BORDER, EDITOR_GROUP_HEADER_BORDER } from 'vs/workbench/common/theme'; import { ICloseEditorsFilter, GroupsOrder, ICloseEditorOptions, ICloseAllEditorsOptions, IEditorReplacement } from 'vs/workbench/services/editor/common/editorGroupsService'; import { TabsTitleControl } from 'vs/workbench/browser/parts/editor/tabsTitleControl'; import { EditorPanes } from 'vs/workbench/browser/parts/editor/editorPanes'; import { IEditorProgressService } from 'vs/platform/progress/common/progress'; import { EditorProgressIndicator } from 'vs/workbench/services/progress/browser/progressIndicator'; import { localize } from 'vs/nls'; import { coalesce, firstOrDefault } from 'vs/base/common/arrays'; import { MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { DeferredPromise, Promises, RunOnceWorker } from 'vs/base/common/async'; import { EventType as TouchEventType, GestureEvent } from 'vs/base/browser/touch'; import { TitleControl } from 'vs/workbench/browser/parts/editor/titleControl'; import { IEditorGroupsAccessor, IEditorGroupView, fillActiveEditorViewState, EditorServiceImpl, IEditorGroupTitleHeight, IInternalEditorOpenOptions, IInternalMoveCopyOptions, IInternalEditorCloseOptions, IInternalEditorTitleControlOptions } from 'vs/workbench/browser/parts/editor/editor'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IAction } from 'vs/base/common/actions'; import { NoTabsTitleControl } from 'vs/workbench/browser/parts/editor/noTabsTitleControl'; import { IMenuService, MenuId } from 'vs/platform/actions/common/actions'; import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { createAndFillInActionBarActions } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { hash } from 'vs/base/common/hash'; import { getMimeTypes } from 'vs/editor/common/services/languagesAssociations'; import { extname, isEqual } from 'vs/base/common/resources'; import { FileAccess, Schemas } from 'vs/base/common/network'; import { EditorActivation, IEditorOptions } from 'vs/platform/editor/common/editor'; import { IFileDialogService, ConfirmResult } from 'vs/platform/dialogs/common/dialogs'; import { IFilesConfigurationService, AutoSaveMode } from 'vs/workbench/services/filesConfiguration/common/filesConfigurationService'; import { withNullAsUndefined } from 'vs/base/common/types'; import { URI } from 'vs/base/common/uri'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { isLinux, isMacintosh, isNative, isWindows } from 'vs/base/common/platform'; import { ILogService } from 'vs/platform/log/common/log'; import { getProgressBarStyles } from 'vs/platform/theme/browser/defaultStyles'; export class EditorGroupView extends Themable implements IEditorGroupView { //#region factory static createNew(accessor: IEditorGroupsAccessor, index: number, instantiationService: IInstantiationService): IEditorGroupView { return instantiationService.createInstance(EditorGroupView, accessor, null, index); } static createFromSerialized(serialized: ISerializedEditorGroupModel, accessor: IEditorGroupsAccessor, index: number, instantiationService: IInstantiationService): IEditorGroupView { return instantiationService.createInstance(EditorGroupView, accessor, serialized, index); } static createCopy(copyFrom: IEditorGroupView, accessor: IEditorGroupsAccessor, index: number, instantiationService: IInstantiationService): IEditorGroupView { return instantiationService.createInstance(EditorGroupView, accessor, copyFrom, index); } //#endregion /** * Access to the context key service scoped to this editor group. */ readonly scopedContextKeyService: IContextKeyService; //#region events private readonly _onDidFocus = this._register(new Emitter<void>()); readonly onDidFocus = this._onDidFocus.event; private readonly _onWillDispose = this._register(new Emitter<void>()); readonly onWillDispose = this._onWillDispose.event; private readonly _onDidModelChange = this._register(new Emitter<IGroupModelChangeEvent>()); readonly onDidModelChange = this._onDidModelChange.event; private readonly _onDidActiveEditorChange = this._register(new Emitter<IActiveEditorChangeEvent>()); readonly onDidActiveEditorChange = this._onDidActiveEditorChange.event; private readonly _onDidOpenEditorFail = this._register(new Emitter<EditorInput>()); readonly onDidOpenEditorFail = this._onDidOpenEditorFail.event; private readonly _onWillCloseEditor = this._register(new Emitter<IEditorCloseEvent>()); readonly onWillCloseEditor = this._onWillCloseEditor.event; private readonly _onDidCloseEditor = this._register(new Emitter<IEditorCloseEvent>()); readonly onDidCloseEditor = this._onDidCloseEditor.event; private readonly _onWillMoveEditor = this._register(new Emitter<IEditorWillMoveEvent>()); readonly onWillMoveEditor = this._onWillMoveEditor.event; private readonly _onWillOpenEditor = this._register(new Emitter<IEditorWillOpenEvent>()); readonly onWillOpenEditor = this._onWillOpenEditor.event; //#endregion private readonly model: EditorGroupModel; private active: boolean | undefined; private lastLayout: IDomNodePagePosition | undefined; private readonly scopedInstantiationService: IInstantiationService; private readonly titleContainer: HTMLElement; private titleAreaControl: TitleControl; private readonly progressBar: ProgressBar; private readonly editorContainer: HTMLElement; private readonly editorPane: EditorPanes; private readonly disposedEditorsWorker = this._register(new RunOnceWorker<EditorInput>(editors => this.handleDisposedEditors(editors), 0)); private readonly mapEditorToPendingConfirmation = new Map<EditorInput, Promise<boolean>>(); private readonly containerToolBarMenuDisposable = this._register(new MutableDisposable()); private readonly whenRestoredPromise = new DeferredPromise<void>(); readonly whenRestored = this.whenRestoredPromise.p; constructor( private accessor: IEditorGroupsAccessor, from: IEditorGroupView | ISerializedEditorGroupModel | null, private _index: number, @IInstantiationService private readonly instantiationService: IInstantiationService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IThemeService themeService: IThemeService, @ITelemetryService private readonly telemetryService: ITelemetryService, @IKeybindingService private readonly keybindingService: IKeybindingService, @IMenuService private readonly menuService: IMenuService, @IContextMenuService private readonly contextMenuService: IContextMenuService, @IFileDialogService private readonly fileDialogService: IFileDialogService, @IEditorService private readonly editorService: EditorServiceImpl, @IFilesConfigurationService private readonly filesConfigurationService: IFilesConfigurationService, @IUriIdentityService private readonly uriIdentityService: IUriIdentityService, @ILogService private readonly logService: ILogService ) { super(themeService); if (from instanceof EditorGroupView) { this.model = this._register(from.model.clone()); } else if (isSerializedEditorGroupModel(from)) { this.model = this._register(instantiationService.createInstance(EditorGroupModel, from)); } else { this.model = this._register(instantiationService.createInstance(EditorGroupModel, undefined)); } //#region create() { // Scoped context key service this.scopedContextKeyService = this._register(this.contextKeyService.createScoped(this.element)); // Container this.element.classList.add('editor-group-container'); // Container listeners this.registerContainerListeners(); // Container toolbar this.createContainerToolbar(); // Container context menu this.createContainerContextMenu(); // Letterpress container const letterpressContainer = document.createElement('div'); letterpressContainer.classList.add('editor-group-letterpress'); this.element.appendChild(letterpressContainer); // Progress bar this.progressBar = this._register(new ProgressBar(this.element, getProgressBarStyles())); this.progressBar.hide(); // Scoped instantiation service this.scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection( [IContextKeyService, this.scopedContextKeyService], [IEditorProgressService, this._register(new EditorProgressIndicator(this.progressBar, this))] )); // Context keys this.handleGroupContextKeys(); // Title container this.titleContainer = document.createElement('div'); this.titleContainer.classList.add('title'); this.element.appendChild(this.titleContainer); // Title control this.titleAreaControl = this.createTitleAreaControl(); // Editor container this.editorContainer = document.createElement('div'); this.editorContainer.classList.add('editor-container'); this.element.appendChild(this.editorContainer); // Editor pane this.editorPane = this._register(this.scopedInstantiationService.createInstance(EditorPanes, this.editorContainer, this)); this._onDidChange.input = this.editorPane.onDidChangeSizeConstraints; // Track Focus this.doTrackFocus(); // Update containers this.updateTitleContainer(); this.updateContainer(); // Update styles this.updateStyles(); } //#endregion // Restore editors if provided const restoreEditorsPromise = this.restoreEditors(from) ?? Promise.resolve(); // Signal restored once editors have restored restoreEditorsPromise.finally(() => { this.whenRestoredPromise.complete(); }); // Register Listeners this.registerListeners(); } private handleGroupContextKeys(): void { const groupActiveEditorDirtyContext = ActiveEditorDirtyContext.bindTo(this.scopedContextKeyService); const groupActiveEditorPinnedContext = ActiveEditorPinnedContext.bindTo(this.scopedContextKeyService); const groupActiveEditorFirstContext = ActiveEditorFirstInGroupContext.bindTo(this.scopedContextKeyService); const groupActiveEditorLastContext = ActiveEditorLastInGroupContext.bindTo(this.scopedContextKeyService); const groupActiveEditorStickyContext = ActiveEditorStickyContext.bindTo(this.scopedContextKeyService); const groupEditorsCountContext = EditorGroupEditorsCountContext.bindTo(this.scopedContextKeyService); const groupLockedContext = ActiveEditorGroupLockedContext.bindTo(this.scopedContextKeyService); const activeEditorListener = new MutableDisposable(); const observeActiveEditor = () => { activeEditorListener.clear(); const activeEditor = this.model.activeEditor; if (activeEditor) { groupActiveEditorDirtyContext.set(activeEditor.isDirty() && !activeEditor.isSaving()); activeEditorListener.value = activeEditor.onDidChangeDirty(() => { groupActiveEditorDirtyContext.set(activeEditor.isDirty() && !activeEditor.isSaving()); }); } else { groupActiveEditorDirtyContext.set(false); } }; // Update group contexts based on group changes this._register(this.onDidModelChange(e => { switch (e.kind) { case GroupModelChangeKind.GROUP_LOCKED: groupLockedContext.set(this.isLocked); break; case GroupModelChangeKind.EDITOR_ACTIVE: case GroupModelChangeKind.EDITOR_CLOSE: case GroupModelChangeKind.EDITOR_OPEN: case GroupModelChangeKind.EDITOR_MOVE: groupActiveEditorFirstContext.set(this.model.isFirst(this.model.activeEditor)); groupActiveEditorLastContext.set(this.model.isLast(this.model.activeEditor)); break; case GroupModelChangeKind.EDITOR_PIN: if (e.editor && e.editor === this.model.activeEditor) { groupActiveEditorPinnedContext.set(this.model.isPinned(this.model.activeEditor)); } break; case GroupModelChangeKind.EDITOR_STICKY: if (e.editor && e.editor === this.model.activeEditor) { groupActiveEditorStickyContext.set(this.model.isSticky(this.model.activeEditor)); } break; } // Group editors count context groupEditorsCountContext.set(this.count); })); // Track the active editor and update context key that reflects // the dirty state of this editor this._register(this.onDidActiveEditorChange(() => { observeActiveEditor(); })); observeActiveEditor(); } private registerContainerListeners(): void { // Open new file via doubleclick on empty container this._register(addDisposableListener(this.element, EventType.DBLCLICK, e => { if (this.isEmpty) { EventHelper.stop(e); this.editorService.openEditor({ resource: undefined, options: { pinned: true, override: DEFAULT_EDITOR_ASSOCIATION.id } }, this.id); } })); // Close empty editor group via middle mouse click this._register(addDisposableListener(this.element, EventType.AUXCLICK, e => { if (this.isEmpty && e.button === 1 /* Middle Button */) { EventHelper.stop(e, true); this.accessor.removeGroup(this); } })); } private createContainerToolbar(): void { // Toolbar Container const toolbarContainer = document.createElement('div'); toolbarContainer.classList.add('editor-group-container-toolbar'); this.element.appendChild(toolbarContainer); // Toolbar const containerToolbar = this._register(new ActionBar(toolbarContainer, { ariaLabel: localize('ariaLabelGroupActions', "Empty editor group actions") })); // Toolbar actions const containerToolbarMenu = this._register(this.menuService.createMenu(MenuId.EmptyEditorGroup, this.scopedContextKeyService)); const updateContainerToolbar = () => { const actions: { primary: IAction[]; secondary: IAction[] } = { primary: [], secondary: [] }; // Clear old actions this.containerToolBarMenuDisposable.value = toDisposable(() => containerToolbar.clear()); // Create new actions createAndFillInActionBarActions( containerToolbarMenu, { arg: { groupId: this.id }, shouldForwardArgs: true }, actions, 'navigation' ); for (const action of [...actions.primary, ...actions.secondary]) { const keybinding = this.keybindingService.lookupKeybinding(action.id); containerToolbar.push(action, { icon: true, label: false, keybinding: keybinding?.getLabel() }); } }; updateContainerToolbar(); this._register(containerToolbarMenu.onDidChange(updateContainerToolbar)); } private createContainerContextMenu(): void { this._register(addDisposableListener(this.element, EventType.CONTEXT_MENU, e => this.onShowContainerContextMenu(e))); this._register(addDisposableListener(this.element, TouchEventType.Contextmenu, () => this.onShowContainerContextMenu())); } private onShowContainerContextMenu(e?: MouseEvent): void { if (!this.isEmpty) { return; // only for empty editor groups } // Find target anchor let anchor: HTMLElement | { x: number; y: number } = this.element; if (e instanceof MouseEvent) { const event = new StandardMouseEvent(e); anchor = { x: event.posx, y: event.posy }; } // Show it this.contextMenuService.showContextMenu({ menuId: MenuId.EmptyEditorGroupContext, contextKeyService: this.contextKeyService, getAnchor: () => anchor, onHide: () => { this.focus(); } }); } private doTrackFocus(): void { // Container const containerFocusTracker = this._register(trackFocus(this.element)); this._register(containerFocusTracker.onDidFocus(() => { if (this.isEmpty) { this._onDidFocus.fire(); // only when empty to prevent accident focus } })); // Title Container const handleTitleClickOrTouch = (e: MouseEvent | GestureEvent): void => { let target: HTMLElement; if (e instanceof MouseEvent) { if (e.button !== 0 || (isMacintosh && e.ctrlKey)) { return undefined; // only for left mouse click (ctrl+click on macos is right-click) } target = e.target as HTMLElement; } else { target = (e as GestureEvent).initialTarget as HTMLElement; } if (findParentWithClass(target, 'monaco-action-bar', this.titleContainer) || findParentWithClass(target, 'monaco-breadcrumb-item', this.titleContainer) ) { return; // not when clicking on actions or breadcrumbs } // timeout to keep focus in editor after mouse up setTimeout(() => { this.focus(); }); }; this._register(addDisposableListener(this.titleContainer, EventType.MOUSE_DOWN, e => handleTitleClickOrTouch(e))); this._register(addDisposableListener(this.titleContainer, TouchEventType.Tap, e => handleTitleClickOrTouch(e))); // Editor pane this._register(this.editorPane.onDidFocus(() => { this._onDidFocus.fire(); })); } private updateContainer(): void { // Empty Container: add some empty container attributes if (this.isEmpty) { this.element.classList.add('empty'); this.element.tabIndex = 0; this.element.setAttribute('aria-label', localize('emptyEditorGroup', "{0} (empty)", this.label)); } // Non-Empty Container: revert empty container attributes else { this.element.classList.remove('empty'); this.element.removeAttribute('tabIndex'); this.element.removeAttribute('aria-label'); } // Update styles this.updateStyles(); } private updateTitleContainer(): void { this.titleContainer.classList.toggle('tabs', this.accessor.partOptions.showTabs); this.titleContainer.classList.toggle('show-file-icons', this.accessor.partOptions.showIcons); } private createTitleAreaControl(): TitleControl { // Clear old if existing if (this.titleAreaControl) { this.titleAreaControl.dispose(); clearNode(this.titleContainer); } // Create new based on options if (this.accessor.partOptions.showTabs) { this.titleAreaControl = this.scopedInstantiationService.createInstance(TabsTitleControl, this.titleContainer, this.accessor, this); } else { this.titleAreaControl = this.scopedInstantiationService.createInstance(NoTabsTitleControl, this.titleContainer, this.accessor, this); } return this.titleAreaControl; } private restoreEditors(from: IEditorGroupView | ISerializedEditorGroupModel | null): Promise<void> | undefined { if (this.count === 0) { return; // nothing to show } // Determine editor options let options: IEditorOptions; if (from instanceof EditorGroupView) { options = fillActiveEditorViewState(from); // if we copy from another group, ensure to copy its active editor viewstate } else { options = Object.create(null); } const activeEditor = this.model.activeEditor; if (!activeEditor) { return; } options.pinned = this.model.isPinned(activeEditor); // preserve pinned state options.sticky = this.model.isSticky(activeEditor); // preserve sticky state options.preserveFocus = true; // handle focus after editor is opened const activeElement = document.activeElement; // Show active editor (intentionally not using async to keep // `restoreEditors` from executing in same stack) return this.doShowEditor(activeEditor, { active: true, isNew: false /* restored */ }, options).then(() => { // Set focused now if this is the active group and focus has // not changed meanwhile. This prevents focus from being // stolen accidentally on startup when the user already // clicked somewhere. if (this.accessor.activeGroup === this && activeElement === document.activeElement) { this.focus(); } }); } //#region event handling private registerListeners(): void { // Model Events this._register(this.model.onDidModelChange(e => this.onDidGroupModelChange(e))); // Option Changes this._register(this.accessor.onDidChangeEditorPartOptions(e => this.onDidChangeEditorPartOptions(e))); // Visibility this._register(this.accessor.onDidVisibilityChange(e => this.onDidVisibilityChange(e))); } private onDidGroupModelChange(e: IGroupModelChangeEvent): void { // Re-emit to outside this._onDidModelChange.fire(e); // Handle within if (!e.editor) { return; } switch (e.kind) { case GroupModelChangeKind.EDITOR_OPEN: if (isGroupEditorOpenEvent(e)) { this.onDidOpenEditor(e.editor, e.editorIndex); } break; case GroupModelChangeKind.EDITOR_CLOSE: if (isGroupEditorCloseEvent(e)) { this.handleOnDidCloseEditor(e.editor, e.editorIndex, e.context, e.sticky); } break; case GroupModelChangeKind.EDITOR_WILL_DISPOSE: this.onWillDisposeEditor(e.editor); break; case GroupModelChangeKind.EDITOR_DIRTY: this.onDidChangeEditorDirty(e.editor); break; case GroupModelChangeKind.EDITOR_LABEL: this.onDidChangeEditorLabel(e.editor); break; } } private onDidOpenEditor(editor: EditorInput, editorIndex: number): void { /* __GDPR__ "editorOpened" : { "owner": "bpasero", "${include}": [ "${EditorTelemetryDescriptor}" ] } */ this.telemetryService.publicLog('editorOpened', this.toEditorTelemetryDescriptor(editor)); // Update container this.updateContainer(); } private handleOnDidCloseEditor(editor: EditorInput, editorIndex: number, context: EditorCloseContext, sticky: boolean): void { // Before close this._onWillCloseEditor.fire({ groupId: this.id, editor, context, index: editorIndex, sticky }); // Handle event const editorsToClose: EditorInput[] = [editor]; // Include both sides of side by side editors when being closed if (editor instanceof SideBySideEditorInput) { editorsToClose.push(editor.primary, editor.secondary); } // For each editor to close, we call dispose() to free up any resources. // However, certain editors might be shared across multiple editor groups // (including being visible in side by side / diff editors) and as such we // only dispose when they are not opened elsewhere. for (const editor of editorsToClose) { if (this.canDispose(editor)) { editor.dispose(); } } /* __GDPR__ "editorClosed" : { "owner": "bpasero", "${include}": [ "${EditorTelemetryDescriptor}" ] } */ this.telemetryService.publicLog('editorClosed', this.toEditorTelemetryDescriptor(editor)); // Update container this.updateContainer(); // Event this._onDidCloseEditor.fire({ groupId: this.id, editor, context, index: editorIndex, sticky }); } private canDispose(editor: EditorInput): boolean { for (const groupView of this.accessor.groups) { if (groupView instanceof EditorGroupView && groupView.model.contains(editor, { strictEquals: true, // only if this input is not shared across editor groups supportSideBySide: SideBySideEditor.ANY // include any side of an opened side by side editor })) { return false; } } return true; } private toEditorTelemetryDescriptor(editor: EditorInput): object { const descriptor = editor.getTelemetryDescriptor(); const resource = EditorResourceAccessor.getOriginalUri(editor); const path = resource ? resource.scheme === Schemas.file ? resource.fsPath : resource.path : undefined; if (resource && path) { let resourceExt = extname(resource); // Remove query parameters from the resource extension const queryStringLocation = resourceExt.indexOf('?'); resourceExt = queryStringLocation !== -1 ? resourceExt.substr(0, queryStringLocation) : resourceExt; descriptor['resource'] = { mimeType: getMimeTypes(resource).join(', '), scheme: resource.scheme, ext: resourceExt, path: hash(path) }; /* __GDPR__FRAGMENT__ "EditorTelemetryDescriptor" : { "resource": { "${inline}": [ "${URIDescriptor}" ] } } */ return descriptor; } return descriptor; } private onWillDisposeEditor(editor: EditorInput): void { // To prevent race conditions, we handle disposed editors in our worker with a timeout // because it can happen that an input is being disposed with the intent to replace // it with some other input right after. this.disposedEditorsWorker.work(editor); } private handleDisposedEditors(editors: EditorInput[]): void { // Split between visible and hidden editors let activeEditor: EditorInput | undefined; const inactiveEditors: EditorInput[] = []; for (const editor of editors) { if (this.model.isActive(editor)) { activeEditor = editor; } else if (this.model.contains(editor)) { inactiveEditors.push(editor); } } // Close all inactive editors first to prevent UI flicker for (const inactiveEditor of inactiveEditors) { this.doCloseEditor(inactiveEditor, false); } // Close active one last if (activeEditor) { this.doCloseEditor(activeEditor, false); } } private onDidChangeEditorPartOptions(event: IEditorPartOptionsChangeEvent): void { // Title container this.updateTitleContainer(); // Title control Switch between showing tabs <=> not showing tabs if (event.oldPartOptions.showTabs !== event.newPartOptions.showTabs) { // Recreate title control this.createTitleAreaControl(); // Re-layout this.relayout(); // Ensure to show active editor if any if (this.model.activeEditor) { this.titleAreaControl.openEditor(this.model.activeEditor); } } // Just update title control else { this.titleAreaControl.updateOptions(event.oldPartOptions, event.newPartOptions); } // Styles this.updateStyles(); // Pin preview editor once user disables preview if (event.oldPartOptions.enablePreview && !event.newPartOptions.enablePreview) { if (this.model.previewEditor) { this.pinEditor(this.model.previewEditor); } } } private onDidChangeEditorDirty(editor: EditorInput): void { // Always show dirty editors pinned this.pinEditor(editor); // Forward to title control this.titleAreaControl.updateEditorDirty(editor); } private onDidChangeEditorLabel(editor: EditorInput): void { // Forward to title control this.titleAreaControl.updateEditorLabel(editor); } private onDidVisibilityChange(visible: boolean): void { // Forward to active editor pane this.editorPane.setVisible(visible); } //#endregion //#region IEditorGroupView get index(): number { return this._index; } get label(): string { return localize('groupLabel', "Group {0}", this._index + 1); } get ariaLabel(): string { return localize('groupAriaLabel', "Editor Group {0}", this._index + 1); } private _disposed = false; get disposed(): boolean { return this._disposed; } get isEmpty(): boolean { return this.count === 0; } get titleHeight(): IEditorGroupTitleHeight { return this.titleAreaControl.getHeight(); } notifyIndexChanged(newIndex: number): void { if (this._index !== newIndex) { this._index = newIndex; this.model.setIndex(newIndex); } } setActive(isActive: boolean): void { this.active = isActive; // Update container this.element.classList.toggle('active', isActive); this.element.classList.toggle('inactive', !isActive); // Update title control this.titleAreaControl.setActive(isActive); // Update styles this.updateStyles(); // Update model this.model.setActive(undefined /* entire group got active */); } //#endregion //#region IEditorGroup //#region basics() get id(): GroupIdentifier { return this.model.id; } get editors(): EditorInput[] { return this.model.getEditors(EditorsOrder.SEQUENTIAL); } get count(): number { return this.model.count; } get stickyCount(): number { return this.model.stickyCount; } get activeEditorPane(): IVisibleEditorPane | undefined { return this.editorPane ? withNullAsUndefined(this.editorPane.activeEditorPane) : undefined; } get activeEditor(): EditorInput | null { return this.model.activeEditor; } get previewEditor(): EditorInput | null { return this.model.previewEditor; } isPinned(editorOrIndex: EditorInput | number): boolean { return this.model.isPinned(editorOrIndex); } isSticky(editorOrIndex: EditorInput | number): boolean { return this.model.isSticky(editorOrIndex); } isActive(editor: EditorInput | IUntypedEditorInput): boolean { return this.model.isActive(editor); } contains(candidate: EditorInput | IUntypedEditorInput, options?: IMatchEditorOptions): boolean { return this.model.contains(candidate, options); } getEditors(order: EditorsOrder, options?: { excludeSticky?: boolean }): EditorInput[] { return this.model.getEditors(order, options); } findEditors(resource: URI, options?: IFindEditorOptions): EditorInput[] { const canonicalResource = this.uriIdentityService.asCanonicalUri(resource); return this.getEditors(EditorsOrder.SEQUENTIAL).filter(editor => { if (editor.resource && isEqual(editor.resource, canonicalResource)) { return true; } // Support side by side editor primary side if specified if (options?.supportSideBySide === SideBySideEditor.PRIMARY || options?.supportSideBySide === SideBySideEditor.ANY) { const primaryResource = EditorResourceAccessor.getCanonicalUri(editor, { supportSideBySide: SideBySideEditor.PRIMARY }); if (primaryResource && isEqual(primaryResource, canonicalResource)) { return true; } } // Support side by side editor secondary side if specified if (options?.supportSideBySide === SideBySideEditor.SECONDARY || options?.supportSideBySide === SideBySideEditor.ANY) { const secondaryResource = EditorResourceAccessor.getCanonicalUri(editor, { supportSideBySide: SideBySideEditor.SECONDARY }); if (secondaryResource && isEqual(secondaryResource, canonicalResource)) { return true; } } return false; }); } getEditorByIndex(index: number): EditorInput | undefined { return this.model.getEditorByIndex(index); } getIndexOfEditor(editor: EditorInput): number { return this.model.indexOf(editor); } isFirst(editor: EditorInput): boolean { return this.model.isFirst(editor); } isLast(editor: EditorInput): boolean { return this.model.isLast(editor); } focus(): void { // Pass focus to editor panes if (this.activeEditorPane) { this.activeEditorPane.focus(); } else { this.element.focus(); } // Event this._onDidFocus.fire(); } pinEditor(candidate: EditorInput | undefined = this.activeEditor || undefined): void { if (candidate && !this.model.isPinned(candidate)) { // Update model const editor = this.model.pin(candidate); // Forward to title control if (editor) { this.titleAreaControl.pinEditor(editor); } } } stickEditor(candidate: EditorInput | undefined = this.activeEditor || undefined): void { this.doStickEditor(candidate, true); } unstickEditor(candidate: EditorInput | undefined = this.activeEditor || undefined): void { this.doStickEditor(candidate, false); } private doStickEditor(candidate: EditorInput | undefined, sticky: boolean): void { if (candidate && this.model.isSticky(candidate) !== sticky) { const oldIndexOfEditor = this.getIndexOfEditor(candidate); // Update model const editor = sticky ? this.model.stick(candidate) : this.model.unstick(candidate); if (!editor) { return; } // If the index of the editor changed, we need to forward this to // title control and also make sure to emit this as an event const newIndexOfEditor = this.getIndexOfEditor(editor); if (newIndexOfEditor !== oldIndexOfEditor) { this.titleAreaControl.moveEditor(editor, oldIndexOfEditor, newIndexOfEditor); } // Forward sticky state to title control if (sticky) { this.titleAreaControl.stickEditor(editor); } else { this.titleAreaControl.unstickEditor(editor); } } } //#endregion //#region openEditor() async openEditor(editor: EditorInput, options?: IEditorOptions): Promise<IEditorPane | undefined> { return this.doOpenEditor(editor, options, { // Allow to match on a side-by-side editor when same // editor is opened on both sides. In that case we // do not want to open a new editor but reuse that one. supportSideBySide: SideBySideEditor.BOTH }); } private async doOpenEditor(editor: EditorInput, options?: IEditorOptions, internalOptions?: IInternalEditorOpenOptions): Promise<IEditorPane | undefined> { // Guard against invalid editors. Disposed editors // should never open because they emit no events // e.g. to indicate dirty changes. if (!editor || editor.isDisposed()) { return; } // Fire the event letting everyone know we are about to open an editor this._onWillOpenEditor.fire({ editor, groupId: this.id }); // Determine options const openEditorOptions: IEditorOpenOptions = { index: options ? options.index : undefined, pinned: options?.sticky || !this.accessor.partOptions.enablePreview || editor.isDirty() || (options?.pinned ?? typeof options?.index === 'number' /* unless specified, prefer to pin when opening with index */) || (typeof options?.index === 'number' && this.model.isSticky(options.index)), sticky: options?.sticky || (typeof options?.index === 'number' && this.model.isSticky(options.index)), active: this.count === 0 || !options || !options.inactive, supportSideBySide: internalOptions?.supportSideBySide }; if (options?.sticky && typeof options?.index === 'number' && !this.model.isSticky(options.index)) { // Special case: we are to open an editor sticky but at an index that is not sticky // In that case we prefer to open the editor at the index but not sticky. This enables // to drag a sticky editor to an index that is not sticky to unstick it. openEditorOptions.sticky = false; } if (!openEditorOptions.active && !openEditorOptions.pinned && this.model.activeEditor && !this.model.isPinned(this.model.activeEditor)) { // Special case: we are to open an editor inactive and not pinned, but the current active // editor is also not pinned, which means it will get replaced with this one. As such, // the editor can only be active. openEditorOptions.active = true; } let activateGroup = false; let restoreGroup = false; if (options?.activation === EditorActivation.ACTIVATE) { // Respect option to force activate an editor group. activateGroup = true; } else if (options?.activation === EditorActivation.RESTORE) { // Respect option to force restore an editor group. restoreGroup = true; } else if (options?.activation === EditorActivation.PRESERVE) { // Respect option to preserve active editor group. activateGroup = false; restoreGroup = false; } else if (openEditorOptions.active) { // Finally, we only activate/restore an editor which is // opening as active editor. // If preserveFocus is enabled, we only restore but never // activate the group. activateGroup = !options || !options.preserveFocus; restoreGroup = !activateGroup; } // Actually move the editor if a specific index is provided and we figure // out that the editor is already opened at a different index. This // ensures the right set of events are fired to the outside. if (typeof openEditorOptions.index === 'number') { const indexOfEditor = this.model.indexOf(editor); if (indexOfEditor !== -1 && indexOfEditor !== openEditorOptions.index) { this.doMoveEditorInsideGroup(editor, openEditorOptions); } } // Update model and make sure to continue to use the editor we get from // the model. It is possible that the editor was already opened and we // want to ensure that we use the existing instance in that case. const { editor: openedEditor, isNew } = this.model.openEditor(editor, openEditorOptions); // Conditionally lock the group if ( isNew && // only if this editor was new for the group this.count === 1 && // only when this editor was the first editor in the group this.accessor.groups.length > 1 // only when there are more than one groups open ) { // only when the editor identifier is configured as such if (openedEditor.editorId && this.accessor.partOptions.autoLockGroups?.has(openedEditor.editorId)) { this.lock(true); } } // Show editor const showEditorResult = this.doShowEditor(openedEditor, { active: !!openEditorOptions.active, isNew }, options, internalOptions); // Finally make sure the group is active or restored as instructed if (activateGroup) { this.accessor.activateGroup(this); } else if (restoreGroup) { this.accessor.restoreGroup(this); } return showEditorResult; } private doShowEditor(editor: EditorInput, context: { active: boolean; isNew: boolean }, options?: IEditorOptions, internalOptions?: IInternalEditorOpenOptions): Promise<IEditorPane | undefined> { // Show in editor control if the active editor changed let openEditorPromise: Promise<IEditorPane | undefined>; if (context.active) { openEditorPromise = (async () => { const { pane, changed, cancelled, error } = await this.editorPane.openEditor(editor, options, { newInGroup: context.isNew }); // Return early if the operation was cancelled by another operation if (cancelled) { return undefined; } // Editor change event if (changed) { this._onDidActiveEditorChange.fire({ editor }); } // Indicate error as an event but do not bubble them up if (error) { this._onDidOpenEditorFail.fire(editor); } // Without an editor pane, recover by closing the active editor // (if the input is still the active one) if (!pane && this.activeEditor === editor) { const focusNext = !options || !options.preserveFocus; this.doCloseEditor(editor, focusNext, { fromError: true }); } return pane; })(); } else { openEditorPromise = Promise.resolve(undefined); // inactive: return undefined as result to signal this } // Show in title control after editor control because some actions depend on it // but respect the internal options in case title control updates should skip. if (!internalOptions?.skipTitleUpdate) { this.titleAreaControl.openEditor(editor); } return openEditorPromise; } //#endregion //#region openEditors() async openEditors(editors: { editor: EditorInput; options?: IEditorOptions }[]): Promise<IEditorPane | undefined> { // Guard against invalid editors. Disposed editors // should never open because they emit no events // e.g. to indicate dirty changes. const editorsToOpen = coalesce(editors).filter(({ editor }) => !editor.isDisposed()); // Use the first editor as active editor const firstEditor = firstOrDefault(editorsToOpen); if (!firstEditor) { return; } const openEditorsOptions: IInternalEditorOpenOptions = { // Allow to match on a side-by-side editor when same // editor is opened on both sides. In that case we // do not want to open a new editor but reuse that one. supportSideBySide: SideBySideEditor.BOTH }; await this.doOpenEditor(firstEditor.editor, firstEditor.options, openEditorsOptions); // Open the other ones inactive const inactiveEditors = editorsToOpen.slice(1); const startingIndex = this.getIndexOfEditor(firstEditor.editor) + 1; await Promises.settled(inactiveEditors.map(({ editor, options }, index) => { return this.doOpenEditor(editor, { ...options, inactive: true, pinned: true, index: startingIndex + index }, { ...openEditorsOptions, // optimization: update the title control later // https://github.com/microsoft/vscode/issues/130634 skipTitleUpdate: true }); })); // Update the title control all at once with all editors this.titleAreaControl.openEditors(inactiveEditors.map(({ editor }) => editor)); // Opening many editors at once can put any editor to be // the active one depending on options. As such, we simply // return the active editor pane after this operation. return withNullAsUndefined(this.editorPane.activeEditorPane); } //#endregion //#region moveEditor() moveEditors(editors: { editor: EditorInput; options?: IEditorOptions }[], target: EditorGroupView): void { // Optimization: knowing that we move many editors, we // delay the title update to a later point for this group // through a method that allows for bulk updates but only // when moving to a different group where many editors // are more likely to occur. const internalOptions: IInternalMoveCopyOptions = { skipTitleUpdate: this !== target }; for (const { editor, options } of editors) { this.moveEditor(editor, target, options, internalOptions); } // Update the title control all at once with all editors // in source and target if the title update was skipped if (internalOptions.skipTitleUpdate) { const movedEditors = editors.map(({ editor }) => editor); target.titleAreaControl.openEditors(movedEditors); this.titleAreaControl.closeEditors(movedEditors); } } moveEditor(editor: EditorInput, target: EditorGroupView, options?: IEditorOptions, internalOptions?: IInternalEditorTitleControlOptions): void { // Move within same group if (this === target) { this.doMoveEditorInsideGroup(editor, options); } // Move across groups else { this.doMoveOrCopyEditorAcrossGroups(editor, target, options, { ...internalOptions, keepCopy: false }); } } private doMoveEditorInsideGroup(candidate: EditorInput, options?: IEditorOpenOptions): void { const moveToIndex = options ? options.index : undefined; if (typeof moveToIndex !== 'number') { return; // do nothing if we move into same group without index } const currentIndex = this.model.indexOf(candidate); if (currentIndex === -1 || currentIndex === moveToIndex) { return; // do nothing if editor unknown in model or is already at the given index } // Update model and make sure to continue to use the editor we get from // the model. It is possible that the editor was already opened and we // want to ensure that we use the existing instance in that case. const editor = this.model.getEditorByIndex(currentIndex); if (!editor) { return; } // Update model this.model.moveEditor(editor, moveToIndex); this.model.pin(editor); // Forward to title area this.titleAreaControl.moveEditor(editor, currentIndex, moveToIndex); this.titleAreaControl.pinEditor(editor); } private doMoveOrCopyEditorAcrossGroups(editor: EditorInput, target: EditorGroupView, openOptions?: IEditorOpenOptions, internalOptions?: IInternalMoveCopyOptions): void { const keepCopy = internalOptions?.keepCopy; // When moving/copying an editor, try to preserve as much view state as possible // by checking for the editor to be a text editor and creating the options accordingly // if so const options = fillActiveEditorViewState(this, editor, { ...openOptions, pinned: true, // always pin moved editor sticky: !keepCopy && this.model.isSticky(editor) // preserve sticky state only if editor is moved (https://github.com/microsoft/vscode/issues/99035) }); // Indicate will move event if (!keepCopy) { this._onWillMoveEditor.fire({ groupId: this.id, editor, target: target.id }); } // A move to another group is an open first... target.doOpenEditor(keepCopy ? editor.copy() : editor, options, internalOptions); // ...and a close afterwards (unless we copy) if (!keepCopy) { this.doCloseEditor(editor, false /* do not focus next one behind if any */, { ...internalOptions, context: EditorCloseContext.MOVE }); } } //#endregion //#region copyEditor() copyEditors(editors: { editor: EditorInput; options?: IEditorOptions }[], target: EditorGroupView): void { // Optimization: knowing that we move many editors, we // delay the title update to a later point for this group // through a method that allows for bulk updates but only // when moving to a different group where many editors // are more likely to occur. const internalOptions: IInternalMoveCopyOptions = { skipTitleUpdate: this !== target }; for (const { editor, options } of editors) { this.copyEditor(editor, target, options, internalOptions); } // Update the title control all at once with all editors // in target if the title update was skipped if (internalOptions.skipTitleUpdate) { const copiedEditors = editors.map(({ editor }) => editor); target.titleAreaControl.openEditors(copiedEditors); } } copyEditor(editor: EditorInput, target: EditorGroupView, options?: IEditorOptions, internalOptions?: IInternalEditorTitleControlOptions): void { // Move within same group because we do not support to show the same editor // multiple times in the same group if (this === target) { this.doMoveEditorInsideGroup(editor, options); } // Copy across groups else { this.doMoveOrCopyEditorAcrossGroups(editor, target, options, { ...internalOptions, keepCopy: true }); } } //#endregion //#region closeEditor() async closeEditor(editor: EditorInput | undefined = this.activeEditor || undefined, options?: ICloseEditorOptions): Promise<boolean> { return this.doCloseEditorWithConfirmationHandling(editor, options); } private async doCloseEditorWithConfirmationHandling(editor: EditorInput | undefined = this.activeEditor || undefined, options?: ICloseEditorOptions, internalOptions?: IInternalEditorCloseOptions): Promise<boolean> { if (!editor) { return false; } // Check for confirmation and veto const veto = await this.handleCloseConfirmation([editor]); if (veto) { return false; } // Do close this.doCloseEditor(editor, options?.preserveFocus ? false : undefined, internalOptions); return true; } private doCloseEditor(editor: EditorInput, focusNext = (this.accessor.activeGroup === this), internalOptions?: IInternalEditorCloseOptions): void { let index: number | undefined; // Closing the active editor of the group is a bit more work if (this.model.isActive(editor)) { index = this.doCloseActiveEditor(focusNext, internalOptions); } // Closing inactive editor is just a model update else { index = this.doCloseInactiveEditor(editor, internalOptions); } // Forward to title control unless skipped via internal options if (!internalOptions?.skipTitleUpdate) { this.titleAreaControl.closeEditor(editor, index); } } private doCloseActiveEditor(focusNext = (this.accessor.activeGroup === this), internalOptions?: IInternalEditorCloseOptions): number | undefined { const editorToClose = this.activeEditor; const restoreFocus = this.shouldRestoreFocus(this.element); // Optimization: if we are about to close the last editor in this group and settings // are configured to close the group since it will be empty, we first set the last // active group as empty before closing the editor. This reduces the amount of editor // change events that this operation emits and will reduce flicker. Without this // optimization, this group (if active) would first trigger a active editor change // event because it became empty, only to then trigger another one when the next // group gets active. const closeEmptyGroup = this.accessor.partOptions.closeEmptyGroups; if (closeEmptyGroup && this.active && this.count === 1) { const mostRecentlyActiveGroups = this.accessor.getGroups(GroupsOrder.MOST_RECENTLY_ACTIVE); const nextActiveGroup = mostRecentlyActiveGroups[1]; // [0] will be the current one, so take [1] if (nextActiveGroup) { if (restoreFocus) { nextActiveGroup.focus(); } else { this.accessor.activateGroup(nextActiveGroup); } } } // Update model let index: number | undefined = undefined; if (editorToClose) { index = this.model.closeEditor(editorToClose, internalOptions?.context)?.editorIndex; } // Open next active if there are more to show const nextActiveEditor = this.model.activeEditor; if (nextActiveEditor) { const preserveFocus = !focusNext; let activation: EditorActivation | undefined = undefined; if (preserveFocus && this.accessor.activeGroup !== this) { // If we are opening the next editor in an inactive group // without focussing it, ensure we preserve the editor // group sizes in case that group is minimized. // https://github.com/microsoft/vscode/issues/117686 activation = EditorActivation.PRESERVE; } const options: IEditorOptions = { preserveFocus, activation, // When closing an editor due to an error we can end up in a loop where we continue closing // editors that fail to open (e.g. when the file no longer exists). We do not want to show // repeated errors in this case to the user. As such, if we open the next editor and we are // in a scope of a previous editor failing, we silence the input errors until the editor is // opened by setting ignoreError: true. ignoreError: internalOptions?.fromError }; this.doOpenEditor(nextActiveEditor, options); } // Otherwise we are empty, so clear from editor control and send event else { // Forward to editor pane if (editorToClose) { this.editorPane.closeEditor(editorToClose); } // Restore focus to group container as needed unless group gets closed if (restoreFocus && !closeEmptyGroup) { this.focus(); } // Events this._onDidActiveEditorChange.fire({ editor: undefined }); // Remove empty group if we should if (closeEmptyGroup) { this.accessor.removeGroup(this); } } return index; } private shouldRestoreFocus(target: Element): boolean { const activeElement = document.activeElement; if (activeElement === document.body) { return true; // always restore focus if nothing is focused currently } // otherwise check for the active element being an ancestor of the target return isAncestor(activeElement, target); } private doCloseInactiveEditor(editor: EditorInput, internalOptions?: IInternalEditorCloseOptions): number | undefined { // Update model return this.model.closeEditor(editor, internalOptions?.context)?.editorIndex; } private async handleCloseConfirmation(editors: EditorInput[]): Promise<boolean /* veto */> { if (!editors.length) { return false; // no veto } const editor = editors.shift()!; // To prevent multiple confirmation dialogs from showing up one after the other // we check if a pending confirmation is currently showing and if so, join that let handleCloseConfirmationPromise = this.mapEditorToPendingConfirmation.get(editor); if (!handleCloseConfirmationPromise) { handleCloseConfirmationPromise = this.doHandleCloseConfirmation(editor); this.mapEditorToPendingConfirmation.set(editor, handleCloseConfirmationPromise); } let veto: boolean; try { veto = await handleCloseConfirmationPromise; } finally { this.mapEditorToPendingConfirmation.delete(editor); } // Return for the first veto we got if (veto) { return veto; } // Otherwise continue with the remainders return this.handleCloseConfirmation(editors); } private async doHandleCloseConfirmation(editor: EditorInput, options?: { skipAutoSave: boolean }): Promise<boolean /* veto */> { if (!this.shouldConfirmClose(editor)) { return false; // no veto } if (editor instanceof SideBySideEditorInput && this.model.contains(editor.primary)) { return false; // primary-side of editor is still opened somewhere else } // Note: we explicitly decide to ask for confirm if closing a normal editor even // if it is opened in a side-by-side editor in the group. This decision is made // because it may be less obvious that one side of a side by side editor is dirty // and can still be changed. // The only exception is when the same editor is opened on both sides of a side // by side editor (https://github.com/microsoft/vscode/issues/138442) if (this.accessor.groups.some(groupView => { if (groupView === this) { return false; // skip (we already handled our group above) } const otherGroup = groupView; if (otherGroup.contains(editor, { supportSideBySide: SideBySideEditor.BOTH })) { return true; // exact editor still opened (either single, or split-in-group) } if (editor instanceof SideBySideEditorInput && otherGroup.contains(editor.primary)) { return true; // primary side of side by side editor still opened } return false; })) { return false; // editor is still editable somewhere else } // In some cases trigger save before opening the dialog depending // on auto-save configuration. // However, make sure to respect `skipAutoSave` option in case the automated // save fails which would result in the editor never closing. // Also, we only do this if no custom confirmation handling is implemented. let confirmation = ConfirmResult.CANCEL; let saveReason = SaveReason.EXPLICIT; let autoSave = false; if (!editor.hasCapability(EditorInputCapabilities.Untitled) && !options?.skipAutoSave && !editor.closeHandler) { // Auto-save on focus change: save, because a dialog would steal focus // (see https://github.com/microsoft/vscode/issues/108752) if (this.filesConfigurationService.getAutoSaveMode() === AutoSaveMode.ON_FOCUS_CHANGE) { autoSave = true; confirmation = ConfirmResult.SAVE; saveReason = SaveReason.FOCUS_CHANGE; } // Auto-save on window change: save, because on Windows and Linux, a // native dialog triggers the window focus change // (see https://github.com/microsoft/vscode/issues/134250) else if ((isNative && (isWindows || isLinux)) && this.filesConfigurationService.getAutoSaveMode() === AutoSaveMode.ON_WINDOW_CHANGE) { autoSave = true; confirmation = ConfirmResult.SAVE; saveReason = SaveReason.WINDOW_CHANGE; } } // No auto-save on focus change or custom confirmation handler: ask user if (!autoSave) { // Switch to editor that we want to handle for confirmation await this.doOpenEditor(editor); // Let editor handle confirmation if implemented if (typeof editor.closeHandler?.confirm === 'function') { confirmation = await editor.closeHandler.confirm([{ editor, groupId: this.id }]); } // Show a file specific confirmation else { let name: string; if (editor instanceof SideBySideEditorInput) { name = editor.primary.getName(); // prefer shorter names by using primary's name in this case } else { name = editor.getName(); } confirmation = await this.fileDialogService.showSaveConfirm([name]); } } // It could be that the editor's choice of confirmation has changed // given the check for confirmation is long running, so we check // again to see if anything needs to happen before closing for good. // This can happen for example if `autoSave: onFocusChange` is configured // so that the save happens when the dialog opens. // However, we only do this unless a custom confirm handler is installed // that may not be fit to be asked a second time right after. if (!editor.closeHandler && !this.shouldConfirmClose(editor)) { return confirmation === ConfirmResult.CANCEL ? true : false; } // Otherwise, handle accordingly switch (confirmation) { case ConfirmResult.SAVE: { const result = await editor.save(this.id, { reason: saveReason }); if (!result && autoSave) { // Save failed and we need to signal this back to the user, so // we handle the dirty editor again but this time ensuring to // show the confirm dialog // (see https://github.com/microsoft/vscode/issues/108752) return this.doHandleCloseConfirmation(editor, { skipAutoSave: true }); } return editor.isDirty(); // veto if still dirty } case ConfirmResult.DONT_SAVE: try { // first try a normal revert where the contents of the editor are restored await editor.revert(this.id); return editor.isDirty(); // veto if still dirty } catch (error) { this.logService.error(error); // if that fails, since we are about to close the editor, we accept that // the editor cannot be reverted and instead do a soft revert that just // enables us to close the editor. With this, a user can always close a // dirty editor even when reverting fails. await editor.revert(this.id, { soft: true }); return editor.isDirty(); // veto if still dirty } case ConfirmResult.CANCEL: return true; // veto } } private shouldConfirmClose(editor: EditorInput): boolean { if (editor.closeHandler) { return editor.closeHandler.showConfirm(); // custom handling of confirmation on close } return editor.isDirty() && !editor.isSaving(); // editor must be dirty and not saving } //#endregion //#region closeEditors() async closeEditors(args: EditorInput[] | ICloseEditorsFilter, options?: ICloseEditorOptions): Promise<boolean> { if (this.isEmpty) { return true; } const editors = this.doGetEditorsToClose(args); // Check for confirmation and veto const veto = await this.handleCloseConfirmation(editors.slice(0)); if (veto) { return false; } // Do close this.doCloseEditors(editors, options); return true; } private doGetEditorsToClose(args: EditorInput[] | ICloseEditorsFilter): EditorInput[] { if (Array.isArray(args)) { return args; } const filter = args; const hasDirection = typeof filter.direction === 'number'; let editorsToClose = this.model.getEditors(hasDirection ? EditorsOrder.SEQUENTIAL : EditorsOrder.MOST_RECENTLY_ACTIVE, filter); // in MRU order only if direction is not specified // Filter: saved or saving only if (filter.savedOnly) { editorsToClose = editorsToClose.filter(editor => !editor.isDirty() || editor.isSaving()); } // Filter: direction (left / right) else if (hasDirection && filter.except) { editorsToClose = (filter.direction === CloseDirection.LEFT) ? editorsToClose.slice(0, this.model.indexOf(filter.except, editorsToClose)) : editorsToClose.slice(this.model.indexOf(filter.except, editorsToClose) + 1); } // Filter: except else if (filter.except) { editorsToClose = editorsToClose.filter(editor => filter.except && !editor.matches(filter.except)); } return editorsToClose; } private doCloseEditors(editors: EditorInput[], options?: ICloseEditorOptions): void { // Close all inactive editors first let closeActiveEditor = false; for (const editor of editors) { if (!this.isActive(editor)) { this.doCloseInactiveEditor(editor); } else { closeActiveEditor = true; } } // Close active editor last if contained in editors list to close if (closeActiveEditor) { this.doCloseActiveEditor(options?.preserveFocus ? false : undefined); } // Forward to title control if (editors.length) { this.titleAreaControl.closeEditors(editors); } } //#endregion //#region closeAllEditors() async closeAllEditors(options?: ICloseAllEditorsOptions): Promise<boolean> { if (this.isEmpty) { // If the group is empty and the request is to close all editors, we still close // the editor group is the related setting to close empty groups is enabled for // a convenient way of removing empty editor groups for the user. if (this.accessor.partOptions.closeEmptyGroups) { this.accessor.removeGroup(this); } return true; } // Check for confirmation and veto const veto = await this.handleCloseConfirmation(this.model.getEditors(EditorsOrder.MOST_RECENTLY_ACTIVE, options)); if (veto) { return false; } // Do close this.doCloseAllEditors(options); return true; } private doCloseAllEditors(options?: ICloseAllEditorsOptions): void { // Close all inactive editors first const editorsToClose: EditorInput[] = []; for (const editor of this.model.getEditors(EditorsOrder.SEQUENTIAL, options)) { if (!this.isActive(editor)) { this.doCloseInactiveEditor(editor); } editorsToClose.push(editor); } // Close active editor last (unless we skip it, e.g. because it is sticky) if (this.activeEditor && editorsToClose.includes(this.activeEditor)) { this.doCloseActiveEditor(); } // Forward to title control if (editorsToClose.length) { this.titleAreaControl.closeEditors(editorsToClose); } } //#endregion //#region replaceEditors() async replaceEditors(editors: EditorReplacement[]): Promise<void> { // Extract active vs. inactive replacements let activeReplacement: EditorReplacement | undefined; const inactiveReplacements: EditorReplacement[] = []; for (let { editor, replacement, forceReplaceDirty, options } of editors) { const index = this.getIndexOfEditor(editor); if (index >= 0) { const isActiveEditor = this.isActive(editor); // make sure we respect the index of the editor to replace if (options) { options.index = index; } else { options = { index }; } options.inactive = !isActiveEditor; options.pinned = options.pinned ?? true; // unless specified, prefer to pin upon replace const editorToReplace = { editor, replacement, forceReplaceDirty, options }; if (isActiveEditor) { activeReplacement = editorToReplace; } else { inactiveReplacements.push(editorToReplace); } } } // Handle inactive first for (const { editor, replacement, forceReplaceDirty, options } of inactiveReplacements) { // Open inactive editor await this.doOpenEditor(replacement, options); // Close replaced inactive editor unless they match if (!editor.matches(replacement)) { let closed = false; if (forceReplaceDirty) { this.doCloseEditor(editor, false, { context: EditorCloseContext.REPLACE }); closed = true; } else { closed = await this.doCloseEditorWithConfirmationHandling(editor, { preserveFocus: true }, { context: EditorCloseContext.REPLACE }); } if (!closed) { return; // canceled } } } // Handle active last if (activeReplacement) { // Open replacement as active editor const openEditorResult = this.doOpenEditor(activeReplacement.replacement, activeReplacement.options); // Close replaced active editor unless they match if (!activeReplacement.editor.matches(activeReplacement.replacement)) { if (activeReplacement.forceReplaceDirty) { this.doCloseEditor(activeReplacement.editor, false, { context: EditorCloseContext.REPLACE }); } else { await this.doCloseEditorWithConfirmationHandling(activeReplacement.editor, { preserveFocus: true }, { context: EditorCloseContext.REPLACE }); } } await openEditorResult; } } //#endregion //#region Locking get isLocked(): boolean { if (this.accessor.groups.length === 1) { // Special case: if only 1 group is opened, never report it as locked // to ensure editors can always open in the "default" editor group return false; } return this.model.isLocked; } lock(locked: boolean): void { if (this.accessor.groups.length === 1) { // Special case: if only 1 group is opened, never allow to lock // to ensure editors can always open in the "default" editor group locked = false; } this.model.lock(locked); } //#endregion //#region Themable protected override updateStyles(): void { const isEmpty = this.isEmpty; // Container if (isEmpty) { this.element.style.backgroundColor = this.getColor(EDITOR_GROUP_EMPTY_BACKGROUND) || ''; } else { this.element.style.backgroundColor = ''; } // Title control const borderColor = this.getColor(EDITOR_GROUP_HEADER_BORDER) || this.getColor(contrastBorder); if (!isEmpty && borderColor) { this.titleContainer.classList.add('title-border-bottom'); this.titleContainer.style.setProperty('--title-border-bottom-color', borderColor.toString()); } else { this.titleContainer.classList.remove('title-border-bottom'); this.titleContainer.style.removeProperty('--title-border-bottom-color'); } const { showTabs } = this.accessor.partOptions; this.titleContainer.style.backgroundColor = this.getColor(showTabs ? EDITOR_GROUP_HEADER_TABS_BACKGROUND : EDITOR_GROUP_HEADER_NO_TABS_BACKGROUND) || ''; // Editor container this.editorContainer.style.backgroundColor = this.getColor(editorBackground) || ''; } //#endregion //#region ISerializableView readonly element: HTMLElement = document.createElement('div'); get minimumWidth(): number { return this.editorPane.minimumWidth; } get minimumHeight(): number { return this.editorPane.minimumHeight; } get maximumWidth(): number { return this.editorPane.maximumWidth; } get maximumHeight(): number { return this.editorPane.maximumHeight; } private _onDidChange = this._register(new Relay<{ width: number; height: number } | undefined>()); readonly onDidChange = this._onDidChange.event; layout(width: number, height: number, top: number, left: number): void { this.lastLayout = { width, height, top, left }; // Layout the title area first to receive the size it occupies const titleAreaSize = this.titleAreaControl.layout({ container: new Dimension(width, height), available: new Dimension(width, height - this.editorPane.minimumHeight) }); // Pass the container width and remaining height to the editor layout const editorHeight = Math.max(0, height - titleAreaSize.height); this.editorContainer.style.height = `${editorHeight}px`; this.editorPane.layout({ width, height: editorHeight, top: top + titleAreaSize.height, left }); } relayout(): void { if (this.lastLayout) { const { width, height, top, left } = this.lastLayout; this.layout(width, height, top, left); } } toJSON(): ISerializedEditorGroupModel { return this.model.serialize(); } //#endregion override dispose(): void { this._disposed = true; this._onWillDispose.fire(); this.titleAreaControl.dispose(); super.dispose(); } } export interface EditorReplacement extends IEditorReplacement { readonly editor: EditorInput; readonly replacement: EditorInput; readonly options?: IEditorOptions; } registerThemingParticipant((theme, collector) => { // Letterpress const letterpress = `./media/letterpress-${theme.type}.svg`; collector.addRule(` .monaco-workbench .part.editor > .content .editor-group-container.empty .editor-group-letterpress { background-image: ${asCSSUrl(FileAccess.asBrowserUri(letterpress, require))} } `); // Focused Empty Group Border const focusedEmptyGroupBorder = theme.getColor(EDITOR_GROUP_FOCUSED_EMPTY_BORDER); if (focusedEmptyGroupBorder) { collector.addRule(` .monaco-workbench .part.editor > .content:not(.empty) .editor-group-container.empty.active:focus { outline-width: 1px; outline-color: ${focusedEmptyGroupBorder}; outline-offset: -2px; outline-style: solid; } .monaco-workbench .part.editor > .content.empty .editor-group-container.empty.active:focus { outline: none; /* never show outline for empty group if it is the last */ } `); } else { collector.addRule(` .monaco-workbench .part.editor > .content .editor-group-container.empty.active:focus { outline: none; /* disable focus outline unless active empty group border is defined */ } `); } });
src/vs/workbench/browser/parts/editor/editorGroupView.ts
1
https://github.com/microsoft/vscode/commit/9dabc131d81eb802f28765ac96cfed8794ffb533
[ 0.980129599571228, 0.008761098608374596, 0.000160826210048981, 0.0001688387565081939, 0.0848793238401413 ]
{ "id": 1, "code_window": [ "\t\tconst handleClickOrTouch = (e: MouseEvent | GestureEvent, preserveFocus: boolean): void => {\n", "\t\t\ttab.blur(); // prevent flicker of focus outline on tab until editor got focus\n", "\n", "\t\t\tif (e instanceof MouseEvent && e.button !== 0) {\n", "\t\t\t\tif (e.button === 1) {\n", "\t\t\t\t\te.preventDefault(); // required to prevent auto-scrolling (https://github.com/microsoft/vscode/issues/16690)\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (e instanceof MouseEvent && (e.button !== 0 /* middle/right mouse button */ || (isMacintosh && e.ctrlKey /* macOS context menu */))) {\n" ], "file_path": "src/vs/workbench/browser/parts/editor/tabsTitleControl.ts", "type": "replace", "edit_start_line_idx": 693 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ declare module 'vscode' { // https://github.com/microsoft/vscode/issues/127473 /** * The state of a comment thread. */ export enum CommentThreadState { Unresolved = 0, Resolved = 1 } export interface CommentThread { /** * The optional state of a comment thread, which may affect how the comment is displayed. */ state?: CommentThreadState; } }
src/vscode-dts/vscode.proposed.commentsResolvedState.d.ts
0
https://github.com/microsoft/vscode/commit/9dabc131d81eb802f28765ac96cfed8794ffb533
[ 0.0002394470211584121, 0.00019203907868359238, 0.00016647505981381983, 0.0001701951987342909, 0.00003355685112182982 ]
{ "id": 1, "code_window": [ "\t\tconst handleClickOrTouch = (e: MouseEvent | GestureEvent, preserveFocus: boolean): void => {\n", "\t\t\ttab.blur(); // prevent flicker of focus outline on tab until editor got focus\n", "\n", "\t\t\tif (e instanceof MouseEvent && e.button !== 0) {\n", "\t\t\t\tif (e.button === 1) {\n", "\t\t\t\t\te.preventDefault(); // required to prevent auto-scrolling (https://github.com/microsoft/vscode/issues/16690)\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (e instanceof MouseEvent && (e.button !== 0 /* middle/right mouse button */ || (isMacintosh && e.ctrlKey /* macOS context menu */))) {\n" ], "file_path": "src/vs/workbench/browser/parts/editor/tabsTitleControl.ts", "type": "replace", "edit_start_line_idx": 693 }
test/** cgmanifest.json
extensions/xml/.vscodeignore
0
https://github.com/microsoft/vscode/commit/9dabc131d81eb802f28765ac96cfed8794ffb533
[ 0.00017263639892917126, 0.00017263639892917126, 0.00017263639892917126, 0.00017263639892917126, 0 ]
{ "id": 1, "code_window": [ "\t\tconst handleClickOrTouch = (e: MouseEvent | GestureEvent, preserveFocus: boolean): void => {\n", "\t\t\ttab.blur(); // prevent flicker of focus outline on tab until editor got focus\n", "\n", "\t\t\tif (e instanceof MouseEvent && e.button !== 0) {\n", "\t\t\t\tif (e.button === 1) {\n", "\t\t\t\t\te.preventDefault(); // required to prevent auto-scrolling (https://github.com/microsoft/vscode/issues/16690)\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (e instanceof MouseEvent && (e.button !== 0 /* middle/right mouse button */ || (isMacintosh && e.ctrlKey /* macOS context menu */))) {\n" ], "file_path": "src/vs/workbench/browser/parts/editor/tabsTitleControl.ts", "type": "replace", "edit_start_line_idx": 693 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { MarkedString } from 'vscode'; export function textToMarkedString(text: string): MarkedString { return text.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash }
extensions/php-language-features/src/features/utils/markedTextUtil.ts
0
https://github.com/microsoft/vscode/commit/9dabc131d81eb802f28765ac96cfed8794ffb533
[ 0.00017361198842991143, 0.0001726788468658924, 0.00017174570530187339, 0.0001726788468658924, 9.331415640190244e-7 ]
{ "id": 2, "code_window": [ "\t\t\t\tif (e.button === 1) {\n", "\t\t\t\t\te.preventDefault(); // required to prevent auto-scrolling (https://github.com/microsoft/vscode/issues/16690)\n", "\t\t\t\t}\n", "\n", "\t\t\t\treturn undefined; // only for left mouse click\n", "\t\t\t}\n", "\n", "\t\t\tif (this.originatesFromTabActionBar(e)) {\n", "\t\t\t\treturn; // not when clicking on actions\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\treturn undefined;\n" ], "file_path": "src/vs/workbench/browser/parts/editor/tabsTitleControl.ts", "type": "replace", "edit_start_line_idx": 698 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/editorgroupview'; import { EditorGroupModel, IEditorOpenOptions, IGroupModelChangeEvent, ISerializedEditorGroupModel, isGroupEditorCloseEvent, isGroupEditorOpenEvent, isSerializedEditorGroupModel } from 'vs/workbench/common/editor/editorGroupModel'; import { GroupIdentifier, CloseDirection, IEditorCloseEvent, IEditorPane, SaveReason, IEditorPartOptionsChangeEvent, EditorsOrder, IVisibleEditorPane, EditorResourceAccessor, EditorInputCapabilities, IUntypedEditorInput, DEFAULT_EDITOR_ASSOCIATION, SideBySideEditor, EditorCloseContext, IEditorWillMoveEvent, IEditorWillOpenEvent, IMatchEditorOptions, GroupModelChangeKind, IActiveEditorChangeEvent, IFindEditorOptions } from 'vs/workbench/common/editor'; import { ActiveEditorGroupLockedContext, ActiveEditorDirtyContext, EditorGroupEditorsCountContext, ActiveEditorStickyContext, ActiveEditorPinnedContext, ActiveEditorLastInGroupContext, ActiveEditorFirstInGroupContext } from 'vs/workbench/common/contextkeys'; import { EditorInput } from 'vs/workbench/common/editor/editorInput'; import { SideBySideEditorInput } from 'vs/workbench/common/editor/sideBySideEditorInput'; import { Emitter, Relay } from 'vs/base/common/event'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { Dimension, trackFocus, addDisposableListener, EventType, EventHelper, findParentWithClass, clearNode, isAncestor, asCSSUrl, IDomNodePagePosition } from 'vs/base/browser/dom'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { IThemeService, registerThemingParticipant, Themable } from 'vs/platform/theme/common/themeService'; import { editorBackground, contrastBorder } from 'vs/platform/theme/common/colorRegistry'; import { EDITOR_GROUP_HEADER_TABS_BACKGROUND, EDITOR_GROUP_HEADER_NO_TABS_BACKGROUND, EDITOR_GROUP_EMPTY_BACKGROUND, EDITOR_GROUP_FOCUSED_EMPTY_BORDER, EDITOR_GROUP_HEADER_BORDER } from 'vs/workbench/common/theme'; import { ICloseEditorsFilter, GroupsOrder, ICloseEditorOptions, ICloseAllEditorsOptions, IEditorReplacement } from 'vs/workbench/services/editor/common/editorGroupsService'; import { TabsTitleControl } from 'vs/workbench/browser/parts/editor/tabsTitleControl'; import { EditorPanes } from 'vs/workbench/browser/parts/editor/editorPanes'; import { IEditorProgressService } from 'vs/platform/progress/common/progress'; import { EditorProgressIndicator } from 'vs/workbench/services/progress/browser/progressIndicator'; import { localize } from 'vs/nls'; import { coalesce, firstOrDefault } from 'vs/base/common/arrays'; import { MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { DeferredPromise, Promises, RunOnceWorker } from 'vs/base/common/async'; import { EventType as TouchEventType, GestureEvent } from 'vs/base/browser/touch'; import { TitleControl } from 'vs/workbench/browser/parts/editor/titleControl'; import { IEditorGroupsAccessor, IEditorGroupView, fillActiveEditorViewState, EditorServiceImpl, IEditorGroupTitleHeight, IInternalEditorOpenOptions, IInternalMoveCopyOptions, IInternalEditorCloseOptions, IInternalEditorTitleControlOptions } from 'vs/workbench/browser/parts/editor/editor'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IAction } from 'vs/base/common/actions'; import { NoTabsTitleControl } from 'vs/workbench/browser/parts/editor/noTabsTitleControl'; import { IMenuService, MenuId } from 'vs/platform/actions/common/actions'; import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { createAndFillInActionBarActions } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { hash } from 'vs/base/common/hash'; import { getMimeTypes } from 'vs/editor/common/services/languagesAssociations'; import { extname, isEqual } from 'vs/base/common/resources'; import { FileAccess, Schemas } from 'vs/base/common/network'; import { EditorActivation, IEditorOptions } from 'vs/platform/editor/common/editor'; import { IFileDialogService, ConfirmResult } from 'vs/platform/dialogs/common/dialogs'; import { IFilesConfigurationService, AutoSaveMode } from 'vs/workbench/services/filesConfiguration/common/filesConfigurationService'; import { withNullAsUndefined } from 'vs/base/common/types'; import { URI } from 'vs/base/common/uri'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { isLinux, isMacintosh, isNative, isWindows } from 'vs/base/common/platform'; import { ILogService } from 'vs/platform/log/common/log'; import { getProgressBarStyles } from 'vs/platform/theme/browser/defaultStyles'; export class EditorGroupView extends Themable implements IEditorGroupView { //#region factory static createNew(accessor: IEditorGroupsAccessor, index: number, instantiationService: IInstantiationService): IEditorGroupView { return instantiationService.createInstance(EditorGroupView, accessor, null, index); } static createFromSerialized(serialized: ISerializedEditorGroupModel, accessor: IEditorGroupsAccessor, index: number, instantiationService: IInstantiationService): IEditorGroupView { return instantiationService.createInstance(EditorGroupView, accessor, serialized, index); } static createCopy(copyFrom: IEditorGroupView, accessor: IEditorGroupsAccessor, index: number, instantiationService: IInstantiationService): IEditorGroupView { return instantiationService.createInstance(EditorGroupView, accessor, copyFrom, index); } //#endregion /** * Access to the context key service scoped to this editor group. */ readonly scopedContextKeyService: IContextKeyService; //#region events private readonly _onDidFocus = this._register(new Emitter<void>()); readonly onDidFocus = this._onDidFocus.event; private readonly _onWillDispose = this._register(new Emitter<void>()); readonly onWillDispose = this._onWillDispose.event; private readonly _onDidModelChange = this._register(new Emitter<IGroupModelChangeEvent>()); readonly onDidModelChange = this._onDidModelChange.event; private readonly _onDidActiveEditorChange = this._register(new Emitter<IActiveEditorChangeEvent>()); readonly onDidActiveEditorChange = this._onDidActiveEditorChange.event; private readonly _onDidOpenEditorFail = this._register(new Emitter<EditorInput>()); readonly onDidOpenEditorFail = this._onDidOpenEditorFail.event; private readonly _onWillCloseEditor = this._register(new Emitter<IEditorCloseEvent>()); readonly onWillCloseEditor = this._onWillCloseEditor.event; private readonly _onDidCloseEditor = this._register(new Emitter<IEditorCloseEvent>()); readonly onDidCloseEditor = this._onDidCloseEditor.event; private readonly _onWillMoveEditor = this._register(new Emitter<IEditorWillMoveEvent>()); readonly onWillMoveEditor = this._onWillMoveEditor.event; private readonly _onWillOpenEditor = this._register(new Emitter<IEditorWillOpenEvent>()); readonly onWillOpenEditor = this._onWillOpenEditor.event; //#endregion private readonly model: EditorGroupModel; private active: boolean | undefined; private lastLayout: IDomNodePagePosition | undefined; private readonly scopedInstantiationService: IInstantiationService; private readonly titleContainer: HTMLElement; private titleAreaControl: TitleControl; private readonly progressBar: ProgressBar; private readonly editorContainer: HTMLElement; private readonly editorPane: EditorPanes; private readonly disposedEditorsWorker = this._register(new RunOnceWorker<EditorInput>(editors => this.handleDisposedEditors(editors), 0)); private readonly mapEditorToPendingConfirmation = new Map<EditorInput, Promise<boolean>>(); private readonly containerToolBarMenuDisposable = this._register(new MutableDisposable()); private readonly whenRestoredPromise = new DeferredPromise<void>(); readonly whenRestored = this.whenRestoredPromise.p; constructor( private accessor: IEditorGroupsAccessor, from: IEditorGroupView | ISerializedEditorGroupModel | null, private _index: number, @IInstantiationService private readonly instantiationService: IInstantiationService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IThemeService themeService: IThemeService, @ITelemetryService private readonly telemetryService: ITelemetryService, @IKeybindingService private readonly keybindingService: IKeybindingService, @IMenuService private readonly menuService: IMenuService, @IContextMenuService private readonly contextMenuService: IContextMenuService, @IFileDialogService private readonly fileDialogService: IFileDialogService, @IEditorService private readonly editorService: EditorServiceImpl, @IFilesConfigurationService private readonly filesConfigurationService: IFilesConfigurationService, @IUriIdentityService private readonly uriIdentityService: IUriIdentityService, @ILogService private readonly logService: ILogService ) { super(themeService); if (from instanceof EditorGroupView) { this.model = this._register(from.model.clone()); } else if (isSerializedEditorGroupModel(from)) { this.model = this._register(instantiationService.createInstance(EditorGroupModel, from)); } else { this.model = this._register(instantiationService.createInstance(EditorGroupModel, undefined)); } //#region create() { // Scoped context key service this.scopedContextKeyService = this._register(this.contextKeyService.createScoped(this.element)); // Container this.element.classList.add('editor-group-container'); // Container listeners this.registerContainerListeners(); // Container toolbar this.createContainerToolbar(); // Container context menu this.createContainerContextMenu(); // Letterpress container const letterpressContainer = document.createElement('div'); letterpressContainer.classList.add('editor-group-letterpress'); this.element.appendChild(letterpressContainer); // Progress bar this.progressBar = this._register(new ProgressBar(this.element, getProgressBarStyles())); this.progressBar.hide(); // Scoped instantiation service this.scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection( [IContextKeyService, this.scopedContextKeyService], [IEditorProgressService, this._register(new EditorProgressIndicator(this.progressBar, this))] )); // Context keys this.handleGroupContextKeys(); // Title container this.titleContainer = document.createElement('div'); this.titleContainer.classList.add('title'); this.element.appendChild(this.titleContainer); // Title control this.titleAreaControl = this.createTitleAreaControl(); // Editor container this.editorContainer = document.createElement('div'); this.editorContainer.classList.add('editor-container'); this.element.appendChild(this.editorContainer); // Editor pane this.editorPane = this._register(this.scopedInstantiationService.createInstance(EditorPanes, this.editorContainer, this)); this._onDidChange.input = this.editorPane.onDidChangeSizeConstraints; // Track Focus this.doTrackFocus(); // Update containers this.updateTitleContainer(); this.updateContainer(); // Update styles this.updateStyles(); } //#endregion // Restore editors if provided const restoreEditorsPromise = this.restoreEditors(from) ?? Promise.resolve(); // Signal restored once editors have restored restoreEditorsPromise.finally(() => { this.whenRestoredPromise.complete(); }); // Register Listeners this.registerListeners(); } private handleGroupContextKeys(): void { const groupActiveEditorDirtyContext = ActiveEditorDirtyContext.bindTo(this.scopedContextKeyService); const groupActiveEditorPinnedContext = ActiveEditorPinnedContext.bindTo(this.scopedContextKeyService); const groupActiveEditorFirstContext = ActiveEditorFirstInGroupContext.bindTo(this.scopedContextKeyService); const groupActiveEditorLastContext = ActiveEditorLastInGroupContext.bindTo(this.scopedContextKeyService); const groupActiveEditorStickyContext = ActiveEditorStickyContext.bindTo(this.scopedContextKeyService); const groupEditorsCountContext = EditorGroupEditorsCountContext.bindTo(this.scopedContextKeyService); const groupLockedContext = ActiveEditorGroupLockedContext.bindTo(this.scopedContextKeyService); const activeEditorListener = new MutableDisposable(); const observeActiveEditor = () => { activeEditorListener.clear(); const activeEditor = this.model.activeEditor; if (activeEditor) { groupActiveEditorDirtyContext.set(activeEditor.isDirty() && !activeEditor.isSaving()); activeEditorListener.value = activeEditor.onDidChangeDirty(() => { groupActiveEditorDirtyContext.set(activeEditor.isDirty() && !activeEditor.isSaving()); }); } else { groupActiveEditorDirtyContext.set(false); } }; // Update group contexts based on group changes this._register(this.onDidModelChange(e => { switch (e.kind) { case GroupModelChangeKind.GROUP_LOCKED: groupLockedContext.set(this.isLocked); break; case GroupModelChangeKind.EDITOR_ACTIVE: case GroupModelChangeKind.EDITOR_CLOSE: case GroupModelChangeKind.EDITOR_OPEN: case GroupModelChangeKind.EDITOR_MOVE: groupActiveEditorFirstContext.set(this.model.isFirst(this.model.activeEditor)); groupActiveEditorLastContext.set(this.model.isLast(this.model.activeEditor)); break; case GroupModelChangeKind.EDITOR_PIN: if (e.editor && e.editor === this.model.activeEditor) { groupActiveEditorPinnedContext.set(this.model.isPinned(this.model.activeEditor)); } break; case GroupModelChangeKind.EDITOR_STICKY: if (e.editor && e.editor === this.model.activeEditor) { groupActiveEditorStickyContext.set(this.model.isSticky(this.model.activeEditor)); } break; } // Group editors count context groupEditorsCountContext.set(this.count); })); // Track the active editor and update context key that reflects // the dirty state of this editor this._register(this.onDidActiveEditorChange(() => { observeActiveEditor(); })); observeActiveEditor(); } private registerContainerListeners(): void { // Open new file via doubleclick on empty container this._register(addDisposableListener(this.element, EventType.DBLCLICK, e => { if (this.isEmpty) { EventHelper.stop(e); this.editorService.openEditor({ resource: undefined, options: { pinned: true, override: DEFAULT_EDITOR_ASSOCIATION.id } }, this.id); } })); // Close empty editor group via middle mouse click this._register(addDisposableListener(this.element, EventType.AUXCLICK, e => { if (this.isEmpty && e.button === 1 /* Middle Button */) { EventHelper.stop(e, true); this.accessor.removeGroup(this); } })); } private createContainerToolbar(): void { // Toolbar Container const toolbarContainer = document.createElement('div'); toolbarContainer.classList.add('editor-group-container-toolbar'); this.element.appendChild(toolbarContainer); // Toolbar const containerToolbar = this._register(new ActionBar(toolbarContainer, { ariaLabel: localize('ariaLabelGroupActions', "Empty editor group actions") })); // Toolbar actions const containerToolbarMenu = this._register(this.menuService.createMenu(MenuId.EmptyEditorGroup, this.scopedContextKeyService)); const updateContainerToolbar = () => { const actions: { primary: IAction[]; secondary: IAction[] } = { primary: [], secondary: [] }; // Clear old actions this.containerToolBarMenuDisposable.value = toDisposable(() => containerToolbar.clear()); // Create new actions createAndFillInActionBarActions( containerToolbarMenu, { arg: { groupId: this.id }, shouldForwardArgs: true }, actions, 'navigation' ); for (const action of [...actions.primary, ...actions.secondary]) { const keybinding = this.keybindingService.lookupKeybinding(action.id); containerToolbar.push(action, { icon: true, label: false, keybinding: keybinding?.getLabel() }); } }; updateContainerToolbar(); this._register(containerToolbarMenu.onDidChange(updateContainerToolbar)); } private createContainerContextMenu(): void { this._register(addDisposableListener(this.element, EventType.CONTEXT_MENU, e => this.onShowContainerContextMenu(e))); this._register(addDisposableListener(this.element, TouchEventType.Contextmenu, () => this.onShowContainerContextMenu())); } private onShowContainerContextMenu(e?: MouseEvent): void { if (!this.isEmpty) { return; // only for empty editor groups } // Find target anchor let anchor: HTMLElement | { x: number; y: number } = this.element; if (e instanceof MouseEvent) { const event = new StandardMouseEvent(e); anchor = { x: event.posx, y: event.posy }; } // Show it this.contextMenuService.showContextMenu({ menuId: MenuId.EmptyEditorGroupContext, contextKeyService: this.contextKeyService, getAnchor: () => anchor, onHide: () => { this.focus(); } }); } private doTrackFocus(): void { // Container const containerFocusTracker = this._register(trackFocus(this.element)); this._register(containerFocusTracker.onDidFocus(() => { if (this.isEmpty) { this._onDidFocus.fire(); // only when empty to prevent accident focus } })); // Title Container const handleTitleClickOrTouch = (e: MouseEvent | GestureEvent): void => { let target: HTMLElement; if (e instanceof MouseEvent) { if (e.button !== 0 || (isMacintosh && e.ctrlKey)) { return undefined; // only for left mouse click (ctrl+click on macos is right-click) } target = e.target as HTMLElement; } else { target = (e as GestureEvent).initialTarget as HTMLElement; } if (findParentWithClass(target, 'monaco-action-bar', this.titleContainer) || findParentWithClass(target, 'monaco-breadcrumb-item', this.titleContainer) ) { return; // not when clicking on actions or breadcrumbs } // timeout to keep focus in editor after mouse up setTimeout(() => { this.focus(); }); }; this._register(addDisposableListener(this.titleContainer, EventType.MOUSE_DOWN, e => handleTitleClickOrTouch(e))); this._register(addDisposableListener(this.titleContainer, TouchEventType.Tap, e => handleTitleClickOrTouch(e))); // Editor pane this._register(this.editorPane.onDidFocus(() => { this._onDidFocus.fire(); })); } private updateContainer(): void { // Empty Container: add some empty container attributes if (this.isEmpty) { this.element.classList.add('empty'); this.element.tabIndex = 0; this.element.setAttribute('aria-label', localize('emptyEditorGroup', "{0} (empty)", this.label)); } // Non-Empty Container: revert empty container attributes else { this.element.classList.remove('empty'); this.element.removeAttribute('tabIndex'); this.element.removeAttribute('aria-label'); } // Update styles this.updateStyles(); } private updateTitleContainer(): void { this.titleContainer.classList.toggle('tabs', this.accessor.partOptions.showTabs); this.titleContainer.classList.toggle('show-file-icons', this.accessor.partOptions.showIcons); } private createTitleAreaControl(): TitleControl { // Clear old if existing if (this.titleAreaControl) { this.titleAreaControl.dispose(); clearNode(this.titleContainer); } // Create new based on options if (this.accessor.partOptions.showTabs) { this.titleAreaControl = this.scopedInstantiationService.createInstance(TabsTitleControl, this.titleContainer, this.accessor, this); } else { this.titleAreaControl = this.scopedInstantiationService.createInstance(NoTabsTitleControl, this.titleContainer, this.accessor, this); } return this.titleAreaControl; } private restoreEditors(from: IEditorGroupView | ISerializedEditorGroupModel | null): Promise<void> | undefined { if (this.count === 0) { return; // nothing to show } // Determine editor options let options: IEditorOptions; if (from instanceof EditorGroupView) { options = fillActiveEditorViewState(from); // if we copy from another group, ensure to copy its active editor viewstate } else { options = Object.create(null); } const activeEditor = this.model.activeEditor; if (!activeEditor) { return; } options.pinned = this.model.isPinned(activeEditor); // preserve pinned state options.sticky = this.model.isSticky(activeEditor); // preserve sticky state options.preserveFocus = true; // handle focus after editor is opened const activeElement = document.activeElement; // Show active editor (intentionally not using async to keep // `restoreEditors` from executing in same stack) return this.doShowEditor(activeEditor, { active: true, isNew: false /* restored */ }, options).then(() => { // Set focused now if this is the active group and focus has // not changed meanwhile. This prevents focus from being // stolen accidentally on startup when the user already // clicked somewhere. if (this.accessor.activeGroup === this && activeElement === document.activeElement) { this.focus(); } }); } //#region event handling private registerListeners(): void { // Model Events this._register(this.model.onDidModelChange(e => this.onDidGroupModelChange(e))); // Option Changes this._register(this.accessor.onDidChangeEditorPartOptions(e => this.onDidChangeEditorPartOptions(e))); // Visibility this._register(this.accessor.onDidVisibilityChange(e => this.onDidVisibilityChange(e))); } private onDidGroupModelChange(e: IGroupModelChangeEvent): void { // Re-emit to outside this._onDidModelChange.fire(e); // Handle within if (!e.editor) { return; } switch (e.kind) { case GroupModelChangeKind.EDITOR_OPEN: if (isGroupEditorOpenEvent(e)) { this.onDidOpenEditor(e.editor, e.editorIndex); } break; case GroupModelChangeKind.EDITOR_CLOSE: if (isGroupEditorCloseEvent(e)) { this.handleOnDidCloseEditor(e.editor, e.editorIndex, e.context, e.sticky); } break; case GroupModelChangeKind.EDITOR_WILL_DISPOSE: this.onWillDisposeEditor(e.editor); break; case GroupModelChangeKind.EDITOR_DIRTY: this.onDidChangeEditorDirty(e.editor); break; case GroupModelChangeKind.EDITOR_LABEL: this.onDidChangeEditorLabel(e.editor); break; } } private onDidOpenEditor(editor: EditorInput, editorIndex: number): void { /* __GDPR__ "editorOpened" : { "owner": "bpasero", "${include}": [ "${EditorTelemetryDescriptor}" ] } */ this.telemetryService.publicLog('editorOpened', this.toEditorTelemetryDescriptor(editor)); // Update container this.updateContainer(); } private handleOnDidCloseEditor(editor: EditorInput, editorIndex: number, context: EditorCloseContext, sticky: boolean): void { // Before close this._onWillCloseEditor.fire({ groupId: this.id, editor, context, index: editorIndex, sticky }); // Handle event const editorsToClose: EditorInput[] = [editor]; // Include both sides of side by side editors when being closed if (editor instanceof SideBySideEditorInput) { editorsToClose.push(editor.primary, editor.secondary); } // For each editor to close, we call dispose() to free up any resources. // However, certain editors might be shared across multiple editor groups // (including being visible in side by side / diff editors) and as such we // only dispose when they are not opened elsewhere. for (const editor of editorsToClose) { if (this.canDispose(editor)) { editor.dispose(); } } /* __GDPR__ "editorClosed" : { "owner": "bpasero", "${include}": [ "${EditorTelemetryDescriptor}" ] } */ this.telemetryService.publicLog('editorClosed', this.toEditorTelemetryDescriptor(editor)); // Update container this.updateContainer(); // Event this._onDidCloseEditor.fire({ groupId: this.id, editor, context, index: editorIndex, sticky }); } private canDispose(editor: EditorInput): boolean { for (const groupView of this.accessor.groups) { if (groupView instanceof EditorGroupView && groupView.model.contains(editor, { strictEquals: true, // only if this input is not shared across editor groups supportSideBySide: SideBySideEditor.ANY // include any side of an opened side by side editor })) { return false; } } return true; } private toEditorTelemetryDescriptor(editor: EditorInput): object { const descriptor = editor.getTelemetryDescriptor(); const resource = EditorResourceAccessor.getOriginalUri(editor); const path = resource ? resource.scheme === Schemas.file ? resource.fsPath : resource.path : undefined; if (resource && path) { let resourceExt = extname(resource); // Remove query parameters from the resource extension const queryStringLocation = resourceExt.indexOf('?'); resourceExt = queryStringLocation !== -1 ? resourceExt.substr(0, queryStringLocation) : resourceExt; descriptor['resource'] = { mimeType: getMimeTypes(resource).join(', '), scheme: resource.scheme, ext: resourceExt, path: hash(path) }; /* __GDPR__FRAGMENT__ "EditorTelemetryDescriptor" : { "resource": { "${inline}": [ "${URIDescriptor}" ] } } */ return descriptor; } return descriptor; } private onWillDisposeEditor(editor: EditorInput): void { // To prevent race conditions, we handle disposed editors in our worker with a timeout // because it can happen that an input is being disposed with the intent to replace // it with some other input right after. this.disposedEditorsWorker.work(editor); } private handleDisposedEditors(editors: EditorInput[]): void { // Split between visible and hidden editors let activeEditor: EditorInput | undefined; const inactiveEditors: EditorInput[] = []; for (const editor of editors) { if (this.model.isActive(editor)) { activeEditor = editor; } else if (this.model.contains(editor)) { inactiveEditors.push(editor); } } // Close all inactive editors first to prevent UI flicker for (const inactiveEditor of inactiveEditors) { this.doCloseEditor(inactiveEditor, false); } // Close active one last if (activeEditor) { this.doCloseEditor(activeEditor, false); } } private onDidChangeEditorPartOptions(event: IEditorPartOptionsChangeEvent): void { // Title container this.updateTitleContainer(); // Title control Switch between showing tabs <=> not showing tabs if (event.oldPartOptions.showTabs !== event.newPartOptions.showTabs) { // Recreate title control this.createTitleAreaControl(); // Re-layout this.relayout(); // Ensure to show active editor if any if (this.model.activeEditor) { this.titleAreaControl.openEditor(this.model.activeEditor); } } // Just update title control else { this.titleAreaControl.updateOptions(event.oldPartOptions, event.newPartOptions); } // Styles this.updateStyles(); // Pin preview editor once user disables preview if (event.oldPartOptions.enablePreview && !event.newPartOptions.enablePreview) { if (this.model.previewEditor) { this.pinEditor(this.model.previewEditor); } } } private onDidChangeEditorDirty(editor: EditorInput): void { // Always show dirty editors pinned this.pinEditor(editor); // Forward to title control this.titleAreaControl.updateEditorDirty(editor); } private onDidChangeEditorLabel(editor: EditorInput): void { // Forward to title control this.titleAreaControl.updateEditorLabel(editor); } private onDidVisibilityChange(visible: boolean): void { // Forward to active editor pane this.editorPane.setVisible(visible); } //#endregion //#region IEditorGroupView get index(): number { return this._index; } get label(): string { return localize('groupLabel', "Group {0}", this._index + 1); } get ariaLabel(): string { return localize('groupAriaLabel', "Editor Group {0}", this._index + 1); } private _disposed = false; get disposed(): boolean { return this._disposed; } get isEmpty(): boolean { return this.count === 0; } get titleHeight(): IEditorGroupTitleHeight { return this.titleAreaControl.getHeight(); } notifyIndexChanged(newIndex: number): void { if (this._index !== newIndex) { this._index = newIndex; this.model.setIndex(newIndex); } } setActive(isActive: boolean): void { this.active = isActive; // Update container this.element.classList.toggle('active', isActive); this.element.classList.toggle('inactive', !isActive); // Update title control this.titleAreaControl.setActive(isActive); // Update styles this.updateStyles(); // Update model this.model.setActive(undefined /* entire group got active */); } //#endregion //#region IEditorGroup //#region basics() get id(): GroupIdentifier { return this.model.id; } get editors(): EditorInput[] { return this.model.getEditors(EditorsOrder.SEQUENTIAL); } get count(): number { return this.model.count; } get stickyCount(): number { return this.model.stickyCount; } get activeEditorPane(): IVisibleEditorPane | undefined { return this.editorPane ? withNullAsUndefined(this.editorPane.activeEditorPane) : undefined; } get activeEditor(): EditorInput | null { return this.model.activeEditor; } get previewEditor(): EditorInput | null { return this.model.previewEditor; } isPinned(editorOrIndex: EditorInput | number): boolean { return this.model.isPinned(editorOrIndex); } isSticky(editorOrIndex: EditorInput | number): boolean { return this.model.isSticky(editorOrIndex); } isActive(editor: EditorInput | IUntypedEditorInput): boolean { return this.model.isActive(editor); } contains(candidate: EditorInput | IUntypedEditorInput, options?: IMatchEditorOptions): boolean { return this.model.contains(candidate, options); } getEditors(order: EditorsOrder, options?: { excludeSticky?: boolean }): EditorInput[] { return this.model.getEditors(order, options); } findEditors(resource: URI, options?: IFindEditorOptions): EditorInput[] { const canonicalResource = this.uriIdentityService.asCanonicalUri(resource); return this.getEditors(EditorsOrder.SEQUENTIAL).filter(editor => { if (editor.resource && isEqual(editor.resource, canonicalResource)) { return true; } // Support side by side editor primary side if specified if (options?.supportSideBySide === SideBySideEditor.PRIMARY || options?.supportSideBySide === SideBySideEditor.ANY) { const primaryResource = EditorResourceAccessor.getCanonicalUri(editor, { supportSideBySide: SideBySideEditor.PRIMARY }); if (primaryResource && isEqual(primaryResource, canonicalResource)) { return true; } } // Support side by side editor secondary side if specified if (options?.supportSideBySide === SideBySideEditor.SECONDARY || options?.supportSideBySide === SideBySideEditor.ANY) { const secondaryResource = EditorResourceAccessor.getCanonicalUri(editor, { supportSideBySide: SideBySideEditor.SECONDARY }); if (secondaryResource && isEqual(secondaryResource, canonicalResource)) { return true; } } return false; }); } getEditorByIndex(index: number): EditorInput | undefined { return this.model.getEditorByIndex(index); } getIndexOfEditor(editor: EditorInput): number { return this.model.indexOf(editor); } isFirst(editor: EditorInput): boolean { return this.model.isFirst(editor); } isLast(editor: EditorInput): boolean { return this.model.isLast(editor); } focus(): void { // Pass focus to editor panes if (this.activeEditorPane) { this.activeEditorPane.focus(); } else { this.element.focus(); } // Event this._onDidFocus.fire(); } pinEditor(candidate: EditorInput | undefined = this.activeEditor || undefined): void { if (candidate && !this.model.isPinned(candidate)) { // Update model const editor = this.model.pin(candidate); // Forward to title control if (editor) { this.titleAreaControl.pinEditor(editor); } } } stickEditor(candidate: EditorInput | undefined = this.activeEditor || undefined): void { this.doStickEditor(candidate, true); } unstickEditor(candidate: EditorInput | undefined = this.activeEditor || undefined): void { this.doStickEditor(candidate, false); } private doStickEditor(candidate: EditorInput | undefined, sticky: boolean): void { if (candidate && this.model.isSticky(candidate) !== sticky) { const oldIndexOfEditor = this.getIndexOfEditor(candidate); // Update model const editor = sticky ? this.model.stick(candidate) : this.model.unstick(candidate); if (!editor) { return; } // If the index of the editor changed, we need to forward this to // title control and also make sure to emit this as an event const newIndexOfEditor = this.getIndexOfEditor(editor); if (newIndexOfEditor !== oldIndexOfEditor) { this.titleAreaControl.moveEditor(editor, oldIndexOfEditor, newIndexOfEditor); } // Forward sticky state to title control if (sticky) { this.titleAreaControl.stickEditor(editor); } else { this.titleAreaControl.unstickEditor(editor); } } } //#endregion //#region openEditor() async openEditor(editor: EditorInput, options?: IEditorOptions): Promise<IEditorPane | undefined> { return this.doOpenEditor(editor, options, { // Allow to match on a side-by-side editor when same // editor is opened on both sides. In that case we // do not want to open a new editor but reuse that one. supportSideBySide: SideBySideEditor.BOTH }); } private async doOpenEditor(editor: EditorInput, options?: IEditorOptions, internalOptions?: IInternalEditorOpenOptions): Promise<IEditorPane | undefined> { // Guard against invalid editors. Disposed editors // should never open because they emit no events // e.g. to indicate dirty changes. if (!editor || editor.isDisposed()) { return; } // Fire the event letting everyone know we are about to open an editor this._onWillOpenEditor.fire({ editor, groupId: this.id }); // Determine options const openEditorOptions: IEditorOpenOptions = { index: options ? options.index : undefined, pinned: options?.sticky || !this.accessor.partOptions.enablePreview || editor.isDirty() || (options?.pinned ?? typeof options?.index === 'number' /* unless specified, prefer to pin when opening with index */) || (typeof options?.index === 'number' && this.model.isSticky(options.index)), sticky: options?.sticky || (typeof options?.index === 'number' && this.model.isSticky(options.index)), active: this.count === 0 || !options || !options.inactive, supportSideBySide: internalOptions?.supportSideBySide }; if (options?.sticky && typeof options?.index === 'number' && !this.model.isSticky(options.index)) { // Special case: we are to open an editor sticky but at an index that is not sticky // In that case we prefer to open the editor at the index but not sticky. This enables // to drag a sticky editor to an index that is not sticky to unstick it. openEditorOptions.sticky = false; } if (!openEditorOptions.active && !openEditorOptions.pinned && this.model.activeEditor && !this.model.isPinned(this.model.activeEditor)) { // Special case: we are to open an editor inactive and not pinned, but the current active // editor is also not pinned, which means it will get replaced with this one. As such, // the editor can only be active. openEditorOptions.active = true; } let activateGroup = false; let restoreGroup = false; if (options?.activation === EditorActivation.ACTIVATE) { // Respect option to force activate an editor group. activateGroup = true; } else if (options?.activation === EditorActivation.RESTORE) { // Respect option to force restore an editor group. restoreGroup = true; } else if (options?.activation === EditorActivation.PRESERVE) { // Respect option to preserve active editor group. activateGroup = false; restoreGroup = false; } else if (openEditorOptions.active) { // Finally, we only activate/restore an editor which is // opening as active editor. // If preserveFocus is enabled, we only restore but never // activate the group. activateGroup = !options || !options.preserveFocus; restoreGroup = !activateGroup; } // Actually move the editor if a specific index is provided and we figure // out that the editor is already opened at a different index. This // ensures the right set of events are fired to the outside. if (typeof openEditorOptions.index === 'number') { const indexOfEditor = this.model.indexOf(editor); if (indexOfEditor !== -1 && indexOfEditor !== openEditorOptions.index) { this.doMoveEditorInsideGroup(editor, openEditorOptions); } } // Update model and make sure to continue to use the editor we get from // the model. It is possible that the editor was already opened and we // want to ensure that we use the existing instance in that case. const { editor: openedEditor, isNew } = this.model.openEditor(editor, openEditorOptions); // Conditionally lock the group if ( isNew && // only if this editor was new for the group this.count === 1 && // only when this editor was the first editor in the group this.accessor.groups.length > 1 // only when there are more than one groups open ) { // only when the editor identifier is configured as such if (openedEditor.editorId && this.accessor.partOptions.autoLockGroups?.has(openedEditor.editorId)) { this.lock(true); } } // Show editor const showEditorResult = this.doShowEditor(openedEditor, { active: !!openEditorOptions.active, isNew }, options, internalOptions); // Finally make sure the group is active or restored as instructed if (activateGroup) { this.accessor.activateGroup(this); } else if (restoreGroup) { this.accessor.restoreGroup(this); } return showEditorResult; } private doShowEditor(editor: EditorInput, context: { active: boolean; isNew: boolean }, options?: IEditorOptions, internalOptions?: IInternalEditorOpenOptions): Promise<IEditorPane | undefined> { // Show in editor control if the active editor changed let openEditorPromise: Promise<IEditorPane | undefined>; if (context.active) { openEditorPromise = (async () => { const { pane, changed, cancelled, error } = await this.editorPane.openEditor(editor, options, { newInGroup: context.isNew }); // Return early if the operation was cancelled by another operation if (cancelled) { return undefined; } // Editor change event if (changed) { this._onDidActiveEditorChange.fire({ editor }); } // Indicate error as an event but do not bubble them up if (error) { this._onDidOpenEditorFail.fire(editor); } // Without an editor pane, recover by closing the active editor // (if the input is still the active one) if (!pane && this.activeEditor === editor) { const focusNext = !options || !options.preserveFocus; this.doCloseEditor(editor, focusNext, { fromError: true }); } return pane; })(); } else { openEditorPromise = Promise.resolve(undefined); // inactive: return undefined as result to signal this } // Show in title control after editor control because some actions depend on it // but respect the internal options in case title control updates should skip. if (!internalOptions?.skipTitleUpdate) { this.titleAreaControl.openEditor(editor); } return openEditorPromise; } //#endregion //#region openEditors() async openEditors(editors: { editor: EditorInput; options?: IEditorOptions }[]): Promise<IEditorPane | undefined> { // Guard against invalid editors. Disposed editors // should never open because they emit no events // e.g. to indicate dirty changes. const editorsToOpen = coalesce(editors).filter(({ editor }) => !editor.isDisposed()); // Use the first editor as active editor const firstEditor = firstOrDefault(editorsToOpen); if (!firstEditor) { return; } const openEditorsOptions: IInternalEditorOpenOptions = { // Allow to match on a side-by-side editor when same // editor is opened on both sides. In that case we // do not want to open a new editor but reuse that one. supportSideBySide: SideBySideEditor.BOTH }; await this.doOpenEditor(firstEditor.editor, firstEditor.options, openEditorsOptions); // Open the other ones inactive const inactiveEditors = editorsToOpen.slice(1); const startingIndex = this.getIndexOfEditor(firstEditor.editor) + 1; await Promises.settled(inactiveEditors.map(({ editor, options }, index) => { return this.doOpenEditor(editor, { ...options, inactive: true, pinned: true, index: startingIndex + index }, { ...openEditorsOptions, // optimization: update the title control later // https://github.com/microsoft/vscode/issues/130634 skipTitleUpdate: true }); })); // Update the title control all at once with all editors this.titleAreaControl.openEditors(inactiveEditors.map(({ editor }) => editor)); // Opening many editors at once can put any editor to be // the active one depending on options. As such, we simply // return the active editor pane after this operation. return withNullAsUndefined(this.editorPane.activeEditorPane); } //#endregion //#region moveEditor() moveEditors(editors: { editor: EditorInput; options?: IEditorOptions }[], target: EditorGroupView): void { // Optimization: knowing that we move many editors, we // delay the title update to a later point for this group // through a method that allows for bulk updates but only // when moving to a different group where many editors // are more likely to occur. const internalOptions: IInternalMoveCopyOptions = { skipTitleUpdate: this !== target }; for (const { editor, options } of editors) { this.moveEditor(editor, target, options, internalOptions); } // Update the title control all at once with all editors // in source and target if the title update was skipped if (internalOptions.skipTitleUpdate) { const movedEditors = editors.map(({ editor }) => editor); target.titleAreaControl.openEditors(movedEditors); this.titleAreaControl.closeEditors(movedEditors); } } moveEditor(editor: EditorInput, target: EditorGroupView, options?: IEditorOptions, internalOptions?: IInternalEditorTitleControlOptions): void { // Move within same group if (this === target) { this.doMoveEditorInsideGroup(editor, options); } // Move across groups else { this.doMoveOrCopyEditorAcrossGroups(editor, target, options, { ...internalOptions, keepCopy: false }); } } private doMoveEditorInsideGroup(candidate: EditorInput, options?: IEditorOpenOptions): void { const moveToIndex = options ? options.index : undefined; if (typeof moveToIndex !== 'number') { return; // do nothing if we move into same group without index } const currentIndex = this.model.indexOf(candidate); if (currentIndex === -1 || currentIndex === moveToIndex) { return; // do nothing if editor unknown in model or is already at the given index } // Update model and make sure to continue to use the editor we get from // the model. It is possible that the editor was already opened and we // want to ensure that we use the existing instance in that case. const editor = this.model.getEditorByIndex(currentIndex); if (!editor) { return; } // Update model this.model.moveEditor(editor, moveToIndex); this.model.pin(editor); // Forward to title area this.titleAreaControl.moveEditor(editor, currentIndex, moveToIndex); this.titleAreaControl.pinEditor(editor); } private doMoveOrCopyEditorAcrossGroups(editor: EditorInput, target: EditorGroupView, openOptions?: IEditorOpenOptions, internalOptions?: IInternalMoveCopyOptions): void { const keepCopy = internalOptions?.keepCopy; // When moving/copying an editor, try to preserve as much view state as possible // by checking for the editor to be a text editor and creating the options accordingly // if so const options = fillActiveEditorViewState(this, editor, { ...openOptions, pinned: true, // always pin moved editor sticky: !keepCopy && this.model.isSticky(editor) // preserve sticky state only if editor is moved (https://github.com/microsoft/vscode/issues/99035) }); // Indicate will move event if (!keepCopy) { this._onWillMoveEditor.fire({ groupId: this.id, editor, target: target.id }); } // A move to another group is an open first... target.doOpenEditor(keepCopy ? editor.copy() : editor, options, internalOptions); // ...and a close afterwards (unless we copy) if (!keepCopy) { this.doCloseEditor(editor, false /* do not focus next one behind if any */, { ...internalOptions, context: EditorCloseContext.MOVE }); } } //#endregion //#region copyEditor() copyEditors(editors: { editor: EditorInput; options?: IEditorOptions }[], target: EditorGroupView): void { // Optimization: knowing that we move many editors, we // delay the title update to a later point for this group // through a method that allows for bulk updates but only // when moving to a different group where many editors // are more likely to occur. const internalOptions: IInternalMoveCopyOptions = { skipTitleUpdate: this !== target }; for (const { editor, options } of editors) { this.copyEditor(editor, target, options, internalOptions); } // Update the title control all at once with all editors // in target if the title update was skipped if (internalOptions.skipTitleUpdate) { const copiedEditors = editors.map(({ editor }) => editor); target.titleAreaControl.openEditors(copiedEditors); } } copyEditor(editor: EditorInput, target: EditorGroupView, options?: IEditorOptions, internalOptions?: IInternalEditorTitleControlOptions): void { // Move within same group because we do not support to show the same editor // multiple times in the same group if (this === target) { this.doMoveEditorInsideGroup(editor, options); } // Copy across groups else { this.doMoveOrCopyEditorAcrossGroups(editor, target, options, { ...internalOptions, keepCopy: true }); } } //#endregion //#region closeEditor() async closeEditor(editor: EditorInput | undefined = this.activeEditor || undefined, options?: ICloseEditorOptions): Promise<boolean> { return this.doCloseEditorWithConfirmationHandling(editor, options); } private async doCloseEditorWithConfirmationHandling(editor: EditorInput | undefined = this.activeEditor || undefined, options?: ICloseEditorOptions, internalOptions?: IInternalEditorCloseOptions): Promise<boolean> { if (!editor) { return false; } // Check for confirmation and veto const veto = await this.handleCloseConfirmation([editor]); if (veto) { return false; } // Do close this.doCloseEditor(editor, options?.preserveFocus ? false : undefined, internalOptions); return true; } private doCloseEditor(editor: EditorInput, focusNext = (this.accessor.activeGroup === this), internalOptions?: IInternalEditorCloseOptions): void { let index: number | undefined; // Closing the active editor of the group is a bit more work if (this.model.isActive(editor)) { index = this.doCloseActiveEditor(focusNext, internalOptions); } // Closing inactive editor is just a model update else { index = this.doCloseInactiveEditor(editor, internalOptions); } // Forward to title control unless skipped via internal options if (!internalOptions?.skipTitleUpdate) { this.titleAreaControl.closeEditor(editor, index); } } private doCloseActiveEditor(focusNext = (this.accessor.activeGroup === this), internalOptions?: IInternalEditorCloseOptions): number | undefined { const editorToClose = this.activeEditor; const restoreFocus = this.shouldRestoreFocus(this.element); // Optimization: if we are about to close the last editor in this group and settings // are configured to close the group since it will be empty, we first set the last // active group as empty before closing the editor. This reduces the amount of editor // change events that this operation emits and will reduce flicker. Without this // optimization, this group (if active) would first trigger a active editor change // event because it became empty, only to then trigger another one when the next // group gets active. const closeEmptyGroup = this.accessor.partOptions.closeEmptyGroups; if (closeEmptyGroup && this.active && this.count === 1) { const mostRecentlyActiveGroups = this.accessor.getGroups(GroupsOrder.MOST_RECENTLY_ACTIVE); const nextActiveGroup = mostRecentlyActiveGroups[1]; // [0] will be the current one, so take [1] if (nextActiveGroup) { if (restoreFocus) { nextActiveGroup.focus(); } else { this.accessor.activateGroup(nextActiveGroup); } } } // Update model let index: number | undefined = undefined; if (editorToClose) { index = this.model.closeEditor(editorToClose, internalOptions?.context)?.editorIndex; } // Open next active if there are more to show const nextActiveEditor = this.model.activeEditor; if (nextActiveEditor) { const preserveFocus = !focusNext; let activation: EditorActivation | undefined = undefined; if (preserveFocus && this.accessor.activeGroup !== this) { // If we are opening the next editor in an inactive group // without focussing it, ensure we preserve the editor // group sizes in case that group is minimized. // https://github.com/microsoft/vscode/issues/117686 activation = EditorActivation.PRESERVE; } const options: IEditorOptions = { preserveFocus, activation, // When closing an editor due to an error we can end up in a loop where we continue closing // editors that fail to open (e.g. when the file no longer exists). We do not want to show // repeated errors in this case to the user. As such, if we open the next editor and we are // in a scope of a previous editor failing, we silence the input errors until the editor is // opened by setting ignoreError: true. ignoreError: internalOptions?.fromError }; this.doOpenEditor(nextActiveEditor, options); } // Otherwise we are empty, so clear from editor control and send event else { // Forward to editor pane if (editorToClose) { this.editorPane.closeEditor(editorToClose); } // Restore focus to group container as needed unless group gets closed if (restoreFocus && !closeEmptyGroup) { this.focus(); } // Events this._onDidActiveEditorChange.fire({ editor: undefined }); // Remove empty group if we should if (closeEmptyGroup) { this.accessor.removeGroup(this); } } return index; } private shouldRestoreFocus(target: Element): boolean { const activeElement = document.activeElement; if (activeElement === document.body) { return true; // always restore focus if nothing is focused currently } // otherwise check for the active element being an ancestor of the target return isAncestor(activeElement, target); } private doCloseInactiveEditor(editor: EditorInput, internalOptions?: IInternalEditorCloseOptions): number | undefined { // Update model return this.model.closeEditor(editor, internalOptions?.context)?.editorIndex; } private async handleCloseConfirmation(editors: EditorInput[]): Promise<boolean /* veto */> { if (!editors.length) { return false; // no veto } const editor = editors.shift()!; // To prevent multiple confirmation dialogs from showing up one after the other // we check if a pending confirmation is currently showing and if so, join that let handleCloseConfirmationPromise = this.mapEditorToPendingConfirmation.get(editor); if (!handleCloseConfirmationPromise) { handleCloseConfirmationPromise = this.doHandleCloseConfirmation(editor); this.mapEditorToPendingConfirmation.set(editor, handleCloseConfirmationPromise); } let veto: boolean; try { veto = await handleCloseConfirmationPromise; } finally { this.mapEditorToPendingConfirmation.delete(editor); } // Return for the first veto we got if (veto) { return veto; } // Otherwise continue with the remainders return this.handleCloseConfirmation(editors); } private async doHandleCloseConfirmation(editor: EditorInput, options?: { skipAutoSave: boolean }): Promise<boolean /* veto */> { if (!this.shouldConfirmClose(editor)) { return false; // no veto } if (editor instanceof SideBySideEditorInput && this.model.contains(editor.primary)) { return false; // primary-side of editor is still opened somewhere else } // Note: we explicitly decide to ask for confirm if closing a normal editor even // if it is opened in a side-by-side editor in the group. This decision is made // because it may be less obvious that one side of a side by side editor is dirty // and can still be changed. // The only exception is when the same editor is opened on both sides of a side // by side editor (https://github.com/microsoft/vscode/issues/138442) if (this.accessor.groups.some(groupView => { if (groupView === this) { return false; // skip (we already handled our group above) } const otherGroup = groupView; if (otherGroup.contains(editor, { supportSideBySide: SideBySideEditor.BOTH })) { return true; // exact editor still opened (either single, or split-in-group) } if (editor instanceof SideBySideEditorInput && otherGroup.contains(editor.primary)) { return true; // primary side of side by side editor still opened } return false; })) { return false; // editor is still editable somewhere else } // In some cases trigger save before opening the dialog depending // on auto-save configuration. // However, make sure to respect `skipAutoSave` option in case the automated // save fails which would result in the editor never closing. // Also, we only do this if no custom confirmation handling is implemented. let confirmation = ConfirmResult.CANCEL; let saveReason = SaveReason.EXPLICIT; let autoSave = false; if (!editor.hasCapability(EditorInputCapabilities.Untitled) && !options?.skipAutoSave && !editor.closeHandler) { // Auto-save on focus change: save, because a dialog would steal focus // (see https://github.com/microsoft/vscode/issues/108752) if (this.filesConfigurationService.getAutoSaveMode() === AutoSaveMode.ON_FOCUS_CHANGE) { autoSave = true; confirmation = ConfirmResult.SAVE; saveReason = SaveReason.FOCUS_CHANGE; } // Auto-save on window change: save, because on Windows and Linux, a // native dialog triggers the window focus change // (see https://github.com/microsoft/vscode/issues/134250) else if ((isNative && (isWindows || isLinux)) && this.filesConfigurationService.getAutoSaveMode() === AutoSaveMode.ON_WINDOW_CHANGE) { autoSave = true; confirmation = ConfirmResult.SAVE; saveReason = SaveReason.WINDOW_CHANGE; } } // No auto-save on focus change or custom confirmation handler: ask user if (!autoSave) { // Switch to editor that we want to handle for confirmation await this.doOpenEditor(editor); // Let editor handle confirmation if implemented if (typeof editor.closeHandler?.confirm === 'function') { confirmation = await editor.closeHandler.confirm([{ editor, groupId: this.id }]); } // Show a file specific confirmation else { let name: string; if (editor instanceof SideBySideEditorInput) { name = editor.primary.getName(); // prefer shorter names by using primary's name in this case } else { name = editor.getName(); } confirmation = await this.fileDialogService.showSaveConfirm([name]); } } // It could be that the editor's choice of confirmation has changed // given the check for confirmation is long running, so we check // again to see if anything needs to happen before closing for good. // This can happen for example if `autoSave: onFocusChange` is configured // so that the save happens when the dialog opens. // However, we only do this unless a custom confirm handler is installed // that may not be fit to be asked a second time right after. if (!editor.closeHandler && !this.shouldConfirmClose(editor)) { return confirmation === ConfirmResult.CANCEL ? true : false; } // Otherwise, handle accordingly switch (confirmation) { case ConfirmResult.SAVE: { const result = await editor.save(this.id, { reason: saveReason }); if (!result && autoSave) { // Save failed and we need to signal this back to the user, so // we handle the dirty editor again but this time ensuring to // show the confirm dialog // (see https://github.com/microsoft/vscode/issues/108752) return this.doHandleCloseConfirmation(editor, { skipAutoSave: true }); } return editor.isDirty(); // veto if still dirty } case ConfirmResult.DONT_SAVE: try { // first try a normal revert where the contents of the editor are restored await editor.revert(this.id); return editor.isDirty(); // veto if still dirty } catch (error) { this.logService.error(error); // if that fails, since we are about to close the editor, we accept that // the editor cannot be reverted and instead do a soft revert that just // enables us to close the editor. With this, a user can always close a // dirty editor even when reverting fails. await editor.revert(this.id, { soft: true }); return editor.isDirty(); // veto if still dirty } case ConfirmResult.CANCEL: return true; // veto } } private shouldConfirmClose(editor: EditorInput): boolean { if (editor.closeHandler) { return editor.closeHandler.showConfirm(); // custom handling of confirmation on close } return editor.isDirty() && !editor.isSaving(); // editor must be dirty and not saving } //#endregion //#region closeEditors() async closeEditors(args: EditorInput[] | ICloseEditorsFilter, options?: ICloseEditorOptions): Promise<boolean> { if (this.isEmpty) { return true; } const editors = this.doGetEditorsToClose(args); // Check for confirmation and veto const veto = await this.handleCloseConfirmation(editors.slice(0)); if (veto) { return false; } // Do close this.doCloseEditors(editors, options); return true; } private doGetEditorsToClose(args: EditorInput[] | ICloseEditorsFilter): EditorInput[] { if (Array.isArray(args)) { return args; } const filter = args; const hasDirection = typeof filter.direction === 'number'; let editorsToClose = this.model.getEditors(hasDirection ? EditorsOrder.SEQUENTIAL : EditorsOrder.MOST_RECENTLY_ACTIVE, filter); // in MRU order only if direction is not specified // Filter: saved or saving only if (filter.savedOnly) { editorsToClose = editorsToClose.filter(editor => !editor.isDirty() || editor.isSaving()); } // Filter: direction (left / right) else if (hasDirection && filter.except) { editorsToClose = (filter.direction === CloseDirection.LEFT) ? editorsToClose.slice(0, this.model.indexOf(filter.except, editorsToClose)) : editorsToClose.slice(this.model.indexOf(filter.except, editorsToClose) + 1); } // Filter: except else if (filter.except) { editorsToClose = editorsToClose.filter(editor => filter.except && !editor.matches(filter.except)); } return editorsToClose; } private doCloseEditors(editors: EditorInput[], options?: ICloseEditorOptions): void { // Close all inactive editors first let closeActiveEditor = false; for (const editor of editors) { if (!this.isActive(editor)) { this.doCloseInactiveEditor(editor); } else { closeActiveEditor = true; } } // Close active editor last if contained in editors list to close if (closeActiveEditor) { this.doCloseActiveEditor(options?.preserveFocus ? false : undefined); } // Forward to title control if (editors.length) { this.titleAreaControl.closeEditors(editors); } } //#endregion //#region closeAllEditors() async closeAllEditors(options?: ICloseAllEditorsOptions): Promise<boolean> { if (this.isEmpty) { // If the group is empty and the request is to close all editors, we still close // the editor group is the related setting to close empty groups is enabled for // a convenient way of removing empty editor groups for the user. if (this.accessor.partOptions.closeEmptyGroups) { this.accessor.removeGroup(this); } return true; } // Check for confirmation and veto const veto = await this.handleCloseConfirmation(this.model.getEditors(EditorsOrder.MOST_RECENTLY_ACTIVE, options)); if (veto) { return false; } // Do close this.doCloseAllEditors(options); return true; } private doCloseAllEditors(options?: ICloseAllEditorsOptions): void { // Close all inactive editors first const editorsToClose: EditorInput[] = []; for (const editor of this.model.getEditors(EditorsOrder.SEQUENTIAL, options)) { if (!this.isActive(editor)) { this.doCloseInactiveEditor(editor); } editorsToClose.push(editor); } // Close active editor last (unless we skip it, e.g. because it is sticky) if (this.activeEditor && editorsToClose.includes(this.activeEditor)) { this.doCloseActiveEditor(); } // Forward to title control if (editorsToClose.length) { this.titleAreaControl.closeEditors(editorsToClose); } } //#endregion //#region replaceEditors() async replaceEditors(editors: EditorReplacement[]): Promise<void> { // Extract active vs. inactive replacements let activeReplacement: EditorReplacement | undefined; const inactiveReplacements: EditorReplacement[] = []; for (let { editor, replacement, forceReplaceDirty, options } of editors) { const index = this.getIndexOfEditor(editor); if (index >= 0) { const isActiveEditor = this.isActive(editor); // make sure we respect the index of the editor to replace if (options) { options.index = index; } else { options = { index }; } options.inactive = !isActiveEditor; options.pinned = options.pinned ?? true; // unless specified, prefer to pin upon replace const editorToReplace = { editor, replacement, forceReplaceDirty, options }; if (isActiveEditor) { activeReplacement = editorToReplace; } else { inactiveReplacements.push(editorToReplace); } } } // Handle inactive first for (const { editor, replacement, forceReplaceDirty, options } of inactiveReplacements) { // Open inactive editor await this.doOpenEditor(replacement, options); // Close replaced inactive editor unless they match if (!editor.matches(replacement)) { let closed = false; if (forceReplaceDirty) { this.doCloseEditor(editor, false, { context: EditorCloseContext.REPLACE }); closed = true; } else { closed = await this.doCloseEditorWithConfirmationHandling(editor, { preserveFocus: true }, { context: EditorCloseContext.REPLACE }); } if (!closed) { return; // canceled } } } // Handle active last if (activeReplacement) { // Open replacement as active editor const openEditorResult = this.doOpenEditor(activeReplacement.replacement, activeReplacement.options); // Close replaced active editor unless they match if (!activeReplacement.editor.matches(activeReplacement.replacement)) { if (activeReplacement.forceReplaceDirty) { this.doCloseEditor(activeReplacement.editor, false, { context: EditorCloseContext.REPLACE }); } else { await this.doCloseEditorWithConfirmationHandling(activeReplacement.editor, { preserveFocus: true }, { context: EditorCloseContext.REPLACE }); } } await openEditorResult; } } //#endregion //#region Locking get isLocked(): boolean { if (this.accessor.groups.length === 1) { // Special case: if only 1 group is opened, never report it as locked // to ensure editors can always open in the "default" editor group return false; } return this.model.isLocked; } lock(locked: boolean): void { if (this.accessor.groups.length === 1) { // Special case: if only 1 group is opened, never allow to lock // to ensure editors can always open in the "default" editor group locked = false; } this.model.lock(locked); } //#endregion //#region Themable protected override updateStyles(): void { const isEmpty = this.isEmpty; // Container if (isEmpty) { this.element.style.backgroundColor = this.getColor(EDITOR_GROUP_EMPTY_BACKGROUND) || ''; } else { this.element.style.backgroundColor = ''; } // Title control const borderColor = this.getColor(EDITOR_GROUP_HEADER_BORDER) || this.getColor(contrastBorder); if (!isEmpty && borderColor) { this.titleContainer.classList.add('title-border-bottom'); this.titleContainer.style.setProperty('--title-border-bottom-color', borderColor.toString()); } else { this.titleContainer.classList.remove('title-border-bottom'); this.titleContainer.style.removeProperty('--title-border-bottom-color'); } const { showTabs } = this.accessor.partOptions; this.titleContainer.style.backgroundColor = this.getColor(showTabs ? EDITOR_GROUP_HEADER_TABS_BACKGROUND : EDITOR_GROUP_HEADER_NO_TABS_BACKGROUND) || ''; // Editor container this.editorContainer.style.backgroundColor = this.getColor(editorBackground) || ''; } //#endregion //#region ISerializableView readonly element: HTMLElement = document.createElement('div'); get minimumWidth(): number { return this.editorPane.minimumWidth; } get minimumHeight(): number { return this.editorPane.minimumHeight; } get maximumWidth(): number { return this.editorPane.maximumWidth; } get maximumHeight(): number { return this.editorPane.maximumHeight; } private _onDidChange = this._register(new Relay<{ width: number; height: number } | undefined>()); readonly onDidChange = this._onDidChange.event; layout(width: number, height: number, top: number, left: number): void { this.lastLayout = { width, height, top, left }; // Layout the title area first to receive the size it occupies const titleAreaSize = this.titleAreaControl.layout({ container: new Dimension(width, height), available: new Dimension(width, height - this.editorPane.minimumHeight) }); // Pass the container width and remaining height to the editor layout const editorHeight = Math.max(0, height - titleAreaSize.height); this.editorContainer.style.height = `${editorHeight}px`; this.editorPane.layout({ width, height: editorHeight, top: top + titleAreaSize.height, left }); } relayout(): void { if (this.lastLayout) { const { width, height, top, left } = this.lastLayout; this.layout(width, height, top, left); } } toJSON(): ISerializedEditorGroupModel { return this.model.serialize(); } //#endregion override dispose(): void { this._disposed = true; this._onWillDispose.fire(); this.titleAreaControl.dispose(); super.dispose(); } } export interface EditorReplacement extends IEditorReplacement { readonly editor: EditorInput; readonly replacement: EditorInput; readonly options?: IEditorOptions; } registerThemingParticipant((theme, collector) => { // Letterpress const letterpress = `./media/letterpress-${theme.type}.svg`; collector.addRule(` .monaco-workbench .part.editor > .content .editor-group-container.empty .editor-group-letterpress { background-image: ${asCSSUrl(FileAccess.asBrowserUri(letterpress, require))} } `); // Focused Empty Group Border const focusedEmptyGroupBorder = theme.getColor(EDITOR_GROUP_FOCUSED_EMPTY_BORDER); if (focusedEmptyGroupBorder) { collector.addRule(` .monaco-workbench .part.editor > .content:not(.empty) .editor-group-container.empty.active:focus { outline-width: 1px; outline-color: ${focusedEmptyGroupBorder}; outline-offset: -2px; outline-style: solid; } .monaco-workbench .part.editor > .content.empty .editor-group-container.empty.active:focus { outline: none; /* never show outline for empty group if it is the last */ } `); } else { collector.addRule(` .monaco-workbench .part.editor > .content .editor-group-container.empty.active:focus { outline: none; /* disable focus outline unless active empty group border is defined */ } `); } });
src/vs/workbench/browser/parts/editor/editorGroupView.ts
1
https://github.com/microsoft/vscode/commit/9dabc131d81eb802f28765ac96cfed8794ffb533
[ 0.013577595353126526, 0.00034869718365371227, 0.00016252350178547204, 0.00016945460811257362, 0.0012608083197847009 ]
{ "id": 2, "code_window": [ "\t\t\t\tif (e.button === 1) {\n", "\t\t\t\t\te.preventDefault(); // required to prevent auto-scrolling (https://github.com/microsoft/vscode/issues/16690)\n", "\t\t\t\t}\n", "\n", "\t\t\t\treturn undefined; // only for left mouse click\n", "\t\t\t}\n", "\n", "\t\t\tif (this.originatesFromTabActionBar(e)) {\n", "\t\t\t\treturn; // not when clicking on actions\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\treturn undefined;\n" ], "file_path": "src/vs/workbench/browser/parts/editor/tabsTitleControl.ts", "type": "replace", "edit_start_line_idx": 698 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ISandboxConfiguration } from 'vs/base/parts/sandbox/common/sandboxTypes'; // Since data sent through the service is serialized to JSON, functions will be lost, so Color objects // should not be sent as their 'toString' method will be stripped. Instead convert to strings before sending. export interface WindowStyles { backgroundColor?: string; color?: string; } export interface WindowData { styles: WindowStyles; zoomLevel: number; } export const enum IssueType { Bug, PerformanceIssue, FeatureRequest } export interface IssueReporterStyles extends WindowStyles { textLinkColor?: string; textLinkActiveForeground?: string; inputBackground?: string; inputForeground?: string; inputBorder?: string; inputErrorBorder?: string; inputErrorBackground?: string; inputErrorForeground?: string; inputActiveBorder?: string; buttonBackground?: string; buttonForeground?: string; buttonHoverBackground?: string; sliderBackgroundColor?: string; sliderHoverColor?: string; sliderActiveColor?: string; } export interface IssueReporterExtensionData { name: string; publisher: string | undefined; version: string; id: string; isTheme: boolean; isBuiltin: boolean; displayName: string | undefined; repositoryUrl: string | undefined; bugsUrl: string | undefined; } export interface IssueReporterData extends WindowData { styles: IssueReporterStyles; enabledExtensions: IssueReporterExtensionData[]; issueType?: IssueType; extensionId?: string; experiments?: string; restrictedMode: boolean; isUnsupported: boolean; isSandboxed: boolean; // TODO@bpasero remove me once sandbox is final githubAccessToken: string; readonly issueTitle?: string; readonly issueBody?: string; } export interface ISettingSearchResult { extensionId: string; key: string; score: number; } export interface ProcessExplorerStyles extends WindowStyles { listHoverBackground?: string; listHoverForeground?: string; listFocusBackground?: string; listFocusForeground?: string; listFocusOutline?: string; listActiveSelectionBackground?: string; listActiveSelectionForeground?: string; listHoverOutline?: string; scrollbarShadowColor?: string; scrollbarSliderBackgroundColor?: string; scrollbarSliderHoverBackgroundColor?: string; scrollbarSliderActiveBackgroundColor?: string; } export interface ProcessExplorerData extends WindowData { pid: number; styles: ProcessExplorerStyles; platform: string; applicationName: string; } export interface ICommonIssueService { readonly _serviceBrand: undefined; openReporter(data: IssueReporterData): Promise<void>; openProcessExplorer(data: ProcessExplorerData): Promise<void>; getSystemStatus(): Promise<string>; } export interface IssueReporterWindowConfiguration extends ISandboxConfiguration { disableExtensions: boolean; data: IssueReporterData; os: { type: string; arch: string; release: string; }; } export interface ProcessExplorerWindowConfiguration extends ISandboxConfiguration { data: ProcessExplorerData; }
src/vs/platform/issue/common/issue.ts
0
https://github.com/microsoft/vscode/commit/9dabc131d81eb802f28765ac96cfed8794ffb533
[ 0.00019170730956830084, 0.000170882252859883, 0.00016544376558158547, 0.00016946077812463045, 0.000006634831152041443 ]
{ "id": 2, "code_window": [ "\t\t\t\tif (e.button === 1) {\n", "\t\t\t\t\te.preventDefault(); // required to prevent auto-scrolling (https://github.com/microsoft/vscode/issues/16690)\n", "\t\t\t\t}\n", "\n", "\t\t\t\treturn undefined; // only for left mouse click\n", "\t\t\t}\n", "\n", "\t\t\tif (this.originatesFromTabActionBar(e)) {\n", "\t\t\t\treturn; // not when clicking on actions\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\treturn undefined;\n" ], "file_path": "src/vs/workbench/browser/parts/editor/tabsTitleControl.ts", "type": "replace", "edit_start_line_idx": 698 }
This is some UTF 8 with BOM file.
src/vs/platform/files/test/node/fixtures/service/some_utf8_bom.txt
0
https://github.com/microsoft/vscode/commit/9dabc131d81eb802f28765ac96cfed8794ffb533
[ 0.00016427188529632986, 0.00016427188529632986, 0.00016427188529632986, 0.00016427188529632986, 0 ]
{ "id": 2, "code_window": [ "\t\t\t\tif (e.button === 1) {\n", "\t\t\t\t\te.preventDefault(); // required to prevent auto-scrolling (https://github.com/microsoft/vscode/issues/16690)\n", "\t\t\t\t}\n", "\n", "\t\t\t\treturn undefined; // only for left mouse click\n", "\t\t\t}\n", "\n", "\t\t\tif (this.originatesFromTabActionBar(e)) {\n", "\t\t\t\treturn; // not when clicking on actions\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\treturn undefined;\n" ], "file_path": "src/vs/workbench/browser/parts/editor/tabsTitleControl.ts", "type": "replace", "edit_start_line_idx": 698 }
'use strict'; var Workforce; (function (Workforce) { var Employee = (function () { function Employee() { } return Employee; })(); (property); name: string, property; basepay: number; implements; IEmployee; { name; basepay; } var SalesEmployee = (function () { function SalesEmployee() { } return SalesEmployee; })(); (); Employee(name, basepay); { function calculatePay() { var multiplier = (document.getElementById("mult")), as = any, value; return _super.calculatePay.call(this) * multiplier + bonus; } } var employee = new Employee('Bob', 1000); var salesEmployee = new SalesEmployee('Jim', 800, 400); salesEmployee.calclatePay(); // error: No member 'calclatePay' on SalesEmployee })(Workforce || (Workforce = {})); extern; var $; var s = Workforce.salesEmployee.calculatePay(); $('#results').text(s);
src/vs/platform/files/test/node/fixtures/resolver/other/deep/employee.js
0
https://github.com/microsoft/vscode/commit/9dabc131d81eb802f28765ac96cfed8794ffb533
[ 0.00017288135131821036, 0.00017008961003739387, 0.00016639585373923182, 0.00017054061754606664, 0.0000025381780233146856 ]
{ "id": 0, "code_window": [ "import { resolvePagesRoutes, normalizeRoutes, resolveMiddleware, getImportName } from './utils'\n", "import { TransformMacroPlugin, TransformMacroPluginOptions } from './macros'\n", "\n", "export default defineNuxtModule({\n", " meta: {\n", " name: 'router'\n", " },\n", " setup (_options, nuxt) {\n", " const pagesDirs = nuxt.options._layers.map(\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " name: 'pages'\n" ], "file_path": "packages/nuxt3/src/pages/module.ts", "type": "replace", "edit_start_line_idx": 11 }
export default { /** * Configure Nuxt component auto-registration. * * Any components in the directories configured here can be used throughout your * pages, layouts (and other components) without needing to explicitly import them. * * @default {{ dirs: [`~/components`] }} * @see [Nuxt 3](https://v3.nuxtjs.org/guide/directory-structure/components) and * [Nuxt 2](https://nuxtjs.org/docs/directory-structure/components/) documentation * @type {boolean | typeof import('../src/types/components').ComponentsOptions | typeof import('../src/types/components').ComponentsOptions['dirs']} * @version 2 * @version 3 */ components: { $resolve: (val, get) => { if (Array.isArray(val)) { return { dirs: val } } if (val === undefined || val === true) { return { dirs: ['~/components'] } } return val } }, /** * Configure how Nuxt auto-imports composables into your application. * * @see [Nuxt 3 documentation](https://v3.nuxtjs.org/guide/directory-structure/composables) * @type {typeof import('../src/types/imports').AutoImportsOptions} * @version 3 */ autoImports: { global: false, dirs: [] }, }
packages/schema/src/config/_adhoc.ts
1
https://github.com/nuxt/nuxt/commit/f4fb9160c612bf9400861be6d4f76d762ca41f73
[ 0.0003217357734683901, 0.00022498889302369207, 0.00016970967408269644, 0.00020425506227184087, 0.000058335481298854575 ]
{ "id": 0, "code_window": [ "import { resolvePagesRoutes, normalizeRoutes, resolveMiddleware, getImportName } from './utils'\n", "import { TransformMacroPlugin, TransformMacroPluginOptions } from './macros'\n", "\n", "export default defineNuxtModule({\n", " meta: {\n", " name: 'router'\n", " },\n", " setup (_options, nuxt) {\n", " const pagesDirs = nuxt.options._layers.map(\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " name: 'pages'\n" ], "file_path": "packages/nuxt3/src/pages/module.ts", "type": "replace", "edit_start_line_idx": 11 }
import { basename, extname, join, dirname, relative } from 'pathe' import { globby } from 'globby' import { pascalCase, splitByCase } from 'scule' import type { Component, ComponentsDir } from '@nuxt/schema' import { isIgnored } from '@nuxt/kit' import { hyphenate } from '@vue/shared' /** * Scan the components inside different components folders * and return a unique list of components * * @param dirs all folders where components are defined * @param srcDir src path of your app * @returns {Promise} Component found promise */ export async function scanComponents (dirs: ComponentsDir[], srcDir: string): Promise<Component[]> { // All scanned components const components: Component[] = [] // Keep resolved path to avoid duplicates const filePaths = new Set<string>() // All scanned paths const scannedPaths: string[] = [] for (const dir of dirs) { // A map from resolved path to component name (used for making duplicate warning message) const resolvedNames = new Map<string, string>() for (const _file of await globby(dir.pattern!, { cwd: dir.path, ignore: dir.ignore })) { const filePath = join(dir.path, _file) if (scannedPaths.find(d => filePath.startsWith(d)) || isIgnored(filePath)) { continue } // Avoid duplicate paths if (filePaths.has(filePath)) { continue } filePaths.add(filePath) /** * Create an array of prefixes base on the prefix config * Empty prefix will be an empty array * * @example prefix: 'nuxt' -> ['nuxt'] * @example prefix: 'nuxt-test' -> ['nuxt', 'test'] */ const prefixParts = ([] as string[]).concat( dir.prefix ? splitByCase(dir.prefix) : [], (dir.pathPrefix !== false) ? splitByCase(relative(dir.path, dirname(filePath))) : [] ) /** * In case we have index as filename the component become the parent path * * @example third-components/index.vue -> third-component * if not take the filename * @example thid-components/Awesome.vue -> Awesome */ let fileName = basename(filePath, extname(filePath)) if (fileName.toLowerCase() === 'index') { fileName = dir.pathPrefix === false ? basename(dirname(filePath)) : '' /* inherits from path */ } /** * Array of fileName parts splitted by case, / or - * * @example third-component -> ['third', 'component'] * @example AwesomeComponent -> ['Awesome', 'Component'] */ const fileNameParts = splitByCase(fileName) const componentNameParts: string[] = [] while (prefixParts.length && (prefixParts[0] || '').toLowerCase() !== (fileNameParts[0] || '').toLowerCase() ) { componentNameParts.push(prefixParts.shift()!) } const componentName = pascalCase(componentNameParts) + pascalCase(fileNameParts) if (resolvedNames.has(componentName)) { console.warn(`Two component files resolving to the same name \`${componentName}\`:\n` + `\n - ${filePath}` + `\n - ${resolvedNames.get(componentName)}` ) continue } resolvedNames.set(componentName, filePath) const pascalName = pascalCase(componentName).replace(/["']/g, '') const kebabName = hyphenate(componentName) const shortPath = relative(srcDir, filePath) const chunkName = 'components/' + kebabName let component: Component = { filePath, pascalName, kebabName, chunkName, shortPath, export: 'default', global: dir.global, prefetch: Boolean(dir.prefetch), preload: Boolean(dir.preload) } if (typeof dir.extendComponent === 'function') { component = (await dir.extendComponent(component)) || component } // Ignore component if component is already defined if (!components.find(c => c.pascalName === component.pascalName)) { components.push(component) } } scannedPaths.push(dir.path) } return components }
packages/nuxt3/src/components/scan.ts
0
https://github.com/nuxt/nuxt/commit/f4fb9160c612bf9400861be6d4f76d762ca41f73
[ 0.000682093552313745, 0.00023557340318802744, 0.0001673376391408965, 0.00017273059347644448, 0.00015439845446962863 ]
{ "id": 0, "code_window": [ "import { resolvePagesRoutes, normalizeRoutes, resolveMiddleware, getImportName } from './utils'\n", "import { TransformMacroPlugin, TransformMacroPluginOptions } from './macros'\n", "\n", "export default defineNuxtModule({\n", " meta: {\n", " name: 'router'\n", " },\n", " setup (_options, nuxt) {\n", " const pagesDirs = nuxt.options._layers.map(\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " name: 'pages'\n" ], "file_path": "packages/nuxt3/src/pages/module.ts", "type": "replace", "edit_start_line_idx": 11 }
{ "name": "example-wasm", "private": true, "devDependencies": { "@nuxt/ui": "npm:@nuxt/ui-edge@latest", "nuxt3": "latest" }, "scripts": { "dev": "nuxi dev", "build": "nuxi build", "start": "nuxi preview" } }
examples/experimental/wasm/package.json
0
https://github.com/nuxt/nuxt/commit/f4fb9160c612bf9400861be6d4f76d762ca41f73
[ 0.00017016386846080422, 0.00016903477080632, 0.0001679056731518358, 0.00016903477080632, 0.0000011290976544842124 ]
{ "id": 0, "code_window": [ "import { resolvePagesRoutes, normalizeRoutes, resolveMiddleware, getImportName } from './utils'\n", "import { TransformMacroPlugin, TransformMacroPluginOptions } from './macros'\n", "\n", "export default defineNuxtModule({\n", " meta: {\n", " name: 'router'\n", " },\n", " setup (_options, nuxt) {\n", " const pagesDirs = nuxt.options._layers.map(\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " name: 'pages'\n" ], "file_path": "packages/nuxt3/src/pages/module.ts", "type": "replace", "edit_start_line_idx": 11 }
{ "extends": "./.nuxt/tsconfig.json" }
examples/advanced/module-extend-pages/tsconfig.json
0
https://github.com/nuxt/nuxt/commit/f4fb9160c612bf9400861be6d4f76d762ca41f73
[ 0.000172167900018394, 0.000172167900018394, 0.000172167900018394, 0.000172167900018394, 0 ]
{ "id": 1, "code_window": [ " setup (_options, nuxt) {\n", " const pagesDirs = nuxt.options._layers.map(\n", " layer => resolve(layer.config.srcDir, layer.config.dir?.pages || 'pages')\n", " )\n", "\n", " // Disable module (and use universal router) if pages dir do not exists\n", " if (!pagesDirs.some(dir => existsSync(dir))) {\n", " addPlugin(resolve(distDir, 'app/plugins/router'))\n", " return\n", " }\n", "\n", " const runtimeDir = resolve(distDir, 'pages/runtime')\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // Disable module (and use universal router) if pages dir do not exists or user has disabled it\n", " if (nuxt.options.pages === false || (nuxt.options.pages !== true && !pagesDirs.some(dir => existsSync(dir)))) {\n" ], "file_path": "packages/nuxt3/src/pages/module.ts", "type": "replace", "edit_start_line_idx": 18 }
import { existsSync } from 'fs' import { defineNuxtModule, addTemplate, addPlugin, addVitePlugin, addWebpackPlugin, findPath } from '@nuxt/kit' import { resolve } from 'pathe' import { genDynamicImport, genString, genArrayFromRaw, genImport, genObjectFromRawEntries } from 'knitwork' import escapeRE from 'escape-string-regexp' import { distDir } from '../dirs' import { resolvePagesRoutes, normalizeRoutes, resolveMiddleware, getImportName } from './utils' import { TransformMacroPlugin, TransformMacroPluginOptions } from './macros' export default defineNuxtModule({ meta: { name: 'router' }, setup (_options, nuxt) { const pagesDirs = nuxt.options._layers.map( layer => resolve(layer.config.srcDir, layer.config.dir?.pages || 'pages') ) // Disable module (and use universal router) if pages dir do not exists if (!pagesDirs.some(dir => existsSync(dir))) { addPlugin(resolve(distDir, 'app/plugins/router')) return } const runtimeDir = resolve(distDir, 'pages/runtime') // Add $router types nuxt.hook('prepare:types', ({ references }) => { references.push({ types: 'vue-router' }) }) // Regenerate templates when adding or removing pages nuxt.hook('builder:watch', async (event, path) => { const dirs = [ nuxt.options.dir.pages, nuxt.options.dir.layouts, nuxt.options.dir.middleware ].filter(Boolean) const pathPattern = new RegExp(`^(${dirs.map(escapeRE).join('|')})/`) if (event !== 'change' && path.match(pathPattern)) { await nuxt.callHook('builder:generateApp') } }) nuxt.hook('app:resolve', (app) => { // Add default layout for pages if (app.mainComponent.includes('@nuxt/ui-templates')) { app.mainComponent = resolve(runtimeDir, 'app.vue') } }) nuxt.hook('autoImports:extend', (autoImports) => { autoImports.push({ name: 'definePageMeta', as: 'definePageMeta', from: resolve(runtimeDir, 'composables') }) }) // Extract macros from pages const macroOptions: TransformMacroPluginOptions = { dev: nuxt.options.dev, macros: { definePageMeta: 'meta' } } addVitePlugin(TransformMacroPlugin.vite(macroOptions)) addWebpackPlugin(TransformMacroPlugin.webpack(macroOptions)) // Add router plugin addPlugin(resolve(runtimeDir, 'router')) // Add routes template addTemplate({ filename: 'routes.mjs', async getContents () { const pages = await resolvePagesRoutes() await nuxt.callHook('pages:extend', pages) const { routes, imports } = normalizeRoutes(pages) return [...imports, `export default ${routes}`].join('\n') } }) // Add router options template addTemplate({ filename: 'router.options.mjs', getContents: async () => { // Check for router options const routerOptionsFiles = (await Promise.all(nuxt.options._layers.map( async layer => await findPath(resolve(layer.config.srcDir, 'app/router.options')) ))).filter(Boolean) const configRouterOptions = genObjectFromRawEntries(Object.entries(nuxt.options.router.options) .map(([key, value]) => [key, genString(value as string)])) return [ ...routerOptionsFiles.map((file, index) => genImport(file, `routerOptions${index}`)), `const configRouterOptions = ${configRouterOptions}`, 'export default {', '...configRouterOptions,', // We need to reverse spreading order to respect layers priority ...routerOptionsFiles.map((_, index) => `...routerOptions${index},`).reverse(), '}' ].join('\n') } }) // Add middleware template addTemplate({ filename: 'middleware.mjs', async getContents () { const middleware = await resolveMiddleware() await nuxt.callHook('pages:middleware:extend', middleware) const globalMiddleware = middleware.filter(mw => mw.global) const namedMiddleware = middleware.filter(mw => !mw.global) const namedMiddlewareObject = genObjectFromRawEntries(namedMiddleware.map(mw => [mw.name, genDynamicImport(mw.path)])) return [ ...globalMiddleware.map(mw => genImport(mw.path, getImportName(mw.name))), `export const globalMiddleware = ${genArrayFromRaw(globalMiddleware.map(mw => getImportName(mw.name)))}`, `export const namedMiddleware = ${namedMiddlewareObject}` ].join('\n') } }) addTemplate({ filename: 'types/middleware.d.ts', getContents: async () => { const composablesFile = resolve(runtimeDir, 'composables') const middleware = await resolveMiddleware() const namedMiddleware = middleware.filter(mw => !mw.global) return [ 'import type { NavigationGuard } from \'vue-router\'', `export type MiddlewareKey = ${namedMiddleware.map(mw => genString(mw.name)).join(' | ') || 'string'}`, `declare module ${genString(composablesFile)} {`, ' interface PageMeta {', ' middleware?: MiddlewareKey | NavigationGuard | Array<MiddlewareKey | NavigationGuard>', ' }', '}' ].join('\n') } }) addTemplate({ filename: 'types/layouts.d.ts', getContents: ({ app }) => { const composablesFile = resolve(runtimeDir, 'composables') return [ 'import { ComputedRef, Ref } from \'vue\'', `export type LayoutKey = ${Object.keys(app.layouts).map(name => genString(name)).join(' | ') || 'string'}`, `declare module ${genString(composablesFile)} {`, ' interface PageMeta {', ' layout?: false | LayoutKey | Ref<LayoutKey> | ComputedRef<LayoutKey>', ' }', '}' ].join('\n') } }) // Add declarations for middleware keys nuxt.hook('prepare:types', ({ references }) => { references.push({ path: resolve(nuxt.options.buildDir, 'types/middleware.d.ts') }) references.push({ path: resolve(nuxt.options.buildDir, 'types/layouts.d.ts') }) }) } })
packages/nuxt3/src/pages/module.ts
1
https://github.com/nuxt/nuxt/commit/f4fb9160c612bf9400861be6d4f76d762ca41f73
[ 0.9983134269714355, 0.35459282994270325, 0.0001646429009269923, 0.008797526359558105, 0.47136661410331726 ]
{ "id": 1, "code_window": [ " setup (_options, nuxt) {\n", " const pagesDirs = nuxt.options._layers.map(\n", " layer => resolve(layer.config.srcDir, layer.config.dir?.pages || 'pages')\n", " )\n", "\n", " // Disable module (and use universal router) if pages dir do not exists\n", " if (!pagesDirs.some(dir => existsSync(dir))) {\n", " addPlugin(resolve(distDir, 'app/plugins/router'))\n", " return\n", " }\n", "\n", " const runtimeDir = resolve(distDir, 'pages/runtime')\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // Disable module (and use universal router) if pages dir do not exists or user has disabled it\n", " if (nuxt.options.pages === false || (nuxt.options.pages !== true && !pagesDirs.some(dir => existsSync(dir)))) {\n" ], "file_path": "packages/nuxt3/src/pages/module.ts", "type": "replace", "edit_start_line_idx": 18 }
export * from './composables'
packages/nuxt3/src/pages/runtime/index.ts
0
https://github.com/nuxt/nuxt/commit/f4fb9160c612bf9400861be6d4f76d762ca41f73
[ 0.0001727292692521587, 0.0001727292692521587, 0.0001727292692521587, 0.0001727292692521587, 0 ]
{ "id": 1, "code_window": [ " setup (_options, nuxt) {\n", " const pagesDirs = nuxt.options._layers.map(\n", " layer => resolve(layer.config.srcDir, layer.config.dir?.pages || 'pages')\n", " )\n", "\n", " // Disable module (and use universal router) if pages dir do not exists\n", " if (!pagesDirs.some(dir => existsSync(dir))) {\n", " addPlugin(resolve(distDir, 'app/plugins/router'))\n", " return\n", " }\n", "\n", " const runtimeDir = resolve(distDir, 'pages/runtime')\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // Disable module (and use universal router) if pages dir do not exists or user has disabled it\n", " if (nuxt.options.pages === false || (nuxt.options.pages !== true && !pagesDirs.some(dir => existsSync(dir)))) {\n" ], "file_path": "packages/nuxt3/src/pages/module.ts", "type": "replace", "edit_start_line_idx": 18 }
import type { TestHooks } from '../types' export default function setupJest (hooks: TestHooks) { // TODO: add globals existing check to provide better error message // @ts-expect-error jest types test('setup', hooks.setup, 120 * 1000) // @ts-expect-error jest types beforeEach(hooks.beforeEach) // @ts-expect-error jest types afterEach(hooks.afterEach) // @ts-expect-error jest types afterAll(hooks.afterAll) }
packages/test-utils/src/setup/jest.ts
0
https://github.com/nuxt/nuxt/commit/f4fb9160c612bf9400861be6d4f76d762ca41f73
[ 0.00017455882334616035, 0.00017403633682988584, 0.00017351385031361133, 0.00017403633682988584, 5.224865162745118e-7 ]
{ "id": 1, "code_window": [ " setup (_options, nuxt) {\n", " const pagesDirs = nuxt.options._layers.map(\n", " layer => resolve(layer.config.srcDir, layer.config.dir?.pages || 'pages')\n", " )\n", "\n", " // Disable module (and use universal router) if pages dir do not exists\n", " if (!pagesDirs.some(dir => existsSync(dir))) {\n", " addPlugin(resolve(distDir, 'app/plugins/router'))\n", " return\n", " }\n", "\n", " const runtimeDir = resolve(distDir, 'pages/runtime')\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // Disable module (and use universal router) if pages dir do not exists or user has disabled it\n", " if (nuxt.options.pages === false || (nuxt.options.pages !== true && !pagesDirs.some(dir => existsSync(dir)))) {\n" ], "file_path": "packages/nuxt3/src/pages/module.ts", "type": "replace", "edit_start_line_idx": 18 }
--- title: Examples layout.aside: true layout.fluid: true navigation: exclusive: true collapse: true redirect: /examples/essentials/hello-world ---
docs/content/4.examples/index.md
0
https://github.com/nuxt/nuxt/commit/f4fb9160c612bf9400861be6d4f76d762ca41f73
[ 0.0001762244792189449, 0.0001762244792189449, 0.0001762244792189449, 0.0001762244792189449, 0 ]
{ "id": 2, "code_window": [ " global: false,\n", " dirs: []\n", " },\n", "}" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " /**\n", " * Whether to use the vue-router integration in Nuxt 3. If you do not provide a value it will be\n", " * enabled if you have a `pages/` directory in your source folder.\n", " *\n", " * @type {boolean}\n", " * @version 3\n", " */\n", " pages: undefined\n" ], "file_path": "packages/schema/src/config/_adhoc.ts", "type": "add", "edit_start_line_idx": 37 }
import { existsSync } from 'fs' import { defineNuxtModule, addTemplate, addPlugin, addVitePlugin, addWebpackPlugin, findPath } from '@nuxt/kit' import { resolve } from 'pathe' import { genDynamicImport, genString, genArrayFromRaw, genImport, genObjectFromRawEntries } from 'knitwork' import escapeRE from 'escape-string-regexp' import { distDir } from '../dirs' import { resolvePagesRoutes, normalizeRoutes, resolveMiddleware, getImportName } from './utils' import { TransformMacroPlugin, TransformMacroPluginOptions } from './macros' export default defineNuxtModule({ meta: { name: 'router' }, setup (_options, nuxt) { const pagesDirs = nuxt.options._layers.map( layer => resolve(layer.config.srcDir, layer.config.dir?.pages || 'pages') ) // Disable module (and use universal router) if pages dir do not exists if (!pagesDirs.some(dir => existsSync(dir))) { addPlugin(resolve(distDir, 'app/plugins/router')) return } const runtimeDir = resolve(distDir, 'pages/runtime') // Add $router types nuxt.hook('prepare:types', ({ references }) => { references.push({ types: 'vue-router' }) }) // Regenerate templates when adding or removing pages nuxt.hook('builder:watch', async (event, path) => { const dirs = [ nuxt.options.dir.pages, nuxt.options.dir.layouts, nuxt.options.dir.middleware ].filter(Boolean) const pathPattern = new RegExp(`^(${dirs.map(escapeRE).join('|')})/`) if (event !== 'change' && path.match(pathPattern)) { await nuxt.callHook('builder:generateApp') } }) nuxt.hook('app:resolve', (app) => { // Add default layout for pages if (app.mainComponent.includes('@nuxt/ui-templates')) { app.mainComponent = resolve(runtimeDir, 'app.vue') } }) nuxt.hook('autoImports:extend', (autoImports) => { autoImports.push({ name: 'definePageMeta', as: 'definePageMeta', from: resolve(runtimeDir, 'composables') }) }) // Extract macros from pages const macroOptions: TransformMacroPluginOptions = { dev: nuxt.options.dev, macros: { definePageMeta: 'meta' } } addVitePlugin(TransformMacroPlugin.vite(macroOptions)) addWebpackPlugin(TransformMacroPlugin.webpack(macroOptions)) // Add router plugin addPlugin(resolve(runtimeDir, 'router')) // Add routes template addTemplate({ filename: 'routes.mjs', async getContents () { const pages = await resolvePagesRoutes() await nuxt.callHook('pages:extend', pages) const { routes, imports } = normalizeRoutes(pages) return [...imports, `export default ${routes}`].join('\n') } }) // Add router options template addTemplate({ filename: 'router.options.mjs', getContents: async () => { // Check for router options const routerOptionsFiles = (await Promise.all(nuxt.options._layers.map( async layer => await findPath(resolve(layer.config.srcDir, 'app/router.options')) ))).filter(Boolean) const configRouterOptions = genObjectFromRawEntries(Object.entries(nuxt.options.router.options) .map(([key, value]) => [key, genString(value as string)])) return [ ...routerOptionsFiles.map((file, index) => genImport(file, `routerOptions${index}`)), `const configRouterOptions = ${configRouterOptions}`, 'export default {', '...configRouterOptions,', // We need to reverse spreading order to respect layers priority ...routerOptionsFiles.map((_, index) => `...routerOptions${index},`).reverse(), '}' ].join('\n') } }) // Add middleware template addTemplate({ filename: 'middleware.mjs', async getContents () { const middleware = await resolveMiddleware() await nuxt.callHook('pages:middleware:extend', middleware) const globalMiddleware = middleware.filter(mw => mw.global) const namedMiddleware = middleware.filter(mw => !mw.global) const namedMiddlewareObject = genObjectFromRawEntries(namedMiddleware.map(mw => [mw.name, genDynamicImport(mw.path)])) return [ ...globalMiddleware.map(mw => genImport(mw.path, getImportName(mw.name))), `export const globalMiddleware = ${genArrayFromRaw(globalMiddleware.map(mw => getImportName(mw.name)))}`, `export const namedMiddleware = ${namedMiddlewareObject}` ].join('\n') } }) addTemplate({ filename: 'types/middleware.d.ts', getContents: async () => { const composablesFile = resolve(runtimeDir, 'composables') const middleware = await resolveMiddleware() const namedMiddleware = middleware.filter(mw => !mw.global) return [ 'import type { NavigationGuard } from \'vue-router\'', `export type MiddlewareKey = ${namedMiddleware.map(mw => genString(mw.name)).join(' | ') || 'string'}`, `declare module ${genString(composablesFile)} {`, ' interface PageMeta {', ' middleware?: MiddlewareKey | NavigationGuard | Array<MiddlewareKey | NavigationGuard>', ' }', '}' ].join('\n') } }) addTemplate({ filename: 'types/layouts.d.ts', getContents: ({ app }) => { const composablesFile = resolve(runtimeDir, 'composables') return [ 'import { ComputedRef, Ref } from \'vue\'', `export type LayoutKey = ${Object.keys(app.layouts).map(name => genString(name)).join(' | ') || 'string'}`, `declare module ${genString(composablesFile)} {`, ' interface PageMeta {', ' layout?: false | LayoutKey | Ref<LayoutKey> | ComputedRef<LayoutKey>', ' }', '}' ].join('\n') } }) // Add declarations for middleware keys nuxt.hook('prepare:types', ({ references }) => { references.push({ path: resolve(nuxt.options.buildDir, 'types/middleware.d.ts') }) references.push({ path: resolve(nuxt.options.buildDir, 'types/layouts.d.ts') }) }) } })
packages/nuxt3/src/pages/module.ts
1
https://github.com/nuxt/nuxt/commit/f4fb9160c612bf9400861be6d4f76d762ca41f73
[ 0.014538515359163284, 0.0010430695256218314, 0.0001664207666181028, 0.00016849297389853746, 0.003375018248334527 ]
{ "id": 2, "code_window": [ " global: false,\n", " dirs: []\n", " },\n", "}" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " /**\n", " * Whether to use the vue-router integration in Nuxt 3. If you do not provide a value it will be\n", " * enabled if you have a `pages/` directory in your source folder.\n", " *\n", " * @type {boolean}\n", " * @version 3\n", " */\n", " pages: undefined\n" ], "file_path": "packages/schema/src/config/_adhoc.ts", "type": "add", "edit_start_line_idx": 37 }
import { KeepAlive, h } from 'vue' import { RouterView, RouteLocationMatched, RouteLocationNormalizedLoaded } from 'vue-router' type InstanceOf<T> = T extends new (...args: any[]) => infer R ? R : never export type RouterViewSlotProps = Parameters<InstanceOf<typeof RouterView>['$slots']['default']>[0] const interpolatePath = (route: RouteLocationNormalizedLoaded, match: RouteLocationMatched) => { return match.path .replace(/(:\w+)\([^)]+\)/g, '$1') .replace(/(:\w+)[?+*]/g, '$1') .replace(/:\w+/g, r => route.params[r.slice(1)]?.toString() || '') } export const generateRouteKey = (override: string | ((route: RouteLocationNormalizedLoaded) => string), routeProps: RouterViewSlotProps) => { const matchedRoute = routeProps.route.matched.find(m => m.components.default === routeProps.Component.type) const source = override ?? matchedRoute?.meta.key ?? interpolatePath(routeProps.route, matchedRoute) return typeof source === 'function' ? source(routeProps.route) : source } export const wrapInKeepAlive = (props: any, children: any) => { return { default: () => process.client && props ? h(KeepAlive, props === true ? {} : props, children) : children } }
packages/nuxt3/src/pages/runtime/utils.ts
0
https://github.com/nuxt/nuxt/commit/f4fb9160c612bf9400861be6d4f76d762ca41f73
[ 0.00016906783275771886, 0.00016755245451349765, 0.0001657734828768298, 0.00016781603335402906, 0.0000013577659956354182 ]
{ "id": 2, "code_window": [ " global: false,\n", " dirs: []\n", " },\n", "}" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " /**\n", " * Whether to use the vue-router integration in Nuxt 3. If you do not provide a value it will be\n", " * enabled if you have a `pages/` directory in your source folder.\n", " *\n", " * @type {boolean}\n", " * @version 3\n", " */\n", " pages: undefined\n" ], "file_path": "packages/schema/src/config/_adhoc.ts", "type": "add", "edit_start_line_idx": 37 }
import { defineNuxtConfig } from 'nuxt3' export default defineNuxtConfig({ components: [ { path: './components', prefix: 'UI' } ] })
examples/advanced/config-extends/ui/nuxt.config.ts
0
https://github.com/nuxt/nuxt/commit/f4fb9160c612bf9400861be6d4f76d762ca41f73
[ 0.00018531283421907574, 0.00018531283421907574, 0.00018531283421907574, 0.00018531283421907574, 0 ]
{ "id": 2, "code_window": [ " global: false,\n", " dirs: []\n", " },\n", "}" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " /**\n", " * Whether to use the vue-router integration in Nuxt 3. If you do not provide a value it will be\n", " * enabled if you have a `pages/` directory in your source folder.\n", " *\n", " * @type {boolean}\n", " * @version 3\n", " */\n", " pages: undefined\n" ], "file_path": "packages/schema/src/config/_adhoc.ts", "type": "add", "edit_start_line_idx": 37 }
import { createRenderer } from 'vue-bundle-renderer' import { eventHandler, useQuery } from 'h3' import devalue from '@nuxt/devalue' import { useRuntimeConfig } from '#nitro' import { buildAssetsURL } from '#paths' // @ts-ignore import htmlTemplate from '#build/views/document.template.mjs' const STATIC_ASSETS_BASE = process.env.NUXT_STATIC_BASE + '/' + process.env.NUXT_STATIC_VERSION const NUXT_NO_SSR = process.env.NUXT_NO_SSR const PAYLOAD_JS = '/payload.js' const getClientManifest = cachedImport(() => import('#build/dist/server/client.manifest.mjs')) const getSSRApp = !process.env.NUXT_NO_SSR && cachedImport(() => import('#build/dist/server/server.mjs')) const getSSRRenderer = cachedResult(async () => { // Load client manifest const clientManifest = await getClientManifest() if (!clientManifest) { throw new Error('client.manifest is not available') } // Load server bundle const createSSRApp = await getSSRApp() if (!createSSRApp) { throw new Error('Server bundle is not available') } // Create renderer const { renderToString } = await import('#vue-renderer') // Alias to vue2.ts or vue3.ts return createRenderer((createSSRApp), { clientManifest, renderToString, publicPath: buildAssetsURL() }).renderToString }) const getSPARenderer = cachedResult(async () => { const clientManifest = await getClientManifest() return (ssrContext) => { const config = useRuntimeConfig() ssrContext.nuxt = { serverRendered: false, config: { public: config.public, app: config.app } } let entryFiles = Object.values(clientManifest).filter( (fileValue: any) => fileValue.isEntry ) if ('all' in clientManifest && 'initial' in clientManifest) { // Upgrade legacy manifest (also see normalizeClientManifest in vue-bundle-renderer) // https://github.com/nuxt-contrib/vue-bundle-renderer/issues/12 entryFiles = clientManifest.initial.map(file => ({ file })) } return { html: '<div id="__nuxt"></div>', renderResourceHints: () => '', renderStyles: () => entryFiles .flatMap(({ css }) => css) .filter(css => css != null) .map(file => `<link rel="stylesheet" href="${buildAssetsURL(file)}">`) .join(''), renderScripts: () => entryFiles .map(({ file }) => { const isMJS = !file.endsWith('.js') return `<script ${isMJS ? 'type="module"' : ''} src="${buildAssetsURL(file)}"></script>` }) .join('') } } }) function renderToString (ssrContext) { const getRenderer = (NUXT_NO_SSR || ssrContext.noSSR) ? getSPARenderer : getSSRRenderer return getRenderer().then(renderToString => renderToString(ssrContext)) } export default eventHandler(async (event) => { // Whether we're rendering an error page const ssrError = event.req.url?.startsWith('/__nuxt_error') ? useQuery(event) : null let url = ssrError?.url as string || event.req.url! // payload.json request detection let isPayloadReq = false if (url.startsWith(STATIC_ASSETS_BASE) && url.endsWith(PAYLOAD_JS)) { isPayloadReq = true url = url.slice(STATIC_ASSETS_BASE.length, url.length - PAYLOAD_JS.length) || '/' } // Initialize ssr context const ssrContext = { url, event, req: event.req, res: event.res, runtimeConfig: useRuntimeConfig(), noSSR: event.req.headers['x-nuxt-no-ssr'], error: ssrError, redirected: undefined, nuxt: undefined, /* NuxtApp */ payload: undefined } // Render app const rendered = await renderToString(ssrContext).catch((e) => { if (!ssrError) { throw e } }) // If we error on rendering error page, we bail out and directly return to the error handler if (!rendered) { return } if (ssrContext.redirected || event.res.writableEnded) { return } const error = ssrContext.error /* nuxt 3 */ || ssrContext.nuxt?.error // Handle errors if (error && !ssrError) { throw error } if (ssrContext.nuxt?.hooks) { await ssrContext.nuxt.hooks.callHook('app:rendered') } // TODO: nuxt3 should not reuse `nuxt` property for different purpose! const payload = ssrContext.payload /* nuxt 3 */ || ssrContext.nuxt /* nuxt 2 */ if (process.env.NUXT_FULL_STATIC) { payload.staticAssetsBase = STATIC_ASSETS_BASE } let data if (isPayloadReq) { data = renderPayload(payload, url) event.res.setHeader('Content-Type', 'text/javascript;charset=UTF-8') } else { data = await renderHTML(payload, rendered, ssrContext) event.res.setHeader('Content-Type', 'text/html;charset=UTF-8') } event.res.end(data, 'utf-8') }) async function renderHTML (payload, rendered, ssrContext) { const state = `<script>window.__NUXT__=${devalue(payload)}</script>` const html = rendered.html if ('renderMeta' in ssrContext) { rendered.meta = await ssrContext.renderMeta() } const { htmlAttrs = '', bodyAttrs = '', headAttrs = '', headTags = '', bodyScriptsPrepend = '', bodyScripts = '' } = rendered.meta || {} return htmlTemplate({ HTML_ATTRS: htmlAttrs, HEAD_ATTRS: headAttrs, HEAD: headTags + rendered.renderResourceHints() + rendered.renderStyles() + (ssrContext.styles || ''), BODY_ATTRS: bodyAttrs, BODY_PREPEND: ssrContext.teleports?.body || '', APP: bodyScriptsPrepend + html + state + rendered.renderScripts() + bodyScripts }) } function renderPayload (payload, url) { return `__NUXT_JSONP__("${url}", ${devalue(payload)})` } function _interopDefault (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e } function cachedImport <M> (importer: () => Promise<M>) { return cachedResult(() => importer().then(_interopDefault)) as () => Promise<M> } function cachedResult <T> (fn: () => Promise<T>): () => Promise<T> { let res: Promise<T> | null = null return () => { if (res === null) { res = fn().catch((err) => { res = null; throw err }) } return res } }
packages/nuxt3/src/core/runtime/nitro/renderer.ts
0
https://github.com/nuxt/nuxt/commit/f4fb9160c612bf9400861be6d4f76d762ca41f73
[ 0.00018122117035090923, 0.00016915981541387737, 0.00016509534907527268, 0.00016794315888546407, 0.000003925089458789444 ]
{ "id": 0, "code_window": [ "karma_web_test_suite(\n", " name = \"test\",\n", " bootstrap = [\n", " \":elements_test_bootstrap_scripts\",\n", " ],\n", " deps = [\n", " \":test_lib\",\n", " ],\n", ")" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " tags = [\n", " # disabled on 2020-04-14 due to failure on saucelabs monitor job\n", " # https://app.circleci.com/pipelines/github/angular/angular/13320/workflows/9ca3527a-d448-4a64-880a-fb4de9d1fece/jobs/680645\n", " # ```\n", " # IE 10.0.0 (Windows 8.0.0) ERROR\n", " # An error was thrown in afterAll\n", " # Syntax error\n", " # ```\n", " \"fixme-saucelabs-ve\",\n", " \"fixme-saucelabs-ivy\",\n", " ],\n" ], "file_path": "packages/elements/test/BUILD.bazel", "type": "add", "edit_start_line_idx": 45 }
load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library") load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test") circular_dependency_test( name = "circular_deps_test", entry_point = "angular/packages/router/index.js", deps = ["//packages/router"], ) circular_dependency_test( name = "testing_circular_deps_test", entry_point = "angular/packages/router/testing/index.js", deps = ["//packages/router/testing"], ) ts_library( name = "test_lib", testonly = True, srcs = glob(["**/*.ts"]), # Visible to //:saucelabs_unit_tests_poc target visibility = ["//:__pkg__"], deps = [ "//packages/common", "//packages/common/testing", "//packages/core", "//packages/core/testing", "//packages/platform-browser", "//packages/platform-browser-dynamic", "//packages/platform-browser/testing", "//packages/private/testing", "//packages/router", "//packages/router/testing", "@npm//rxjs", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_es5"], deps = [ ":test_lib", ], ) karma_web_test_suite( name = "test_web", deps = [ ":test_lib", ], )
packages/router/test/BUILD.bazel
1
https://github.com/angular/angular/commit/d50cb3044355d13dcaf1812e55bc624d771ebddf
[ 0.010310825891792774, 0.003878564340993762, 0.0001664495066506788, 0.0029340172186493874, 0.003915128763765097 ]
{ "id": 0, "code_window": [ "karma_web_test_suite(\n", " name = \"test\",\n", " bootstrap = [\n", " \":elements_test_bootstrap_scripts\",\n", " ],\n", " deps = [\n", " \":test_lib\",\n", " ],\n", ")" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " tags = [\n", " # disabled on 2020-04-14 due to failure on saucelabs monitor job\n", " # https://app.circleci.com/pipelines/github/angular/angular/13320/workflows/9ca3527a-d448-4a64-880a-fb4de9d1fece/jobs/680645\n", " # ```\n", " # IE 10.0.0 (Windows 8.0.0) ERROR\n", " # An error was thrown in afterAll\n", " # Syntax error\n", " # ```\n", " \"fixme-saucelabs-ve\",\n", " \"fixme-saucelabs-ivy\",\n", " ],\n" ], "file_path": "packages/elements/test/BUILD.bazel", "type": "add", "edit_start_line_idx": 45 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import '../zone-spec/fake-async-test'; Zone.__load_patch('fakeasync', (global: any, Zone: ZoneType, api: _ZonePrivate) => { const FakeAsyncTestZoneSpec = Zone && (Zone as any)['FakeAsyncTestZoneSpec']; type ProxyZoneSpec = { setDelegate(delegateSpec: ZoneSpec): void; getDelegate(): ZoneSpec; resetDelegate(): void; }; const ProxyZoneSpec: {get(): ProxyZoneSpec; assertPresent: () => ProxyZoneSpec} = Zone && (Zone as any)['ProxyZoneSpec']; let _fakeAsyncTestZoneSpec: any = null; /** * Clears out the shared fake async zone for a test. * To be called in a global `beforeEach`. * * @experimental */ function resetFakeAsyncZone() { if (_fakeAsyncTestZoneSpec) { _fakeAsyncTestZoneSpec.unlockDatePatch(); } _fakeAsyncTestZoneSpec = null; // in node.js testing we may not have ProxyZoneSpec in which case there is nothing to reset. ProxyZoneSpec && ProxyZoneSpec.assertPresent().resetDelegate(); } /** * Wraps a function to be executed in the fakeAsync zone: * - microtasks are manually executed by calling `flushMicrotasks()`, * - timers are synchronous, `tick()` simulates the asynchronous passage of time. * * If there are any pending timers at the end of the function, an exception will be thrown. * * Can be used to wrap inject() calls. * * ## Example * * {@example core/testing/ts/fake_async.ts region='basic'} * * @param fn * @returns The function wrapped to be executed in the fakeAsync zone * * @experimental */ function fakeAsync(fn: Function): (...args: any[]) => any { // Not using an arrow function to preserve context passed from call site return function(this: unknown, ...args: any[]) { const proxyZoneSpec = ProxyZoneSpec.assertPresent(); if (Zone.current.get('FakeAsyncTestZoneSpec')) { throw new Error('fakeAsync() calls can not be nested'); } try { // in case jasmine.clock init a fakeAsyncTestZoneSpec if (!_fakeAsyncTestZoneSpec) { if (proxyZoneSpec.getDelegate() instanceof FakeAsyncTestZoneSpec) { throw new Error('fakeAsync() calls can not be nested'); } _fakeAsyncTestZoneSpec = new FakeAsyncTestZoneSpec(); } let res: any; const lastProxyZoneSpec = proxyZoneSpec.getDelegate(); proxyZoneSpec.setDelegate(_fakeAsyncTestZoneSpec); _fakeAsyncTestZoneSpec.lockDatePatch(); try { res = fn.apply(this, args); flushMicrotasks(); } finally { proxyZoneSpec.setDelegate(lastProxyZoneSpec); } if (_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length > 0) { throw new Error( `${_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length} ` + `periodic timer(s) still in the queue.`); } if (_fakeAsyncTestZoneSpec.pendingTimers.length > 0) { throw new Error( `${_fakeAsyncTestZoneSpec.pendingTimers.length} timer(s) still in the queue.`); } return res; } finally { resetFakeAsyncZone(); } }; } function _getFakeAsyncZoneSpec(): any { if (_fakeAsyncTestZoneSpec == null) { _fakeAsyncTestZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec'); if (_fakeAsyncTestZoneSpec == null) { throw new Error('The code should be running in the fakeAsync zone to call this function'); } } return _fakeAsyncTestZoneSpec; } /** * Simulates the asynchronous passage of time for the timers in the fakeAsync zone. * * The microtasks queue is drained at the very start of this function and after any timer callback * has been executed. * * ## Example * * {@example core/testing/ts/fake_async.ts region='basic'} * * @experimental */ function tick(millis: number = 0, ignoreNestedTimeout = false): void { _getFakeAsyncZoneSpec().tick(millis, null, ignoreNestedTimeout); } /** * Simulates the asynchronous passage of time for the timers in the fakeAsync zone by * draining the macrotask queue until it is empty. The returned value is the milliseconds * of time that would have been elapsed. * * @param maxTurns * @returns The simulated time elapsed, in millis. * * @experimental */ function flush(maxTurns?: number): number { return _getFakeAsyncZoneSpec().flush(maxTurns); } /** * Discard all remaining periodic tasks. * * @experimental */ function discardPeriodicTasks(): void { const zoneSpec = _getFakeAsyncZoneSpec(); const pendingTimers = zoneSpec.pendingPeriodicTimers; zoneSpec.pendingPeriodicTimers.length = 0; } /** * Flush any pending microtasks. * * @experimental */ function flushMicrotasks(): void { _getFakeAsyncZoneSpec().flushMicrotasks(); } (Zone as any)[api.symbol('fakeAsyncTest')] = { resetFakeAsyncZone, flushMicrotasks, discardPeriodicTasks, tick, flush, fakeAsync}; });
packages/zone.js/lib/testing/fake-async.ts
0
https://github.com/angular/angular/commit/d50cb3044355d13dcaf1812e55bc624d771ebddf
[ 0.00017844868125393987, 0.000170861414517276, 0.000163733318913728, 0.0001706303155515343, 0.00000449519393441733 ]
{ "id": 0, "code_window": [ "karma_web_test_suite(\n", " name = \"test\",\n", " bootstrap = [\n", " \":elements_test_bootstrap_scripts\",\n", " ],\n", " deps = [\n", " \":test_lib\",\n", " ],\n", ")" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " tags = [\n", " # disabled on 2020-04-14 due to failure on saucelabs monitor job\n", " # https://app.circleci.com/pipelines/github/angular/angular/13320/workflows/9ca3527a-d448-4a64-880a-fb4de9d1fece/jobs/680645\n", " # ```\n", " # IE 10.0.0 (Windows 8.0.0) ERROR\n", " # An error was thrown in afterAll\n", " # Syntax error\n", " # ```\n", " \"fixme-saucelabs-ve\",\n", " \"fixme-saucelabs-ivy\",\n", " ],\n" ], "file_path": "packages/elements/test/BUILD.bazel", "type": "add", "edit_start_line_idx": 45 }
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!-- Created with Inkscape (http://www.inkscape.org/) --> <svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" width="169.02681mm" height="196.58119mm" viewBox="0 0 169.02681 196.58119" version="1.1" id="svg8" inkscape:version="0.92.2pre0 (973e216, 2017-07-25)" sodipodi:docname="component-hierarchy.svg"> <defs id="defs2" /> <sodipodi:namedview id="base" pagecolor="#ffffff" bordercolor="#666666" borderopacity="1.0" inkscape:pageopacity="0.0" inkscape:pageshadow="2" inkscape:zoom="0.7" inkscape:cx="377.11192" inkscape:cy="120.53249" inkscape:document-units="mm" inkscape:current-layer="layer1" showgrid="false" inkscape:window-width="1920" inkscape:window-height="1139" inkscape:window-x="0" inkscape:window-y="0" inkscape:window-maximized="1" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" /> <metadata id="metadata5"> <rdf:RDF> <cc:Work rdf:about=""> <dc:format>image/svg+xml</dc:format> <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> <dc:title></dc:title> </cc:Work> </rdf:RDF> </metadata> <g inkscape:label="Layer 1" inkscape:groupmode="layer" id="layer1" transform="translate(-11.039021,5.3032374)"> <circle style="fill:#0000ff;fill-opacity:1;stroke:#000000;stroke-width:2.11243343;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0.08092484" id="path12" cx="33.639881" cy="83.821426" r="21.544643" /> <circle style="fill:#ff8080;fill-opacity:1;stroke:#000000;stroke-width:2.11243343;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0.08092484" id="path12-3" cx="109.23512" cy="83.821426" r="21.544643" /> <circle style="fill:#0000ff;fill-opacity:1;stroke:#000000;stroke-width:2.11243343;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0.08092484" id="path12-5" cx="72.571426" cy="17.297623" r="21.544643" /> <path style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="M 61.689542,35.89191 44.521765,65.227139" id="path71" inkscape:connector-type="polyline" inkscape:connector-curvature="0" inkscape:connection-start="#path12-5" inkscape:connection-end="#path12" /> <path style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="M 82.970619,36.166257 98.83593,64.952792" id="path73" inkscape:connector-type="polyline" inkscape:connector-curvature="0" inkscape:connection-start="#path12-5" inkscape:connection-end="#path12-3" /> <path style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.31964195px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="M 103.53288,104.6224 78.282491,168.85238" id="path75" inkscape:connector-type="polyline" inkscape:connector-curvature="0" /> <circle style="fill:#0000ff;fill-opacity:1;stroke:#000000;stroke-width:2.11243343;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0.08092484" id="path12-6" cx="81.113686" cy="168.67709" r="21.544643" /> <path style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.27186683px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m 121.11015,101.79948 40.28397,69.33358" id="path77" inkscape:connector-type="polyline" inkscape:connector-curvature="0" /> <circle style="fill:#ff8080;fill-opacity:1;stroke:#000000;stroke-width:2.11243343;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:0.08092484" id="path12-7" cx="157.46497" cy="166.97621" r="21.544643" /> </g> </svg>
aio/content/images/guide/toh/component-hierarchy.svg
0
https://github.com/angular/angular/commit/d50cb3044355d13dcaf1812e55bc624d771ebddf
[ 0.00017972529167309403, 0.00017655343981459737, 0.0001714104728307575, 0.00017688595107756555, 0.0000020831357687711716 ]
{ "id": 0, "code_window": [ "karma_web_test_suite(\n", " name = \"test\",\n", " bootstrap = [\n", " \":elements_test_bootstrap_scripts\",\n", " ],\n", " deps = [\n", " \":test_lib\",\n", " ],\n", ")" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " tags = [\n", " # disabled on 2020-04-14 due to failure on saucelabs monitor job\n", " # https://app.circleci.com/pipelines/github/angular/angular/13320/workflows/9ca3527a-d448-4a64-880a-fb4de9d1fece/jobs/680645\n", " # ```\n", " # IE 10.0.0 (Windows 8.0.0) ERROR\n", " # An error was thrown in afterAll\n", " # Syntax error\n", " # ```\n", " \"fixme-saucelabs-ve\",\n", " \"fixme-saucelabs-ivy\",\n", " ],\n" ], "file_path": "packages/elements/test/BUILD.bazel", "type": "add", "edit_start_line_idx": 45 }
import { AppPage } from './app.po'; import { browser, logging } from 'protractor'; describe('cli-hello-world-ivy-minimal App', () => { // Ivy renderComponent apps fail on protractor when waiting for Angular. browser.waitForAngularEnabled(false); let page: AppPage; beforeEach(() => { page = new AppPage(); }); it('should display welcome message', () => { page.navigateTo(); expect(page.getParagraphText()).toEqual('Welcome to cli-hello-world-ivy-minimal!'); }); afterEach(async () => { // Assert that there are no errors emitted from the browser const logs = await browser.manage().logs().get(logging.Type.BROWSER); expect(logs).not.toContain(jasmine.objectContaining({ level: logging.Level.SEVERE, } as logging.Entry)); }); });
integration/cli-hello-world-ivy-minimal/e2e/src/app.e2e-spec.ts
0
https://github.com/angular/angular/commit/d50cb3044355d13dcaf1812e55bc624d771ebddf
[ 0.00017319037578999996, 0.0001720764412311837, 0.0001701166620478034, 0.00017292224220000207, 0.0000013900795465815463 ]
{ "id": 1, "code_window": [ "\n", "karma_web_test_suite(\n", " name = \"test_web\",\n", " deps = [\n", " \":test_lib\",\n", " ],\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " tags = [\n", " # disabled on 2020-04-14 due to failure on saucelabs monitor job\n", " # https://app.circleci.com/pipelines/github/angular/angular/13320/workflows/9ca3527a-d448-4a64-880a-fb4de9d1fece/jobs/680645\n", " # ```\n", " # IE 11.0.0 (Windows 8.1.0.0) template-driven forms integration tests basic functionality should report properties which are written outside of template bindings FAILED\n", " # InvalidStateError: InvalidStateError\n", " # ```\n", " \"fixme-saucelabs-ivy\",\n", " ],\n" ], "file_path": "packages/forms/test/BUILD.bazel", "type": "add", "edit_start_line_idx": 37 }
load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library") load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test") circular_dependency_test( name = "circular_deps_test", entry_point = "angular/packages/router/index.js", deps = ["//packages/router"], ) circular_dependency_test( name = "testing_circular_deps_test", entry_point = "angular/packages/router/testing/index.js", deps = ["//packages/router/testing"], ) ts_library( name = "test_lib", testonly = True, srcs = glob(["**/*.ts"]), # Visible to //:saucelabs_unit_tests_poc target visibility = ["//:__pkg__"], deps = [ "//packages/common", "//packages/common/testing", "//packages/core", "//packages/core/testing", "//packages/platform-browser", "//packages/platform-browser-dynamic", "//packages/platform-browser/testing", "//packages/private/testing", "//packages/router", "//packages/router/testing", "@npm//rxjs", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_es5"], deps = [ ":test_lib", ], ) karma_web_test_suite( name = "test_web", deps = [ ":test_lib", ], )
packages/router/test/BUILD.bazel
1
https://github.com/angular/angular/commit/d50cb3044355d13dcaf1812e55bc624d771ebddf
[ 0.9976800084114075, 0.3240578770637512, 0.00016475269512739033, 0.00029815963353030384, 0.4582040309906006 ]
{ "id": 1, "code_window": [ "\n", "karma_web_test_suite(\n", " name = \"test_web\",\n", " deps = [\n", " \":test_lib\",\n", " ],\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " tags = [\n", " # disabled on 2020-04-14 due to failure on saucelabs monitor job\n", " # https://app.circleci.com/pipelines/github/angular/angular/13320/workflows/9ca3527a-d448-4a64-880a-fb4de9d1fece/jobs/680645\n", " # ```\n", " # IE 11.0.0 (Windows 8.1.0.0) template-driven forms integration tests basic functionality should report properties which are written outside of template bindings FAILED\n", " # InvalidStateError: InvalidStateError\n", " # ```\n", " \"fixme-saucelabs-ivy\",\n", " ],\n" ], "file_path": "packages/forms/test/BUILD.bazel", "type": "add", "edit_start_line_idx": 37 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; export default [ [ ['mi', 'n', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], ['midnight', 'noon', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], u ], [['midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'], u, u], [ '00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'], ['21:00', '06:00'] ] ];
packages/common/locales/extra/en-SG.ts
0
https://github.com/angular/angular/commit/d50cb3044355d13dcaf1812e55bc624d771ebddf
[ 0.00017605771427042782, 0.00017371145077049732, 0.00017004595429170877, 0.00017503066919744015, 0.000002625589104354731 ]
{ "id": 1, "code_window": [ "\n", "karma_web_test_suite(\n", " name = \"test_web\",\n", " deps = [\n", " \":test_lib\",\n", " ],\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " tags = [\n", " # disabled on 2020-04-14 due to failure on saucelabs monitor job\n", " # https://app.circleci.com/pipelines/github/angular/angular/13320/workflows/9ca3527a-d448-4a64-880a-fb4de9d1fece/jobs/680645\n", " # ```\n", " # IE 11.0.0 (Windows 8.1.0.0) template-driven forms integration tests basic functionality should report properties which are written outside of template bindings FAILED\n", " # InvalidStateError: InvalidStateError\n", " # ```\n", " \"fixme-saucelabs-ivy\",\n", " ],\n" ], "file_path": "packages/forms/test/BUILD.bazel", "type": "add", "edit_start_line_idx": 37 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; export default [ [ ['mi', 'n', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], ['midnight', 'noon', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], u ], [['midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'], u, u], [ '00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'], ['21:00', '06:00'] ] ];
packages/common/locales/extra/en-DE.ts
0
https://github.com/angular/angular/commit/d50cb3044355d13dcaf1812e55bc624d771ebddf
[ 0.00017605771427042782, 0.00017371145077049732, 0.00017004595429170877, 0.00017503066919744015, 0.000002625589104354731 ]
{ "id": 1, "code_window": [ "\n", "karma_web_test_suite(\n", " name = \"test_web\",\n", " deps = [\n", " \":test_lib\",\n", " ],\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " tags = [\n", " # disabled on 2020-04-14 due to failure on saucelabs monitor job\n", " # https://app.circleci.com/pipelines/github/angular/angular/13320/workflows/9ca3527a-d448-4a64-880a-fb4de9d1fece/jobs/680645\n", " # ```\n", " # IE 11.0.0 (Windows 8.1.0.0) template-driven forms integration tests basic functionality should report properties which are written outside of template bindings FAILED\n", " # InvalidStateError: InvalidStateError\n", " # ```\n", " \"fixme-saucelabs-ivy\",\n", " ],\n" ], "file_path": "packages/forms/test/BUILD.bazel", "type": "add", "edit_start_line_idx": 37 }
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import { catchError, map, tap } from 'rxjs/operators'; import { Hero } from './hero'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; @Injectable() export class HeroService { readonly heroesUrl = 'api/heroes'; // URL to web api constructor(private http: HttpClient) { } /** GET heroes from the server */ getHeroes(): Observable<Hero[]> { return this.http.get<Hero[]>(this.heroesUrl) .pipe( tap(heroes => this.log(`fetched heroes`)), catchError(this.handleError('getHeroes')) ) as Observable<Hero[]>; } /** GET hero by id. Return `undefined` when id not found */ getHero<Data>(id: number | string): Observable<Hero> { if (typeof id === 'string') { id = parseInt(id, 10); } const url = `${this.heroesUrl}/?id=${id}`; return this.http.get<Hero[]>(url) .pipe( map(heroes => heroes[0]), // returns a {0|1} element array tap(h => { const outcome = h ? `fetched` : `did not find`; this.log(`${outcome} hero id=${id}`); }), catchError(this.handleError<Hero>(`getHero id=${id}`)) ); } //////// Save methods ////////// /** POST: add a new hero to the server */ addHero(hero: Hero): Observable<Hero> { return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe( tap((addedHero) => this.log(`added hero w/ id=${addedHero.id}`)), catchError(this.handleError<Hero>('addHero')) ); } /** DELETE: delete the hero from the server */ deleteHero(hero: Hero | number): Observable<Hero> { const id = typeof hero === 'number' ? hero : hero.id; const url = `${this.heroesUrl}/${id}`; return this.http.delete<Hero>(url, httpOptions).pipe( tap(_ => this.log(`deleted hero id=${id}`)), catchError(this.handleError<Hero>('deleteHero')) ); } /** PUT: update the hero on the server */ updateHero(hero: Hero): Observable<any> { return this.http.put(this.heroesUrl, hero, httpOptions).pipe( tap(_ => this.log(`updated hero id=${hero.id}`)), catchError(this.handleError<any>('updateHero')) ); } /** * Returns a function that handles Http operation failures. * This error handler lets the app continue to run as if no error occurred. * @param operation - name of the operation that failed */ private handleError<T>(operation = 'operation') { return (error: HttpErrorResponse): Observable<T> => { // TODO: send the error to remote logging infrastructure console.error(error); // log to console instead const message = (error.error instanceof ErrorEvent) ? error.error.message : `server returned code ${error.status} with body "${error.error}"`; // TODO: better job of transforming error for user consumption throw new Error(`${operation} failed: ${message}`); }; } private log(message: string) { console.log('HeroService: ' + message); } }
aio/content/examples/testing/src/app/model/hero.service.ts
0
https://github.com/angular/angular/commit/d50cb3044355d13dcaf1812e55bc624d771ebddf
[ 0.00019893163698725402, 0.00017646211199462414, 0.00016836915165185928, 0.0001750962110236287, 0.000007815734534233343 ]
{ "id": 2, "code_window": [ "karma_web_test_suite(\n", " name = \"test_web\",\n", " static_files = [\n", " \":static_assets/test.html\",\n", " ],\n", " deps = [\n", " \":test_lib\",\n", " ],\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " tags = [\n", " # disabled on 2020-04-14 due to failure on saucelabs monitor job\n", " # https://app.circleci.com/pipelines/github/angular/angular/13320/workflows/9ca3527a-d448-4a64-880a-fb4de9d1fece/jobs/680645\n", " # ```\n", " # Chrome 73.0.3683 (Windows 7.0.0) public testing API using the test injector with modules components with template url should allow to createSync components with templateUrl after explicit async compilation FAILED\n", " # Error: Component 'CompWithUrlTemplate' is not resolved:\n", " # IE 10.0.0 (Windows 8.0.0) ERROR: 'Unhandled Promise rejection:', 'Failed to load ./sometemplate.html', '; Zone:', 'ProxyZone', '; Task:', 'Promise.then', '; Value:', 'Failed to load ./sometemplate.html', undefined\n", " # Chrome Mobile 74.0.3729 (Android 0.0.0) ERROR: 'Unhandled Promise rejection:', 'Failed to load ./sometemplate.html', '; Zone:', 'ProxyZone', '; Task:', 'Promise.then', '; Value:', 'Failed to load ./sometemplate.html', undefined\n", " # ```\n", " \"fixme-saucelabs-ivy\",\n", " ],\n" ], "file_path": "packages/platform-browser/test/BUILD.bazel", "type": "add", "edit_start_line_idx": 55 }
load("//tools:defaults.bzl", "karma_web_test_suite", "ts_library") load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test") circular_dependency_test( name = "circular_deps_test", entry_point = "angular/packages/elements/index.js", deps = ["//packages/elements"], ) ts_library( name = "test_lib", testonly = True, srcs = glob(["**/*.ts"]), deps = [ "//packages:types", "//packages/compiler", "//packages/core", "//packages/core/testing", "//packages/elements", "//packages/platform-browser", "//packages/platform-browser-dynamic", "//packages/platform-browser-dynamic/testing", "//packages/platform-browser/testing", "@npm//rxjs", ], ) filegroup( name = "elements_test_bootstrap_scripts", testonly = True, # do not sort srcs = [ "@npm//:node_modules/core-js/client/core.js", "@npm//:node_modules/@webcomponents/custom-elements/src/native-shim.js", "@npm//:node_modules/reflect-metadata/Reflect.js", "//packages/zone.js/dist:zone.js", "//packages/zone.js/dist:zone-testing.js", ], ) karma_web_test_suite( name = "test", bootstrap = [ ":elements_test_bootstrap_scripts", ], deps = [ ":test_lib", ], )
packages/elements/test/BUILD.bazel
1
https://github.com/angular/angular/commit/d50cb3044355d13dcaf1812e55bc624d771ebddf
[ 0.0052908314391970634, 0.0016018865862861276, 0.00016913701256271452, 0.0007557900971733034, 0.00191941624507308 ]
{ "id": 2, "code_window": [ "karma_web_test_suite(\n", " name = \"test_web\",\n", " static_files = [\n", " \":static_assets/test.html\",\n", " ],\n", " deps = [\n", " \":test_lib\",\n", " ],\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " tags = [\n", " # disabled on 2020-04-14 due to failure on saucelabs monitor job\n", " # https://app.circleci.com/pipelines/github/angular/angular/13320/workflows/9ca3527a-d448-4a64-880a-fb4de9d1fece/jobs/680645\n", " # ```\n", " # Chrome 73.0.3683 (Windows 7.0.0) public testing API using the test injector with modules components with template url should allow to createSync components with templateUrl after explicit async compilation FAILED\n", " # Error: Component 'CompWithUrlTemplate' is not resolved:\n", " # IE 10.0.0 (Windows 8.0.0) ERROR: 'Unhandled Promise rejection:', 'Failed to load ./sometemplate.html', '; Zone:', 'ProxyZone', '; Task:', 'Promise.then', '; Value:', 'Failed to load ./sometemplate.html', undefined\n", " # Chrome Mobile 74.0.3729 (Android 0.0.0) ERROR: 'Unhandled Promise rejection:', 'Failed to load ./sometemplate.html', '; Zone:', 'ProxyZone', '; Task:', 'Promise.then', '; Value:', 'Failed to load ./sometemplate.html', undefined\n", " # ```\n", " \"fixme-saucelabs-ivy\",\n", " ],\n" ], "file_path": "packages/platform-browser/test/BUILD.bazel", "type": "add", "edit_start_line_idx": 55 }
// #docregion import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { }
aio/content/examples/testing/src/app/app.component.ts
0
https://github.com/angular/angular/commit/d50cb3044355d13dcaf1812e55bc624d771ebddf
[ 0.00016802482423372567, 0.00016802482423372567, 0.00016802482423372567, 0.00016802482423372567, 0 ]
{ "id": 2, "code_window": [ "karma_web_test_suite(\n", " name = \"test_web\",\n", " static_files = [\n", " \":static_assets/test.html\",\n", " ],\n", " deps = [\n", " \":test_lib\",\n", " ],\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " tags = [\n", " # disabled on 2020-04-14 due to failure on saucelabs monitor job\n", " # https://app.circleci.com/pipelines/github/angular/angular/13320/workflows/9ca3527a-d448-4a64-880a-fb4de9d1fece/jobs/680645\n", " # ```\n", " # Chrome 73.0.3683 (Windows 7.0.0) public testing API using the test injector with modules components with template url should allow to createSync components with templateUrl after explicit async compilation FAILED\n", " # Error: Component 'CompWithUrlTemplate' is not resolved:\n", " # IE 10.0.0 (Windows 8.0.0) ERROR: 'Unhandled Promise rejection:', 'Failed to load ./sometemplate.html', '; Zone:', 'ProxyZone', '; Task:', 'Promise.then', '; Value:', 'Failed to load ./sometemplate.html', undefined\n", " # Chrome Mobile 74.0.3729 (Android 0.0.0) ERROR: 'Unhandled Promise rejection:', 'Failed to load ./sometemplate.html', '; Zone:', 'ProxyZone', '; Task:', 'Promise.then', '; Value:', 'Failed to load ./sometemplate.html', undefined\n", " # ```\n", " \"fixme-saucelabs-ivy\",\n", " ],\n" ], "file_path": "packages/platform-browser/test/BUILD.bazel", "type": "add", "edit_start_line_idx": 55 }
export * from './core'; export * from './app.component';
aio/content/examples/styleguide/src/03-03/app/index.ts
0
https://github.com/angular/angular/commit/d50cb3044355d13dcaf1812e55bc624d771ebddf
[ 0.00017629339708946645, 0.00017629339708946645, 0.00017629339708946645, 0.00017629339708946645, 0 ]
{ "id": 2, "code_window": [ "karma_web_test_suite(\n", " name = \"test_web\",\n", " static_files = [\n", " \":static_assets/test.html\",\n", " ],\n", " deps = [\n", " \":test_lib\",\n", " ],\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " tags = [\n", " # disabled on 2020-04-14 due to failure on saucelabs monitor job\n", " # https://app.circleci.com/pipelines/github/angular/angular/13320/workflows/9ca3527a-d448-4a64-880a-fb4de9d1fece/jobs/680645\n", " # ```\n", " # Chrome 73.0.3683 (Windows 7.0.0) public testing API using the test injector with modules components with template url should allow to createSync components with templateUrl after explicit async compilation FAILED\n", " # Error: Component 'CompWithUrlTemplate' is not resolved:\n", " # IE 10.0.0 (Windows 8.0.0) ERROR: 'Unhandled Promise rejection:', 'Failed to load ./sometemplate.html', '; Zone:', 'ProxyZone', '; Task:', 'Promise.then', '; Value:', 'Failed to load ./sometemplate.html', undefined\n", " # Chrome Mobile 74.0.3729 (Android 0.0.0) ERROR: 'Unhandled Promise rejection:', 'Failed to load ./sometemplate.html', '; Zone:', 'ProxyZone', '; Task:', 'Promise.then', '; Value:', 'Failed to load ./sometemplate.html', undefined\n", " # ```\n", " \"fixme-saucelabs-ivy\",\n", " ],\n" ], "file_path": "packages/platform-browser/test/BUILD.bazel", "type": "add", "edit_start_line_idx": 55 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {NgQueryDefinition} from '../../angular/query-definition'; import {TimingResult, TimingStrategy} from '../timing-strategy'; /** * Query timing strategy that is used for queries used within test files. The query * timing is not analyzed for test files as the template strategy cannot work within * spec files (due to missing component modules) and the usage strategy is not capable * of detecting the timing of queries based on how they are used in tests. */ export class QueryTestStrategy implements TimingStrategy { setup() {} /** * Detects the timing for a given query. For queries within tests, we always * add a TODO and print a message saying that the timing can't be detected for tests. */ detectTiming(query: NgQueryDefinition): TimingResult { return {timing: null, message: 'Timing within tests cannot be detected.'}; } }
packages/core/schematics/migrations/static-queries/strategies/test_strategy/test_strategy.ts
0
https://github.com/angular/angular/commit/d50cb3044355d13dcaf1812e55bc624d771ebddf
[ 0.0001778097212081775, 0.0001711914810584858, 0.0001676399406278506, 0.000168124824995175, 0.000004683976840169635 ]
{ "id": 3, "code_window": [ ")\n", "\n", "karma_web_test_suite(\n", " name = \"test_web\",\n", " deps = [\n", " \":test_lib\",\n", " ],\n", ")" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " tags = [\n", " # disabled on 2020-04-14 due to failure on saucelabs monitor job\n", " # https://app.circleci.com/pipelines/github/angular/angular/13320/workflows/9ca3527a-d448-4a64-880a-fb4de9d1fece/jobs/680645\n", " # ```\n", " # Chrome 73.0.3683 (Windows 7.0.0) ERROR: 'ERROR', Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'aa'\n", " # Error: Cannot match any routes. URL Segment: 'aa'\n", " # IE 11.0.0 (Windows 8.1.0.0) ERROR: 'ERROR', Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'aa'\n", " # Error: Cannot match any routes. URL Segment: 'aa'\n", " # Firefox 65.0.0 (Windows 7.0.0) ERROR: 'ERROR', Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'aa'\n", " # IE 10.0.0 (Windows 8.0.0) ERROR: 'ERROR', Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'aa'\n", " # Error: Cannot match any routes. URL Segment: 'aa'\n", " # ```\n", " \"fixme-saucelabs-ve\",\n", " \"fixme-saucelabs-ivy\",\n", " ],\n" ], "file_path": "packages/router/test/BUILD.bazel", "type": "add", "edit_start_line_idx": 46 }
load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library") load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test") circular_dependency_test( name = "circular_deps_test", entry_point = "angular/packages/router/index.js", deps = ["//packages/router"], ) circular_dependency_test( name = "testing_circular_deps_test", entry_point = "angular/packages/router/testing/index.js", deps = ["//packages/router/testing"], ) ts_library( name = "test_lib", testonly = True, srcs = glob(["**/*.ts"]), # Visible to //:saucelabs_unit_tests_poc target visibility = ["//:__pkg__"], deps = [ "//packages/common", "//packages/common/testing", "//packages/core", "//packages/core/testing", "//packages/platform-browser", "//packages/platform-browser-dynamic", "//packages/platform-browser/testing", "//packages/private/testing", "//packages/router", "//packages/router/testing", "@npm//rxjs", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node_es5"], deps = [ ":test_lib", ], ) karma_web_test_suite( name = "test_web", deps = [ ":test_lib", ], )
packages/router/test/BUILD.bazel
1
https://github.com/angular/angular/commit/d50cb3044355d13dcaf1812e55bc624d771ebddf
[ 0.9973324537277222, 0.3259676396846771, 0.00016508637054357678, 0.0002148904895875603, 0.4608561098575592 ]
{ "id": 3, "code_window": [ ")\n", "\n", "karma_web_test_suite(\n", " name = \"test_web\",\n", " deps = [\n", " \":test_lib\",\n", " ],\n", ")" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " tags = [\n", " # disabled on 2020-04-14 due to failure on saucelabs monitor job\n", " # https://app.circleci.com/pipelines/github/angular/angular/13320/workflows/9ca3527a-d448-4a64-880a-fb4de9d1fece/jobs/680645\n", " # ```\n", " # Chrome 73.0.3683 (Windows 7.0.0) ERROR: 'ERROR', Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'aa'\n", " # Error: Cannot match any routes. URL Segment: 'aa'\n", " # IE 11.0.0 (Windows 8.1.0.0) ERROR: 'ERROR', Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'aa'\n", " # Error: Cannot match any routes. URL Segment: 'aa'\n", " # Firefox 65.0.0 (Windows 7.0.0) ERROR: 'ERROR', Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'aa'\n", " # IE 10.0.0 (Windows 8.0.0) ERROR: 'ERROR', Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'aa'\n", " # Error: Cannot match any routes. URL Segment: 'aa'\n", " # ```\n", " \"fixme-saucelabs-ve\",\n", " \"fixme-saucelabs-ivy\",\n", " ],\n" ], "file_path": "packages/router/test/BUILD.bazel", "type": "add", "edit_start_line_idx": 46 }
load("//tools:defaults.bzl", "ng_module", "ts_devserver") package(default_visibility = ["//modules/playground:__subpackages__"]) ng_module( name = "todo", srcs = glob(["**/*.ts"]), assets = [ "todo.html", "css/base.css", ], tsconfig = "//modules/playground:tsconfig-build.json", deps = [ "//packages/core", "//packages/platform-browser", "//packages/platform-browser-dynamic", ], ) ts_devserver( name = "devserver", bootstrap = [ "//packages/zone.js/dist:zone.js", "@npm//:node_modules/reflect-metadata/Reflect.js", ], entry_module = "angular/modules/playground/src/todo/index", port = 4200, scripts = ["@npm//:node_modules/tslib/tslib.js"], static_files = ["index.html"] + glob(["**/*.css"]), deps = [":todo"], )
modules/playground/src/todo/BUILD.bazel
0
https://github.com/angular/angular/commit/d50cb3044355d13dcaf1812e55bc624d771ebddf
[ 0.00017936319636646658, 0.0001700750581221655, 0.0001651230559218675, 0.0001679070119280368, 0.0000055483815231127664 ]
{ "id": 3, "code_window": [ ")\n", "\n", "karma_web_test_suite(\n", " name = \"test_web\",\n", " deps = [\n", " \":test_lib\",\n", " ],\n", ")" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " tags = [\n", " # disabled on 2020-04-14 due to failure on saucelabs monitor job\n", " # https://app.circleci.com/pipelines/github/angular/angular/13320/workflows/9ca3527a-d448-4a64-880a-fb4de9d1fece/jobs/680645\n", " # ```\n", " # Chrome 73.0.3683 (Windows 7.0.0) ERROR: 'ERROR', Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'aa'\n", " # Error: Cannot match any routes. URL Segment: 'aa'\n", " # IE 11.0.0 (Windows 8.1.0.0) ERROR: 'ERROR', Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'aa'\n", " # Error: Cannot match any routes. URL Segment: 'aa'\n", " # Firefox 65.0.0 (Windows 7.0.0) ERROR: 'ERROR', Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'aa'\n", " # IE 10.0.0 (Windows 8.0.0) ERROR: 'ERROR', Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'aa'\n", " # Error: Cannot match any routes. URL Segment: 'aa'\n", " # ```\n", " \"fixme-saucelabs-ve\",\n", " \"fixme-saucelabs-ivy\",\n", " ],\n" ], "file_path": "packages/router/test/BUILD.bazel", "type": "add", "edit_start_line_idx": 46 }
// #docregion import { animation, style, animate } from '@angular/animations'; export const transAnimation = animation([ style({ height: '{{ height }}', opacity: '{{ opacity }}', backgroundColor: '{{ backgroundColor }}' }), animate('{{ time }}') ]);
aio/content/examples/animations/src/app/animations.1.ts
0
https://github.com/angular/angular/commit/d50cb3044355d13dcaf1812e55bc624d771ebddf
[ 0.00018024029850494117, 0.00017947015294339508, 0.000178700007381849, 0.00017947015294339508, 7.701455615460873e-7 ]
{ "id": 3, "code_window": [ ")\n", "\n", "karma_web_test_suite(\n", " name = \"test_web\",\n", " deps = [\n", " \":test_lib\",\n", " ],\n", ")" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " tags = [\n", " # disabled on 2020-04-14 due to failure on saucelabs monitor job\n", " # https://app.circleci.com/pipelines/github/angular/angular/13320/workflows/9ca3527a-d448-4a64-880a-fb4de9d1fece/jobs/680645\n", " # ```\n", " # Chrome 73.0.3683 (Windows 7.0.0) ERROR: 'ERROR', Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'aa'\n", " # Error: Cannot match any routes. URL Segment: 'aa'\n", " # IE 11.0.0 (Windows 8.1.0.0) ERROR: 'ERROR', Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'aa'\n", " # Error: Cannot match any routes. URL Segment: 'aa'\n", " # Firefox 65.0.0 (Windows 7.0.0) ERROR: 'ERROR', Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'aa'\n", " # IE 10.0.0 (Windows 8.0.0) ERROR: 'ERROR', Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'aa'\n", " # Error: Cannot match any routes. URL Segment: 'aa'\n", " # ```\n", " \"fixme-saucelabs-ve\",\n", " \"fixme-saucelabs-ivy\",\n", " ],\n" ], "file_path": "packages/router/test/BUILD.bazel", "type": "add", "edit_start_line_idx": 46 }
# `indexer` The `indexer` module generates semantic analysis about components used in an Angular project. The module is consumed by a semantic analysis API on an Angular program, which can be invoked separately from the regular Angular compilation pipeline. The module is _not_ a fully-featured source code indexer. Rather, it is designed to produce semantic information about an Angular project that can then be used by language analysis tools to generate, for example, cross-references in Angular templates. The `indexer` module is developed primarily with the [Kythe](https://github.com/kythe/kythe) ecosystem in mind as an indexing service. ### Scope of Analysis The scope of analysis performed by the module includes - indexing template syntax identifiers in a component template - generating information about directives used in a template - generating metadata about component and template source files The module does not support indexing TypeScript source code.
packages/compiler-cli/src/ngtsc/indexer/README.md
0
https://github.com/angular/angular/commit/d50cb3044355d13dcaf1812e55bc624d771ebddf
[ 0.00017172275693155825, 0.00016899600450415164, 0.00016721768770366907, 0.00016804758342914283, 0.0000019576425529521657 ]
{ "id": 1, "code_window": [ " if (elementName.indexOf('-') !== -1) {\n", " errorMsg +=\n", " `. To ignore this error on custom elements, add the \"CUSTOM_ELEMENTS_SCHEMA\" to the NgModule of this component`;\n", " }\n", " this._reportError(errorMsg, sourceSpan);\n", " }\n", " }\n", " } else {\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " `\\n1. If '${elementName}' is an Angular component and it has '${boundPropertyName}' input, then verify that it is part of this module.` +\n", " `\\n2. If '${elementName}' is a Web Component then add \"CUSTOM_ELEMENTS_SCHEMA\" to the '@NgModule.schema' of this component to suppress this message.\\n`;\n" ], "file_path": "modules/@angular/compiler/src/template_parser/template_parser.ts", "type": "replace", "edit_start_line_idx": 820 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Inject, Injectable, OpaqueToken, Optional, SchemaMetadata, SecurityContext} from '@angular/core'; import {Console, MAX_INTERPOLATION_VALUES} from '../../core_private'; import {ListWrapper, StringMapWrapper, SetWrapper,} from '../facade/collection'; import {RegExpWrapper, isPresent, isBlank} from '../facade/lang'; import {BaseException} from '../facade/exceptions'; import {EmptyExpr, AST, Interpolation, ASTWithSource, TemplateBinding, RecursiveAstVisitor, BindingPipe, ParserError} from '../expression_parser/ast'; import {Parser} from '../expression_parser/parser'; import {CompileDirectiveMetadata, CompilePipeMetadata, CompileTokenMetadata, removeIdentifierDuplicates,} from '../compile_metadata'; import {HtmlParser, ParseTreeResult} from '../html_parser/html_parser'; import {splitNsName, mergeNsAndName} from '../html_parser/tags'; import {ParseSourceSpan, ParseError, ParseErrorLevel} from '../parse_util'; import {InterpolationConfig} from '../html_parser/interpolation_config'; import {ElementAst, BoundElementPropertyAst, BoundEventAst, ReferenceAst, TemplateAst, TemplateAstVisitor, templateVisitAll, TextAst, BoundTextAst, EmbeddedTemplateAst, AttrAst, NgContentAst, PropertyBindingType, DirectiveAst, BoundDirectivePropertyAst, VariableAst} from './template_ast'; import {CssSelector, SelectorMatcher} from '../selector'; import {ElementSchemaRegistry} from '../schema/element_schema_registry'; import {preparseElement, PreparsedElementType} from './template_preparser'; import {isStyleUrlResolvable} from '../style_url_resolver'; import * as html from '../html_parser/ast'; import {splitAtColon} from '../util'; import {identifierToken, Identifiers} from '../identifiers'; import {expandNodes} from '../html_parser/icu_ast_expander'; import {ProviderElementContext, ProviderViewContext} from '../provider_analyzer'; // Group 1 = "bind-" // Group 2 = "var-" // Group 3 = "let-" // Group 4 = "ref-/#" // Group 5 = "on-" // Group 6 = "bindon-" // Group 7 = "animate-/@" // Group 8 = the identifier after "bind-", "var-/#", or "on-" // Group 9 = identifier inside [()] // Group 10 = identifier inside [] // Group 11 = identifier inside () const BIND_NAME_REGEXP = /^(?:(?:(?:(bind-)|(var-)|(let-)|(ref-|#)|(on-)|(bindon-)|(animate-|@))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/g; const TEMPLATE_ELEMENT = 'template'; const TEMPLATE_ATTR = 'template'; const TEMPLATE_ATTR_PREFIX = '*'; const CLASS_ATTR = 'class'; const PROPERTY_PARTS_SEPARATOR = '.'; const ATTRIBUTE_PREFIX = 'attr'; const CLASS_PREFIX = 'class'; const STYLE_PREFIX = 'style'; const TEXT_CSS_SELECTOR = CssSelector.parse('*')[0]; /** * Provides an array of {@link TemplateAstVisitor}s which will be used to transform * parsed templates before compilation is invoked, allowing custom expression syntax * and other advanced transformations. * * This is currently an internal-only feature and not meant for general use. */ export const TEMPLATE_TRANSFORMS: any = new OpaqueToken('TemplateTransforms'); export class TemplateParseError extends ParseError { constructor(message: string, span: ParseSourceSpan, level: ParseErrorLevel) { super(span, message, level); } } export class TemplateParseResult { constructor(public templateAst?: TemplateAst[], public errors?: ParseError[]) {} } @Injectable() export class TemplateParser { constructor( private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry, private _htmlParser: HtmlParser, private _console: Console, @Optional() @Inject(TEMPLATE_TRANSFORMS) public transforms: TemplateAstVisitor[]) {} parse( component: CompileDirectiveMetadata, template: string, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[], schemas: SchemaMetadata[], templateUrl: string): TemplateAst[] { const result = this.tryParse(component, template, directives, pipes, schemas, templateUrl); const warnings = result.errors.filter(error => error.level === ParseErrorLevel.WARNING); const errors = result.errors.filter(error => error.level === ParseErrorLevel.FATAL); if (warnings.length > 0) { this._console.warn(`Template parse warnings:\n${warnings.join('\n')}`); } if (errors.length > 0) { const errorString = errors.join('\n'); throw new BaseException(`Template parse errors:\n${errorString}`); } return result.templateAst; } tryParse( component: CompileDirectiveMetadata, template: string, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[], schemas: SchemaMetadata[], templateUrl: string): TemplateParseResult { let interpolationConfig: any; if (component.template) { interpolationConfig = InterpolationConfig.fromArray(component.template.interpolation); } let htmlAstWithErrors = this._htmlParser.parse(template, templateUrl, true, interpolationConfig); const errors: ParseError[] = htmlAstWithErrors.errors; let result: TemplateAst[]; if (errors.length == 0) { // Transform ICU messages to angular directives const expandedHtmlAst = expandNodes(htmlAstWithErrors.rootNodes); errors.push(...expandedHtmlAst.errors); htmlAstWithErrors = new ParseTreeResult(expandedHtmlAst.nodes, errors); } if (htmlAstWithErrors.rootNodes.length > 0) { const uniqDirectives = removeIdentifierDuplicates(directives); const uniqPipes = removeIdentifierDuplicates(pipes); const providerViewContext = new ProviderViewContext(component, htmlAstWithErrors.rootNodes[0].sourceSpan); const parseVisitor = new TemplateParseVisitor( providerViewContext, uniqDirectives, uniqPipes, schemas, this._exprParser, this._schemaRegistry); result = html.visitAll(parseVisitor, htmlAstWithErrors.rootNodes, EMPTY_ELEMENT_CONTEXT); errors.push(...parseVisitor.errors, ...providerViewContext.errors); } else { result = []; } this._assertNoReferenceDuplicationOnTemplate(result, errors); if (errors.length > 0) { return new TemplateParseResult(result, errors); } if (isPresent(this.transforms)) { this.transforms.forEach( (transform: TemplateAstVisitor) => { result = templateVisitAll(transform, result); }); } return new TemplateParseResult(result, errors); } /** @internal */ _assertNoReferenceDuplicationOnTemplate(result: TemplateAst[], errors: TemplateParseError[]): void { const existingReferences: string[] = []; result.filter(element => !!(<any>element).references) .forEach(element => (<any>element).references.forEach((reference: ReferenceAst) => { const name = reference.name; if (existingReferences.indexOf(name) < 0) { existingReferences.push(name); } else { const error = new TemplateParseError( `Reference "#${name}" is defined several times`, reference.sourceSpan, ParseErrorLevel.FATAL); errors.push(error); } })); } } class TemplateParseVisitor implements html.Visitor { selectorMatcher: SelectorMatcher; errors: TemplateParseError[] = []; directivesIndex = new Map<CompileDirectiveMetadata, number>(); ngContentCount: number = 0; pipesByName: Map<string, CompilePipeMetadata>; private _interpolationConfig: InterpolationConfig; constructor( public providerViewContext: ProviderViewContext, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[], private _schemas: SchemaMetadata[], private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry) { this.selectorMatcher = new SelectorMatcher(); const tempMeta = providerViewContext.component.template; if (isPresent(tempMeta) && isPresent(tempMeta.interpolation)) { this._interpolationConfig = { start: tempMeta.interpolation[0], end: tempMeta.interpolation[1] }; } ListWrapper.forEachWithIndex( directives, (directive: CompileDirectiveMetadata, index: number) => { const selector = CssSelector.parse(directive.selector); this.selectorMatcher.addSelectables(selector, directive); this.directivesIndex.set(directive, index); }); this.pipesByName = new Map<string, CompilePipeMetadata>(); pipes.forEach(pipe => this.pipesByName.set(pipe.name, pipe)); } private _reportError( message: string, sourceSpan: ParseSourceSpan, level: ParseErrorLevel = ParseErrorLevel.FATAL) { this.errors.push(new TemplateParseError(message, sourceSpan, level)); } private _reportParserErors(errors: ParserError[], sourceSpan: ParseSourceSpan) { for (const error of errors) { this._reportError(error.message, sourceSpan); } } private _parseInterpolation(value: string, sourceSpan: ParseSourceSpan): ASTWithSource { const sourceInfo = sourceSpan.start.toString(); try { const ast = this._exprParser.parseInterpolation(value, sourceInfo, this._interpolationConfig); if (ast) this._reportParserErors(ast.errors, sourceSpan); this._checkPipes(ast, sourceSpan); if (isPresent(ast) && (<Interpolation>ast.ast).expressions.length > MAX_INTERPOLATION_VALUES) { throw new BaseException( `Only support at most ${MAX_INTERPOLATION_VALUES} interpolation values!`); } return ast; } catch (e) { this._reportError(`${e}`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); } } private _parseAction(value: string, sourceSpan: ParseSourceSpan): ASTWithSource { const sourceInfo = sourceSpan.start.toString(); try { const ast = this._exprParser.parseAction(value, sourceInfo, this._interpolationConfig); if (ast) { this._reportParserErors(ast.errors, sourceSpan); } if (!ast || ast.ast instanceof EmptyExpr) { this._reportError(`Empty expressions are not allowed`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); } this._checkPipes(ast, sourceSpan); return ast; } catch (e) { this._reportError(`${e}`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); } } private _parseBinding(value: string, sourceSpan: ParseSourceSpan): ASTWithSource { const sourceInfo = sourceSpan.start.toString(); try { const ast = this._exprParser.parseBinding(value, sourceInfo, this._interpolationConfig); if (ast) this._reportParserErors(ast.errors, sourceSpan); this._checkPipes(ast, sourceSpan); return ast; } catch (e) { this._reportError(`${e}`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); } } private _parseTemplateBindings(value: string, sourceSpan: ParseSourceSpan): TemplateBinding[] { const sourceInfo = sourceSpan.start.toString(); try { const bindingsResult = this._exprParser.parseTemplateBindings(value, sourceInfo); this._reportParserErors(bindingsResult.errors, sourceSpan); bindingsResult.templateBindings.forEach((binding) => { if (isPresent(binding.expression)) { this._checkPipes(binding.expression, sourceSpan); } }); bindingsResult.warnings.forEach( (warning) => { this._reportError(warning, sourceSpan, ParseErrorLevel.WARNING); }); return bindingsResult.templateBindings; } catch (e) { this._reportError(`${e}`, sourceSpan); return []; } } private _checkPipes(ast: ASTWithSource, sourceSpan: ParseSourceSpan) { if (isPresent(ast)) { const collector = new PipeCollector(); ast.visit(collector); collector.pipes.forEach((pipeName) => { if (!this.pipesByName.has(pipeName)) { this._reportError(`The pipe '${pipeName}' could not be found`, sourceSpan); } }); } } visitExpansion(expansion: html.Expansion, context: any): any { return null; } visitExpansionCase(expansionCase: html.ExpansionCase, context: any): any { return null; } visitText(text: html.Text, parent: ElementContext): any { const ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR); const expr = this._parseInterpolation(text.value, text.sourceSpan); if (isPresent(expr)) { return new BoundTextAst(expr, ngContentIndex, text.sourceSpan); } else { return new TextAst(text.value, ngContentIndex, text.sourceSpan); } } visitAttribute(attribute: html.Attribute, contex: any): any { return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan); } visitComment(comment: html.Comment, context: any): any { return null; } visitElement(element: html.Element, parent: ElementContext): any { const nodeName = element.name; const preparsedElement = preparseElement(element); if (preparsedElement.type === PreparsedElementType.SCRIPT || preparsedElement.type === PreparsedElementType.STYLE) { // Skipping <script> for security reasons // Skipping <style> as we already processed them // in the StyleCompiler return null; } if (preparsedElement.type === PreparsedElementType.STYLESHEET && isStyleUrlResolvable(preparsedElement.hrefAttr)) { // Skipping stylesheets with either relative urls or package scheme as we already processed // them in the StyleCompiler return null; } const matchableAttrs: string[][] = []; const elementOrDirectiveProps: BoundElementOrDirectiveProperty[] = []; const elementOrDirectiveRefs: ElementOrDirectiveRef[] = []; const elementVars: VariableAst[] = []; const animationProps: BoundElementPropertyAst[] = []; const events: BoundEventAst[] = []; const templateElementOrDirectiveProps: BoundElementOrDirectiveProperty[] = []; const templateMatchableAttrs: string[][] = []; const templateElementVars: VariableAst[] = []; let hasInlineTemplates = false; const attrs: AttrAst[] = []; const lcElName = splitNsName(nodeName.toLowerCase())[1]; const isTemplateElement = lcElName == TEMPLATE_ELEMENT; element.attrs.forEach(attr => { const hasBinding = this._parseAttr( isTemplateElement, attr, matchableAttrs, elementOrDirectiveProps, animationProps, events, elementOrDirectiveRefs, elementVars); const hasTemplateBinding = this._parseInlineTemplateBinding( attr, templateMatchableAttrs, templateElementOrDirectiveProps, templateElementVars); if (hasTemplateBinding && hasInlineTemplates) { this._reportError( `Can't have multiple template bindings on one element. Use only one attribute named 'template' or prefixed with *`, attr.sourceSpan); } if (!hasBinding && !hasTemplateBinding) { // don't include the bindings as attributes as well in the AST attrs.push(this.visitAttribute(attr, null)); matchableAttrs.push([attr.name, attr.value]); } if (hasTemplateBinding) { hasInlineTemplates = true; } }); const elementCssSelector = createElementCssSelector(nodeName, matchableAttrs); const directiveMetas = this._parseDirectives(this.selectorMatcher, elementCssSelector); const references: ReferenceAst[] = []; const directiveAsts = this._createDirectiveAsts( isTemplateElement, element.name, directiveMetas, elementOrDirectiveProps, elementOrDirectiveRefs, element.sourceSpan, references); const elementProps: BoundElementPropertyAst[] = this._createElementPropertyAsts(element.name, elementOrDirectiveProps, directiveAsts) .concat(animationProps); const isViewRoot = parent.isTemplateElement || hasInlineTemplates; const providerContext = new ProviderElementContext( this.providerViewContext, parent.providerContext, isViewRoot, directiveAsts, attrs, references, element.sourceSpan); const children = html.visitAll( preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this, element.children, ElementContext.create( isTemplateElement, directiveAsts, isTemplateElement ? parent.providerContext : providerContext)); providerContext.afterElement(); // Override the actual selector when the `ngProjectAs` attribute is provided const projectionSelector = isPresent(preparsedElement.projectAs) ? CssSelector.parse(preparsedElement.projectAs)[0] : elementCssSelector; const ngContentIndex = parent.findNgContentIndex(projectionSelector); let parsedElement: TemplateAst; if (preparsedElement.type === PreparsedElementType.NG_CONTENT) { if (isPresent(element.children) && element.children.length > 0) { this._reportError( `<ng-content> element cannot have content. <ng-content> must be immediately followed by </ng-content>`, element.sourceSpan); } parsedElement = new NgContentAst( this.ngContentCount++, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan); } else if (isTemplateElement) { this._assertAllEventsPublishedByDirectives(directiveAsts, events); this._assertNoComponentsNorElementBindingsOnTemplate( directiveAsts, elementProps, element.sourceSpan); parsedElement = new EmbeddedTemplateAst( attrs, events, references, elementVars, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, children, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan); } else { this._assertOnlyOneComponent(directiveAsts, element.sourceSpan); const ngContentIndex = hasInlineTemplates ? null : parent.findNgContentIndex(projectionSelector); parsedElement = new ElementAst( nodeName, attrs, elementProps, events, references, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, children, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan); } if (hasInlineTemplates) { const templateCssSelector = createElementCssSelector(TEMPLATE_ELEMENT, templateMatchableAttrs); const templateDirectiveMetas = this._parseDirectives(this.selectorMatcher, templateCssSelector); const templateDirectiveAsts = this._createDirectiveAsts( true, element.name, templateDirectiveMetas, templateElementOrDirectiveProps, [], element.sourceSpan, []); const templateElementProps: BoundElementPropertyAst[] = this._createElementPropertyAsts( element.name, templateElementOrDirectiveProps, templateDirectiveAsts); this._assertNoComponentsNorElementBindingsOnTemplate( templateDirectiveAsts, templateElementProps, element.sourceSpan); const templateProviderContext = new ProviderElementContext( this.providerViewContext, parent.providerContext, parent.isTemplateElement, templateDirectiveAsts, [], [], element.sourceSpan); templateProviderContext.afterElement(); parsedElement = new EmbeddedTemplateAst( [], [], [], templateElementVars, templateProviderContext.transformedDirectiveAsts, templateProviderContext.transformProviders, templateProviderContext.transformedHasViewContainer, [parsedElement], ngContentIndex, element.sourceSpan); } return parsedElement; } private _parseInlineTemplateBinding( attr: html.Attribute, targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[], targetVars: VariableAst[]): boolean { let templateBindingsSource: string = null; if (this._normalizeAttributeName(attr.name) == TEMPLATE_ATTR) { templateBindingsSource = attr.value; } else if (attr.name.startsWith(TEMPLATE_ATTR_PREFIX)) { const key = attr.name.substring(TEMPLATE_ATTR_PREFIX.length); // remove the star templateBindingsSource = (attr.value.length == 0) ? key : key + ' ' + attr.value; } if (isPresent(templateBindingsSource)) { const bindings = this._parseTemplateBindings(templateBindingsSource, attr.sourceSpan); for (let i = 0; i < bindings.length; i++) { const binding = bindings[i]; if (binding.keyIsVar) { targetVars.push(new VariableAst(binding.key, binding.name, attr.sourceSpan)); } else if (isPresent(binding.expression)) { this._parsePropertyAst( binding.key, binding.expression, attr.sourceSpan, targetMatchableAttrs, targetProps); } else { targetMatchableAttrs.push([binding.key, '']); this._parseLiteralAttr(binding.key, null, attr.sourceSpan, targetProps); } } return true; } return false; } private _parseAttr( isTemplateElement: boolean, attr: html.Attribute, targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[], targetAnimationProps: BoundElementPropertyAst[], targetEvents: BoundEventAst[], targetRefs: ElementOrDirectiveRef[], targetVars: VariableAst[]): boolean { const attrName = this._normalizeAttributeName(attr.name); const attrValue = attr.value; const bindParts = RegExpWrapper.firstMatch(BIND_NAME_REGEXP, attrName); let hasBinding = false; if (isPresent(bindParts)) { hasBinding = true; if (isPresent(bindParts[1])) { // match: bind-prop this._parsePropertyOrAnimation( bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps, targetAnimationProps); } else if (isPresent(bindParts[2])) { // match: var-name / var-name="iden" const identifier = bindParts[8]; if (isTemplateElement) { this._reportError( `"var-" on <template> elements is deprecated. Use "let-" instead!`, attr.sourceSpan, ParseErrorLevel.WARNING); this._parseVariable(identifier, attrValue, attr.sourceSpan, targetVars); } else { this._reportError( `"var-" on non <template> elements is deprecated. Use "ref-" instead!`, attr.sourceSpan, ParseErrorLevel.WARNING); this._parseReference(identifier, attrValue, attr.sourceSpan, targetRefs); } } else if (isPresent(bindParts[3])) { // match: let-name if (isTemplateElement) { const identifier = bindParts[8]; this._parseVariable(identifier, attrValue, attr.sourceSpan, targetVars); } else { this._reportError(`"let-" is only supported on template elements.`, attr.sourceSpan); } } else if (isPresent(bindParts[4])) { // match: ref- / #iden const identifier = bindParts[8]; this._parseReference(identifier, attrValue, attr.sourceSpan, targetRefs); } else if (isPresent(bindParts[5])) { // match: on-event this._parseEvent( bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); } else if (isPresent(bindParts[6])) { // match: bindon-prop this._parsePropertyOrAnimation( bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps, targetAnimationProps); this._parseAssignmentEvent( bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); } else if (isPresent(bindParts[7])) { // match: animate-name if (attrName[0] == '@' && isPresent(attrValue) && attrValue.length > 0) { this._reportError( `Assigning animation triggers via @prop="exp" attributes with an expression is deprecated. Use [@prop]="exp" instead!`, attr.sourceSpan, ParseErrorLevel.WARNING); } this._parseAnimation( bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetAnimationProps); } else if (isPresent(bindParts[9])) { // match: [(expr)] this._parsePropertyOrAnimation( bindParts[9], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps, targetAnimationProps); this._parseAssignmentEvent( bindParts[9], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); } else if (isPresent(bindParts[10])) { // match: [expr] this._parsePropertyOrAnimation( bindParts[10], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps, targetAnimationProps); } else if (isPresent(bindParts[11])) { // match: (event) this._parseEvent( bindParts[11], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); } } else { hasBinding = this._parsePropertyInterpolation( attrName, attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps); } if (!hasBinding) { this._parseLiteralAttr(attrName, attrValue, attr.sourceSpan, targetProps); } return hasBinding; } private _normalizeAttributeName(attrName: string): string { return attrName.toLowerCase().startsWith('data-') ? attrName.substring(5) : attrName; } private _parseVariable( identifier: string, value: string, sourceSpan: ParseSourceSpan, targetVars: VariableAst[]) { if (identifier.indexOf('-') > -1) { this._reportError(`"-" is not allowed in variable names`, sourceSpan); } targetVars.push(new VariableAst(identifier, value, sourceSpan)); } private _parseReference( identifier: string, value: string, sourceSpan: ParseSourceSpan, targetRefs: ElementOrDirectiveRef[]) { if (identifier.indexOf('-') > -1) { this._reportError(`"-" is not allowed in reference names`, sourceSpan); } targetRefs.push(new ElementOrDirectiveRef(identifier, value, sourceSpan)); } private _parsePropertyOrAnimation( name: string, expression: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[], targetAnimationProps: BoundElementPropertyAst[]) { if (name[0] == '@') { this._parseAnimation( name.substr(1), expression, sourceSpan, targetMatchableAttrs, targetAnimationProps); } else { this._parsePropertyAst( name, this._parseBinding(expression, sourceSpan), sourceSpan, targetMatchableAttrs, targetProps); } } private _parseAnimation( name: string, expression: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetAnimationProps: BoundElementPropertyAst[]) { // This will occur when a @trigger is not paired with an expression. // For animations it is valid to not have an expression since */void // states will be applied by angular when the element is attached/detached if (!isPresent(expression) || expression.length == 0) { expression = 'null'; } const ast = this._parseBinding(expression, sourceSpan); targetMatchableAttrs.push([name, ast.source]); targetAnimationProps.push(new BoundElementPropertyAst( name, PropertyBindingType.Animation, SecurityContext.NONE, ast, null, sourceSpan)); } private _parsePropertyInterpolation( name: string, value: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[]): boolean { const expr = this._parseInterpolation(value, sourceSpan); if (isPresent(expr)) { this._parsePropertyAst(name, expr, sourceSpan, targetMatchableAttrs, targetProps); return true; } return false; } private _parsePropertyAst( name: string, ast: ASTWithSource, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[]) { targetMatchableAttrs.push([name, ast.source]); targetProps.push(new BoundElementOrDirectiveProperty(name, ast, false, sourceSpan)); } private _parseAssignmentEvent( name: string, expression: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetEvents: BoundEventAst[]) { this._parseEvent( `${name}Change`, `${expression}=$event`, sourceSpan, targetMatchableAttrs, targetEvents); } private _parseEvent( name: string, expression: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetEvents: BoundEventAst[]) { // long format: 'target: eventName' const parts = splitAtColon(name, [null, name]); const target = parts[0]; const eventName = parts[1]; const ast = this._parseAction(expression, sourceSpan); targetMatchableAttrs.push([name, ast.source]); targetEvents.push(new BoundEventAst(eventName, target, ast, sourceSpan)); // Don't detect directives for event names for now, // so don't add the event name to the matchableAttrs } private _parseLiteralAttr( name: string, value: string, sourceSpan: ParseSourceSpan, targetProps: BoundElementOrDirectiveProperty[]) { targetProps.push(new BoundElementOrDirectiveProperty( name, this._exprParser.wrapLiteralPrimitive(value, ''), true, sourceSpan)); } private _parseDirectives(selectorMatcher: SelectorMatcher, elementCssSelector: CssSelector): CompileDirectiveMetadata[] { // Need to sort the directives so that we get consistent results throughout, // as selectorMatcher uses Maps inside. // Also dedupe directives as they might match more than one time! const directives = ListWrapper.createFixedSize(this.directivesIndex.size); selectorMatcher.match(elementCssSelector, (selector, directive) => { directives[this.directivesIndex.get(directive)] = directive; }); return directives.filter(dir => isPresent(dir)); } private _createDirectiveAsts( isTemplateElement: boolean, elementName: string, directives: CompileDirectiveMetadata[], props: BoundElementOrDirectiveProperty[], elementOrDirectiveRefs: ElementOrDirectiveRef[], elementSourceSpan: ParseSourceSpan, targetReferences: ReferenceAst[]): DirectiveAst[] { const matchedReferences = new Set<string>(); let component: CompileDirectiveMetadata = null; const directiveAsts = directives.map((directive: CompileDirectiveMetadata) => { const sourceSpan = new ParseSourceSpan( elementSourceSpan.start, elementSourceSpan.end, `Directive ${directive.type.name}`); if (directive.isComponent) { component = directive; } const hostProperties: BoundElementPropertyAst[] = []; const hostEvents: BoundEventAst[] = []; const directiveProperties: BoundDirectivePropertyAst[] = []; this._createDirectiveHostPropertyAsts( elementName, directive.hostProperties, sourceSpan, hostProperties); this._createDirectiveHostEventAsts(directive.hostListeners, sourceSpan, hostEvents); this._createDirectivePropertyAsts(directive.inputs, props, directiveProperties); elementOrDirectiveRefs.forEach((elOrDirRef) => { if ((elOrDirRef.value.length === 0 && directive.isComponent) || (directive.exportAs == elOrDirRef.value)) { targetReferences.push(new ReferenceAst( elOrDirRef.name, identifierToken(directive.type), elOrDirRef.sourceSpan)); matchedReferences.add(elOrDirRef.name); } }); return new DirectiveAst( directive, directiveProperties, hostProperties, hostEvents, sourceSpan); }); elementOrDirectiveRefs.forEach((elOrDirRef) => { if (elOrDirRef.value.length > 0) { if (!SetWrapper.has(matchedReferences, elOrDirRef.name)) { this._reportError( `There is no directive with "exportAs" set to "${elOrDirRef.value}"`, elOrDirRef.sourceSpan); } } else if (isBlank(component)) { let refToken: CompileTokenMetadata = null; if (isTemplateElement) { refToken = identifierToken(Identifiers.TemplateRef); } targetReferences.push(new ReferenceAst(elOrDirRef.name, refToken, elOrDirRef.sourceSpan)); } }); // fix syntax highlighting issue: ` return directiveAsts; } private _createDirectiveHostPropertyAsts( elementName: string, hostProps: {[key: string]: string}, sourceSpan: ParseSourceSpan, targetPropertyAsts: BoundElementPropertyAst[]) { if (isPresent(hostProps)) { StringMapWrapper.forEach(hostProps, (expression: string, propName: string) => { const exprAst = this._parseBinding(expression, sourceSpan); targetPropertyAsts.push( this._createElementPropertyAst(elementName, propName, exprAst, sourceSpan)); }); } } private _createDirectiveHostEventAsts( hostListeners: {[key: string]: string}, sourceSpan: ParseSourceSpan, targetEventAsts: BoundEventAst[]) { if (isPresent(hostListeners)) { StringMapWrapper.forEach(hostListeners, (expression: string, propName: string) => { this._parseEvent(propName, expression, sourceSpan, [], targetEventAsts); }); } } private _createDirectivePropertyAsts( directiveProperties: {[key: string]: string}, boundProps: BoundElementOrDirectiveProperty[], targetBoundDirectiveProps: BoundDirectivePropertyAst[]) { if (isPresent(directiveProperties)) { const boundPropsByName = new Map<string, BoundElementOrDirectiveProperty>(); boundProps.forEach(boundProp => { const prevValue = boundPropsByName.get(boundProp.name); if (isBlank(prevValue) || prevValue.isLiteral) { // give [a]="b" a higher precedence than a="b" on the same element boundPropsByName.set(boundProp.name, boundProp); } }); StringMapWrapper.forEach(directiveProperties, (elProp: string, dirProp: string) => { const boundProp = boundPropsByName.get(elProp); // Bindings are optional, so this binding only needs to be set up if an expression is given. if (isPresent(boundProp)) { targetBoundDirectiveProps.push(new BoundDirectivePropertyAst( dirProp, boundProp.name, boundProp.expression, boundProp.sourceSpan)); } }); } } private _createElementPropertyAsts( elementName: string, props: BoundElementOrDirectiveProperty[], directives: DirectiveAst[]): BoundElementPropertyAst[] { const boundElementProps: BoundElementPropertyAst[] = []; const boundDirectivePropsIndex = new Map<string, BoundDirectivePropertyAst>(); directives.forEach((directive: DirectiveAst) => { directive.inputs.forEach((prop: BoundDirectivePropertyAst) => { boundDirectivePropsIndex.set(prop.templateName, prop); }); }); props.forEach((prop: BoundElementOrDirectiveProperty) => { if (!prop.isLiteral && isBlank(boundDirectivePropsIndex.get(prop.name))) { boundElementProps.push(this._createElementPropertyAst( elementName, prop.name, prop.expression, prop.sourceSpan)); } }); return boundElementProps; } private _createElementPropertyAst( elementName: string, name: string, ast: AST, sourceSpan: ParseSourceSpan): BoundElementPropertyAst { let unit: string = null; let bindingType: PropertyBindingType; let boundPropertyName: string; const parts = name.split(PROPERTY_PARTS_SEPARATOR); let securityContext: SecurityContext; if (parts.length === 1) { var partValue = parts[0]; if (partValue[0] == '@') { boundPropertyName = partValue.substr(1); bindingType = PropertyBindingType.Animation; securityContext = SecurityContext.NONE; this._reportError( `Assigning animation triggers within host data as attributes such as "@prop": "exp" is deprecated. Use "[@prop]": "exp" instead!`, sourceSpan, ParseErrorLevel.WARNING); } else { boundPropertyName = this._schemaRegistry.getMappedPropName(partValue); securityContext = this._schemaRegistry.securityContext(elementName, boundPropertyName); bindingType = PropertyBindingType.Property; if (!this._schemaRegistry.hasProperty(elementName, boundPropertyName, this._schemas)) { let errorMsg = `Can't bind to '${boundPropertyName}' since it isn't a known native property`; if (elementName.indexOf('-') !== -1) { errorMsg += `. To ignore this error on custom elements, add the "CUSTOM_ELEMENTS_SCHEMA" to the NgModule of this component`; } this._reportError(errorMsg, sourceSpan); } } } else { if (parts[0] == ATTRIBUTE_PREFIX) { boundPropertyName = parts[1]; if (boundPropertyName.toLowerCase().startsWith('on')) { this._reportError( `Binding to event attribute '${boundPropertyName}' is disallowed ` + `for security reasons, please use (${boundPropertyName.slice(2)})=...`, sourceSpan); } // NB: For security purposes, use the mapped property name, not the attribute name. securityContext = this._schemaRegistry.securityContext( elementName, this._schemaRegistry.getMappedPropName(boundPropertyName)); let nsSeparatorIdx = boundPropertyName.indexOf(':'); if (nsSeparatorIdx > -1) { let ns = boundPropertyName.substring(0, nsSeparatorIdx); let name = boundPropertyName.substring(nsSeparatorIdx + 1); boundPropertyName = mergeNsAndName(ns, name); } bindingType = PropertyBindingType.Attribute; } else if (parts[0] == CLASS_PREFIX) { boundPropertyName = parts[1]; bindingType = PropertyBindingType.Class; securityContext = SecurityContext.NONE; } else if (parts[0] == STYLE_PREFIX) { unit = parts.length > 2 ? parts[2] : null; boundPropertyName = parts[1]; bindingType = PropertyBindingType.Style; securityContext = SecurityContext.STYLE; } else { this._reportError(`Invalid property name '${name}'`, sourceSpan); bindingType = null; securityContext = null; } } return new BoundElementPropertyAst( boundPropertyName, bindingType, securityContext, ast, unit, sourceSpan); } private _findComponentDirectiveNames(directives: DirectiveAst[]): string[] { const componentTypeNames: string[] = []; directives.forEach(directive => { const typeName = directive.directive.type.name; if (directive.directive.isComponent) { componentTypeNames.push(typeName); } }); return componentTypeNames; } private _assertOnlyOneComponent(directives: DirectiveAst[], sourceSpan: ParseSourceSpan) { const componentTypeNames = this._findComponentDirectiveNames(directives); if (componentTypeNames.length > 1) { this._reportError(`More than one component: ${componentTypeNames.join(',')}`, sourceSpan); } } private _assertNoComponentsNorElementBindingsOnTemplate( directives: DirectiveAst[], elementProps: BoundElementPropertyAst[], sourceSpan: ParseSourceSpan) { const componentTypeNames: string[] = this._findComponentDirectiveNames(directives); if (componentTypeNames.length > 0) { this._reportError( `Components on an embedded template: ${componentTypeNames.join(',')}`, sourceSpan); } elementProps.forEach(prop => { this._reportError( `Property binding ${prop.name} not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "directives" section.`, sourceSpan); }); } private _assertAllEventsPublishedByDirectives( directives: DirectiveAst[], events: BoundEventAst[]) { const allDirectiveEvents = new Set<string>(); directives.forEach(directive => { StringMapWrapper.forEach(directive.directive.outputs, (eventName: string) => { allDirectiveEvents.add(eventName); }); }); events.forEach(event => { if (isPresent(event.target) || !SetWrapper.has(allDirectiveEvents, event.name)) { this._reportError( `Event binding ${event.fullName} not emitted by any directive on an embedded template. Make sure that the event name is spelled correctly and all directives are listed in the "directives" section.`, event.sourceSpan); } }); } } class NonBindableVisitor implements html.Visitor { visitElement(ast: html.Element, parent: ElementContext): ElementAst { const preparsedElement = preparseElement(ast); if (preparsedElement.type === PreparsedElementType.SCRIPT || preparsedElement.type === PreparsedElementType.STYLE || preparsedElement.type === PreparsedElementType.STYLESHEET) { // Skipping <script> for security reasons // Skipping <style> and stylesheets as we already processed them // in the StyleCompiler return null; } const attrNameAndValues = ast.attrs.map(attrAst => [attrAst.name, attrAst.value]); const selector = createElementCssSelector(ast.name, attrNameAndValues); const ngContentIndex = parent.findNgContentIndex(selector); const children = html.visitAll(this, ast.children, EMPTY_ELEMENT_CONTEXT); return new ElementAst( ast.name, html.visitAll(this, ast.attrs), [], [], [], [], [], false, children, ngContentIndex, ast.sourceSpan); } visitComment(comment: html.Comment, context: any): any { return null; } visitAttribute(attribute: html.Attribute, context: any): AttrAst { return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan); } visitText(text: html.Text, parent: ElementContext): TextAst { const ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR); return new TextAst(text.value, ngContentIndex, text.sourceSpan); } visitExpansion(expansion: html.Expansion, context: any): any { return expansion; } visitExpansionCase(expansionCase: html.ExpansionCase, context: any): any { return expansionCase; } } class BoundElementOrDirectiveProperty { constructor( public name: string, public expression: AST, public isLiteral: boolean, public sourceSpan: ParseSourceSpan) {} } class ElementOrDirectiveRef { constructor(public name: string, public value: string, public sourceSpan: ParseSourceSpan) {} } export function splitClasses(classAttrValue: string): string[] { return classAttrValue.trim().split(/\s+/g); } class ElementContext { static create( isTemplateElement: boolean, directives: DirectiveAst[], providerContext: ProviderElementContext): ElementContext { const matcher = new SelectorMatcher(); let wildcardNgContentIndex: number = null; const component = directives.find(directive => directive.directive.isComponent); if (isPresent(component)) { const ngContentSelectors = component.directive.template.ngContentSelectors; for (let i = 0; i < ngContentSelectors.length; i++) { const selector = ngContentSelectors[i]; if (selector === '*') { wildcardNgContentIndex = i; } else { matcher.addSelectables(CssSelector.parse(ngContentSelectors[i]), i); } } } return new ElementContext(isTemplateElement, matcher, wildcardNgContentIndex, providerContext); } constructor( public isTemplateElement: boolean, private _ngContentIndexMatcher: SelectorMatcher, private _wildcardNgContentIndex: number, public providerContext: ProviderElementContext) {} findNgContentIndex(selector: CssSelector): number { const ngContentIndices: number[] = []; this._ngContentIndexMatcher.match( selector, (selector, ngContentIndex) => { ngContentIndices.push(ngContentIndex); }); ListWrapper.sort(ngContentIndices); if (isPresent(this._wildcardNgContentIndex)) { ngContentIndices.push(this._wildcardNgContentIndex); } return ngContentIndices.length > 0 ? ngContentIndices[0] : null; } } function createElementCssSelector(elementName: string, matchableAttrs: string[][]): CssSelector { const cssSelector = new CssSelector(); let elNameNoNs = splitNsName(elementName)[1]; cssSelector.setElement(elNameNoNs); for (let i = 0; i < matchableAttrs.length; i++) { let attrName = matchableAttrs[i][0]; let attrNameNoNs = splitNsName(attrName)[1]; let attrValue = matchableAttrs[i][1]; cssSelector.addAttribute(attrNameNoNs, attrValue); if (attrName.toLowerCase() == CLASS_ATTR) { const classes = splitClasses(attrValue); classes.forEach(className => cssSelector.addClassName(className)); } } return cssSelector; } const EMPTY_ELEMENT_CONTEXT = new ElementContext(true, new SelectorMatcher(), null, null); const NON_BINDABLE_VISITOR = new NonBindableVisitor(); export class PipeCollector extends RecursiveAstVisitor { pipes: Set<string> = new Set<string>(); visitPipe(ast: BindingPipe, context: any): any { this.pipes.add(ast.name); ast.exp.visit(this); this.visitAll(ast.args, context); return null; } }
modules/@angular/compiler/src/template_parser/template_parser.ts
1
https://github.com/angular/angular/commit/a55d796c4b4cbe5bc1256339bd398090f58b4d69
[ 0.9934357404708862, 0.01022615097463131, 0.00016280934505630285, 0.0002120919816661626, 0.09689602255821228 ]
{ "id": 1, "code_window": [ " if (elementName.indexOf('-') !== -1) {\n", " errorMsg +=\n", " `. To ignore this error on custom elements, add the \"CUSTOM_ELEMENTS_SCHEMA\" to the NgModule of this component`;\n", " }\n", " this._reportError(errorMsg, sourceSpan);\n", " }\n", " }\n", " } else {\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " `\\n1. If '${elementName}' is an Angular component and it has '${boundPropertyName}' input, then verify that it is part of this module.` +\n", " `\\n2. If '${elementName}' is a Web Component then add \"CUSTOM_ELEMENTS_SCHEMA\" to the '@NgModule.schema' of this component to suppress this message.\\n`;\n" ], "file_path": "modules/@angular/compiler/src/template_parser/template_parser.ts", "type": "replace", "edit_start_line_idx": 820 }
import {verifyNoBrowserErrors} from 'angular2/src/testing/perf_util'; describe('ng2 largetable benchmark', function() { var URL = 'benchmarks/src/page_load/page_load.html'; var runner = global['benchpressRunner']; afterEach(verifyNoBrowserErrors); it('should log the load time', function(done) { runner.sample({ id: 'loadTime', prepare: null, microMetrics: null, userMetrics: {loadTime: 'The time in milliseconds to bootstrap', someConstant: 'Some constant'}, bindings: [ benchpress.bind(benchpress.SizeValidator.SAMPLE_SIZE) .toValue(2), benchpress.bind(benchpress.RegressionSlopeValidator.SAMPLE_SIZE).toValue(2), benchpress.bind(benchpress.RegressionSlopeValidator.METRIC).toValue('someConstant') ], execute: () => { browser.get(URL); } }) .then(report => { expect(report.completeSample.map(val => val.values.someConstant) .every(v => v === 1234567890)) .toBe(true); expect(report.completeSample.map(val => val.values.loadTime) .filter(t => typeof t === 'number' && t > 0) .length) .toBeGreaterThan(1); }) .then(done); }); });
modules/benchmarks/e2e_test/page_load_perf.ts
0
https://github.com/angular/angular/commit/a55d796c4b4cbe5bc1256339bd398090f58b4d69
[ 0.00017513867351226509, 0.00017305441724602133, 0.00017084932187572122, 0.00017311485134996474, 0.0000015177502064034343 ]
{ "id": 1, "code_window": [ " if (elementName.indexOf('-') !== -1) {\n", " errorMsg +=\n", " `. To ignore this error on custom elements, add the \"CUSTOM_ELEMENTS_SCHEMA\" to the NgModule of this component`;\n", " }\n", " this._reportError(errorMsg, sourceSpan);\n", " }\n", " }\n", " } else {\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " `\\n1. If '${elementName}' is an Angular component and it has '${boundPropertyName}' input, then verify that it is part of this module.` +\n", " `\\n2. If '${elementName}' is a Web Component then add \"CUSTOM_ELEMENTS_SCHEMA\" to the '@NgModule.schema' of this component to suppress this message.\\n`;\n" ], "file_path": "modules/@angular/compiler/src/template_parser/template_parser.ts", "type": "replace", "edit_start_line_idx": 820 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @module * @description * This module provides a set of common Pipes. */ export {AsyncPipe} from './pipes/async_pipe'; export {COMMON_PIPES} from './pipes/common_pipes'; export {DatePipe} from './pipes/date_pipe'; export {I18nPluralPipe} from './pipes/i18n_plural_pipe'; export {I18nSelectPipe} from './pipes/i18n_select_pipe'; export {JsonPipe} from './pipes/json_pipe'; export {LowerCasePipe} from './pipes/lowercase_pipe'; export {CurrencyPipe, DecimalPipe, PercentPipe} from './pipes/number_pipe'; export {ReplacePipe} from './pipes/replace_pipe'; export {SlicePipe} from './pipes/slice_pipe'; export {UpperCasePipe} from './pipes/uppercase_pipe';
modules/@angular/common/src/pipes.ts
0
https://github.com/angular/angular/commit/a55d796c4b4cbe5bc1256339bd398090f58b4d69
[ 0.00017485216085333377, 0.00017280330939684063, 0.00017051877512130886, 0.00017303902131970972, 0.0000017769307305570692 ]
{ "id": 1, "code_window": [ " if (elementName.indexOf('-') !== -1) {\n", " errorMsg +=\n", " `. To ignore this error on custom elements, add the \"CUSTOM_ELEMENTS_SCHEMA\" to the NgModule of this component`;\n", " }\n", " this._reportError(errorMsg, sourceSpan);\n", " }\n", " }\n", " } else {\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " `\\n1. If '${elementName}' is an Angular component and it has '${boundPropertyName}' input, then verify that it is part of this module.` +\n", " `\\n2. If '${elementName}' is a Web Component then add \"CUSTOM_ELEMENTS_SCHEMA\" to the '@NgModule.schema' of this component to suppress this message.\\n`;\n" ], "file_path": "modules/@angular/compiler/src/template_parser/template_parser.ts", "type": "replace", "edit_start_line_idx": 820 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {bootstrap} from '@angular/platform-browser-dynamic'; import {Component} from '@angular/core'; import {NgFor} from '@angular/common'; import {Store, Todo, TodoFactory} from './app/TodoStore'; @Component({ selector: 'todo-app', viewProviders: [Store, TodoFactory], templateUrl: 'todo.html', directives: [NgFor] }) class TodoApp { todoEdit: Todo = null; constructor(public todoStore: Store<Todo>, public factory: TodoFactory) {} enterTodo(inputElement: any /** TODO #9100 */): void { this.addTodo(inputElement.value); inputElement.value = ''; } editTodo(todo: Todo): void { this.todoEdit = todo; } doneEditing($event: any /** TODO #9100 */, todo: Todo): void { var which = $event.which; var target = $event.target; if (which === 13) { todo.title = target.value; this.todoEdit = null; } else if (which === 27) { this.todoEdit = null; target.value = todo.title; } } addTodo(newTitle: string): void { this.todoStore.add(this.factory.create(newTitle, false)); } completeMe(todo: Todo): void { todo.completed = !todo.completed; } deleteMe(todo: Todo): void { this.todoStore.remove(todo); } toggleAll($event: any /** TODO #9100 */): void { var isComplete = $event.target.checked; this.todoStore.list.forEach((todo: Todo) => { todo.completed = isComplete; }); } clearCompleted(): void { this.todoStore.removeBy((todo: Todo) => todo.completed); } } export function main() { bootstrap(TodoApp); }
modules/playground/src/todo/index.ts
0
https://github.com/angular/angular/commit/a55d796c4b4cbe5bc1256339bd398090f58b4d69
[ 0.0001764514745445922, 0.0001741693413350731, 0.00017229550576303154, 0.000174198838067241, 0.0000015964433259796351 ]
{ "id": 2, "code_window": [ " expect(() => parse('<p [bar.foo]>', []))\n", " .toThrowError(\n", " `Template parse errors:\\nInvalid property name 'bar.foo' (\"<p [ERROR ->][bar.foo]>\"): TestComp@0:3`);\n", " });\n", "\n", " it('should parse bound properties via [...] and not report them as attributes', () => {\n", " expect(humanizeTplAst(parse('<div [prop]=\"v\">', []))).toEqual([\n", " [ElementAst, 'div'],\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " describe('errors', () => {\n", " it('should throw error when binding to an unkonown property', () => {\n", " expect(() => parse('<my-component [invalidProp]=\"bar\"></my-component>', []))\n", " .toThrowError(`Template parse errors:\n", "Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.\n", "1. If 'my-component' is an Angular component and it has 'invalidProp' input, then verify that it is part of this module.\n", "2. If 'my-component' is a Web Component then add \"CUSTOM_ELEMENTS_SCHEMA\" to the '@NgModule.schema' of this component to suppress this message.\n", " (\"<my-component [ERROR ->][invalidProp]=\"bar\"></my-component>\"): TestComp@0:14`);\n", " });\n", " });\n", "\n" ], "file_path": "modules/@angular/compiler/test/template_parser/template_parser_spec.ts", "type": "add", "edit_start_line_idx": 254 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Inject, Injectable, OpaqueToken, Optional, SchemaMetadata, SecurityContext} from '@angular/core'; import {Console, MAX_INTERPOLATION_VALUES} from '../../core_private'; import {ListWrapper, StringMapWrapper, SetWrapper,} from '../facade/collection'; import {RegExpWrapper, isPresent, isBlank} from '../facade/lang'; import {BaseException} from '../facade/exceptions'; import {EmptyExpr, AST, Interpolation, ASTWithSource, TemplateBinding, RecursiveAstVisitor, BindingPipe, ParserError} from '../expression_parser/ast'; import {Parser} from '../expression_parser/parser'; import {CompileDirectiveMetadata, CompilePipeMetadata, CompileTokenMetadata, removeIdentifierDuplicates,} from '../compile_metadata'; import {HtmlParser, ParseTreeResult} from '../html_parser/html_parser'; import {splitNsName, mergeNsAndName} from '../html_parser/tags'; import {ParseSourceSpan, ParseError, ParseErrorLevel} from '../parse_util'; import {InterpolationConfig} from '../html_parser/interpolation_config'; import {ElementAst, BoundElementPropertyAst, BoundEventAst, ReferenceAst, TemplateAst, TemplateAstVisitor, templateVisitAll, TextAst, BoundTextAst, EmbeddedTemplateAst, AttrAst, NgContentAst, PropertyBindingType, DirectiveAst, BoundDirectivePropertyAst, VariableAst} from './template_ast'; import {CssSelector, SelectorMatcher} from '../selector'; import {ElementSchemaRegistry} from '../schema/element_schema_registry'; import {preparseElement, PreparsedElementType} from './template_preparser'; import {isStyleUrlResolvable} from '../style_url_resolver'; import * as html from '../html_parser/ast'; import {splitAtColon} from '../util'; import {identifierToken, Identifiers} from '../identifiers'; import {expandNodes} from '../html_parser/icu_ast_expander'; import {ProviderElementContext, ProviderViewContext} from '../provider_analyzer'; // Group 1 = "bind-" // Group 2 = "var-" // Group 3 = "let-" // Group 4 = "ref-/#" // Group 5 = "on-" // Group 6 = "bindon-" // Group 7 = "animate-/@" // Group 8 = the identifier after "bind-", "var-/#", or "on-" // Group 9 = identifier inside [()] // Group 10 = identifier inside [] // Group 11 = identifier inside () const BIND_NAME_REGEXP = /^(?:(?:(?:(bind-)|(var-)|(let-)|(ref-|#)|(on-)|(bindon-)|(animate-|@))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/g; const TEMPLATE_ELEMENT = 'template'; const TEMPLATE_ATTR = 'template'; const TEMPLATE_ATTR_PREFIX = '*'; const CLASS_ATTR = 'class'; const PROPERTY_PARTS_SEPARATOR = '.'; const ATTRIBUTE_PREFIX = 'attr'; const CLASS_PREFIX = 'class'; const STYLE_PREFIX = 'style'; const TEXT_CSS_SELECTOR = CssSelector.parse('*')[0]; /** * Provides an array of {@link TemplateAstVisitor}s which will be used to transform * parsed templates before compilation is invoked, allowing custom expression syntax * and other advanced transformations. * * This is currently an internal-only feature and not meant for general use. */ export const TEMPLATE_TRANSFORMS: any = new OpaqueToken('TemplateTransforms'); export class TemplateParseError extends ParseError { constructor(message: string, span: ParseSourceSpan, level: ParseErrorLevel) { super(span, message, level); } } export class TemplateParseResult { constructor(public templateAst?: TemplateAst[], public errors?: ParseError[]) {} } @Injectable() export class TemplateParser { constructor( private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry, private _htmlParser: HtmlParser, private _console: Console, @Optional() @Inject(TEMPLATE_TRANSFORMS) public transforms: TemplateAstVisitor[]) {} parse( component: CompileDirectiveMetadata, template: string, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[], schemas: SchemaMetadata[], templateUrl: string): TemplateAst[] { const result = this.tryParse(component, template, directives, pipes, schemas, templateUrl); const warnings = result.errors.filter(error => error.level === ParseErrorLevel.WARNING); const errors = result.errors.filter(error => error.level === ParseErrorLevel.FATAL); if (warnings.length > 0) { this._console.warn(`Template parse warnings:\n${warnings.join('\n')}`); } if (errors.length > 0) { const errorString = errors.join('\n'); throw new BaseException(`Template parse errors:\n${errorString}`); } return result.templateAst; } tryParse( component: CompileDirectiveMetadata, template: string, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[], schemas: SchemaMetadata[], templateUrl: string): TemplateParseResult { let interpolationConfig: any; if (component.template) { interpolationConfig = InterpolationConfig.fromArray(component.template.interpolation); } let htmlAstWithErrors = this._htmlParser.parse(template, templateUrl, true, interpolationConfig); const errors: ParseError[] = htmlAstWithErrors.errors; let result: TemplateAst[]; if (errors.length == 0) { // Transform ICU messages to angular directives const expandedHtmlAst = expandNodes(htmlAstWithErrors.rootNodes); errors.push(...expandedHtmlAst.errors); htmlAstWithErrors = new ParseTreeResult(expandedHtmlAst.nodes, errors); } if (htmlAstWithErrors.rootNodes.length > 0) { const uniqDirectives = removeIdentifierDuplicates(directives); const uniqPipes = removeIdentifierDuplicates(pipes); const providerViewContext = new ProviderViewContext(component, htmlAstWithErrors.rootNodes[0].sourceSpan); const parseVisitor = new TemplateParseVisitor( providerViewContext, uniqDirectives, uniqPipes, schemas, this._exprParser, this._schemaRegistry); result = html.visitAll(parseVisitor, htmlAstWithErrors.rootNodes, EMPTY_ELEMENT_CONTEXT); errors.push(...parseVisitor.errors, ...providerViewContext.errors); } else { result = []; } this._assertNoReferenceDuplicationOnTemplate(result, errors); if (errors.length > 0) { return new TemplateParseResult(result, errors); } if (isPresent(this.transforms)) { this.transforms.forEach( (transform: TemplateAstVisitor) => { result = templateVisitAll(transform, result); }); } return new TemplateParseResult(result, errors); } /** @internal */ _assertNoReferenceDuplicationOnTemplate(result: TemplateAst[], errors: TemplateParseError[]): void { const existingReferences: string[] = []; result.filter(element => !!(<any>element).references) .forEach(element => (<any>element).references.forEach((reference: ReferenceAst) => { const name = reference.name; if (existingReferences.indexOf(name) < 0) { existingReferences.push(name); } else { const error = new TemplateParseError( `Reference "#${name}" is defined several times`, reference.sourceSpan, ParseErrorLevel.FATAL); errors.push(error); } })); } } class TemplateParseVisitor implements html.Visitor { selectorMatcher: SelectorMatcher; errors: TemplateParseError[] = []; directivesIndex = new Map<CompileDirectiveMetadata, number>(); ngContentCount: number = 0; pipesByName: Map<string, CompilePipeMetadata>; private _interpolationConfig: InterpolationConfig; constructor( public providerViewContext: ProviderViewContext, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[], private _schemas: SchemaMetadata[], private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry) { this.selectorMatcher = new SelectorMatcher(); const tempMeta = providerViewContext.component.template; if (isPresent(tempMeta) && isPresent(tempMeta.interpolation)) { this._interpolationConfig = { start: tempMeta.interpolation[0], end: tempMeta.interpolation[1] }; } ListWrapper.forEachWithIndex( directives, (directive: CompileDirectiveMetadata, index: number) => { const selector = CssSelector.parse(directive.selector); this.selectorMatcher.addSelectables(selector, directive); this.directivesIndex.set(directive, index); }); this.pipesByName = new Map<string, CompilePipeMetadata>(); pipes.forEach(pipe => this.pipesByName.set(pipe.name, pipe)); } private _reportError( message: string, sourceSpan: ParseSourceSpan, level: ParseErrorLevel = ParseErrorLevel.FATAL) { this.errors.push(new TemplateParseError(message, sourceSpan, level)); } private _reportParserErors(errors: ParserError[], sourceSpan: ParseSourceSpan) { for (const error of errors) { this._reportError(error.message, sourceSpan); } } private _parseInterpolation(value: string, sourceSpan: ParseSourceSpan): ASTWithSource { const sourceInfo = sourceSpan.start.toString(); try { const ast = this._exprParser.parseInterpolation(value, sourceInfo, this._interpolationConfig); if (ast) this._reportParserErors(ast.errors, sourceSpan); this._checkPipes(ast, sourceSpan); if (isPresent(ast) && (<Interpolation>ast.ast).expressions.length > MAX_INTERPOLATION_VALUES) { throw new BaseException( `Only support at most ${MAX_INTERPOLATION_VALUES} interpolation values!`); } return ast; } catch (e) { this._reportError(`${e}`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); } } private _parseAction(value: string, sourceSpan: ParseSourceSpan): ASTWithSource { const sourceInfo = sourceSpan.start.toString(); try { const ast = this._exprParser.parseAction(value, sourceInfo, this._interpolationConfig); if (ast) { this._reportParserErors(ast.errors, sourceSpan); } if (!ast || ast.ast instanceof EmptyExpr) { this._reportError(`Empty expressions are not allowed`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); } this._checkPipes(ast, sourceSpan); return ast; } catch (e) { this._reportError(`${e}`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); } } private _parseBinding(value: string, sourceSpan: ParseSourceSpan): ASTWithSource { const sourceInfo = sourceSpan.start.toString(); try { const ast = this._exprParser.parseBinding(value, sourceInfo, this._interpolationConfig); if (ast) this._reportParserErors(ast.errors, sourceSpan); this._checkPipes(ast, sourceSpan); return ast; } catch (e) { this._reportError(`${e}`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); } } private _parseTemplateBindings(value: string, sourceSpan: ParseSourceSpan): TemplateBinding[] { const sourceInfo = sourceSpan.start.toString(); try { const bindingsResult = this._exprParser.parseTemplateBindings(value, sourceInfo); this._reportParserErors(bindingsResult.errors, sourceSpan); bindingsResult.templateBindings.forEach((binding) => { if (isPresent(binding.expression)) { this._checkPipes(binding.expression, sourceSpan); } }); bindingsResult.warnings.forEach( (warning) => { this._reportError(warning, sourceSpan, ParseErrorLevel.WARNING); }); return bindingsResult.templateBindings; } catch (e) { this._reportError(`${e}`, sourceSpan); return []; } } private _checkPipes(ast: ASTWithSource, sourceSpan: ParseSourceSpan) { if (isPresent(ast)) { const collector = new PipeCollector(); ast.visit(collector); collector.pipes.forEach((pipeName) => { if (!this.pipesByName.has(pipeName)) { this._reportError(`The pipe '${pipeName}' could not be found`, sourceSpan); } }); } } visitExpansion(expansion: html.Expansion, context: any): any { return null; } visitExpansionCase(expansionCase: html.ExpansionCase, context: any): any { return null; } visitText(text: html.Text, parent: ElementContext): any { const ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR); const expr = this._parseInterpolation(text.value, text.sourceSpan); if (isPresent(expr)) { return new BoundTextAst(expr, ngContentIndex, text.sourceSpan); } else { return new TextAst(text.value, ngContentIndex, text.sourceSpan); } } visitAttribute(attribute: html.Attribute, contex: any): any { return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan); } visitComment(comment: html.Comment, context: any): any { return null; } visitElement(element: html.Element, parent: ElementContext): any { const nodeName = element.name; const preparsedElement = preparseElement(element); if (preparsedElement.type === PreparsedElementType.SCRIPT || preparsedElement.type === PreparsedElementType.STYLE) { // Skipping <script> for security reasons // Skipping <style> as we already processed them // in the StyleCompiler return null; } if (preparsedElement.type === PreparsedElementType.STYLESHEET && isStyleUrlResolvable(preparsedElement.hrefAttr)) { // Skipping stylesheets with either relative urls or package scheme as we already processed // them in the StyleCompiler return null; } const matchableAttrs: string[][] = []; const elementOrDirectiveProps: BoundElementOrDirectiveProperty[] = []; const elementOrDirectiveRefs: ElementOrDirectiveRef[] = []; const elementVars: VariableAst[] = []; const animationProps: BoundElementPropertyAst[] = []; const events: BoundEventAst[] = []; const templateElementOrDirectiveProps: BoundElementOrDirectiveProperty[] = []; const templateMatchableAttrs: string[][] = []; const templateElementVars: VariableAst[] = []; let hasInlineTemplates = false; const attrs: AttrAst[] = []; const lcElName = splitNsName(nodeName.toLowerCase())[1]; const isTemplateElement = lcElName == TEMPLATE_ELEMENT; element.attrs.forEach(attr => { const hasBinding = this._parseAttr( isTemplateElement, attr, matchableAttrs, elementOrDirectiveProps, animationProps, events, elementOrDirectiveRefs, elementVars); const hasTemplateBinding = this._parseInlineTemplateBinding( attr, templateMatchableAttrs, templateElementOrDirectiveProps, templateElementVars); if (hasTemplateBinding && hasInlineTemplates) { this._reportError( `Can't have multiple template bindings on one element. Use only one attribute named 'template' or prefixed with *`, attr.sourceSpan); } if (!hasBinding && !hasTemplateBinding) { // don't include the bindings as attributes as well in the AST attrs.push(this.visitAttribute(attr, null)); matchableAttrs.push([attr.name, attr.value]); } if (hasTemplateBinding) { hasInlineTemplates = true; } }); const elementCssSelector = createElementCssSelector(nodeName, matchableAttrs); const directiveMetas = this._parseDirectives(this.selectorMatcher, elementCssSelector); const references: ReferenceAst[] = []; const directiveAsts = this._createDirectiveAsts( isTemplateElement, element.name, directiveMetas, elementOrDirectiveProps, elementOrDirectiveRefs, element.sourceSpan, references); const elementProps: BoundElementPropertyAst[] = this._createElementPropertyAsts(element.name, elementOrDirectiveProps, directiveAsts) .concat(animationProps); const isViewRoot = parent.isTemplateElement || hasInlineTemplates; const providerContext = new ProviderElementContext( this.providerViewContext, parent.providerContext, isViewRoot, directiveAsts, attrs, references, element.sourceSpan); const children = html.visitAll( preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this, element.children, ElementContext.create( isTemplateElement, directiveAsts, isTemplateElement ? parent.providerContext : providerContext)); providerContext.afterElement(); // Override the actual selector when the `ngProjectAs` attribute is provided const projectionSelector = isPresent(preparsedElement.projectAs) ? CssSelector.parse(preparsedElement.projectAs)[0] : elementCssSelector; const ngContentIndex = parent.findNgContentIndex(projectionSelector); let parsedElement: TemplateAst; if (preparsedElement.type === PreparsedElementType.NG_CONTENT) { if (isPresent(element.children) && element.children.length > 0) { this._reportError( `<ng-content> element cannot have content. <ng-content> must be immediately followed by </ng-content>`, element.sourceSpan); } parsedElement = new NgContentAst( this.ngContentCount++, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan); } else if (isTemplateElement) { this._assertAllEventsPublishedByDirectives(directiveAsts, events); this._assertNoComponentsNorElementBindingsOnTemplate( directiveAsts, elementProps, element.sourceSpan); parsedElement = new EmbeddedTemplateAst( attrs, events, references, elementVars, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, children, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan); } else { this._assertOnlyOneComponent(directiveAsts, element.sourceSpan); const ngContentIndex = hasInlineTemplates ? null : parent.findNgContentIndex(projectionSelector); parsedElement = new ElementAst( nodeName, attrs, elementProps, events, references, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, children, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan); } if (hasInlineTemplates) { const templateCssSelector = createElementCssSelector(TEMPLATE_ELEMENT, templateMatchableAttrs); const templateDirectiveMetas = this._parseDirectives(this.selectorMatcher, templateCssSelector); const templateDirectiveAsts = this._createDirectiveAsts( true, element.name, templateDirectiveMetas, templateElementOrDirectiveProps, [], element.sourceSpan, []); const templateElementProps: BoundElementPropertyAst[] = this._createElementPropertyAsts( element.name, templateElementOrDirectiveProps, templateDirectiveAsts); this._assertNoComponentsNorElementBindingsOnTemplate( templateDirectiveAsts, templateElementProps, element.sourceSpan); const templateProviderContext = new ProviderElementContext( this.providerViewContext, parent.providerContext, parent.isTemplateElement, templateDirectiveAsts, [], [], element.sourceSpan); templateProviderContext.afterElement(); parsedElement = new EmbeddedTemplateAst( [], [], [], templateElementVars, templateProviderContext.transformedDirectiveAsts, templateProviderContext.transformProviders, templateProviderContext.transformedHasViewContainer, [parsedElement], ngContentIndex, element.sourceSpan); } return parsedElement; } private _parseInlineTemplateBinding( attr: html.Attribute, targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[], targetVars: VariableAst[]): boolean { let templateBindingsSource: string = null; if (this._normalizeAttributeName(attr.name) == TEMPLATE_ATTR) { templateBindingsSource = attr.value; } else if (attr.name.startsWith(TEMPLATE_ATTR_PREFIX)) { const key = attr.name.substring(TEMPLATE_ATTR_PREFIX.length); // remove the star templateBindingsSource = (attr.value.length == 0) ? key : key + ' ' + attr.value; } if (isPresent(templateBindingsSource)) { const bindings = this._parseTemplateBindings(templateBindingsSource, attr.sourceSpan); for (let i = 0; i < bindings.length; i++) { const binding = bindings[i]; if (binding.keyIsVar) { targetVars.push(new VariableAst(binding.key, binding.name, attr.sourceSpan)); } else if (isPresent(binding.expression)) { this._parsePropertyAst( binding.key, binding.expression, attr.sourceSpan, targetMatchableAttrs, targetProps); } else { targetMatchableAttrs.push([binding.key, '']); this._parseLiteralAttr(binding.key, null, attr.sourceSpan, targetProps); } } return true; } return false; } private _parseAttr( isTemplateElement: boolean, attr: html.Attribute, targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[], targetAnimationProps: BoundElementPropertyAst[], targetEvents: BoundEventAst[], targetRefs: ElementOrDirectiveRef[], targetVars: VariableAst[]): boolean { const attrName = this._normalizeAttributeName(attr.name); const attrValue = attr.value; const bindParts = RegExpWrapper.firstMatch(BIND_NAME_REGEXP, attrName); let hasBinding = false; if (isPresent(bindParts)) { hasBinding = true; if (isPresent(bindParts[1])) { // match: bind-prop this._parsePropertyOrAnimation( bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps, targetAnimationProps); } else if (isPresent(bindParts[2])) { // match: var-name / var-name="iden" const identifier = bindParts[8]; if (isTemplateElement) { this._reportError( `"var-" on <template> elements is deprecated. Use "let-" instead!`, attr.sourceSpan, ParseErrorLevel.WARNING); this._parseVariable(identifier, attrValue, attr.sourceSpan, targetVars); } else { this._reportError( `"var-" on non <template> elements is deprecated. Use "ref-" instead!`, attr.sourceSpan, ParseErrorLevel.WARNING); this._parseReference(identifier, attrValue, attr.sourceSpan, targetRefs); } } else if (isPresent(bindParts[3])) { // match: let-name if (isTemplateElement) { const identifier = bindParts[8]; this._parseVariable(identifier, attrValue, attr.sourceSpan, targetVars); } else { this._reportError(`"let-" is only supported on template elements.`, attr.sourceSpan); } } else if (isPresent(bindParts[4])) { // match: ref- / #iden const identifier = bindParts[8]; this._parseReference(identifier, attrValue, attr.sourceSpan, targetRefs); } else if (isPresent(bindParts[5])) { // match: on-event this._parseEvent( bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); } else if (isPresent(bindParts[6])) { // match: bindon-prop this._parsePropertyOrAnimation( bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps, targetAnimationProps); this._parseAssignmentEvent( bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); } else if (isPresent(bindParts[7])) { // match: animate-name if (attrName[0] == '@' && isPresent(attrValue) && attrValue.length > 0) { this._reportError( `Assigning animation triggers via @prop="exp" attributes with an expression is deprecated. Use [@prop]="exp" instead!`, attr.sourceSpan, ParseErrorLevel.WARNING); } this._parseAnimation( bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetAnimationProps); } else if (isPresent(bindParts[9])) { // match: [(expr)] this._parsePropertyOrAnimation( bindParts[9], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps, targetAnimationProps); this._parseAssignmentEvent( bindParts[9], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); } else if (isPresent(bindParts[10])) { // match: [expr] this._parsePropertyOrAnimation( bindParts[10], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps, targetAnimationProps); } else if (isPresent(bindParts[11])) { // match: (event) this._parseEvent( bindParts[11], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); } } else { hasBinding = this._parsePropertyInterpolation( attrName, attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps); } if (!hasBinding) { this._parseLiteralAttr(attrName, attrValue, attr.sourceSpan, targetProps); } return hasBinding; } private _normalizeAttributeName(attrName: string): string { return attrName.toLowerCase().startsWith('data-') ? attrName.substring(5) : attrName; } private _parseVariable( identifier: string, value: string, sourceSpan: ParseSourceSpan, targetVars: VariableAst[]) { if (identifier.indexOf('-') > -1) { this._reportError(`"-" is not allowed in variable names`, sourceSpan); } targetVars.push(new VariableAst(identifier, value, sourceSpan)); } private _parseReference( identifier: string, value: string, sourceSpan: ParseSourceSpan, targetRefs: ElementOrDirectiveRef[]) { if (identifier.indexOf('-') > -1) { this._reportError(`"-" is not allowed in reference names`, sourceSpan); } targetRefs.push(new ElementOrDirectiveRef(identifier, value, sourceSpan)); } private _parsePropertyOrAnimation( name: string, expression: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[], targetAnimationProps: BoundElementPropertyAst[]) { if (name[0] == '@') { this._parseAnimation( name.substr(1), expression, sourceSpan, targetMatchableAttrs, targetAnimationProps); } else { this._parsePropertyAst( name, this._parseBinding(expression, sourceSpan), sourceSpan, targetMatchableAttrs, targetProps); } } private _parseAnimation( name: string, expression: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetAnimationProps: BoundElementPropertyAst[]) { // This will occur when a @trigger is not paired with an expression. // For animations it is valid to not have an expression since */void // states will be applied by angular when the element is attached/detached if (!isPresent(expression) || expression.length == 0) { expression = 'null'; } const ast = this._parseBinding(expression, sourceSpan); targetMatchableAttrs.push([name, ast.source]); targetAnimationProps.push(new BoundElementPropertyAst( name, PropertyBindingType.Animation, SecurityContext.NONE, ast, null, sourceSpan)); } private _parsePropertyInterpolation( name: string, value: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[]): boolean { const expr = this._parseInterpolation(value, sourceSpan); if (isPresent(expr)) { this._parsePropertyAst(name, expr, sourceSpan, targetMatchableAttrs, targetProps); return true; } return false; } private _parsePropertyAst( name: string, ast: ASTWithSource, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[]) { targetMatchableAttrs.push([name, ast.source]); targetProps.push(new BoundElementOrDirectiveProperty(name, ast, false, sourceSpan)); } private _parseAssignmentEvent( name: string, expression: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetEvents: BoundEventAst[]) { this._parseEvent( `${name}Change`, `${expression}=$event`, sourceSpan, targetMatchableAttrs, targetEvents); } private _parseEvent( name: string, expression: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetEvents: BoundEventAst[]) { // long format: 'target: eventName' const parts = splitAtColon(name, [null, name]); const target = parts[0]; const eventName = parts[1]; const ast = this._parseAction(expression, sourceSpan); targetMatchableAttrs.push([name, ast.source]); targetEvents.push(new BoundEventAst(eventName, target, ast, sourceSpan)); // Don't detect directives for event names for now, // so don't add the event name to the matchableAttrs } private _parseLiteralAttr( name: string, value: string, sourceSpan: ParseSourceSpan, targetProps: BoundElementOrDirectiveProperty[]) { targetProps.push(new BoundElementOrDirectiveProperty( name, this._exprParser.wrapLiteralPrimitive(value, ''), true, sourceSpan)); } private _parseDirectives(selectorMatcher: SelectorMatcher, elementCssSelector: CssSelector): CompileDirectiveMetadata[] { // Need to sort the directives so that we get consistent results throughout, // as selectorMatcher uses Maps inside. // Also dedupe directives as they might match more than one time! const directives = ListWrapper.createFixedSize(this.directivesIndex.size); selectorMatcher.match(elementCssSelector, (selector, directive) => { directives[this.directivesIndex.get(directive)] = directive; }); return directives.filter(dir => isPresent(dir)); } private _createDirectiveAsts( isTemplateElement: boolean, elementName: string, directives: CompileDirectiveMetadata[], props: BoundElementOrDirectiveProperty[], elementOrDirectiveRefs: ElementOrDirectiveRef[], elementSourceSpan: ParseSourceSpan, targetReferences: ReferenceAst[]): DirectiveAst[] { const matchedReferences = new Set<string>(); let component: CompileDirectiveMetadata = null; const directiveAsts = directives.map((directive: CompileDirectiveMetadata) => { const sourceSpan = new ParseSourceSpan( elementSourceSpan.start, elementSourceSpan.end, `Directive ${directive.type.name}`); if (directive.isComponent) { component = directive; } const hostProperties: BoundElementPropertyAst[] = []; const hostEvents: BoundEventAst[] = []; const directiveProperties: BoundDirectivePropertyAst[] = []; this._createDirectiveHostPropertyAsts( elementName, directive.hostProperties, sourceSpan, hostProperties); this._createDirectiveHostEventAsts(directive.hostListeners, sourceSpan, hostEvents); this._createDirectivePropertyAsts(directive.inputs, props, directiveProperties); elementOrDirectiveRefs.forEach((elOrDirRef) => { if ((elOrDirRef.value.length === 0 && directive.isComponent) || (directive.exportAs == elOrDirRef.value)) { targetReferences.push(new ReferenceAst( elOrDirRef.name, identifierToken(directive.type), elOrDirRef.sourceSpan)); matchedReferences.add(elOrDirRef.name); } }); return new DirectiveAst( directive, directiveProperties, hostProperties, hostEvents, sourceSpan); }); elementOrDirectiveRefs.forEach((elOrDirRef) => { if (elOrDirRef.value.length > 0) { if (!SetWrapper.has(matchedReferences, elOrDirRef.name)) { this._reportError( `There is no directive with "exportAs" set to "${elOrDirRef.value}"`, elOrDirRef.sourceSpan); } } else if (isBlank(component)) { let refToken: CompileTokenMetadata = null; if (isTemplateElement) { refToken = identifierToken(Identifiers.TemplateRef); } targetReferences.push(new ReferenceAst(elOrDirRef.name, refToken, elOrDirRef.sourceSpan)); } }); // fix syntax highlighting issue: ` return directiveAsts; } private _createDirectiveHostPropertyAsts( elementName: string, hostProps: {[key: string]: string}, sourceSpan: ParseSourceSpan, targetPropertyAsts: BoundElementPropertyAst[]) { if (isPresent(hostProps)) { StringMapWrapper.forEach(hostProps, (expression: string, propName: string) => { const exprAst = this._parseBinding(expression, sourceSpan); targetPropertyAsts.push( this._createElementPropertyAst(elementName, propName, exprAst, sourceSpan)); }); } } private _createDirectiveHostEventAsts( hostListeners: {[key: string]: string}, sourceSpan: ParseSourceSpan, targetEventAsts: BoundEventAst[]) { if (isPresent(hostListeners)) { StringMapWrapper.forEach(hostListeners, (expression: string, propName: string) => { this._parseEvent(propName, expression, sourceSpan, [], targetEventAsts); }); } } private _createDirectivePropertyAsts( directiveProperties: {[key: string]: string}, boundProps: BoundElementOrDirectiveProperty[], targetBoundDirectiveProps: BoundDirectivePropertyAst[]) { if (isPresent(directiveProperties)) { const boundPropsByName = new Map<string, BoundElementOrDirectiveProperty>(); boundProps.forEach(boundProp => { const prevValue = boundPropsByName.get(boundProp.name); if (isBlank(prevValue) || prevValue.isLiteral) { // give [a]="b" a higher precedence than a="b" on the same element boundPropsByName.set(boundProp.name, boundProp); } }); StringMapWrapper.forEach(directiveProperties, (elProp: string, dirProp: string) => { const boundProp = boundPropsByName.get(elProp); // Bindings are optional, so this binding only needs to be set up if an expression is given. if (isPresent(boundProp)) { targetBoundDirectiveProps.push(new BoundDirectivePropertyAst( dirProp, boundProp.name, boundProp.expression, boundProp.sourceSpan)); } }); } } private _createElementPropertyAsts( elementName: string, props: BoundElementOrDirectiveProperty[], directives: DirectiveAst[]): BoundElementPropertyAst[] { const boundElementProps: BoundElementPropertyAst[] = []; const boundDirectivePropsIndex = new Map<string, BoundDirectivePropertyAst>(); directives.forEach((directive: DirectiveAst) => { directive.inputs.forEach((prop: BoundDirectivePropertyAst) => { boundDirectivePropsIndex.set(prop.templateName, prop); }); }); props.forEach((prop: BoundElementOrDirectiveProperty) => { if (!prop.isLiteral && isBlank(boundDirectivePropsIndex.get(prop.name))) { boundElementProps.push(this._createElementPropertyAst( elementName, prop.name, prop.expression, prop.sourceSpan)); } }); return boundElementProps; } private _createElementPropertyAst( elementName: string, name: string, ast: AST, sourceSpan: ParseSourceSpan): BoundElementPropertyAst { let unit: string = null; let bindingType: PropertyBindingType; let boundPropertyName: string; const parts = name.split(PROPERTY_PARTS_SEPARATOR); let securityContext: SecurityContext; if (parts.length === 1) { var partValue = parts[0]; if (partValue[0] == '@') { boundPropertyName = partValue.substr(1); bindingType = PropertyBindingType.Animation; securityContext = SecurityContext.NONE; this._reportError( `Assigning animation triggers within host data as attributes such as "@prop": "exp" is deprecated. Use "[@prop]": "exp" instead!`, sourceSpan, ParseErrorLevel.WARNING); } else { boundPropertyName = this._schemaRegistry.getMappedPropName(partValue); securityContext = this._schemaRegistry.securityContext(elementName, boundPropertyName); bindingType = PropertyBindingType.Property; if (!this._schemaRegistry.hasProperty(elementName, boundPropertyName, this._schemas)) { let errorMsg = `Can't bind to '${boundPropertyName}' since it isn't a known native property`; if (elementName.indexOf('-') !== -1) { errorMsg += `. To ignore this error on custom elements, add the "CUSTOM_ELEMENTS_SCHEMA" to the NgModule of this component`; } this._reportError(errorMsg, sourceSpan); } } } else { if (parts[0] == ATTRIBUTE_PREFIX) { boundPropertyName = parts[1]; if (boundPropertyName.toLowerCase().startsWith('on')) { this._reportError( `Binding to event attribute '${boundPropertyName}' is disallowed ` + `for security reasons, please use (${boundPropertyName.slice(2)})=...`, sourceSpan); } // NB: For security purposes, use the mapped property name, not the attribute name. securityContext = this._schemaRegistry.securityContext( elementName, this._schemaRegistry.getMappedPropName(boundPropertyName)); let nsSeparatorIdx = boundPropertyName.indexOf(':'); if (nsSeparatorIdx > -1) { let ns = boundPropertyName.substring(0, nsSeparatorIdx); let name = boundPropertyName.substring(nsSeparatorIdx + 1); boundPropertyName = mergeNsAndName(ns, name); } bindingType = PropertyBindingType.Attribute; } else if (parts[0] == CLASS_PREFIX) { boundPropertyName = parts[1]; bindingType = PropertyBindingType.Class; securityContext = SecurityContext.NONE; } else if (parts[0] == STYLE_PREFIX) { unit = parts.length > 2 ? parts[2] : null; boundPropertyName = parts[1]; bindingType = PropertyBindingType.Style; securityContext = SecurityContext.STYLE; } else { this._reportError(`Invalid property name '${name}'`, sourceSpan); bindingType = null; securityContext = null; } } return new BoundElementPropertyAst( boundPropertyName, bindingType, securityContext, ast, unit, sourceSpan); } private _findComponentDirectiveNames(directives: DirectiveAst[]): string[] { const componentTypeNames: string[] = []; directives.forEach(directive => { const typeName = directive.directive.type.name; if (directive.directive.isComponent) { componentTypeNames.push(typeName); } }); return componentTypeNames; } private _assertOnlyOneComponent(directives: DirectiveAst[], sourceSpan: ParseSourceSpan) { const componentTypeNames = this._findComponentDirectiveNames(directives); if (componentTypeNames.length > 1) { this._reportError(`More than one component: ${componentTypeNames.join(',')}`, sourceSpan); } } private _assertNoComponentsNorElementBindingsOnTemplate( directives: DirectiveAst[], elementProps: BoundElementPropertyAst[], sourceSpan: ParseSourceSpan) { const componentTypeNames: string[] = this._findComponentDirectiveNames(directives); if (componentTypeNames.length > 0) { this._reportError( `Components on an embedded template: ${componentTypeNames.join(',')}`, sourceSpan); } elementProps.forEach(prop => { this._reportError( `Property binding ${prop.name} not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "directives" section.`, sourceSpan); }); } private _assertAllEventsPublishedByDirectives( directives: DirectiveAst[], events: BoundEventAst[]) { const allDirectiveEvents = new Set<string>(); directives.forEach(directive => { StringMapWrapper.forEach(directive.directive.outputs, (eventName: string) => { allDirectiveEvents.add(eventName); }); }); events.forEach(event => { if (isPresent(event.target) || !SetWrapper.has(allDirectiveEvents, event.name)) { this._reportError( `Event binding ${event.fullName} not emitted by any directive on an embedded template. Make sure that the event name is spelled correctly and all directives are listed in the "directives" section.`, event.sourceSpan); } }); } } class NonBindableVisitor implements html.Visitor { visitElement(ast: html.Element, parent: ElementContext): ElementAst { const preparsedElement = preparseElement(ast); if (preparsedElement.type === PreparsedElementType.SCRIPT || preparsedElement.type === PreparsedElementType.STYLE || preparsedElement.type === PreparsedElementType.STYLESHEET) { // Skipping <script> for security reasons // Skipping <style> and stylesheets as we already processed them // in the StyleCompiler return null; } const attrNameAndValues = ast.attrs.map(attrAst => [attrAst.name, attrAst.value]); const selector = createElementCssSelector(ast.name, attrNameAndValues); const ngContentIndex = parent.findNgContentIndex(selector); const children = html.visitAll(this, ast.children, EMPTY_ELEMENT_CONTEXT); return new ElementAst( ast.name, html.visitAll(this, ast.attrs), [], [], [], [], [], false, children, ngContentIndex, ast.sourceSpan); } visitComment(comment: html.Comment, context: any): any { return null; } visitAttribute(attribute: html.Attribute, context: any): AttrAst { return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan); } visitText(text: html.Text, parent: ElementContext): TextAst { const ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR); return new TextAst(text.value, ngContentIndex, text.sourceSpan); } visitExpansion(expansion: html.Expansion, context: any): any { return expansion; } visitExpansionCase(expansionCase: html.ExpansionCase, context: any): any { return expansionCase; } } class BoundElementOrDirectiveProperty { constructor( public name: string, public expression: AST, public isLiteral: boolean, public sourceSpan: ParseSourceSpan) {} } class ElementOrDirectiveRef { constructor(public name: string, public value: string, public sourceSpan: ParseSourceSpan) {} } export function splitClasses(classAttrValue: string): string[] { return classAttrValue.trim().split(/\s+/g); } class ElementContext { static create( isTemplateElement: boolean, directives: DirectiveAst[], providerContext: ProviderElementContext): ElementContext { const matcher = new SelectorMatcher(); let wildcardNgContentIndex: number = null; const component = directives.find(directive => directive.directive.isComponent); if (isPresent(component)) { const ngContentSelectors = component.directive.template.ngContentSelectors; for (let i = 0; i < ngContentSelectors.length; i++) { const selector = ngContentSelectors[i]; if (selector === '*') { wildcardNgContentIndex = i; } else { matcher.addSelectables(CssSelector.parse(ngContentSelectors[i]), i); } } } return new ElementContext(isTemplateElement, matcher, wildcardNgContentIndex, providerContext); } constructor( public isTemplateElement: boolean, private _ngContentIndexMatcher: SelectorMatcher, private _wildcardNgContentIndex: number, public providerContext: ProviderElementContext) {} findNgContentIndex(selector: CssSelector): number { const ngContentIndices: number[] = []; this._ngContentIndexMatcher.match( selector, (selector, ngContentIndex) => { ngContentIndices.push(ngContentIndex); }); ListWrapper.sort(ngContentIndices); if (isPresent(this._wildcardNgContentIndex)) { ngContentIndices.push(this._wildcardNgContentIndex); } return ngContentIndices.length > 0 ? ngContentIndices[0] : null; } } function createElementCssSelector(elementName: string, matchableAttrs: string[][]): CssSelector { const cssSelector = new CssSelector(); let elNameNoNs = splitNsName(elementName)[1]; cssSelector.setElement(elNameNoNs); for (let i = 0; i < matchableAttrs.length; i++) { let attrName = matchableAttrs[i][0]; let attrNameNoNs = splitNsName(attrName)[1]; let attrValue = matchableAttrs[i][1]; cssSelector.addAttribute(attrNameNoNs, attrValue); if (attrName.toLowerCase() == CLASS_ATTR) { const classes = splitClasses(attrValue); classes.forEach(className => cssSelector.addClassName(className)); } } return cssSelector; } const EMPTY_ELEMENT_CONTEXT = new ElementContext(true, new SelectorMatcher(), null, null); const NON_BINDABLE_VISITOR = new NonBindableVisitor(); export class PipeCollector extends RecursiveAstVisitor { pipes: Set<string> = new Set<string>(); visitPipe(ast: BindingPipe, context: any): any { this.pipes.add(ast.name); ast.exp.visit(this); this.visitAll(ast.args, context); return null; } }
modules/@angular/compiler/src/template_parser/template_parser.ts
1
https://github.com/angular/angular/commit/a55d796c4b4cbe5bc1256339bd398090f58b4d69
[ 0.005582696292549372, 0.00036274531157687306, 0.00016305326425936073, 0.00017543253488838673, 0.0006257473141886294 ]
{ "id": 2, "code_window": [ " expect(() => parse('<p [bar.foo]>', []))\n", " .toThrowError(\n", " `Template parse errors:\\nInvalid property name 'bar.foo' (\"<p [ERROR ->][bar.foo]>\"): TestComp@0:3`);\n", " });\n", "\n", " it('should parse bound properties via [...] and not report them as attributes', () => {\n", " expect(humanizeTplAst(parse('<div [prop]=\"v\">', []))).toEqual([\n", " [ElementAst, 'div'],\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " describe('errors', () => {\n", " it('should throw error when binding to an unkonown property', () => {\n", " expect(() => parse('<my-component [invalidProp]=\"bar\"></my-component>', []))\n", " .toThrowError(`Template parse errors:\n", "Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.\n", "1. If 'my-component' is an Angular component and it has 'invalidProp' input, then verify that it is part of this module.\n", "2. If 'my-component' is a Web Component then add \"CUSTOM_ELEMENTS_SCHEMA\" to the '@NgModule.schema' of this component to suppress this message.\n", " (\"<my-component [ERROR ->][invalidProp]=\"bar\"></my-component>\"): TestComp@0:14`);\n", " });\n", " });\n", "\n" ], "file_path": "modules/@angular/compiler/test/template_parser/template_parser_spec.ts", "type": "add", "edit_start_line_idx": 254 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import './init'; import * as fs from 'fs'; import * as path from 'path'; describe('template i18n extraction output', () => { const outDir = ''; it('should extract i18n messages', () => { const EXPECTED = `<? xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE messagebundle [ <!ELEMENT messagebundle (msg)*> <!ATTLIST messagebundle class CDATA #IMPLIED> <!ELEMENT msg (#PCDATA|ph|source)*> <!ATTLIST msg id CDATA #IMPLIED> <!ATTLIST msg seq CDATA #IMPLIED> <!ATTLIST msg name CDATA #IMPLIED> <!ATTLIST msg desc CDATA #IMPLIED> <!ATTLIST msg meaning CDATA #IMPLIED> <!ATTLIST msg obsolete (obsolete) #IMPLIED> <!ATTLIST msg xml:space (default|preserve) "default"> <!ATTLIST msg is_hidden CDATA #IMPLIED> <!ELEMENT source (#PCDATA)> <!ELEMENT ph (#PCDATA|ex)*> <!ATTLIST ph name CDATA #REQUIRED> <!ELEMENT ex (#PCDATA)> ]> <messagebundle> <msg id="5a2858f1" desc="desc" meaning="meaning">translate me</msg> </messagebundle>`; const xmbOutput = path.join(outDir, 'messages.xmb'); expect(fs.existsSync(xmbOutput)).toBeTruthy(); const xmb = fs.readFileSync(xmbOutput, {encoding: 'utf-8'}); expect(xmb).toEqual(EXPECTED); }); });
modules/@angular/compiler-cli/integrationtest/test/i18n_spec.ts
0
https://github.com/angular/angular/commit/a55d796c4b4cbe5bc1256339bd398090f58b4d69
[ 0.0001745839399518445, 0.00017140537966042757, 0.00016797275748103857, 0.00017046627181116492, 0.0000025791428015509155 ]
{ "id": 2, "code_window": [ " expect(() => parse('<p [bar.foo]>', []))\n", " .toThrowError(\n", " `Template parse errors:\\nInvalid property name 'bar.foo' (\"<p [ERROR ->][bar.foo]>\"): TestComp@0:3`);\n", " });\n", "\n", " it('should parse bound properties via [...] and not report them as attributes', () => {\n", " expect(humanizeTplAst(parse('<div [prop]=\"v\">', []))).toEqual([\n", " [ElementAst, 'div'],\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " describe('errors', () => {\n", " it('should throw error when binding to an unkonown property', () => {\n", " expect(() => parse('<my-component [invalidProp]=\"bar\"></my-component>', []))\n", " .toThrowError(`Template parse errors:\n", "Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.\n", "1. If 'my-component' is an Angular component and it has 'invalidProp' input, then verify that it is part of this module.\n", "2. If 'my-component' is a Web Component then add \"CUSTOM_ELEMENTS_SCHEMA\" to the '@NgModule.schema' of this component to suppress this message.\n", " (\"<my-component [ERROR ->][invalidProp]=\"bar\"></my-component>\"): TestComp@0:14`);\n", " });\n", " });\n", "\n" ], "file_path": "modules/@angular/compiler/test/template_parser/template_parser_spec.ts", "type": "add", "edit_start_line_idx": 254 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @module * @description * The `di` module provides dependency injection container services. */ export {HostMetadata, InjectMetadata, InjectableMetadata, OptionalMetadata, SelfMetadata, SkipSelfMetadata} from './di/metadata'; // we have to reexport * because Dart and TS export two different sets of types export * from './di/decorators'; export {forwardRef, resolveForwardRef, ForwardRefFn} from './di/forward_ref'; export {Injector} from './di/injector'; export {ReflectiveInjector} from './di/reflective_injector'; export {Binding, ProviderBuilder, bind, Provider, provide} from './di/provider'; export {ResolvedReflectiveBinding, ResolvedReflectiveFactory, ResolvedReflectiveProvider} from './di/reflective_provider'; export {ReflectiveKey} from './di/reflective_key'; export {NoProviderError, AbstractProviderError, CyclicDependencyError, InstantiationError, InvalidProviderError, NoAnnotationError, OutOfBoundsError} from './di/reflective_exceptions'; export {OpaqueToken} from './di/opaque_token';
modules/@angular/core/src/di.ts
0
https://github.com/angular/angular/commit/a55d796c4b4cbe5bc1256339bd398090f58b4d69
[ 0.00017410102009307593, 0.00017077491793315858, 0.00016624694399069995, 0.00017197674605995417, 0.000003317122036605724 ]
{ "id": 2, "code_window": [ " expect(() => parse('<p [bar.foo]>', []))\n", " .toThrowError(\n", " `Template parse errors:\\nInvalid property name 'bar.foo' (\"<p [ERROR ->][bar.foo]>\"): TestComp@0:3`);\n", " });\n", "\n", " it('should parse bound properties via [...] and not report them as attributes', () => {\n", " expect(humanizeTplAst(parse('<div [prop]=\"v\">', []))).toEqual([\n", " [ElementAst, 'div'],\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " describe('errors', () => {\n", " it('should throw error when binding to an unkonown property', () => {\n", " expect(() => parse('<my-component [invalidProp]=\"bar\"></my-component>', []))\n", " .toThrowError(`Template parse errors:\n", "Can't bind to 'invalidProp' since it isn't a known property of 'my-component'.\n", "1. If 'my-component' is an Angular component and it has 'invalidProp' input, then verify that it is part of this module.\n", "2. If 'my-component' is a Web Component then add \"CUSTOM_ELEMENTS_SCHEMA\" to the '@NgModule.schema' of this component to suppress this message.\n", " (\"<my-component [ERROR ->][invalidProp]=\"bar\"></my-component>\"): TestComp@0:14`);\n", " });\n", " });\n", "\n" ], "file_path": "modules/@angular/compiler/test/template_parser/template_parser_spec.ts", "type": "add", "edit_start_line_idx": 254 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {DomAdapter} from '../dom/dom_adapter'; import {StringMapWrapper} from '../facade/collection'; import {Type, isFunction, isPresent} from '../facade/lang'; /** * Provides DOM operations in any browser environment. */ export abstract class GenericBrowserDomAdapter extends DomAdapter { private _animationPrefix: string = null; private _transitionEnd: string = null; constructor() { super(); try { var element = this.createElement('div', this.defaultDoc()); if (isPresent(this.getStyle(element, 'animationName'))) { this._animationPrefix = ''; } else { var domPrefixes = ['Webkit', 'Moz', 'O', 'ms']; for (var i = 0; i < domPrefixes.length; i++) { if (isPresent(this.getStyle(element, domPrefixes[i] + 'AnimationName'))) { this._animationPrefix = '-' + domPrefixes[i].toLowerCase() + '-'; break; } } } var transEndEventNames: {[key: string]: string} = { WebkitTransition: 'webkitTransitionEnd', MozTransition: 'transitionend', OTransition: 'oTransitionEnd otransitionend', transition: 'transitionend' }; StringMapWrapper.forEach(transEndEventNames, (value: string, key: string) => { if (isPresent(this.getStyle(element, key))) { this._transitionEnd = value; } }); } catch (e) { this._animationPrefix = null; this._transitionEnd = null; } } getDistributedNodes(el: HTMLElement): Node[] { return (<any>el).getDistributedNodes(); } resolveAndSetHref(el: HTMLAnchorElement, baseUrl: string, href: string) { el.href = href == null ? baseUrl : baseUrl + '/../' + href; } supportsDOMEvents(): boolean { return true; } supportsNativeShadowDOM(): boolean { return isFunction((<any>this.defaultDoc().body).createShadowRoot); } getAnimationPrefix(): string { return isPresent(this._animationPrefix) ? this._animationPrefix : ''; } getTransitionEnd(): string { return isPresent(this._transitionEnd) ? this._transitionEnd : ''; } supportsAnimation(): boolean { return isPresent(this._animationPrefix) && isPresent(this._transitionEnd); } }
modules/@angular/platform-browser/src/browser/generic_browser_adapter.ts
0
https://github.com/angular/angular/commit/a55d796c4b4cbe5bc1256339bd398090f58b4d69
[ 0.0001746648777043447, 0.00016913979197852314, 0.00016296109242830426, 0.0001702307490631938, 0.0000043745826587837655 ]
{ "id": 3, "code_window": [ "\n", " it('should report invalid property names', () => {\n", " expect(() => parse('<div [invalidProp]></div>', [])).toThrowError(`Template parse errors:\n", "Can't bind to 'invalidProp' since it isn't a known native property (\"<div [ERROR ->][invalidProp]></div>\"): TestComp@0:5`);\n", " });\n", "\n", " it('should report invalid host property names', () => {\n", " var dirA = CompileDirectiveMetadata.create({\n", " selector: 'div',\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "Can't bind to 'invalidProp' since it isn't a known property of 'div'. (\"<div [ERROR ->][invalidProp]></div>\"): TestComp@0:5`);\n" ], "file_path": "modules/@angular/compiler/test/template_parser/template_parser_spec.ts", "type": "replace", "edit_start_line_idx": 1242 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompilePipeMetadata, CompileProviderMetadata, CompileQueryMetadata, CompileTemplateMetadata, CompileTokenMetadata, CompileTypeMetadata} from '@angular/compiler/src/compile_metadata'; import {DomElementSchemaRegistry} from '@angular/compiler/src/schema/dom_element_schema_registry'; import {ElementSchemaRegistry} from '@angular/compiler/src/schema/element_schema_registry'; import {AttrAst, BoundDirectivePropertyAst, BoundElementPropertyAst, BoundEventAst, BoundTextAst, DirectiveAst, ElementAst, EmbeddedTemplateAst, NgContentAst, PropertyBindingType, ProviderAstType, ReferenceAst, TemplateAst, TemplateAstVisitor, TextAst, VariableAst, templateVisitAll} from '@angular/compiler/src/template_parser/template_ast'; import {TEMPLATE_TRANSFORMS, TemplateParser, splitClasses} from '@angular/compiler/src/template_parser/template_parser'; import {MockSchemaRegistry} from '@angular/compiler/testing'; import {SchemaMetadata, SecurityContext} from '@angular/core'; import {Console} from '@angular/core/src/console'; import {TestBed} from '@angular/core/testing'; import {afterEach, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal'; import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from '../../src/html_parser/interpolation_config'; import {Identifiers, identifierToken} from '../../src/identifiers'; import {unparse} from '../expression_parser/unparser'; import {TEST_COMPILER_PROVIDERS} from '../test_bindings'; var someModuleUrl = 'package:someModule'; var MOCK_SCHEMA_REGISTRY = [{ provide: ElementSchemaRegistry, useValue: new MockSchemaRegistry({'invalidProp': false}, {'mappedAttr': 'mappedProp'}) }]; export function main() { var ngIf: CompileDirectiveMetadata; var parse: (template: string, directives: CompileDirectiveMetadata[], pipes?: CompilePipeMetadata[]) => TemplateAst[]; var console: ArrayConsole; function commonBeforeEach() { beforeEach(() => { console = new ArrayConsole(); TestBed.configureCompiler({providers: [{provide: Console, useValue: console}]}); }); beforeEach(inject([TemplateParser], (parser: TemplateParser) => { var component = CompileDirectiveMetadata.create({ selector: 'root', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'Root'}), isComponent: true }); ngIf = CompileDirectiveMetadata.create({ selector: '[ngIf]', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'NgIf'}), inputs: ['ngIf'] }); parse = (template: string, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[] = null, schemas: SchemaMetadata[] = []): TemplateAst[] => { if (pipes === null) { pipes = []; } return parser.parse(component, template, directives, pipes, schemas, 'TestComp'); }; })); } describe('TemplateParser template transform', () => { beforeEach(() => { TestBed.configureCompiler({providers: TEST_COMPILER_PROVIDERS}); }); beforeEach(() => { TestBed.configureCompiler({ providers: [{provide: TEMPLATE_TRANSFORMS, useValue: new FooAstTransformer(), multi: true}] }); }); describe('single', () => { commonBeforeEach(); it('should transform TemplateAST', () => { expect(humanizeTplAst(parse('<div>', []))).toEqual([[ElementAst, 'foo']]); }); }); describe('multiple', () => { beforeEach(() => { TestBed.configureCompiler({ providers: [{provide: TEMPLATE_TRANSFORMS, useValue: new BarAstTransformer(), multi: true}] }); }); commonBeforeEach(); it('should compose transformers', () => { expect(humanizeTplAst(parse('<div>', []))).toEqual([[ElementAst, 'bar']]); }); }); }); describe('TemplateParser Security', () => { // Semi-integration test to make sure TemplateParser properly sets the security context. // Uses the actual DomElementSchemaRegistry. beforeEach(() => { TestBed.configureCompiler({ providers: [ TEST_COMPILER_PROVIDERS, {provide: ElementSchemaRegistry, useClass: DomElementSchemaRegistry} ] }); }); commonBeforeEach(); describe('security context', () => { function secContext(tpl: string): SecurityContext { let ast = parse(tpl, []); let propBinding = (<ElementAst>ast[0]).inputs[0]; return propBinding.securityContext; } it('should set for properties', () => { expect(secContext('<div [title]="v">')).toBe(SecurityContext.NONE); expect(secContext('<div [innerHTML]="v">')).toBe(SecurityContext.HTML); }); it('should set for property value bindings', () => { expect(secContext('<div innerHTML="{{v}}">')).toBe(SecurityContext.HTML); }); it('should set for attributes', () => { expect(secContext('<a [attr.href]="v">')).toBe(SecurityContext.URL); // NB: attributes below need to change case. expect(secContext('<a [attr.innerHtml]="v">')).toBe(SecurityContext.HTML); expect(secContext('<a [attr.formaction]="v">')).toBe(SecurityContext.URL); }); it('should set for style', () => { expect(secContext('<a [style.backgroundColor]="v">')).toBe(SecurityContext.STYLE); }); }); }); describe('TemplateParser', () => { beforeEach(() => { TestBed.configureCompiler({providers: [TEST_COMPILER_PROVIDERS, MOCK_SCHEMA_REGISTRY]}); }); commonBeforeEach(); describe('parse', () => { describe('nodes without bindings', () => { it('should parse text nodes', () => { expect(humanizeTplAst(parse('a', []))).toEqual([[TextAst, 'a']]); }); it('should parse elements with attributes', () => { expect(humanizeTplAst(parse('<div a=b>', [ ]))).toEqual([[ElementAst, 'div'], [AttrAst, 'a', 'b']]); }); }); it('should parse ngContent', () => { var parsed = parse('<ng-content select="a">', []); expect(humanizeTplAst(parsed)).toEqual([[NgContentAst]]); }); it('should parse ngContent regardless the namespace', () => { var parsed = parse('<svg><ng-content></ng-content></svg>', []); expect(humanizeTplAst(parsed)).toEqual([ [ElementAst, ':svg:svg'], [NgContentAst], ]); }); it('should parse bound text nodes', () => { expect(humanizeTplAst(parse('{{a}}', []))).toEqual([[BoundTextAst, '{{ a }}']]); }); it('should parse with custom interpolation config', inject([TemplateParser], (parser: TemplateParser) => { const component = CompileDirectiveMetadata.create({ selector: 'test', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'Test'}), isComponent: true, template: new CompileTemplateMetadata({interpolation: ['{%', '%}']}) }); expect(humanizeTplAst(parser.parse(component, '{%a%}', [], [], [], 'TestComp'), { start: '{%', end: '%}' })).toEqual([[BoundTextAst, '{% a %}']]); })); describe('bound properties', () => { it('should parse mixed case bound properties', () => { expect(humanizeTplAst(parse('<div [someProp]="v">', []))).toEqual([ [ElementAst, 'div'], [BoundElementPropertyAst, PropertyBindingType.Property, 'someProp', 'v', null] ]); }); it('should parse dash case bound properties', () => { expect(humanizeTplAst(parse('<div [some-prop]="v">', []))).toEqual([ [ElementAst, 'div'], [BoundElementPropertyAst, PropertyBindingType.Property, 'some-prop', 'v', null] ]); }); it('should normalize property names via the element schema', () => { expect(humanizeTplAst(parse('<div [mappedAttr]="v">', []))).toEqual([ [ElementAst, 'div'], [BoundElementPropertyAst, PropertyBindingType.Property, 'mappedProp', 'v', null] ]); }); it('should parse mixed case bound attributes', () => { expect(humanizeTplAst(parse('<div [attr.someAttr]="v">', []))).toEqual([ [ElementAst, 'div'], [BoundElementPropertyAst, PropertyBindingType.Attribute, 'someAttr', 'v', null] ]); }); it('should parse and dash case bound classes', () => { expect(humanizeTplAst(parse('<div [class.some-class]="v">', []))).toEqual([ [ElementAst, 'div'], [BoundElementPropertyAst, PropertyBindingType.Class, 'some-class', 'v', null] ]); }); it('should parse mixed case bound classes', () => { expect(humanizeTplAst(parse('<div [class.someClass]="v">', []))).toEqual([ [ElementAst, 'div'], [BoundElementPropertyAst, PropertyBindingType.Class, 'someClass', 'v', null] ]); }); it('should parse mixed case bound styles', () => { expect(humanizeTplAst(parse('<div [style.someStyle]="v">', []))).toEqual([ [ElementAst, 'div'], [BoundElementPropertyAst, PropertyBindingType.Style, 'someStyle', 'v', null] ]); }); it('should report invalid prefixes', () => { expect(() => parse('<p [atTr.foo]>', [])) .toThrowError( `Template parse errors:\nInvalid property name 'atTr.foo' ("<p [ERROR ->][atTr.foo]>"): TestComp@0:3`); expect(() => parse('<p [sTyle.foo]>', [])) .toThrowError( `Template parse errors:\nInvalid property name 'sTyle.foo' ("<p [ERROR ->][sTyle.foo]>"): TestComp@0:3`); expect(() => parse('<p [Class.foo]>', [])) .toThrowError( `Template parse errors:\nInvalid property name 'Class.foo' ("<p [ERROR ->][Class.foo]>"): TestComp@0:3`); expect(() => parse('<p [bar.foo]>', [])) .toThrowError( `Template parse errors:\nInvalid property name 'bar.foo' ("<p [ERROR ->][bar.foo]>"): TestComp@0:3`); }); it('should parse bound properties via [...] and not report them as attributes', () => { expect(humanizeTplAst(parse('<div [prop]="v">', []))).toEqual([ [ElementAst, 'div'], [BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null] ]); }); it('should parse bound properties via bind- and not report them as attributes', () => { expect(humanizeTplAst(parse('<div bind-prop="v">', []))).toEqual([ [ElementAst, 'div'], [BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null] ]); }); it('should parse bound properties via {{...}} and not report them as attributes', () => { expect(humanizeTplAst(parse('<div prop="{{v}}">', []))).toEqual([ [ElementAst, 'div'], [BoundElementPropertyAst, PropertyBindingType.Property, 'prop', '{{ v }}', null] ]); }); it('should parse bound properties via animate- and not report them as attributes', () => { expect(humanizeTplAst(parse('<div animate-something="value2">', []))).toEqual([ [ElementAst, 'div'], [BoundElementPropertyAst, PropertyBindingType.Animation, 'something', 'value2', null] ]); }); it('should parse bound properties via @ and not report them as attributes and also report a deprecation warning', () => { expect(humanizeTplAst(parse('<div @something="value2">', []))).toEqual([ [ElementAst, 'div'], [ BoundElementPropertyAst, PropertyBindingType.Animation, 'something', 'value2', null ] ]); expect(console.warnings).toEqual([[ 'Template parse warnings:', `Assigning animation triggers via @prop="exp" attributes with an expression is deprecated. Use [@prop]="exp" instead! ("<div [ERROR ->]@something="value2">"): TestComp@0:5` ].join('\n')]); }); it('should issue a warning when host attributes contain a non property-bound animation trigger', () => { var dirA = CompileDirectiveMetadata.create({ selector: 'div', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}), host: {'@prop': 'expr'} }); humanizeTplAst(parse('<div></div>', [dirA])); expect(console.warnings).toEqual([[ 'Template parse warnings:', `Assigning animation triggers within host data as attributes such as "@prop": "exp" is deprecated. Use "[@prop]": "exp" instead! ("[ERROR ->]<div></div>"): TestComp@0:0, Directive DirA` ].join('\n')]); }); it('should not issue a warning when an animation property is bound without an expression', () => { humanizeTplAst(parse('<div @something>', [])); expect(console.warnings.length).toEqual(0); }); it('should parse bound properties via [@] and not report them as attributes', () => { expect(humanizeTplAst(parse('<div [@something]="value2">', []))).toEqual([ [ElementAst, 'div'], [BoundElementPropertyAst, PropertyBindingType.Animation, 'something', 'value2', null] ]); }); }); describe('events', () => { it('should parse bound events with a target', () => { expect(humanizeTplAst(parse('<div (window:event)="v">', []))).toEqual([ [ElementAst, 'div'], [BoundEventAst, 'event', 'window', 'v'], ]); }); it('should report an error on empty expression', () => { expect(() => parse('<div (event)="">', [])) .toThrowError(/Empty expressions are not allowed/); expect(() => parse('<div (event)=" ">', [])) .toThrowError(/Empty expressions are not allowed/); }); it('should parse bound events via (...) and not report them as attributes', () => { expect(humanizeTplAst(parse('<div (event)="v">', [ ]))).toEqual([[ElementAst, 'div'], [BoundEventAst, 'event', null, 'v']]); }); it('should parse event names case sensitive', () => { expect(humanizeTplAst(parse('<div (some-event)="v">', [ ]))).toEqual([[ElementAst, 'div'], [BoundEventAst, 'some-event', null, 'v']]); expect(humanizeTplAst(parse('<div (someEvent)="v">', [ ]))).toEqual([[ElementAst, 'div'], [BoundEventAst, 'someEvent', null, 'v']]); }); it('should parse bound events via on- and not report them as attributes', () => { expect(humanizeTplAst(parse('<div on-event="v">', [ ]))).toEqual([[ElementAst, 'div'], [BoundEventAst, 'event', null, 'v']]); }); it('should allow events on explicit embedded templates that are emitted by a directive', () => { var dirA = CompileDirectiveMetadata.create({ selector: 'template', outputs: ['e'], type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}) }); expect(humanizeTplAst(parse('<template (e)="f"></template>', [dirA]))).toEqual([ [EmbeddedTemplateAst], [BoundEventAst, 'e', null, 'f'], [DirectiveAst, dirA], ]); }); }); describe('bindon', () => { it('should parse bound events and properties via [(...)] and not report them as attributes', () => { expect(humanizeTplAst(parse('<div [(prop)]="v">', []))).toEqual([ [ElementAst, 'div'], [BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null], [BoundEventAst, 'propChange', null, 'v = $event'] ]); }); it('should parse bound events and properties via bindon- and not report them as attributes', () => { expect(humanizeTplAst(parse('<div bindon-prop="v">', []))).toEqual([ [ElementAst, 'div'], [BoundElementPropertyAst, PropertyBindingType.Property, 'prop', 'v', null], [BoundEventAst, 'propChange', null, 'v = $event'] ]); }); }); describe('directives', () => { it('should order directives by the directives array in the View and match them only once', () => { var dirA = CompileDirectiveMetadata.create({ selector: '[a]', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}) }); var dirB = CompileDirectiveMetadata.create({ selector: '[b]', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirB'}) }); var dirC = CompileDirectiveMetadata.create({ selector: '[c]', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirC'}) }); expect(humanizeTplAst(parse('<div a c b a b>', [dirA, dirB, dirC]))).toEqual([ [ElementAst, 'div'], [AttrAst, 'a', ''], [AttrAst, 'c', ''], [AttrAst, 'b', ''], [AttrAst, 'a', ''], [AttrAst, 'b', ''], [DirectiveAst, dirA], [DirectiveAst, dirB], [DirectiveAst, dirC] ]); }); it('should locate directives in property bindings', () => { var dirA = CompileDirectiveMetadata.create({ selector: '[a=b]', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}) }); var dirB = CompileDirectiveMetadata.create({ selector: '[b]', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirB'}) }); expect(humanizeTplAst(parse('<div [a]="b">', [dirA, dirB]))).toEqual([ [ElementAst, 'div'], [BoundElementPropertyAst, PropertyBindingType.Property, 'a', 'b', null], [DirectiveAst, dirA] ]); }); it('should locate directives in event bindings', () => { var dirA = CompileDirectiveMetadata.create({ selector: '[a]', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirB'}) }); expect(humanizeTplAst(parse('<div (a)="b">', [dirA]))).toEqual([ [ElementAst, 'div'], [BoundEventAst, 'a', null, 'b'], [DirectiveAst, dirA] ]); }); it('should parse directive host properties', () => { var dirA = CompileDirectiveMetadata.create({ selector: 'div', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}), host: {'[a]': 'expr'} }); expect(humanizeTplAst(parse('<div></div>', [dirA]))).toEqual([ [ElementAst, 'div'], [DirectiveAst, dirA], [BoundElementPropertyAst, PropertyBindingType.Property, 'a', 'expr', null] ]); }); it('should parse directive host listeners', () => { var dirA = CompileDirectiveMetadata.create({ selector: 'div', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}), host: {'(a)': 'expr'} }); expect(humanizeTplAst(parse('<div></div>', [dirA]))).toEqual([ [ElementAst, 'div'], [DirectiveAst, dirA], [BoundEventAst, 'a', null, 'expr'] ]); }); it('should parse directive properties', () => { var dirA = CompileDirectiveMetadata.create({ selector: 'div', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}), inputs: ['aProp'] }); expect(humanizeTplAst(parse('<div [aProp]="expr"></div>', [dirA]))).toEqual([ [ElementAst, 'div'], [DirectiveAst, dirA], [BoundDirectivePropertyAst, 'aProp', 'expr'] ]); }); it('should parse renamed directive properties', () => { var dirA = CompileDirectiveMetadata.create({ selector: 'div', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}), inputs: ['b:a'] }); expect(humanizeTplAst(parse('<div [a]="expr"></div>', [dirA]))).toEqual([ [ElementAst, 'div'], [DirectiveAst, dirA], [BoundDirectivePropertyAst, 'b', 'expr'] ]); }); it('should parse literal directive properties', () => { var dirA = CompileDirectiveMetadata.create({ selector: 'div', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}), inputs: ['a'] }); expect(humanizeTplAst(parse('<div a="literal"></div>', [dirA]))).toEqual([ [ElementAst, 'div'], [AttrAst, 'a', 'literal'], [DirectiveAst, dirA], [BoundDirectivePropertyAst, 'a', '"literal"'] ]); }); it('should favor explicit bound properties over literal properties', () => { var dirA = CompileDirectiveMetadata.create({ selector: 'div', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}), inputs: ['a'] }); expect(humanizeTplAst(parse('<div a="literal" [a]="\'literal2\'"></div>', [dirA]))) .toEqual([ [ElementAst, 'div'], [AttrAst, 'a', 'literal'], [DirectiveAst, dirA], [BoundDirectivePropertyAst, 'a', '"literal2"'] ]); }); it('should support optional directive properties', () => { var dirA = CompileDirectiveMetadata.create({ selector: 'div', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}), inputs: ['a'] }); expect(humanizeTplAst(parse('<div></div>', [dirA]))).toEqual([ [ElementAst, 'div'], [DirectiveAst, dirA] ]); }); }); describe('providers', () => { var nextProviderId: number; function createToken(value: string): CompileTokenMetadata { let token: CompileTokenMetadata; if (value.startsWith('type:')) { token = new CompileTokenMetadata({ identifier: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: value.substring(5)}) }); } else { token = new CompileTokenMetadata({value: value}); } return token; } function createDep(value: string): CompileDiDependencyMetadata { var isOptional = false; if (value.startsWith('optional:')) { isOptional = true; value = value.substring(9); } var isSelf = false; if (value.startsWith('self:')) { isSelf = true; value = value.substring(5); } var isHost = false; if (value.startsWith('host:')) { isHost = true; value = value.substring(5); } return new CompileDiDependencyMetadata( {token: createToken(value), isOptional: isOptional, isSelf: isSelf, isHost: isHost}); } function createProvider( token: string, {multi = false, deps = []}: {multi?: boolean, deps?: string[]} = {}): CompileProviderMetadata { return new CompileProviderMetadata({ token: createToken(token), multi: multi, useClass: new CompileTypeMetadata({name: `provider${nextProviderId++}`}), deps: deps.map(createDep) }); } function createDir( selector: string, {providers = null, viewProviders = null, deps = [], queries = []}: { providers?: CompileProviderMetadata[], viewProviders?: CompileProviderMetadata[], deps?: string[], queries?: string[] } = {}): CompileDirectiveMetadata { var isComponent = !selector.startsWith('['); return CompileDirectiveMetadata.create({ selector: selector, type: new CompileTypeMetadata( {moduleUrl: someModuleUrl, name: selector, diDeps: deps.map(createDep)}), isComponent: isComponent, template: new CompileTemplateMetadata({ngContentSelectors: []}), providers: providers, viewProviders: viewProviders, queries: queries.map( (value) => new CompileQueryMetadata({selectors: [createToken(value)]})) }); } beforeEach(() => { nextProviderId = 0; }); it('should provide a component', () => { var comp = createDir('my-comp'); var elAst: ElementAst = <ElementAst>parse('<my-comp>', [comp])[0]; expect(elAst.providers.length).toBe(1); expect(elAst.providers[0].providerType).toBe(ProviderAstType.Component); expect(elAst.providers[0].providers[0].useClass).toBe(comp.type); }); it('should provide a directive', () => { var dirA = createDir('[dirA]'); var elAst: ElementAst = <ElementAst>parse('<div dirA>', [dirA])[0]; expect(elAst.providers.length).toBe(1); expect(elAst.providers[0].providerType).toBe(ProviderAstType.Directive); expect(elAst.providers[0].providers[0].useClass).toBe(dirA.type); }); it('should use the public providers of a directive', () => { var provider = createProvider('service'); var dirA = createDir('[dirA]', {providers: [provider]}); var elAst: ElementAst = <ElementAst>parse('<div dirA>', [dirA])[0]; expect(elAst.providers.length).toBe(2); expect(elAst.providers[1].providerType).toBe(ProviderAstType.PublicService); expect(elAst.providers[1].providers).toEqual([provider]); }); it('should use the private providers of a component', () => { var provider = createProvider('service'); var comp = createDir('my-comp', {viewProviders: [provider]}); var elAst: ElementAst = <ElementAst>parse('<my-comp>', [comp])[0]; expect(elAst.providers.length).toBe(2); expect(elAst.providers[1].providerType).toBe(ProviderAstType.PrivateService); expect(elAst.providers[1].providers).toEqual([provider]); }); it('should support multi providers', () => { var provider0 = createProvider('service0', {multi: true}); var provider1 = createProvider('service1', {multi: true}); var provider2 = createProvider('service0', {multi: true}); var dirA = createDir('[dirA]', {providers: [provider0, provider1]}); var dirB = createDir('[dirB]', {providers: [provider2]}); var elAst: ElementAst = <ElementAst>parse('<div dirA dirB>', [dirA, dirB])[0]; expect(elAst.providers.length).toBe(4); expect(elAst.providers[2].providers).toEqual([provider0, provider2]); expect(elAst.providers[3].providers).toEqual([provider1]); }); it('should overwrite non multi providers', () => { var provider1 = createProvider('service0'); var provider2 = createProvider('service1'); var provider3 = createProvider('service0'); var dirA = createDir('[dirA]', {providers: [provider1, provider2]}); var dirB = createDir('[dirB]', {providers: [provider3]}); var elAst: ElementAst = <ElementAst>parse('<div dirA dirB>', [dirA, dirB])[0]; expect(elAst.providers.length).toBe(4); expect(elAst.providers[2].providers).toEqual([provider3]); expect(elAst.providers[3].providers).toEqual([provider2]); }); it('should overwrite component providers by directive providers', () => { var compProvider = createProvider('service0'); var dirProvider = createProvider('service0'); var comp = createDir('my-comp', {providers: [compProvider]}); var dirA = createDir('[dirA]', {providers: [dirProvider]}); var elAst: ElementAst = <ElementAst>parse('<my-comp dirA>', [dirA, comp])[0]; expect(elAst.providers.length).toBe(3); expect(elAst.providers[2].providers).toEqual([dirProvider]); }); it('should overwrite view providers by directive providers', () => { var viewProvider = createProvider('service0'); var dirProvider = createProvider('service0'); var comp = createDir('my-comp', {viewProviders: [viewProvider]}); var dirA = createDir('[dirA]', {providers: [dirProvider]}); var elAst: ElementAst = <ElementAst>parse('<my-comp dirA>', [dirA, comp])[0]; expect(elAst.providers.length).toBe(3); expect(elAst.providers[2].providers).toEqual([dirProvider]); }); it('should overwrite directives by providers', () => { var dirProvider = createProvider('type:my-comp'); var comp = createDir('my-comp', {providers: [dirProvider]}); var elAst: ElementAst = <ElementAst>parse('<my-comp>', [comp])[0]; expect(elAst.providers.length).toBe(1); expect(elAst.providers[0].providers).toEqual([dirProvider]); }); it('if mixing multi and non multi providers', () => { var provider0 = createProvider('service0'); var provider1 = createProvider('service0', {multi: true}); var dirA = createDir('[dirA]', {providers: [provider0]}); var dirB = createDir('[dirB]', {providers: [provider1]}); expect(() => parse('<div dirA dirB>', [dirA, dirB])) .toThrowError( `Template parse errors:\n` + `Mixing multi and non multi provider is not possible for token service0 ("[ERROR ->]<div dirA dirB>"): TestComp@0:0`); }); it('should sort providers by their DI order', () => { var provider0 = createProvider('service0', {deps: ['type:[dir2]']}); var provider1 = createProvider('service1'); var dir2 = createDir('[dir2]', {deps: ['service1']}); var comp = createDir('my-comp', {providers: [provider0, provider1]}); var elAst: ElementAst = <ElementAst>parse('<my-comp dir2>', [comp, dir2])[0]; expect(elAst.providers.length).toBe(4); expect(elAst.providers[0].providers[0].useClass).toEqual(comp.type); expect(elAst.providers[1].providers).toEqual([provider1]); expect(elAst.providers[2].providers[0].useClass).toEqual(dir2.type); expect(elAst.providers[3].providers).toEqual([provider0]); }); it('should sort directives by their DI order', () => { var dir0 = createDir('[dir0]', {deps: ['type:my-comp']}); var dir1 = createDir('[dir1]', {deps: ['type:[dir0]']}); var dir2 = createDir('[dir2]', {deps: ['type:[dir1]']}); var comp = createDir('my-comp'); var elAst: ElementAst = <ElementAst>parse('<my-comp dir2 dir0 dir1>', [comp, dir2, dir0, dir1])[0]; expect(elAst.providers.length).toBe(4); expect(elAst.directives[0].directive).toBe(comp); expect(elAst.directives[1].directive).toBe(dir0); expect(elAst.directives[2].directive).toBe(dir1); expect(elAst.directives[3].directive).toBe(dir2); }); it('should mark directives and dependencies of directives as eager', () => { var provider0 = createProvider('service0'); var provider1 = createProvider('service1'); var dirA = createDir('[dirA]', {providers: [provider0, provider1], deps: ['service0']}); var elAst: ElementAst = <ElementAst>parse('<div dirA>', [dirA])[0]; expect(elAst.providers.length).toBe(3); expect(elAst.providers[0].providers).toEqual([provider0]); expect(elAst.providers[0].eager).toBe(true); expect(elAst.providers[1].providers[0].useClass).toEqual(dirA.type); expect(elAst.providers[1].eager).toBe(true); expect(elAst.providers[2].providers).toEqual([provider1]); expect(elAst.providers[2].eager).toBe(false); }); it('should mark dependencies on parent elements as eager', () => { var provider0 = createProvider('service0'); var provider1 = createProvider('service1'); var dirA = createDir('[dirA]', {providers: [provider0, provider1]}); var dirB = createDir('[dirB]', {deps: ['service0']}); var elAst: ElementAst = <ElementAst>parse('<div dirA><div dirB></div></div>', [dirA, dirB])[0]; expect(elAst.providers.length).toBe(3); expect(elAst.providers[0].providers[0].useClass).toEqual(dirA.type); expect(elAst.providers[0].eager).toBe(true); expect(elAst.providers[1].providers).toEqual([provider0]); expect(elAst.providers[1].eager).toBe(true); expect(elAst.providers[2].providers).toEqual([provider1]); expect(elAst.providers[2].eager).toBe(false); }); it('should mark queried providers as eager', () => { var provider0 = createProvider('service0'); var provider1 = createProvider('service1'); var dirA = createDir('[dirA]', {providers: [provider0, provider1], queries: ['service0']}); var elAst: ElementAst = <ElementAst>parse('<div dirA></div>', [dirA])[0]; expect(elAst.providers.length).toBe(3); expect(elAst.providers[0].providers[0].useClass).toEqual(dirA.type); expect(elAst.providers[0].eager).toBe(true); expect(elAst.providers[1].providers).toEqual([provider0]); expect(elAst.providers[1].eager).toBe(true); expect(elAst.providers[2].providers).toEqual([provider1]); expect(elAst.providers[2].eager).toBe(false); }); it('should not mark dependencies accross embedded views as eager', () => { var provider0 = createProvider('service0'); var dirA = createDir('[dirA]', {providers: [provider0]}); var dirB = createDir('[dirB]', {deps: ['service0']}); var elAst: ElementAst = <ElementAst>parse('<div dirA><div *ngIf dirB></div></div>', [dirA, dirB])[0]; expect(elAst.providers.length).toBe(2); expect(elAst.providers[0].providers[0].useClass).toEqual(dirA.type); expect(elAst.providers[0].eager).toBe(true); expect(elAst.providers[1].providers).toEqual([provider0]); expect(elAst.providers[1].eager).toBe(false); }); it('should report missing @Self() deps as errors', () => { var dirA = createDir('[dirA]', {deps: ['self:provider0']}); expect(() => parse('<div dirA></div>', [dirA])) .toThrowError( 'Template parse errors:\nNo provider for provider0 ("[ERROR ->]<div dirA></div>"): TestComp@0:0'); }); it('should change missing @Self() that are optional to nulls', () => { var dirA = createDir('[dirA]', {deps: ['optional:self:provider0']}); var elAst: ElementAst = <ElementAst>parse('<div dirA></div>', [dirA])[0]; expect(elAst.providers[0].providers[0].deps[0].isValue).toBe(true); expect(elAst.providers[0].providers[0].deps[0].value).toBe(null); }); it('should report missing @Host() deps as errors', () => { var dirA = createDir('[dirA]', {deps: ['host:provider0']}); expect(() => parse('<div dirA></div>', [dirA])) .toThrowError( 'Template parse errors:\nNo provider for provider0 ("[ERROR ->]<div dirA></div>"): TestComp@0:0'); }); it('should change missing @Host() that are optional to nulls', () => { var dirA = createDir('[dirA]', {deps: ['optional:host:provider0']}); var elAst: ElementAst = <ElementAst>parse('<div dirA></div>', [dirA])[0]; expect(elAst.providers[0].providers[0].deps[0].isValue).toBe(true); expect(elAst.providers[0].providers[0].deps[0].value).toBe(null); }); }); describe('references', () => { it('should parse references via #... and not report them as attributes', () => { expect(humanizeTplAst(parse('<div #a>', [ ]))).toEqual([[ElementAst, 'div'], [ReferenceAst, 'a', null]]); }); it('should parse references via ref-... and not report them as attributes', () => { expect(humanizeTplAst(parse('<div ref-a>', [ ]))).toEqual([[ElementAst, 'div'], [ReferenceAst, 'a', null]]); }); it('should parse references via var-... and report them as deprecated', () => { expect(humanizeTplAst(parse('<div var-a>', [ ]))).toEqual([[ElementAst, 'div'], [ReferenceAst, 'a', null]]); expect(console.warnings).toEqual([[ 'Template parse warnings:', '"var-" on non <template> elements is deprecated. Use "ref-" instead! ("<div [ERROR ->]var-a>"): TestComp@0:5' ].join('\n')]); }); it('should parse camel case references', () => { expect(humanizeTplAst(parse('<div ref-someA>', [ ]))).toEqual([[ElementAst, 'div'], [ReferenceAst, 'someA', null]]); }); it('should assign references with empty value to the element', () => { expect(humanizeTplAst(parse('<div #a></div>', [ ]))).toEqual([[ElementAst, 'div'], [ReferenceAst, 'a', null]]); }); it('should assign references to directives via exportAs', () => { var dirA = CompileDirectiveMetadata.create({ selector: '[a]', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}), exportAs: 'dirA' }); expect(humanizeTplAst(parse('<div a #a="dirA"></div>', [dirA]))).toEqual([ [ElementAst, 'div'], [AttrAst, 'a', ''], [ReferenceAst, 'a', identifierToken(dirA.type)], [DirectiveAst, dirA], ]); }); it('should report references with values that dont match a directive as errors', () => { expect(() => parse('<div #a="dirA"></div>', [])).toThrowError(`Template parse errors: There is no directive with "exportAs" set to "dirA" ("<div [ERROR ->]#a="dirA"></div>"): TestComp@0:5`); }); it('should report invalid reference names', () => { expect(() => parse('<div #a-b></div>', [])).toThrowError(`Template parse errors: "-" is not allowed in reference names ("<div [ERROR ->]#a-b></div>"): TestComp@0:5`); }); it('should report variables as errors', () => { expect(() => parse('<div let-a></div>', [])).toThrowError(`Template parse errors: "let-" is only supported on template elements. ("<div [ERROR ->]let-a></div>"): TestComp@0:5`); }); it('should report duplicate reference names', () => { expect(() => parse('<div #a></div><div #a></div>', [])) .toThrowError(`Template parse errors: Reference "#a" is defined several times ("<div #a></div><div [ERROR ->]#a></div>"): TestComp@0:19`); }); it('should not throw error when there is same reference name in different templates', () => { expect(() => parse('<div #a><template #a><span>OK</span></template></div>', [])) .not.toThrowError(); }); it('should assign references with empty value to components', () => { var dirA = CompileDirectiveMetadata.create({ selector: '[a]', isComponent: true, type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}), exportAs: 'dirA', template: new CompileTemplateMetadata({ngContentSelectors: []}) }); expect(humanizeTplAst(parse('<div a #a></div>', [dirA]))).toEqual([ [ElementAst, 'div'], [AttrAst, 'a', ''], [ReferenceAst, 'a', identifierToken(dirA.type)], [DirectiveAst, dirA], ]); }); it('should not locate directives in references', () => { var dirA = CompileDirectiveMetadata.create({ selector: '[a]', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}) }); expect(humanizeTplAst(parse('<div ref-a>', [dirA]))).toEqual([ [ElementAst, 'div'], [ReferenceAst, 'a', null] ]); }); }); describe('explicit templates', () => { it('should create embedded templates for <template> elements', () => { expect(humanizeTplAst(parse('<template></template>', [ ]))).toEqual([[EmbeddedTemplateAst]]); expect(humanizeTplAst(parse('<TEMPLATE></TEMPLATE>', [ ]))).toEqual([[EmbeddedTemplateAst]]); }); it('should create embedded templates for <template> elements regardless the namespace', () => { expect(humanizeTplAst(parse('<svg><template></template></svg>', []))).toEqual([ [ElementAst, ':svg:svg'], [EmbeddedTemplateAst], ]); }); it('should support references via #...', () => { expect(humanizeTplAst(parse('<template #a>', []))).toEqual([ [EmbeddedTemplateAst], [ReferenceAst, 'a', identifierToken(Identifiers.TemplateRef)] ]); }); it('should support references via ref-...', () => { expect(humanizeTplAst(parse('<template ref-a>', []))).toEqual([ [EmbeddedTemplateAst], [ReferenceAst, 'a', identifierToken(Identifiers.TemplateRef)] ]); }); it('should parse variables via let-...', () => { expect(humanizeTplAst(parse('<template let-a="b">', [ ]))).toEqual([[EmbeddedTemplateAst], [VariableAst, 'a', 'b']]); }); it('should parse variables via var-... and report them as deprecated', () => { expect(humanizeTplAst(parse('<template var-a="b">', [ ]))).toEqual([[EmbeddedTemplateAst], [VariableAst, 'a', 'b']]); expect(console.warnings).toEqual([[ 'Template parse warnings:', '"var-" on <template> elements is deprecated. Use "let-" instead! ("<template [ERROR ->]var-a="b">"): TestComp@0:10' ].join('\n')]); }); it('should not locate directives in variables', () => { var dirA = CompileDirectiveMetadata.create({ selector: '[a]', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}) }); expect(humanizeTplAst(parse('<template let-a="b"></template>', [dirA]))).toEqual([ [EmbeddedTemplateAst], [VariableAst, 'a', 'b'] ]); }); }); describe('inline templates', () => { it('should wrap the element into an EmbeddedTemplateAST', () => { expect(humanizeTplAst(parse('<div template>', [ ]))).toEqual([[EmbeddedTemplateAst], [ElementAst, 'div']]); }); it('should wrap the element with data-template attribute into an EmbeddedTemplateAST ', () => { expect(humanizeTplAst(parse('<div data-template>', [ ]))).toEqual([[EmbeddedTemplateAst], [ElementAst, 'div']]); }); it('should parse bound properties', () => { expect(humanizeTplAst(parse('<div template="ngIf test">', [ngIf]))).toEqual([ [EmbeddedTemplateAst], [DirectiveAst, ngIf], [BoundDirectivePropertyAst, 'ngIf', 'test'], [ElementAst, 'div'] ]); }); it('should parse variables via #... and report them as deprecated', () => { expect(humanizeTplAst(parse('<div *ngIf="#a=b">', [ ]))).toEqual([[EmbeddedTemplateAst], [VariableAst, 'a', 'b'], [ElementAst, 'div']]); expect(console.warnings).toEqual([[ 'Template parse warnings:', '"#" inside of expressions is deprecated. Use "let" instead! ("<div [ERROR ->]*ngIf="#a=b">"): TestComp@0:5' ].join('\n')]); }); it('should parse variables via var ... and report them as deprecated', () => { expect(humanizeTplAst(parse('<div *ngIf="var a=b">', [ ]))).toEqual([[EmbeddedTemplateAst], [VariableAst, 'a', 'b'], [ElementAst, 'div']]); expect(console.warnings).toEqual([[ 'Template parse warnings:', '"var" inside of expressions is deprecated. Use "let" instead! ("<div [ERROR ->]*ngIf="var a=b">"): TestComp@0:5' ].join('\n')]); }); it('should parse variables via let ...', () => { expect(humanizeTplAst(parse('<div *ngIf="let a=b">', [ ]))).toEqual([[EmbeddedTemplateAst], [VariableAst, 'a', 'b'], [ElementAst, 'div']]); }); describe('directives', () => { it('should locate directives in property bindings', () => { var dirA = CompileDirectiveMetadata.create({ selector: '[a=b]', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}), inputs: ['a'] }); var dirB = CompileDirectiveMetadata.create({ selector: '[b]', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirB'}) }); expect(humanizeTplAst(parse('<div template="a b" b>', [dirA, dirB]))).toEqual([ [EmbeddedTemplateAst], [DirectiveAst, dirA], [BoundDirectivePropertyAst, 'a', 'b'], [ElementAst, 'div'], [AttrAst, 'b', ''], [DirectiveAst, dirB] ]); }); it('should not locate directives in variables', () => { var dirA = CompileDirectiveMetadata.create({ selector: '[a]', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}) }); expect(humanizeTplAst(parse('<div template="let a=b">', [dirA]))).toEqual([ [EmbeddedTemplateAst], [VariableAst, 'a', 'b'], [ElementAst, 'div'] ]); }); it('should not locate directives in references', () => { var dirA = CompileDirectiveMetadata.create({ selector: '[a]', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}) }); expect(humanizeTplAst(parse('<div ref-a>', [dirA]))).toEqual([ [ElementAst, 'div'], [ReferenceAst, 'a', null] ]); }); }); it('should work with *... and use the attribute name as property binding name', () => { expect(humanizeTplAst(parse('<div *ngIf="test">', [ngIf]))).toEqual([ [EmbeddedTemplateAst], [DirectiveAst, ngIf], [BoundDirectivePropertyAst, 'ngIf', 'test'], [ElementAst, 'div'] ]); }); it('should work with *... and empty value', () => { expect(humanizeTplAst(parse('<div *ngIf>', [ngIf]))).toEqual([ [EmbeddedTemplateAst], [DirectiveAst, ngIf], [BoundDirectivePropertyAst, 'ngIf', 'null'], [ElementAst, 'div'] ]); }); }); }); describe('content projection', () => { var compCounter: any /** TODO #9100 */; beforeEach(() => { compCounter = 0; }); function createComp( selector: string, ngContentSelectors: string[]): CompileDirectiveMetadata { return CompileDirectiveMetadata.create({ selector: selector, isComponent: true, type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: `SomeComp${compCounter++}`}), template: new CompileTemplateMetadata({ngContentSelectors: ngContentSelectors}) }); } function createDir(selector: string): CompileDirectiveMetadata { return CompileDirectiveMetadata.create({ selector: selector, type: new CompileTypeMetadata( {moduleUrl: someModuleUrl, name: `SomeDir${compCounter++}`}) }); } describe('project text nodes', () => { it('should project text nodes with wildcard selector', () => { expect(humanizeContentProjection(parse('<div>hello</div>', [createComp('div', ['*'])]))) .toEqual([['div', null], ['#text(hello)', 0]]); }); }); describe('project elements', () => { it('should project elements with wildcard selector', () => { expect(humanizeContentProjection(parse('<div><span></span></div>', [ createComp('div', ['*']) ]))).toEqual([['div', null], ['span', 0]]); }); it('should project elements with css selector', () => { expect(humanizeContentProjection(parse('<div><a x></a><b></b></div>', [ createComp('div', ['a[x]']) ]))).toEqual([['div', null], ['a', 0], ['b', null]]); }); }); describe('embedded templates', () => { it('should project embedded templates with wildcard selector', () => { expect(humanizeContentProjection(parse('<div><template></template></div>', [ createComp('div', ['*']) ]))).toEqual([['div', null], ['template', 0]]); }); it('should project embedded templates with css selector', () => { expect(humanizeContentProjection(parse( '<div><template x></template><template></template></div>', [createComp('div', ['template[x]'])]))) .toEqual([['div', null], ['template', 0], ['template', null]]); }); }); describe('ng-content', () => { it('should project ng-content with wildcard selector', () => { expect(humanizeContentProjection(parse('<div><ng-content></ng-content></div>', [ createComp('div', ['*']) ]))).toEqual([['div', null], ['ng-content', 0]]); }); it('should project ng-content with css selector', () => { expect(humanizeContentProjection(parse( '<div><ng-content x></ng-content><ng-content></ng-content></div>', [createComp('div', ['ng-content[x]'])]))) .toEqual([['div', null], ['ng-content', 0], ['ng-content', null]]); }); }); it('should project into the first matching ng-content', () => { expect(humanizeContentProjection(parse('<div>hello<b></b><a></a></div>', [ createComp('div', ['a', 'b', '*']) ]))).toEqual([['div', null], ['#text(hello)', 2], ['b', 1], ['a', 0]]); }); it('should project into wildcard ng-content last', () => { expect(humanizeContentProjection(parse('<div>hello<a></a></div>', [ createComp('div', ['*', 'a']) ]))).toEqual([['div', null], ['#text(hello)', 0], ['a', 1]]); }); it('should only project direct child nodes', () => { expect(humanizeContentProjection(parse('<div><span><a></a></span><a></a></div>', [ createComp('div', ['a']) ]))).toEqual([['div', null], ['span', null], ['a', null], ['a', 0]]); }); it('should project nodes of nested components', () => { expect(humanizeContentProjection(parse('<a><b>hello</b></a>', [ createComp('a', ['*']), createComp('b', ['*']) ]))).toEqual([['a', null], ['b', 0], ['#text(hello)', 0]]); }); it('should project children of components with ngNonBindable', () => { expect(humanizeContentProjection(parse('<div ngNonBindable>{{hello}}<span></span></div>', [ createComp('div', ['*']) ]))).toEqual([['div', null], ['#text({{hello}})', 0], ['span', 0]]); }); it('should match the element when there is an inline template', () => { expect(humanizeContentProjection(parse('<div><b *ngIf="cond"></b></div>', [ createComp('div', ['a', 'b']), ngIf ]))).toEqual([['div', null], ['template', 1], ['b', null]]); }); describe('ngProjectAs', () => { it('should override elements', () => { expect(humanizeContentProjection(parse('<div><a ngProjectAs="b"></a></div>', [ createComp('div', ['a', 'b']) ]))).toEqual([['div', null], ['a', 1]]); }); it('should override <ng-content>', () => { expect(humanizeContentProjection(parse( '<div><ng-content ngProjectAs="b"></ng-content></div>', [createComp('div', ['ng-content', 'b'])]))) .toEqual([['div', null], ['ng-content', 1]]); }); it('should override <template>', () => { expect(humanizeContentProjection(parse( '<div><template ngProjectAs="b"></template></div>', [createComp('div', ['template', 'b'])]))) .toEqual([['div', null], ['template', 1]]); }); it('should override inline templates', () => { expect(humanizeContentProjection(parse( '<div><a *ngIf="cond" ngProjectAs="b"></a></div>', [createComp('div', ['a', 'b']), ngIf]))) .toEqual([['div', null], ['template', 1], ['a', null]]); }); }); it('should support other directives before the component', () => { expect(humanizeContentProjection(parse('<div>hello</div>', [ createDir('div'), createComp('div', ['*']) ]))).toEqual([['div', null], ['#text(hello)', 0]]); }); }); describe('splitClasses', () => { it('should keep an empty class', () => { expect(splitClasses('a')).toEqual(['a']); }); it('should split 2 classes', () => { expect(splitClasses('a b')).toEqual(['a', 'b']); }); it('should trim classes', () => { expect(splitClasses(' a b ')).toEqual(['a', 'b']); }); }); describe('error cases', () => { it('should report when ng-content has content', () => { expect(() => parse('<ng-content>content</ng-content>', [])) .toThrowError(`Template parse errors: <ng-content> element cannot have content. <ng-content> must be immediately followed by </ng-content> ("[ERROR ->]<ng-content>content</ng-content>"): TestComp@0:0`); }); it('should treat *attr on a template element as valid', () => { expect(() => parse('<template *ngIf>', [])).not.toThrowError(); }); it('should treat template attribute on a template element as valid', () => { expect(() => parse('<template template="ngIf">', [])).not.toThrowError(); }); it('should report when mutliple *attrs are used on the same element', () => { expect(() => parse('<div *ngIf *ngFor>', [])).toThrowError(`Template parse errors: Can't have multiple template bindings on one element. Use only one attribute named 'template' or prefixed with * ("<div *ngIf [ERROR ->]*ngFor>"): TestComp@0:11`); }); it('should report when mix of template and *attrs are used on the same element', () => { expect(() => parse('<div template="ngIf" *ngFor>', [])).toThrowError(`Template parse errors: Can't have multiple template bindings on one element. Use only one attribute named 'template' or prefixed with * ("<div template="ngIf" [ERROR ->]*ngFor>"): TestComp@0:21`); }); it('should report invalid property names', () => { expect(() => parse('<div [invalidProp]></div>', [])).toThrowError(`Template parse errors: Can't bind to 'invalidProp' since it isn't a known native property ("<div [ERROR ->][invalidProp]></div>"): TestComp@0:5`); }); it('should report invalid host property names', () => { var dirA = CompileDirectiveMetadata.create({ selector: 'div', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}), host: {'[invalidProp]': 'someProp'} }); expect(() => parse('<div></div>', [dirA])).toThrowError(`Template parse errors: Can't bind to 'invalidProp' since it isn't a known native property ("[ERROR ->]<div></div>"): TestComp@0:0, Directive DirA`); }); it('should report errors in expressions', () => { expect(() => parse('<div [prop]="a b"></div>', [])).toThrowError(`Template parse errors: Parser Error: Unexpected token 'b' at column 3 in [a b] in TestComp@0:5 ("<div [ERROR ->][prop]="a b"></div>"): TestComp@0:5`); }); it('should not throw on invalid property names if the property is used by a directive', () => { var dirA = CompileDirectiveMetadata.create({ selector: 'div', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}), inputs: ['invalidProp'] }); expect(() => parse('<div [invalid-prop]></div>', [dirA])).not.toThrow(); }); it('should not allow more than 1 component per element', () => { var dirA = CompileDirectiveMetadata.create({ selector: 'div', isComponent: true, type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}), template: new CompileTemplateMetadata({ngContentSelectors: []}) }); var dirB = CompileDirectiveMetadata.create({ selector: 'div', isComponent: true, type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirB'}), template: new CompileTemplateMetadata({ngContentSelectors: []}) }); expect(() => parse('<div>', [dirB, dirA])).toThrowError(`Template parse errors: More than one component: DirB,DirA ("[ERROR ->]<div>"): TestComp@0:0`); }); it('should not allow components or element bindings nor dom events on explicit embedded templates', () => { var dirA = CompileDirectiveMetadata.create({ selector: '[a]', isComponent: true, type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}), template: new CompileTemplateMetadata({ngContentSelectors: []}) }); expect(() => parse('<template [a]="b" (e)="f"></template>', [dirA])) .toThrowError(`Template parse errors: Event binding e not emitted by any directive on an embedded template. Make sure that the event name is spelled correctly and all directives are listed in the "directives" section. ("<template [a]="b" [ERROR ->](e)="f"></template>"): TestComp@0:18 Components on an embedded template: DirA ("[ERROR ->]<template [a]="b" (e)="f"></template>"): TestComp@0:0 Property binding a not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "directives" section. ("[ERROR ->]<template [a]="b" (e)="f"></template>"): TestComp@0:0`); }); it('should not allow components or element bindings on inline embedded templates', () => { var dirA = CompileDirectiveMetadata.create({ selector: '[a]', isComponent: true, type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}), template: new CompileTemplateMetadata({ngContentSelectors: []}) }); expect(() => parse('<div *a="b"></div>', [dirA])).toThrowError(`Template parse errors: Components on an embedded template: DirA ("[ERROR ->]<div *a="b"></div>"): TestComp@0:0 Property binding a not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "directives" section. ("[ERROR ->]<div *a="b"></div>"): TestComp@0:0`); }); }); describe('ignore elements', () => { it('should ignore <script> elements', () => { expect(humanizeTplAst(parse('<script></script>a', []))).toEqual([[TextAst, 'a']]); }); it('should ignore <style> elements', () => { expect(humanizeTplAst(parse('<style></style>a', []))).toEqual([[TextAst, 'a']]); }); describe('<link rel="stylesheet">', () => { it('should keep <link rel="stylesheet"> elements if they have an absolute non package: url', () => { expect(humanizeTplAst(parse('<link rel="stylesheet" href="http://someurl">a', []))) .toEqual([ [ElementAst, 'link'], [AttrAst, 'rel', 'stylesheet'], [AttrAst, 'href', 'http://someurl'], [TextAst, 'a'] ]); }); it('should keep <link rel="stylesheet"> elements if they have no uri', () => { expect(humanizeTplAst(parse('<link rel="stylesheet">a', [ ]))).toEqual([[ElementAst, 'link'], [AttrAst, 'rel', 'stylesheet'], [TextAst, 'a']]); expect(humanizeTplAst(parse('<link REL="stylesheet">a', [ ]))).toEqual([[ElementAst, 'link'], [AttrAst, 'REL', 'stylesheet'], [TextAst, 'a']]); }); it('should ignore <link rel="stylesheet"> elements if they have a relative uri', () => { expect(humanizeTplAst(parse('<link rel="stylesheet" href="./other.css">a', [ ]))).toEqual([[TextAst, 'a']]); expect(humanizeTplAst(parse('<link rel="stylesheet" HREF="./other.css">a', [ ]))).toEqual([[TextAst, 'a']]); }); it('should ignore <link rel="stylesheet"> elements if they have a package: uri', () => { expect(humanizeTplAst(parse('<link rel="stylesheet" href="package:somePackage">a', [ ]))).toEqual([[TextAst, 'a']]); }); }); it('should ignore bindings on children of elements with ngNonBindable', () => { expect(humanizeTplAst(parse('<div ngNonBindable>{{b}}</div>', [ ]))).toEqual([[ElementAst, 'div'], [AttrAst, 'ngNonBindable', ''], [TextAst, '{{b}}']]); }); it('should keep nested children of elements with ngNonBindable', () => { expect(humanizeTplAst(parse('<div ngNonBindable><span>{{b}}</span></div>', []))).toEqual([ [ElementAst, 'div'], [AttrAst, 'ngNonBindable', ''], [ElementAst, 'span'], [TextAst, '{{b}}'] ]); }); it('should ignore <script> elements inside of elements with ngNonBindable', () => { expect(humanizeTplAst(parse('<div ngNonBindable><script></script>a</div>', [ ]))).toEqual([[ElementAst, 'div'], [AttrAst, 'ngNonBindable', ''], [TextAst, 'a']]); }); it('should ignore <style> elements inside of elements with ngNonBindable', () => { expect(humanizeTplAst(parse('<div ngNonBindable><style></style>a</div>', [ ]))).toEqual([[ElementAst, 'div'], [AttrAst, 'ngNonBindable', ''], [TextAst, 'a']]); }); it('should ignore <link rel="stylesheet"> elements inside of elements with ngNonBindable', () => { expect(humanizeTplAst(parse('<div ngNonBindable><link rel="stylesheet">a</div>', [ ]))).toEqual([[ElementAst, 'div'], [AttrAst, 'ngNonBindable', ''], [TextAst, 'a']]); }); it('should convert <ng-content> elements into regular elements inside of elements with ngNonBindable', () => { expect(humanizeTplAst(parse('<div ngNonBindable><ng-content></ng-content>a</div>', []))) .toEqual([ [ElementAst, 'div'], [AttrAst, 'ngNonBindable', ''], [ElementAst, 'ng-content'], [TextAst, 'a'] ]); }); }); describe('source spans', () => { it('should support ng-content', () => { var parsed = parse('<ng-content select="a">', []); expect(humanizeTplAstSourceSpans(parsed)).toEqual([ [NgContentAst, '<ng-content select="a">'] ]); }); it('should support embedded template', () => { expect(humanizeTplAstSourceSpans(parse('<template></template>', [ ]))).toEqual([[EmbeddedTemplateAst, '<template>']]); }); it('should support element and attributes', () => { expect(humanizeTplAstSourceSpans(parse('<div key=value>', []))).toEqual([ [ElementAst, 'div', '<div key=value>'], [AttrAst, 'key', 'value', 'key=value'] ]); }); it('should support references', () => { expect(humanizeTplAstSourceSpans(parse('<div #a></div>', [ ]))).toEqual([[ElementAst, 'div', '<div #a>'], [ReferenceAst, 'a', null, '#a']]); }); it('should support variables', () => { expect(humanizeTplAstSourceSpans(parse('<template let-a="b"></template>', []))).toEqual([ [EmbeddedTemplateAst, '<template let-a="b">'], [VariableAst, 'a', 'b', 'let-a="b"'] ]); }); it('should support events', () => { expect(humanizeTplAstSourceSpans(parse('<div (window:event)="v">', []))).toEqual([ [ElementAst, 'div', '<div (window:event)="v">'], [BoundEventAst, 'event', 'window', 'v', '(window:event)="v"'] ]); }); it('should support element property', () => { expect(humanizeTplAstSourceSpans(parse('<div [someProp]="v">', []))).toEqual([ [ElementAst, 'div', '<div [someProp]="v">'], [ BoundElementPropertyAst, PropertyBindingType.Property, 'someProp', 'v', null, '[someProp]="v"' ] ]); }); it('should support bound text', () => { expect(humanizeTplAstSourceSpans(parse('{{a}}', [ ]))).toEqual([[BoundTextAst, '{{ a }}', '{{a}}']]); }); it('should support text nodes', () => { expect(humanizeTplAstSourceSpans(parse('a', []))).toEqual([[TextAst, 'a', 'a']]); }); it('should support directive', () => { var dirA = CompileDirectiveMetadata.create({ selector: '[a]', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}) }); var comp = CompileDirectiveMetadata.create({ selector: 'div', isComponent: true, type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'ZComp'}), template: new CompileTemplateMetadata({ngContentSelectors: []}) }); expect(humanizeTplAstSourceSpans(parse('<div a>', [dirA, comp]))).toEqual([ [ElementAst, 'div', '<div a>'], [AttrAst, 'a', '', 'a'], [DirectiveAst, dirA, '<div a>'], [DirectiveAst, comp, '<div a>'] ]); }); it('should support directive in namespace', () => { var tagSel = CompileDirectiveMetadata.create({ selector: 'circle', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'elDir'}) }); var attrSel = CompileDirectiveMetadata.create({ selector: '[href]', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'attrDir'}) }); expect(humanizeTplAstSourceSpans( parse('<svg><circle /><use xlink:href="Port" /></svg>', [tagSel, attrSel]))) .toEqual([ [ElementAst, ':svg:svg', '<svg>'], [ElementAst, ':svg:circle', '<circle />'], [DirectiveAst, tagSel, '<circle />'], [ElementAst, ':svg:use', '<use xlink:href="Port" />'], [AttrAst, ':xlink:href', 'Port', 'xlink:href="Port"'], [DirectiveAst, attrSel, '<use xlink:href="Port" />'], ]); }); it('should support directive property', () => { var dirA = CompileDirectiveMetadata.create({ selector: 'div', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}), inputs: ['aProp'] }); expect(humanizeTplAstSourceSpans(parse('<div [aProp]="foo"></div>', [dirA]))).toEqual([ [ElementAst, 'div', '<div [aProp]="foo">'], [DirectiveAst, dirA, '<div [aProp]="foo">'], [BoundDirectivePropertyAst, 'aProp', 'foo', '[aProp]="foo"'] ]); }); }); describe('pipes', () => { it('should allow pipes that have been defined as dependencies', () => { var testPipe = new CompilePipeMetadata({ name: 'test', type: new CompileTypeMetadata({moduleUrl: someModuleUrl, name: 'DirA'}) }); expect(() => parse('{{a | test}}', [], [testPipe])).not.toThrow(); }); it('should report pipes as error that have not been defined as dependencies', () => { expect(() => parse('{{a | test}}', [])).toThrowError(`Template parse errors: The pipe 'test' could not be found ("[ERROR ->]{{a | test}}"): TestComp@0:0`); }); }); describe('ICU messages', () => { it('should expand plural messages', () => { const shortForm = '{ count, plural, =0 {small} many {big} }'; const expandedForm = '<ng-container [ngPlural]="count">' + '<template ngPluralCase="=0">small</template>' + '<template ngPluralCase="many">big</template>' + '</ng-container>'; expect(humanizeTplAst(parse(shortForm, []))).toEqual(humanizeTplAst(parse(expandedForm, [ ]))); }); it('should expand other messages', () => { const shortForm = '{ sex, gender, =f {foo} other {bar} }'; const expandedForm = '<ng-container [ngSwitch]="sex">' + '<template ngSwitchCase="=f">foo</template>' + '<template ngSwitchCase="other">bar</template>' + '</ng-container>'; expect(humanizeTplAst(parse(shortForm, []))).toEqual(humanizeTplAst(parse(expandedForm, [ ]))); }); it('should be possible to escape ICU messages', () => { const escapedForm = 'escaped {{ "{" }} }'; expect(humanizeTplAst(parse(escapedForm, []))).toEqual([ [BoundTextAst, 'escaped {{ "{" }} }'], ]); }); }); }); } function humanizeTplAst( templateAsts: TemplateAst[], interpolationConfig?: InterpolationConfig): any[] { const humanizer = new TemplateHumanizer(false, interpolationConfig); templateVisitAll(humanizer, templateAsts); return humanizer.result; } function humanizeTplAstSourceSpans( templateAsts: TemplateAst[], interpolationConfig?: InterpolationConfig): any[] { const humanizer = new TemplateHumanizer(true, interpolationConfig); templateVisitAll(humanizer, templateAsts); return humanizer.result; } class TemplateHumanizer implements TemplateAstVisitor { result: any[] = []; constructor( private includeSourceSpan: boolean, private interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG){}; visitNgContent(ast: NgContentAst, context: any): any { var res = [NgContentAst]; this.result.push(this._appendContext(ast, res)); return null; } visitEmbeddedTemplate(ast: EmbeddedTemplateAst, context: any): any { var res = [EmbeddedTemplateAst]; this.result.push(this._appendContext(ast, res)); templateVisitAll(this, ast.attrs); templateVisitAll(this, ast.outputs); templateVisitAll(this, ast.references); templateVisitAll(this, ast.variables); templateVisitAll(this, ast.directives); templateVisitAll(this, ast.children); return null; } visitElement(ast: ElementAst, context: any): any { var res = [ElementAst, ast.name]; this.result.push(this._appendContext(ast, res)); templateVisitAll(this, ast.attrs); templateVisitAll(this, ast.inputs); templateVisitAll(this, ast.outputs); templateVisitAll(this, ast.references); templateVisitAll(this, ast.directives); templateVisitAll(this, ast.children); return null; } visitReference(ast: ReferenceAst, context: any): any { var res = [ReferenceAst, ast.name, ast.value]; this.result.push(this._appendContext(ast, res)); return null; } visitVariable(ast: VariableAst, context: any): any { var res = [VariableAst, ast.name, ast.value]; this.result.push(this._appendContext(ast, res)); return null; } visitEvent(ast: BoundEventAst, context: any): any { var res = [BoundEventAst, ast.name, ast.target, unparse(ast.handler, this.interpolationConfig)]; this.result.push(this._appendContext(ast, res)); return null; } visitElementProperty(ast: BoundElementPropertyAst, context: any): any { var res = [ BoundElementPropertyAst, ast.type, ast.name, unparse(ast.value, this.interpolationConfig), ast.unit ]; this.result.push(this._appendContext(ast, res)); return null; } visitAttr(ast: AttrAst, context: any): any { var res = [AttrAst, ast.name, ast.value]; this.result.push(this._appendContext(ast, res)); return null; } visitBoundText(ast: BoundTextAst, context: any): any { var res = [BoundTextAst, unparse(ast.value, this.interpolationConfig)]; this.result.push(this._appendContext(ast, res)); return null; } visitText(ast: TextAst, context: any): any { var res = [TextAst, ast.value]; this.result.push(this._appendContext(ast, res)); return null; } visitDirective(ast: DirectiveAst, context: any): any { var res = [DirectiveAst, ast.directive]; this.result.push(this._appendContext(ast, res)); templateVisitAll(this, ast.inputs); templateVisitAll(this, ast.hostProperties); templateVisitAll(this, ast.hostEvents); return null; } visitDirectiveProperty(ast: BoundDirectivePropertyAst, context: any): any { var res = [ BoundDirectivePropertyAst, ast.directiveName, unparse(ast.value, this.interpolationConfig) ]; this.result.push(this._appendContext(ast, res)); return null; } private _appendContext(ast: TemplateAst, input: any[]): any[] { if (!this.includeSourceSpan) return input; input.push(ast.sourceSpan.toString()); return input; } } function sourceInfo(ast: TemplateAst): string { return `${ast.sourceSpan}: ${ast.sourceSpan.start}`; } function humanizeContentProjection(templateAsts: TemplateAst[]): any[] { var humanizer = new TemplateContentProjectionHumanizer(); templateVisitAll(humanizer, templateAsts); return humanizer.result; } class TemplateContentProjectionHumanizer implements TemplateAstVisitor { result: any[] = []; visitNgContent(ast: NgContentAst, context: any): any { this.result.push(['ng-content', ast.ngContentIndex]); return null; } visitEmbeddedTemplate(ast: EmbeddedTemplateAst, context: any): any { this.result.push(['template', ast.ngContentIndex]); templateVisitAll(this, ast.children); return null; } visitElement(ast: ElementAst, context: any): any { this.result.push([ast.name, ast.ngContentIndex]); templateVisitAll(this, ast.children); return null; } visitReference(ast: ReferenceAst, context: any): any { return null; } visitVariable(ast: VariableAst, context: any): any { return null; } visitEvent(ast: BoundEventAst, context: any): any { return null; } visitElementProperty(ast: BoundElementPropertyAst, context: any): any { return null; } visitAttr(ast: AttrAst, context: any): any { return null; } visitBoundText(ast: BoundTextAst, context: any): any { this.result.push([`#text(${unparse(ast.value)})`, ast.ngContentIndex]); return null; } visitText(ast: TextAst, context: any): any { this.result.push([`#text(${ast.value})`, ast.ngContentIndex]); return null; } visitDirective(ast: DirectiveAst, context: any): any { return null; } visitDirectiveProperty(ast: BoundDirectivePropertyAst, context: any): any { return null; } } class FooAstTransformer implements TemplateAstVisitor { visitNgContent(ast: NgContentAst, context: any): any { throw 'not implemented'; } visitEmbeddedTemplate(ast: EmbeddedTemplateAst, context: any): any { throw 'not implemented'; } visitElement(ast: ElementAst, context: any): any { if (ast.name != 'div') return ast; return new ElementAst( 'foo', [], [], [], [], [], [], false, [], ast.ngContentIndex, ast.sourceSpan); } visitReference(ast: ReferenceAst, context: any): any { throw 'not implemented'; } visitVariable(ast: VariableAst, context: any): any { throw 'not implemented'; } visitEvent(ast: BoundEventAst, context: any): any { throw 'not implemented'; } visitElementProperty(ast: BoundElementPropertyAst, context: any): any { throw 'not implemented'; } visitAttr(ast: AttrAst, context: any): any { throw 'not implemented'; } visitBoundText(ast: BoundTextAst, context: any): any { throw 'not implemented'; } visitText(ast: TextAst, context: any): any { throw 'not implemented'; } visitDirective(ast: DirectiveAst, context: any): any { throw 'not implemented'; } visitDirectiveProperty(ast: BoundDirectivePropertyAst, context: any): any { throw 'not implemented'; } } class BarAstTransformer extends FooAstTransformer { visitElement(ast: ElementAst, context: any): any { if (ast.name != 'foo') return ast; return new ElementAst( 'bar', [], [], [], [], [], [], false, [], ast.ngContentIndex, ast.sourceSpan); } } class ArrayConsole implements Console { logs: string[] = []; warnings: string[] = []; log(msg: string) { this.logs.push(msg); } warn(msg: string) { this.warnings.push(msg); } }
modules/@angular/compiler/test/template_parser/template_parser_spec.ts
1
https://github.com/angular/angular/commit/a55d796c4b4cbe5bc1256339bd398090f58b4d69
[ 0.998862624168396, 0.24515433609485626, 0.00016247453459072858, 0.00018049016944132745, 0.413713276386261 ]
{ "id": 3, "code_window": [ "\n", " it('should report invalid property names', () => {\n", " expect(() => parse('<div [invalidProp]></div>', [])).toThrowError(`Template parse errors:\n", "Can't bind to 'invalidProp' since it isn't a known native property (\"<div [ERROR ->][invalidProp]></div>\"): TestComp@0:5`);\n", " });\n", "\n", " it('should report invalid host property names', () => {\n", " var dirA = CompileDirectiveMetadata.create({\n", " selector: 'div',\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "Can't bind to 'invalidProp' since it isn't a known property of 'div'. (\"<div [ERROR ->][invalidProp]></div>\"): TestComp@0:5`);\n" ], "file_path": "modules/@angular/compiler/test/template_parser/template_parser_spec.ts", "type": "replace", "edit_start_line_idx": 1242 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {LocationStrategy} from '@angular/common'; import {APP_ID, NgModule, NgZone, OpaqueToken, PLATFORM_COMMON_PROVIDERS, PLATFORM_INITIALIZER, PlatformRef, ReflectiveInjector, assertPlatform, createPlatform, createPlatformFactory, getPlatform, platformCore} from '@angular/core'; import {BrowserModule} from '../src/browser'; import {BrowserDomAdapter} from '../src/browser/browser_adapter'; import {AnimationDriver} from '../src/dom/animation_driver'; import {ELEMENT_PROBE_PROVIDERS} from '../src/dom/debug/ng_probe'; import {BrowserDetection} from './browser_util'; function initBrowserTests() { BrowserDomAdapter.makeCurrent(); BrowserDetection.setup(); } function createNgZone(): NgZone { return new NgZone({enableLongStackTrace: true}); } const _TEST_BROWSER_PLATFORM_PROVIDERS: Array<any /*Type | Provider | any[]*/> = [{provide: PLATFORM_INITIALIZER, useValue: initBrowserTests, multi: true}]; /** * Providers for the browser test platform * * @deprecated Use `platformBrowserTesting()` or create a custom platform factory via * `createPlatformFactory(platformBrowserTesting, ...)` */ export const TEST_BROWSER_PLATFORM_PROVIDERS: Array<any /*Type | Provider | any[]*/> = [PLATFORM_COMMON_PROVIDERS, _TEST_BROWSER_PLATFORM_PROVIDERS]; /** * @deprecated Use initTestEnvironment with BrowserTestModule instead. This is empty for backwards * compatibility, * as all of our bootstrap methods add a module implicitly, i.e. keeping this filled would add the * providers 2x. */ export const TEST_BROWSER_APPLICATION_PROVIDERS: Array<any /*Type | Provider | any[]*/> = []; /** * Platform for testing * * @experimental API related to bootstrapping are still under review. */ export const platformBrowserTesting = createPlatformFactory(platformCore, 'browserTesting', _TEST_BROWSER_PLATFORM_PROVIDERS); /** * @deprecated Use {@link platformBrowserTesting} instead */ export const browserTestingPlatform = platformBrowserTesting; /** * NgModule for testing. * * @experimental */ @NgModule({ exports: [BrowserModule], providers: [ {provide: APP_ID, useValue: 'a'}, ELEMENT_PROBE_PROVIDERS, {provide: NgZone, useFactory: createNgZone}, {provide: AnimationDriver, useValue: AnimationDriver.NOOP} ] }) export class BrowserTestingModule { }
modules/@angular/platform-browser/testing/browser.ts
0
https://github.com/angular/angular/commit/a55d796c4b4cbe5bc1256339bd398090f58b4d69
[ 0.000378007855033502, 0.0002011257311096415, 0.00016960162611212581, 0.00017374225717503577, 0.00006740862590959296 ]
{ "id": 3, "code_window": [ "\n", " it('should report invalid property names', () => {\n", " expect(() => parse('<div [invalidProp]></div>', [])).toThrowError(`Template parse errors:\n", "Can't bind to 'invalidProp' since it isn't a known native property (\"<div [ERROR ->][invalidProp]></div>\"): TestComp@0:5`);\n", " });\n", "\n", " it('should report invalid host property names', () => {\n", " var dirA = CompileDirectiveMetadata.create({\n", " selector: 'div',\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "Can't bind to 'invalidProp' since it isn't a known property of 'div'. (\"<div [ERROR ->][invalidProp]></div>\"): TestComp@0:5`);\n" ], "file_path": "modules/@angular/compiler/test/template_parser/template_parser_spec.ts", "type": "replace", "edit_start_line_idx": 1242 }
modules/@angular/docs/core/04_decorator_directive.md
0
https://github.com/angular/angular/commit/a55d796c4b4cbe5bc1256339bd398090f58b4d69
[ 0.0001709938806015998, 0.0001709938806015998, 0.0001709938806015998, 0.0001709938806015998, 0 ]
{ "id": 3, "code_window": [ "\n", " it('should report invalid property names', () => {\n", " expect(() => parse('<div [invalidProp]></div>', [])).toThrowError(`Template parse errors:\n", "Can't bind to 'invalidProp' since it isn't a known native property (\"<div [ERROR ->][invalidProp]></div>\"): TestComp@0:5`);\n", " });\n", "\n", " it('should report invalid host property names', () => {\n", " var dirA = CompileDirectiveMetadata.create({\n", " selector: 'div',\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "Can't bind to 'invalidProp' since it isn't a known property of 'div'. (\"<div [ERROR ->][invalidProp]></div>\"): TestComp@0:5`);\n" ], "file_path": "modules/@angular/compiler/test/template_parser/template_parser_spec.ts", "type": "replace", "edit_start_line_idx": 1242 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ExtractionResult, extractAstMessages} from '@angular/compiler/src/i18n/extractor'; import {beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal'; import {HtmlParser} from '../../src/html_parser/html_parser'; import {serializeAst} from '../html_parser/ast_serializer_spec'; export function main() { describe('MessageExtractor', () => { describe('elements', () => { it('should extract from elements', () => { expect(extract('<div i18n="m|d|e">text<span>nested</span></div>')).toEqual([ [['text', '<span>nested</span>'], 'm', 'd|e'], ]); }); it('should not create a message for empty elements', () => { expect(extract('<div i18n="m|d"></div>')).toEqual([]); }); }); describe('blocks', () => { it('should extract from blocks', () => { expect(extract(`<!-- i18n: meaning1|desc1 -->message1<!-- /i18n --> <!-- i18n: desc2 -->message2<!-- /i18n --> <!-- i18n -->message3<!-- /i18n -->`)) .toEqual([ [['message1'], 'meaning1', 'desc1'], [['message2'], '', 'desc2'], [['message3'], '', ''], ]); }); it('should extract siblings', () => { expect( extract( `<!-- i18n -->text<p>html<b>nested</b></p>{count, plural, =0 {<span>html</span>}}{{interp}}<!-- /i18n -->`)) .toEqual([ [['{count, plural, =0 {<span>html</span>}}'], '', ''], [ [ 'text', '<p>html<b>nested</b></p>', '{count, plural, =0 {<span>html</span>}}', '{{interp}}' ], '', '' ], ]); }); it('should ignore other comments', () => { expect(extract(`<!-- i18n: meaning1|desc1 --><!-- other -->message1<!-- /i18n -->`)) .toEqual([ [['message1'], 'meaning1', 'desc1'], ]); }); it('should not create a message for empty blocks', () => { expect(extract(`<!-- i18n: meaning1|desc1 --><!-- /i18n -->`)).toEqual([]); }); }); describe('ICU messages', () => { it('should extract ICU messages from translatable elements', () => { // single message when ICU is the only children expect(extract('<div i18n="m|d">{count, plural, =0 {text}}</div>')).toEqual([ [['{count, plural, =0 {text}}'], 'm', 'd'], ]); // one message for the element content and one message for the ICU expect(extract('<div i18n="m|d">before{count, plural, =0 {text}}after</div>')).toEqual([ [['before', '{count, plural, =0 {text}}', 'after'], 'm', 'd'], [['{count, plural, =0 {text}}'], '', ''], ]); }); it('should extract ICU messages from translatable block', () => { // single message when ICU is the only children expect(extract('<!-- i18n:m|d -->{count, plural, =0 {text}}<!-- /i18n -->')).toEqual([ [['{count, plural, =0 {text}}'], 'm', 'd'], ]); // one message for the block content and one message for the ICU expect(extract('<!-- i18n:m|d -->before{count, plural, =0 {text}}after<!-- /i18n -->')) .toEqual([ [['{count, plural, =0 {text}}'], '', ''], [['before', '{count, plural, =0 {text}}', 'after'], 'm', 'd'], ]); }); it('should not extract ICU messages outside of i18n sections', () => { expect(extract('{count, plural, =0 {text}}')).toEqual([]); }); it('should not extract nested ICU messages', () => { expect(extract('<div i18n="m|d">{count, plural, =0 { {sex, gender, =m {m}} }}</div>')) .toEqual([ [['{count, plural, =0 {{sex, gender, =m {m}} }}'], 'm', 'd'], ]); }); }); describe('attributes', () => { it('should extract from attributes outside of translatable section', () => { expect(extract('<div i18n-title="m|d" title="msg"></div>')).toEqual([ [['title="msg"'], 'm', 'd'], ]); }); it('should extract from attributes in translatable element', () => { expect(extract('<div i18n><p><b i18n-title="m|d" title="msg"></b></p></div>')).toEqual([ [['<p><b i18n-title="m|d" title="msg"></b></p>'], '', ''], [['title="msg"'], 'm', 'd'], ]); }); it('should extract from attributes in translatable block', () => { expect(extract('<!-- i18n --><p><b i18n-title="m|d" title="msg"></b></p><!-- /i18n -->')) .toEqual([ [['title="msg"'], 'm', 'd'], [['<p><b i18n-title="m|d" title="msg"></b></p>'], '', ''], ]); }); it('should extract from attributes in translatable ICU', () => { expect( extract( '<!-- i18n -->{count, plural, =0 {<p><b i18n-title="m|d" title="msg"></b></p>}}<!-- /i18n -->')) .toEqual([ [['title="msg"'], 'm', 'd'], [['{count, plural, =0 {<p><b i18n-title="m|d" title="msg"></b></p>}}'], '', ''], ]); }); it('should extract from attributes in non translatable ICU', () => { expect(extract('{count, plural, =0 {<p><b i18n-title="m|d" title="msg"></b></p>}}')) .toEqual([ [['title="msg"'], 'm', 'd'], ]); }); it('should not create a message for empty attributes', () => { expect(extract('<div i18n-title="m|d" title></div>')).toEqual([]); }); }); describe('implicit elements', () => { it('should extract from implicit elements', () => { expect(extract('<b>bold</b><i>italic</i>', ['b'])).toEqual([ [['bold'], '', ''], ]); }); }); describe('implicit attributes', () => { it('should extract implicit attributes', () => { expect(extract('<b title="bb">bold</b><i title="ii">italic</i>', [], {'b': ['title']})) .toEqual([ [['title="bb"'], '', ''], ]); }); }); describe('errors', () => { describe('elements', () => { it('should report nested translatable elements', () => { expect(extractErrors(`<p i18n><b i18n></b></p>`)).toEqual([ ['Could not mark an element as translatable inside a translatable section', '<b i18n>'], ]); }); it('should report translatable elements in implicit elements', () => { expect(extractErrors(`<p><b i18n></b></p>`, ['p'])).toEqual([ ['Could not mark an element as translatable inside a translatable section', '<b i18n>'], ]); }); it('should report translatable elements in translatable blocks', () => { expect(extractErrors(`<!-- i18n --><b i18n></b><!-- /i18n -->`)).toEqual([ ['Could not mark an element as translatable inside a translatable section', '<b i18n>'], ]); }); }); describe('blocks', () => { it('should report nested blocks', () => { expect(extractErrors(`<!-- i18n --><!-- i18n --><!-- /i18n --><!-- /i18n -->`)).toEqual([ ['Could not start a block inside a translatable section', '<!--'], ['Trying to close an unopened block', '<!--'], ]); }); it('should report unclosed blocks', () => { expect(extractErrors(`<!-- i18n -->`)).toEqual([ ['Unclosed block', '<!--'], ]); }); it('should report translatable blocks in translatable elements', () => { expect(extractErrors(`<p i18n><!-- i18n --><!-- /i18n --></p>`)).toEqual([ ['Could not start a block inside a translatable section', '<!--'], ['Trying to close an unopened block', '<!--'], ]); }); it('should report translatable blocks in implicit elements', () => { expect(extractErrors(`<p><!-- i18n --><!-- /i18n --></p>`, ['p'])).toEqual([ ['Could not start a block inside a translatable section', '<!--'], ['Trying to close an unopened block', '<!--'], ]); }); it('should report when start and end of a block are not at the same level', () => { expect(extractErrors(`<!-- i18n --><p><!-- /i18n --></p>`)).toEqual([ ['I18N blocks should not cross element boundaries', '<!--'], ['Unclosed block', '<p>'], ]); expect(extractErrors(`<p><!-- i18n --></p><!-- /i18n -->`)).toEqual([ ['I18N blocks should not cross element boundaries', '<!--'], ['Unclosed block', '<!--'], ]); }); }); describe('implicit elements', () => { it('should report nested implicit elements', () => { expect(extractErrors(`<p><b></b></p>`, ['p', 'b'])).toEqual([ ['Could not mark an element as translatable inside a translatable section', '<b>'], ]); }); it('should report implicit element in translatable element', () => { expect(extractErrors(`<p i18n><b></b></p>`, ['b'])).toEqual([ ['Could not mark an element as translatable inside a translatable section', '<b>'], ]); }); it('should report implicit element in translatable blocks', () => { expect(extractErrors(`<!-- i18n --><b></b><!-- /i18n -->`, ['b'])).toEqual([ ['Could not mark an element as translatable inside a translatable section', '<b>'], ]); }); }); }); }); } function getExtractionResult( html: string, implicitTags: string[], implicitAttrs: {[k: string]: string[]}): ExtractionResult { const htmlParser = new HtmlParser(); const parseResult = htmlParser.parse(html, 'extractor spec', true); if (parseResult.errors.length > 1) { throw Error(`unexpected parse errors: ${parseResult.errors.join('\n')}`); } return extractAstMessages(parseResult.rootNodes, implicitTags, implicitAttrs); } function extract( html: string, implicitTags: string[] = [], implicitAttrs: {[k: string]: string[]} = {}): [string[], string, string][] { const messages = getExtractionResult(html, implicitTags, implicitAttrs).messages; // clang-format off // https://github.com/angular/clang-format/issues/35 return messages.map( message => [serializeAst(message.nodes), message.meaning, message.description, ]) as [string[], string, string][]; // clang-format on } function extractErrors( html: string, implicitTags: string[] = [], implicitAttrs: {[k: string]: string[]} = {}): any[] { const errors = getExtractionResult(html, implicitTags, implicitAttrs).errors; return errors.map((e): [string, string] => [e.msg, e.span.toString()]); }
modules/@angular/compiler/test/i18n/extractor_spec.ts
0
https://github.com/angular/angular/commit/a55d796c4b4cbe5bc1256339bd398090f58b4d69
[ 0.0002373219031142071, 0.00017604546155780554, 0.00016639665409456939, 0.0001726120535749942, 0.000014201922567735892 ]
{ "id": 4, "code_window": [ " host: {'[invalidProp]': 'someProp'}\n", " });\n", " expect(() => parse('<div></div>', [dirA])).toThrowError(`Template parse errors:\n", "Can't bind to 'invalidProp' since it isn't a known native property (\"[ERROR ->]<div></div>\"): TestComp@0:0, Directive DirA`);\n", " });\n", "\n", " it('should report errors in expressions', () => {\n", " expect(() => parse('<div [prop]=\"a b\"></div>', [])).toThrowError(`Template parse errors:\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "Can't bind to 'invalidProp' since it isn't a known property of 'div'. (\"[ERROR ->]<div></div>\"): TestComp@0:0, Directive DirA`);\n" ], "file_path": "modules/@angular/compiler/test/template_parser/template_parser_spec.ts", "type": "replace", "edit_start_line_idx": 1252 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Inject, Injectable, OpaqueToken, Optional, SchemaMetadata, SecurityContext} from '@angular/core'; import {Console, MAX_INTERPOLATION_VALUES} from '../../core_private'; import {ListWrapper, StringMapWrapper, SetWrapper,} from '../facade/collection'; import {RegExpWrapper, isPresent, isBlank} from '../facade/lang'; import {BaseException} from '../facade/exceptions'; import {EmptyExpr, AST, Interpolation, ASTWithSource, TemplateBinding, RecursiveAstVisitor, BindingPipe, ParserError} from '../expression_parser/ast'; import {Parser} from '../expression_parser/parser'; import {CompileDirectiveMetadata, CompilePipeMetadata, CompileTokenMetadata, removeIdentifierDuplicates,} from '../compile_metadata'; import {HtmlParser, ParseTreeResult} from '../html_parser/html_parser'; import {splitNsName, mergeNsAndName} from '../html_parser/tags'; import {ParseSourceSpan, ParseError, ParseErrorLevel} from '../parse_util'; import {InterpolationConfig} from '../html_parser/interpolation_config'; import {ElementAst, BoundElementPropertyAst, BoundEventAst, ReferenceAst, TemplateAst, TemplateAstVisitor, templateVisitAll, TextAst, BoundTextAst, EmbeddedTemplateAst, AttrAst, NgContentAst, PropertyBindingType, DirectiveAst, BoundDirectivePropertyAst, VariableAst} from './template_ast'; import {CssSelector, SelectorMatcher} from '../selector'; import {ElementSchemaRegistry} from '../schema/element_schema_registry'; import {preparseElement, PreparsedElementType} from './template_preparser'; import {isStyleUrlResolvable} from '../style_url_resolver'; import * as html from '../html_parser/ast'; import {splitAtColon} from '../util'; import {identifierToken, Identifiers} from '../identifiers'; import {expandNodes} from '../html_parser/icu_ast_expander'; import {ProviderElementContext, ProviderViewContext} from '../provider_analyzer'; // Group 1 = "bind-" // Group 2 = "var-" // Group 3 = "let-" // Group 4 = "ref-/#" // Group 5 = "on-" // Group 6 = "bindon-" // Group 7 = "animate-/@" // Group 8 = the identifier after "bind-", "var-/#", or "on-" // Group 9 = identifier inside [()] // Group 10 = identifier inside [] // Group 11 = identifier inside () const BIND_NAME_REGEXP = /^(?:(?:(?:(bind-)|(var-)|(let-)|(ref-|#)|(on-)|(bindon-)|(animate-|@))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/g; const TEMPLATE_ELEMENT = 'template'; const TEMPLATE_ATTR = 'template'; const TEMPLATE_ATTR_PREFIX = '*'; const CLASS_ATTR = 'class'; const PROPERTY_PARTS_SEPARATOR = '.'; const ATTRIBUTE_PREFIX = 'attr'; const CLASS_PREFIX = 'class'; const STYLE_PREFIX = 'style'; const TEXT_CSS_SELECTOR = CssSelector.parse('*')[0]; /** * Provides an array of {@link TemplateAstVisitor}s which will be used to transform * parsed templates before compilation is invoked, allowing custom expression syntax * and other advanced transformations. * * This is currently an internal-only feature and not meant for general use. */ export const TEMPLATE_TRANSFORMS: any = new OpaqueToken('TemplateTransforms'); export class TemplateParseError extends ParseError { constructor(message: string, span: ParseSourceSpan, level: ParseErrorLevel) { super(span, message, level); } } export class TemplateParseResult { constructor(public templateAst?: TemplateAst[], public errors?: ParseError[]) {} } @Injectable() export class TemplateParser { constructor( private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry, private _htmlParser: HtmlParser, private _console: Console, @Optional() @Inject(TEMPLATE_TRANSFORMS) public transforms: TemplateAstVisitor[]) {} parse( component: CompileDirectiveMetadata, template: string, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[], schemas: SchemaMetadata[], templateUrl: string): TemplateAst[] { const result = this.tryParse(component, template, directives, pipes, schemas, templateUrl); const warnings = result.errors.filter(error => error.level === ParseErrorLevel.WARNING); const errors = result.errors.filter(error => error.level === ParseErrorLevel.FATAL); if (warnings.length > 0) { this._console.warn(`Template parse warnings:\n${warnings.join('\n')}`); } if (errors.length > 0) { const errorString = errors.join('\n'); throw new BaseException(`Template parse errors:\n${errorString}`); } return result.templateAst; } tryParse( component: CompileDirectiveMetadata, template: string, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[], schemas: SchemaMetadata[], templateUrl: string): TemplateParseResult { let interpolationConfig: any; if (component.template) { interpolationConfig = InterpolationConfig.fromArray(component.template.interpolation); } let htmlAstWithErrors = this._htmlParser.parse(template, templateUrl, true, interpolationConfig); const errors: ParseError[] = htmlAstWithErrors.errors; let result: TemplateAst[]; if (errors.length == 0) { // Transform ICU messages to angular directives const expandedHtmlAst = expandNodes(htmlAstWithErrors.rootNodes); errors.push(...expandedHtmlAst.errors); htmlAstWithErrors = new ParseTreeResult(expandedHtmlAst.nodes, errors); } if (htmlAstWithErrors.rootNodes.length > 0) { const uniqDirectives = removeIdentifierDuplicates(directives); const uniqPipes = removeIdentifierDuplicates(pipes); const providerViewContext = new ProviderViewContext(component, htmlAstWithErrors.rootNodes[0].sourceSpan); const parseVisitor = new TemplateParseVisitor( providerViewContext, uniqDirectives, uniqPipes, schemas, this._exprParser, this._schemaRegistry); result = html.visitAll(parseVisitor, htmlAstWithErrors.rootNodes, EMPTY_ELEMENT_CONTEXT); errors.push(...parseVisitor.errors, ...providerViewContext.errors); } else { result = []; } this._assertNoReferenceDuplicationOnTemplate(result, errors); if (errors.length > 0) { return new TemplateParseResult(result, errors); } if (isPresent(this.transforms)) { this.transforms.forEach( (transform: TemplateAstVisitor) => { result = templateVisitAll(transform, result); }); } return new TemplateParseResult(result, errors); } /** @internal */ _assertNoReferenceDuplicationOnTemplate(result: TemplateAst[], errors: TemplateParseError[]): void { const existingReferences: string[] = []; result.filter(element => !!(<any>element).references) .forEach(element => (<any>element).references.forEach((reference: ReferenceAst) => { const name = reference.name; if (existingReferences.indexOf(name) < 0) { existingReferences.push(name); } else { const error = new TemplateParseError( `Reference "#${name}" is defined several times`, reference.sourceSpan, ParseErrorLevel.FATAL); errors.push(error); } })); } } class TemplateParseVisitor implements html.Visitor { selectorMatcher: SelectorMatcher; errors: TemplateParseError[] = []; directivesIndex = new Map<CompileDirectiveMetadata, number>(); ngContentCount: number = 0; pipesByName: Map<string, CompilePipeMetadata>; private _interpolationConfig: InterpolationConfig; constructor( public providerViewContext: ProviderViewContext, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[], private _schemas: SchemaMetadata[], private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry) { this.selectorMatcher = new SelectorMatcher(); const tempMeta = providerViewContext.component.template; if (isPresent(tempMeta) && isPresent(tempMeta.interpolation)) { this._interpolationConfig = { start: tempMeta.interpolation[0], end: tempMeta.interpolation[1] }; } ListWrapper.forEachWithIndex( directives, (directive: CompileDirectiveMetadata, index: number) => { const selector = CssSelector.parse(directive.selector); this.selectorMatcher.addSelectables(selector, directive); this.directivesIndex.set(directive, index); }); this.pipesByName = new Map<string, CompilePipeMetadata>(); pipes.forEach(pipe => this.pipesByName.set(pipe.name, pipe)); } private _reportError( message: string, sourceSpan: ParseSourceSpan, level: ParseErrorLevel = ParseErrorLevel.FATAL) { this.errors.push(new TemplateParseError(message, sourceSpan, level)); } private _reportParserErors(errors: ParserError[], sourceSpan: ParseSourceSpan) { for (const error of errors) { this._reportError(error.message, sourceSpan); } } private _parseInterpolation(value: string, sourceSpan: ParseSourceSpan): ASTWithSource { const sourceInfo = sourceSpan.start.toString(); try { const ast = this._exprParser.parseInterpolation(value, sourceInfo, this._interpolationConfig); if (ast) this._reportParserErors(ast.errors, sourceSpan); this._checkPipes(ast, sourceSpan); if (isPresent(ast) && (<Interpolation>ast.ast).expressions.length > MAX_INTERPOLATION_VALUES) { throw new BaseException( `Only support at most ${MAX_INTERPOLATION_VALUES} interpolation values!`); } return ast; } catch (e) { this._reportError(`${e}`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); } } private _parseAction(value: string, sourceSpan: ParseSourceSpan): ASTWithSource { const sourceInfo = sourceSpan.start.toString(); try { const ast = this._exprParser.parseAction(value, sourceInfo, this._interpolationConfig); if (ast) { this._reportParserErors(ast.errors, sourceSpan); } if (!ast || ast.ast instanceof EmptyExpr) { this._reportError(`Empty expressions are not allowed`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); } this._checkPipes(ast, sourceSpan); return ast; } catch (e) { this._reportError(`${e}`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); } } private _parseBinding(value: string, sourceSpan: ParseSourceSpan): ASTWithSource { const sourceInfo = sourceSpan.start.toString(); try { const ast = this._exprParser.parseBinding(value, sourceInfo, this._interpolationConfig); if (ast) this._reportParserErors(ast.errors, sourceSpan); this._checkPipes(ast, sourceSpan); return ast; } catch (e) { this._reportError(`${e}`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); } } private _parseTemplateBindings(value: string, sourceSpan: ParseSourceSpan): TemplateBinding[] { const sourceInfo = sourceSpan.start.toString(); try { const bindingsResult = this._exprParser.parseTemplateBindings(value, sourceInfo); this._reportParserErors(bindingsResult.errors, sourceSpan); bindingsResult.templateBindings.forEach((binding) => { if (isPresent(binding.expression)) { this._checkPipes(binding.expression, sourceSpan); } }); bindingsResult.warnings.forEach( (warning) => { this._reportError(warning, sourceSpan, ParseErrorLevel.WARNING); }); return bindingsResult.templateBindings; } catch (e) { this._reportError(`${e}`, sourceSpan); return []; } } private _checkPipes(ast: ASTWithSource, sourceSpan: ParseSourceSpan) { if (isPresent(ast)) { const collector = new PipeCollector(); ast.visit(collector); collector.pipes.forEach((pipeName) => { if (!this.pipesByName.has(pipeName)) { this._reportError(`The pipe '${pipeName}' could not be found`, sourceSpan); } }); } } visitExpansion(expansion: html.Expansion, context: any): any { return null; } visitExpansionCase(expansionCase: html.ExpansionCase, context: any): any { return null; } visitText(text: html.Text, parent: ElementContext): any { const ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR); const expr = this._parseInterpolation(text.value, text.sourceSpan); if (isPresent(expr)) { return new BoundTextAst(expr, ngContentIndex, text.sourceSpan); } else { return new TextAst(text.value, ngContentIndex, text.sourceSpan); } } visitAttribute(attribute: html.Attribute, contex: any): any { return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan); } visitComment(comment: html.Comment, context: any): any { return null; } visitElement(element: html.Element, parent: ElementContext): any { const nodeName = element.name; const preparsedElement = preparseElement(element); if (preparsedElement.type === PreparsedElementType.SCRIPT || preparsedElement.type === PreparsedElementType.STYLE) { // Skipping <script> for security reasons // Skipping <style> as we already processed them // in the StyleCompiler return null; } if (preparsedElement.type === PreparsedElementType.STYLESHEET && isStyleUrlResolvable(preparsedElement.hrefAttr)) { // Skipping stylesheets with either relative urls or package scheme as we already processed // them in the StyleCompiler return null; } const matchableAttrs: string[][] = []; const elementOrDirectiveProps: BoundElementOrDirectiveProperty[] = []; const elementOrDirectiveRefs: ElementOrDirectiveRef[] = []; const elementVars: VariableAst[] = []; const animationProps: BoundElementPropertyAst[] = []; const events: BoundEventAst[] = []; const templateElementOrDirectiveProps: BoundElementOrDirectiveProperty[] = []; const templateMatchableAttrs: string[][] = []; const templateElementVars: VariableAst[] = []; let hasInlineTemplates = false; const attrs: AttrAst[] = []; const lcElName = splitNsName(nodeName.toLowerCase())[1]; const isTemplateElement = lcElName == TEMPLATE_ELEMENT; element.attrs.forEach(attr => { const hasBinding = this._parseAttr( isTemplateElement, attr, matchableAttrs, elementOrDirectiveProps, animationProps, events, elementOrDirectiveRefs, elementVars); const hasTemplateBinding = this._parseInlineTemplateBinding( attr, templateMatchableAttrs, templateElementOrDirectiveProps, templateElementVars); if (hasTemplateBinding && hasInlineTemplates) { this._reportError( `Can't have multiple template bindings on one element. Use only one attribute named 'template' or prefixed with *`, attr.sourceSpan); } if (!hasBinding && !hasTemplateBinding) { // don't include the bindings as attributes as well in the AST attrs.push(this.visitAttribute(attr, null)); matchableAttrs.push([attr.name, attr.value]); } if (hasTemplateBinding) { hasInlineTemplates = true; } }); const elementCssSelector = createElementCssSelector(nodeName, matchableAttrs); const directiveMetas = this._parseDirectives(this.selectorMatcher, elementCssSelector); const references: ReferenceAst[] = []; const directiveAsts = this._createDirectiveAsts( isTemplateElement, element.name, directiveMetas, elementOrDirectiveProps, elementOrDirectiveRefs, element.sourceSpan, references); const elementProps: BoundElementPropertyAst[] = this._createElementPropertyAsts(element.name, elementOrDirectiveProps, directiveAsts) .concat(animationProps); const isViewRoot = parent.isTemplateElement || hasInlineTemplates; const providerContext = new ProviderElementContext( this.providerViewContext, parent.providerContext, isViewRoot, directiveAsts, attrs, references, element.sourceSpan); const children = html.visitAll( preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this, element.children, ElementContext.create( isTemplateElement, directiveAsts, isTemplateElement ? parent.providerContext : providerContext)); providerContext.afterElement(); // Override the actual selector when the `ngProjectAs` attribute is provided const projectionSelector = isPresent(preparsedElement.projectAs) ? CssSelector.parse(preparsedElement.projectAs)[0] : elementCssSelector; const ngContentIndex = parent.findNgContentIndex(projectionSelector); let parsedElement: TemplateAst; if (preparsedElement.type === PreparsedElementType.NG_CONTENT) { if (isPresent(element.children) && element.children.length > 0) { this._reportError( `<ng-content> element cannot have content. <ng-content> must be immediately followed by </ng-content>`, element.sourceSpan); } parsedElement = new NgContentAst( this.ngContentCount++, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan); } else if (isTemplateElement) { this._assertAllEventsPublishedByDirectives(directiveAsts, events); this._assertNoComponentsNorElementBindingsOnTemplate( directiveAsts, elementProps, element.sourceSpan); parsedElement = new EmbeddedTemplateAst( attrs, events, references, elementVars, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, children, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan); } else { this._assertOnlyOneComponent(directiveAsts, element.sourceSpan); const ngContentIndex = hasInlineTemplates ? null : parent.findNgContentIndex(projectionSelector); parsedElement = new ElementAst( nodeName, attrs, elementProps, events, references, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, children, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan); } if (hasInlineTemplates) { const templateCssSelector = createElementCssSelector(TEMPLATE_ELEMENT, templateMatchableAttrs); const templateDirectiveMetas = this._parseDirectives(this.selectorMatcher, templateCssSelector); const templateDirectiveAsts = this._createDirectiveAsts( true, element.name, templateDirectiveMetas, templateElementOrDirectiveProps, [], element.sourceSpan, []); const templateElementProps: BoundElementPropertyAst[] = this._createElementPropertyAsts( element.name, templateElementOrDirectiveProps, templateDirectiveAsts); this._assertNoComponentsNorElementBindingsOnTemplate( templateDirectiveAsts, templateElementProps, element.sourceSpan); const templateProviderContext = new ProviderElementContext( this.providerViewContext, parent.providerContext, parent.isTemplateElement, templateDirectiveAsts, [], [], element.sourceSpan); templateProviderContext.afterElement(); parsedElement = new EmbeddedTemplateAst( [], [], [], templateElementVars, templateProviderContext.transformedDirectiveAsts, templateProviderContext.transformProviders, templateProviderContext.transformedHasViewContainer, [parsedElement], ngContentIndex, element.sourceSpan); } return parsedElement; } private _parseInlineTemplateBinding( attr: html.Attribute, targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[], targetVars: VariableAst[]): boolean { let templateBindingsSource: string = null; if (this._normalizeAttributeName(attr.name) == TEMPLATE_ATTR) { templateBindingsSource = attr.value; } else if (attr.name.startsWith(TEMPLATE_ATTR_PREFIX)) { const key = attr.name.substring(TEMPLATE_ATTR_PREFIX.length); // remove the star templateBindingsSource = (attr.value.length == 0) ? key : key + ' ' + attr.value; } if (isPresent(templateBindingsSource)) { const bindings = this._parseTemplateBindings(templateBindingsSource, attr.sourceSpan); for (let i = 0; i < bindings.length; i++) { const binding = bindings[i]; if (binding.keyIsVar) { targetVars.push(new VariableAst(binding.key, binding.name, attr.sourceSpan)); } else if (isPresent(binding.expression)) { this._parsePropertyAst( binding.key, binding.expression, attr.sourceSpan, targetMatchableAttrs, targetProps); } else { targetMatchableAttrs.push([binding.key, '']); this._parseLiteralAttr(binding.key, null, attr.sourceSpan, targetProps); } } return true; } return false; } private _parseAttr( isTemplateElement: boolean, attr: html.Attribute, targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[], targetAnimationProps: BoundElementPropertyAst[], targetEvents: BoundEventAst[], targetRefs: ElementOrDirectiveRef[], targetVars: VariableAst[]): boolean { const attrName = this._normalizeAttributeName(attr.name); const attrValue = attr.value; const bindParts = RegExpWrapper.firstMatch(BIND_NAME_REGEXP, attrName); let hasBinding = false; if (isPresent(bindParts)) { hasBinding = true; if (isPresent(bindParts[1])) { // match: bind-prop this._parsePropertyOrAnimation( bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps, targetAnimationProps); } else if (isPresent(bindParts[2])) { // match: var-name / var-name="iden" const identifier = bindParts[8]; if (isTemplateElement) { this._reportError( `"var-" on <template> elements is deprecated. Use "let-" instead!`, attr.sourceSpan, ParseErrorLevel.WARNING); this._parseVariable(identifier, attrValue, attr.sourceSpan, targetVars); } else { this._reportError( `"var-" on non <template> elements is deprecated. Use "ref-" instead!`, attr.sourceSpan, ParseErrorLevel.WARNING); this._parseReference(identifier, attrValue, attr.sourceSpan, targetRefs); } } else if (isPresent(bindParts[3])) { // match: let-name if (isTemplateElement) { const identifier = bindParts[8]; this._parseVariable(identifier, attrValue, attr.sourceSpan, targetVars); } else { this._reportError(`"let-" is only supported on template elements.`, attr.sourceSpan); } } else if (isPresent(bindParts[4])) { // match: ref- / #iden const identifier = bindParts[8]; this._parseReference(identifier, attrValue, attr.sourceSpan, targetRefs); } else if (isPresent(bindParts[5])) { // match: on-event this._parseEvent( bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); } else if (isPresent(bindParts[6])) { // match: bindon-prop this._parsePropertyOrAnimation( bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps, targetAnimationProps); this._parseAssignmentEvent( bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); } else if (isPresent(bindParts[7])) { // match: animate-name if (attrName[0] == '@' && isPresent(attrValue) && attrValue.length > 0) { this._reportError( `Assigning animation triggers via @prop="exp" attributes with an expression is deprecated. Use [@prop]="exp" instead!`, attr.sourceSpan, ParseErrorLevel.WARNING); } this._parseAnimation( bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetAnimationProps); } else if (isPresent(bindParts[9])) { // match: [(expr)] this._parsePropertyOrAnimation( bindParts[9], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps, targetAnimationProps); this._parseAssignmentEvent( bindParts[9], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); } else if (isPresent(bindParts[10])) { // match: [expr] this._parsePropertyOrAnimation( bindParts[10], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps, targetAnimationProps); } else if (isPresent(bindParts[11])) { // match: (event) this._parseEvent( bindParts[11], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); } } else { hasBinding = this._parsePropertyInterpolation( attrName, attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps); } if (!hasBinding) { this._parseLiteralAttr(attrName, attrValue, attr.sourceSpan, targetProps); } return hasBinding; } private _normalizeAttributeName(attrName: string): string { return attrName.toLowerCase().startsWith('data-') ? attrName.substring(5) : attrName; } private _parseVariable( identifier: string, value: string, sourceSpan: ParseSourceSpan, targetVars: VariableAst[]) { if (identifier.indexOf('-') > -1) { this._reportError(`"-" is not allowed in variable names`, sourceSpan); } targetVars.push(new VariableAst(identifier, value, sourceSpan)); } private _parseReference( identifier: string, value: string, sourceSpan: ParseSourceSpan, targetRefs: ElementOrDirectiveRef[]) { if (identifier.indexOf('-') > -1) { this._reportError(`"-" is not allowed in reference names`, sourceSpan); } targetRefs.push(new ElementOrDirectiveRef(identifier, value, sourceSpan)); } private _parsePropertyOrAnimation( name: string, expression: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[], targetAnimationProps: BoundElementPropertyAst[]) { if (name[0] == '@') { this._parseAnimation( name.substr(1), expression, sourceSpan, targetMatchableAttrs, targetAnimationProps); } else { this._parsePropertyAst( name, this._parseBinding(expression, sourceSpan), sourceSpan, targetMatchableAttrs, targetProps); } } private _parseAnimation( name: string, expression: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetAnimationProps: BoundElementPropertyAst[]) { // This will occur when a @trigger is not paired with an expression. // For animations it is valid to not have an expression since */void // states will be applied by angular when the element is attached/detached if (!isPresent(expression) || expression.length == 0) { expression = 'null'; } const ast = this._parseBinding(expression, sourceSpan); targetMatchableAttrs.push([name, ast.source]); targetAnimationProps.push(new BoundElementPropertyAst( name, PropertyBindingType.Animation, SecurityContext.NONE, ast, null, sourceSpan)); } private _parsePropertyInterpolation( name: string, value: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[]): boolean { const expr = this._parseInterpolation(value, sourceSpan); if (isPresent(expr)) { this._parsePropertyAst(name, expr, sourceSpan, targetMatchableAttrs, targetProps); return true; } return false; } private _parsePropertyAst( name: string, ast: ASTWithSource, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[]) { targetMatchableAttrs.push([name, ast.source]); targetProps.push(new BoundElementOrDirectiveProperty(name, ast, false, sourceSpan)); } private _parseAssignmentEvent( name: string, expression: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetEvents: BoundEventAst[]) { this._parseEvent( `${name}Change`, `${expression}=$event`, sourceSpan, targetMatchableAttrs, targetEvents); } private _parseEvent( name: string, expression: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetEvents: BoundEventAst[]) { // long format: 'target: eventName' const parts = splitAtColon(name, [null, name]); const target = parts[0]; const eventName = parts[1]; const ast = this._parseAction(expression, sourceSpan); targetMatchableAttrs.push([name, ast.source]); targetEvents.push(new BoundEventAst(eventName, target, ast, sourceSpan)); // Don't detect directives for event names for now, // so don't add the event name to the matchableAttrs } private _parseLiteralAttr( name: string, value: string, sourceSpan: ParseSourceSpan, targetProps: BoundElementOrDirectiveProperty[]) { targetProps.push(new BoundElementOrDirectiveProperty( name, this._exprParser.wrapLiteralPrimitive(value, ''), true, sourceSpan)); } private _parseDirectives(selectorMatcher: SelectorMatcher, elementCssSelector: CssSelector): CompileDirectiveMetadata[] { // Need to sort the directives so that we get consistent results throughout, // as selectorMatcher uses Maps inside. // Also dedupe directives as they might match more than one time! const directives = ListWrapper.createFixedSize(this.directivesIndex.size); selectorMatcher.match(elementCssSelector, (selector, directive) => { directives[this.directivesIndex.get(directive)] = directive; }); return directives.filter(dir => isPresent(dir)); } private _createDirectiveAsts( isTemplateElement: boolean, elementName: string, directives: CompileDirectiveMetadata[], props: BoundElementOrDirectiveProperty[], elementOrDirectiveRefs: ElementOrDirectiveRef[], elementSourceSpan: ParseSourceSpan, targetReferences: ReferenceAst[]): DirectiveAst[] { const matchedReferences = new Set<string>(); let component: CompileDirectiveMetadata = null; const directiveAsts = directives.map((directive: CompileDirectiveMetadata) => { const sourceSpan = new ParseSourceSpan( elementSourceSpan.start, elementSourceSpan.end, `Directive ${directive.type.name}`); if (directive.isComponent) { component = directive; } const hostProperties: BoundElementPropertyAst[] = []; const hostEvents: BoundEventAst[] = []; const directiveProperties: BoundDirectivePropertyAst[] = []; this._createDirectiveHostPropertyAsts( elementName, directive.hostProperties, sourceSpan, hostProperties); this._createDirectiveHostEventAsts(directive.hostListeners, sourceSpan, hostEvents); this._createDirectivePropertyAsts(directive.inputs, props, directiveProperties); elementOrDirectiveRefs.forEach((elOrDirRef) => { if ((elOrDirRef.value.length === 0 && directive.isComponent) || (directive.exportAs == elOrDirRef.value)) { targetReferences.push(new ReferenceAst( elOrDirRef.name, identifierToken(directive.type), elOrDirRef.sourceSpan)); matchedReferences.add(elOrDirRef.name); } }); return new DirectiveAst( directive, directiveProperties, hostProperties, hostEvents, sourceSpan); }); elementOrDirectiveRefs.forEach((elOrDirRef) => { if (elOrDirRef.value.length > 0) { if (!SetWrapper.has(matchedReferences, elOrDirRef.name)) { this._reportError( `There is no directive with "exportAs" set to "${elOrDirRef.value}"`, elOrDirRef.sourceSpan); } } else if (isBlank(component)) { let refToken: CompileTokenMetadata = null; if (isTemplateElement) { refToken = identifierToken(Identifiers.TemplateRef); } targetReferences.push(new ReferenceAst(elOrDirRef.name, refToken, elOrDirRef.sourceSpan)); } }); // fix syntax highlighting issue: ` return directiveAsts; } private _createDirectiveHostPropertyAsts( elementName: string, hostProps: {[key: string]: string}, sourceSpan: ParseSourceSpan, targetPropertyAsts: BoundElementPropertyAst[]) { if (isPresent(hostProps)) { StringMapWrapper.forEach(hostProps, (expression: string, propName: string) => { const exprAst = this._parseBinding(expression, sourceSpan); targetPropertyAsts.push( this._createElementPropertyAst(elementName, propName, exprAst, sourceSpan)); }); } } private _createDirectiveHostEventAsts( hostListeners: {[key: string]: string}, sourceSpan: ParseSourceSpan, targetEventAsts: BoundEventAst[]) { if (isPresent(hostListeners)) { StringMapWrapper.forEach(hostListeners, (expression: string, propName: string) => { this._parseEvent(propName, expression, sourceSpan, [], targetEventAsts); }); } } private _createDirectivePropertyAsts( directiveProperties: {[key: string]: string}, boundProps: BoundElementOrDirectiveProperty[], targetBoundDirectiveProps: BoundDirectivePropertyAst[]) { if (isPresent(directiveProperties)) { const boundPropsByName = new Map<string, BoundElementOrDirectiveProperty>(); boundProps.forEach(boundProp => { const prevValue = boundPropsByName.get(boundProp.name); if (isBlank(prevValue) || prevValue.isLiteral) { // give [a]="b" a higher precedence than a="b" on the same element boundPropsByName.set(boundProp.name, boundProp); } }); StringMapWrapper.forEach(directiveProperties, (elProp: string, dirProp: string) => { const boundProp = boundPropsByName.get(elProp); // Bindings are optional, so this binding only needs to be set up if an expression is given. if (isPresent(boundProp)) { targetBoundDirectiveProps.push(new BoundDirectivePropertyAst( dirProp, boundProp.name, boundProp.expression, boundProp.sourceSpan)); } }); } } private _createElementPropertyAsts( elementName: string, props: BoundElementOrDirectiveProperty[], directives: DirectiveAst[]): BoundElementPropertyAst[] { const boundElementProps: BoundElementPropertyAst[] = []; const boundDirectivePropsIndex = new Map<string, BoundDirectivePropertyAst>(); directives.forEach((directive: DirectiveAst) => { directive.inputs.forEach((prop: BoundDirectivePropertyAst) => { boundDirectivePropsIndex.set(prop.templateName, prop); }); }); props.forEach((prop: BoundElementOrDirectiveProperty) => { if (!prop.isLiteral && isBlank(boundDirectivePropsIndex.get(prop.name))) { boundElementProps.push(this._createElementPropertyAst( elementName, prop.name, prop.expression, prop.sourceSpan)); } }); return boundElementProps; } private _createElementPropertyAst( elementName: string, name: string, ast: AST, sourceSpan: ParseSourceSpan): BoundElementPropertyAst { let unit: string = null; let bindingType: PropertyBindingType; let boundPropertyName: string; const parts = name.split(PROPERTY_PARTS_SEPARATOR); let securityContext: SecurityContext; if (parts.length === 1) { var partValue = parts[0]; if (partValue[0] == '@') { boundPropertyName = partValue.substr(1); bindingType = PropertyBindingType.Animation; securityContext = SecurityContext.NONE; this._reportError( `Assigning animation triggers within host data as attributes such as "@prop": "exp" is deprecated. Use "[@prop]": "exp" instead!`, sourceSpan, ParseErrorLevel.WARNING); } else { boundPropertyName = this._schemaRegistry.getMappedPropName(partValue); securityContext = this._schemaRegistry.securityContext(elementName, boundPropertyName); bindingType = PropertyBindingType.Property; if (!this._schemaRegistry.hasProperty(elementName, boundPropertyName, this._schemas)) { let errorMsg = `Can't bind to '${boundPropertyName}' since it isn't a known native property`; if (elementName.indexOf('-') !== -1) { errorMsg += `. To ignore this error on custom elements, add the "CUSTOM_ELEMENTS_SCHEMA" to the NgModule of this component`; } this._reportError(errorMsg, sourceSpan); } } } else { if (parts[0] == ATTRIBUTE_PREFIX) { boundPropertyName = parts[1]; if (boundPropertyName.toLowerCase().startsWith('on')) { this._reportError( `Binding to event attribute '${boundPropertyName}' is disallowed ` + `for security reasons, please use (${boundPropertyName.slice(2)})=...`, sourceSpan); } // NB: For security purposes, use the mapped property name, not the attribute name. securityContext = this._schemaRegistry.securityContext( elementName, this._schemaRegistry.getMappedPropName(boundPropertyName)); let nsSeparatorIdx = boundPropertyName.indexOf(':'); if (nsSeparatorIdx > -1) { let ns = boundPropertyName.substring(0, nsSeparatorIdx); let name = boundPropertyName.substring(nsSeparatorIdx + 1); boundPropertyName = mergeNsAndName(ns, name); } bindingType = PropertyBindingType.Attribute; } else if (parts[0] == CLASS_PREFIX) { boundPropertyName = parts[1]; bindingType = PropertyBindingType.Class; securityContext = SecurityContext.NONE; } else if (parts[0] == STYLE_PREFIX) { unit = parts.length > 2 ? parts[2] : null; boundPropertyName = parts[1]; bindingType = PropertyBindingType.Style; securityContext = SecurityContext.STYLE; } else { this._reportError(`Invalid property name '${name}'`, sourceSpan); bindingType = null; securityContext = null; } } return new BoundElementPropertyAst( boundPropertyName, bindingType, securityContext, ast, unit, sourceSpan); } private _findComponentDirectiveNames(directives: DirectiveAst[]): string[] { const componentTypeNames: string[] = []; directives.forEach(directive => { const typeName = directive.directive.type.name; if (directive.directive.isComponent) { componentTypeNames.push(typeName); } }); return componentTypeNames; } private _assertOnlyOneComponent(directives: DirectiveAst[], sourceSpan: ParseSourceSpan) { const componentTypeNames = this._findComponentDirectiveNames(directives); if (componentTypeNames.length > 1) { this._reportError(`More than one component: ${componentTypeNames.join(',')}`, sourceSpan); } } private _assertNoComponentsNorElementBindingsOnTemplate( directives: DirectiveAst[], elementProps: BoundElementPropertyAst[], sourceSpan: ParseSourceSpan) { const componentTypeNames: string[] = this._findComponentDirectiveNames(directives); if (componentTypeNames.length > 0) { this._reportError( `Components on an embedded template: ${componentTypeNames.join(',')}`, sourceSpan); } elementProps.forEach(prop => { this._reportError( `Property binding ${prop.name} not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "directives" section.`, sourceSpan); }); } private _assertAllEventsPublishedByDirectives( directives: DirectiveAst[], events: BoundEventAst[]) { const allDirectiveEvents = new Set<string>(); directives.forEach(directive => { StringMapWrapper.forEach(directive.directive.outputs, (eventName: string) => { allDirectiveEvents.add(eventName); }); }); events.forEach(event => { if (isPresent(event.target) || !SetWrapper.has(allDirectiveEvents, event.name)) { this._reportError( `Event binding ${event.fullName} not emitted by any directive on an embedded template. Make sure that the event name is spelled correctly and all directives are listed in the "directives" section.`, event.sourceSpan); } }); } } class NonBindableVisitor implements html.Visitor { visitElement(ast: html.Element, parent: ElementContext): ElementAst { const preparsedElement = preparseElement(ast); if (preparsedElement.type === PreparsedElementType.SCRIPT || preparsedElement.type === PreparsedElementType.STYLE || preparsedElement.type === PreparsedElementType.STYLESHEET) { // Skipping <script> for security reasons // Skipping <style> and stylesheets as we already processed them // in the StyleCompiler return null; } const attrNameAndValues = ast.attrs.map(attrAst => [attrAst.name, attrAst.value]); const selector = createElementCssSelector(ast.name, attrNameAndValues); const ngContentIndex = parent.findNgContentIndex(selector); const children = html.visitAll(this, ast.children, EMPTY_ELEMENT_CONTEXT); return new ElementAst( ast.name, html.visitAll(this, ast.attrs), [], [], [], [], [], false, children, ngContentIndex, ast.sourceSpan); } visitComment(comment: html.Comment, context: any): any { return null; } visitAttribute(attribute: html.Attribute, context: any): AttrAst { return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan); } visitText(text: html.Text, parent: ElementContext): TextAst { const ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR); return new TextAst(text.value, ngContentIndex, text.sourceSpan); } visitExpansion(expansion: html.Expansion, context: any): any { return expansion; } visitExpansionCase(expansionCase: html.ExpansionCase, context: any): any { return expansionCase; } } class BoundElementOrDirectiveProperty { constructor( public name: string, public expression: AST, public isLiteral: boolean, public sourceSpan: ParseSourceSpan) {} } class ElementOrDirectiveRef { constructor(public name: string, public value: string, public sourceSpan: ParseSourceSpan) {} } export function splitClasses(classAttrValue: string): string[] { return classAttrValue.trim().split(/\s+/g); } class ElementContext { static create( isTemplateElement: boolean, directives: DirectiveAst[], providerContext: ProviderElementContext): ElementContext { const matcher = new SelectorMatcher(); let wildcardNgContentIndex: number = null; const component = directives.find(directive => directive.directive.isComponent); if (isPresent(component)) { const ngContentSelectors = component.directive.template.ngContentSelectors; for (let i = 0; i < ngContentSelectors.length; i++) { const selector = ngContentSelectors[i]; if (selector === '*') { wildcardNgContentIndex = i; } else { matcher.addSelectables(CssSelector.parse(ngContentSelectors[i]), i); } } } return new ElementContext(isTemplateElement, matcher, wildcardNgContentIndex, providerContext); } constructor( public isTemplateElement: boolean, private _ngContentIndexMatcher: SelectorMatcher, private _wildcardNgContentIndex: number, public providerContext: ProviderElementContext) {} findNgContentIndex(selector: CssSelector): number { const ngContentIndices: number[] = []; this._ngContentIndexMatcher.match( selector, (selector, ngContentIndex) => { ngContentIndices.push(ngContentIndex); }); ListWrapper.sort(ngContentIndices); if (isPresent(this._wildcardNgContentIndex)) { ngContentIndices.push(this._wildcardNgContentIndex); } return ngContentIndices.length > 0 ? ngContentIndices[0] : null; } } function createElementCssSelector(elementName: string, matchableAttrs: string[][]): CssSelector { const cssSelector = new CssSelector(); let elNameNoNs = splitNsName(elementName)[1]; cssSelector.setElement(elNameNoNs); for (let i = 0; i < matchableAttrs.length; i++) { let attrName = matchableAttrs[i][0]; let attrNameNoNs = splitNsName(attrName)[1]; let attrValue = matchableAttrs[i][1]; cssSelector.addAttribute(attrNameNoNs, attrValue); if (attrName.toLowerCase() == CLASS_ATTR) { const classes = splitClasses(attrValue); classes.forEach(className => cssSelector.addClassName(className)); } } return cssSelector; } const EMPTY_ELEMENT_CONTEXT = new ElementContext(true, new SelectorMatcher(), null, null); const NON_BINDABLE_VISITOR = new NonBindableVisitor(); export class PipeCollector extends RecursiveAstVisitor { pipes: Set<string> = new Set<string>(); visitPipe(ast: BindingPipe, context: any): any { this.pipes.add(ast.name); ast.exp.visit(this); this.visitAll(ast.args, context); return null; } }
modules/@angular/compiler/src/template_parser/template_parser.ts
1
https://github.com/angular/angular/commit/a55d796c4b4cbe5bc1256339bd398090f58b4d69
[ 0.004509094636887312, 0.0003071910177823156, 0.00016470164700876921, 0.00017289174138568342, 0.0006243261159397662 ]
{ "id": 4, "code_window": [ " host: {'[invalidProp]': 'someProp'}\n", " });\n", " expect(() => parse('<div></div>', [dirA])).toThrowError(`Template parse errors:\n", "Can't bind to 'invalidProp' since it isn't a known native property (\"[ERROR ->]<div></div>\"): TestComp@0:0, Directive DirA`);\n", " });\n", "\n", " it('should report errors in expressions', () => {\n", " expect(() => parse('<div [prop]=\"a b\"></div>', [])).toThrowError(`Template parse errors:\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "Can't bind to 'invalidProp' since it isn't a known property of 'div'. (\"[ERROR ->]<div></div>\"): TestComp@0:0, Directive DirA`);\n" ], "file_path": "modules/@angular/compiler/test/template_parser/template_parser_spec.ts", "type": "replace", "edit_start_line_idx": 1252 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {__compiler_private__ as _c} from '@angular/compiler'; export type SelectorMatcher = typeof _c.SelectorMatcher; export var SelectorMatcher: typeof _c.SelectorMatcher = _c.SelectorMatcher; export type CssSelector = typeof _c.CssSelector; export var CssSelector: typeof _c.CssSelector = _c.CssSelector;
modules/@angular/platform-server/compiler_private.ts
0
https://github.com/angular/angular/commit/a55d796c4b4cbe5bc1256339bd398090f58b4d69
[ 0.00017536409723106772, 0.00017404733807779849, 0.00017273059347644448, 0.00017404733807779849, 0.0000013167518773116171 ]
{ "id": 4, "code_window": [ " host: {'[invalidProp]': 'someProp'}\n", " });\n", " expect(() => parse('<div></div>', [dirA])).toThrowError(`Template parse errors:\n", "Can't bind to 'invalidProp' since it isn't a known native property (\"[ERROR ->]<div></div>\"): TestComp@0:0, Directive DirA`);\n", " });\n", "\n", " it('should report errors in expressions', () => {\n", " expect(() => parse('<div [prop]=\"a b\"></div>', [])).toThrowError(`Template parse errors:\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "Can't bind to 'invalidProp' since it isn't a known property of 'div'. (\"[ERROR ->]<div></div>\"): TestComp@0:0, Directive DirA`);\n" ], "file_path": "modules/@angular/compiler/test/template_parser/template_parser_spec.ts", "type": "replace", "edit_start_line_idx": 1252 }
@cheatsheetSection Template syntax @cheatsheetIndex 1 @description @cheatsheetItem syntax: `<input [value]="firstName">`|`[value]` description: Binds property `value` to the result of expression `firstName`. @cheatsheetItem syntax: `<div [attr.role]="myAriaRole">`|`[attr.role]` description: Binds attribute `role` to the result of expression `myAriaRole`. @cheatsheetItem syntax: `<div [class.extra-sparkle]="isDelightful">`|`[class.extra-sparkle]` description: Binds the presence of the CSS class `extra-sparkle` on the element to the truthiness of the expression `isDelightful`. @cheatsheetItem syntax: `<div [style.width.px]="mySize">`|`[style.width.px]` description: Binds style property `width` to the result of expression `mySize` in pixels. Units are optional. @cheatsheetItem syntax: `<button (click)="readRainbow($event)">`|`(click)` description: Calls method `readRainbow` when a click event is triggered on this button element (or its children) and passes in the event object. @cheatsheetItem syntax: `<div title="Hello {{ponyName}}">`|`{{ponyName}}` description: Binds a property to an interpolated string, e.g. "Hello Seabiscuit". Equivalent to: `<div [title]="'Hello ' + ponyName">` @cheatsheetItem syntax: `<p>Hello {{ponyName}}</p>`|`{{ponyName}}` description: Binds text content to an interpolated string, e.g. "Hello Seabiscuit". @cheatsheetItem syntax: `<my-cmp [(title)]="name">`|`[(title)]` description: Sets up two-way data binding. Equivalent to: `<my-cmp [title]="name" (titleChange)="name=$event">` @cheatsheetItem syntax: `<video #movieplayer ...> <button (click)="movieplayer.play()"> </video>`|`#movieplayer`|`(click)` description: Creates a local variable `movieplayer` that provides access to the `video` element instance in data-binding and event-binding expressions in the current template. @cheatsheetItem syntax: `<p *myUnless="myExpression">...</p>`|`*myUnless` description: The `*` symbol means that the current element will be turned into an embedded template. Equivalent to: `<template [myUnless]="myExpression"><p>...</p></template>` @cheatsheetItem syntax: `<p>Card No.: {{cardNumber | myCreditCardNumberFormatter}}</p>`|`{{cardNumber | myCreditCardNumberFormatter}}` description: Transforms the current value of expression `cardNumber` via the pipe called `myCreditCardNumberFormatter`. @cheatsheetItem syntax: `<p>Employer: {{employer?.companyName}}</p>`|`{{employer?.companyName}}` description: The safe navigation operator (`?`) means that the `employer` field is optional and if `undefined`, the rest of the expression should be ignored. @cheatsheetItem syntax: `<svg:rect x="0" y="0" width="100" height="100"/>`|`svg:` description: SVG snippet templates need an `svg:` prefix on their root element to disambiguate the SVG element from an HTML component. @cheatsheetItem syntax: `<svg> <rect x="0" y="0" width="100" height="100"/> </svg>`|`svg` description: `<svg>` root elements are detected as SVG element automatically without the prefix
modules/@angular/docs/cheatsheet/template-syntax.md
0
https://github.com/angular/angular/commit/a55d796c4b4cbe5bc1256339bd398090f58b4d69
[ 0.00017385468527209014, 0.00016977240738924593, 0.0001658373512327671, 0.00017037050565704703, 0.000002340685341550852 ]
{ "id": 4, "code_window": [ " host: {'[invalidProp]': 'someProp'}\n", " });\n", " expect(() => parse('<div></div>', [dirA])).toThrowError(`Template parse errors:\n", "Can't bind to 'invalidProp' since it isn't a known native property (\"[ERROR ->]<div></div>\"): TestComp@0:0, Directive DirA`);\n", " });\n", "\n", " it('should report errors in expressions', () => {\n", " expect(() => parse('<div [prop]=\"a b\"></div>', [])).toThrowError(`Template parse errors:\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "Can't bind to 'invalidProp' since it isn't a known property of 'div'. (\"[ERROR ->]<div></div>\"): TestComp@0:0, Directive DirA`);\n" ], "file_path": "modules/@angular/compiler/test/template_parser/template_parser_spec.ts", "type": "replace", "edit_start_line_idx": 1252 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common'; import {ANALYZE_FOR_ENTRY_COMPONENTS, APP_INITIALIZER, ApplicationRef, ComponentResolver, Injector, NgModuleFactoryLoader, OpaqueToken, SystemJsNgModuleLoader} from '@angular/core'; import {Routes} from './config'; import {Router} from './router'; import {ROUTER_CONFIG, ROUTES} from './router_config_loader'; import {RouterOutletMap} from './router_outlet_map'; import {ActivatedRoute} from './router_state'; import {DefaultUrlSerializer, UrlSerializer} from './url_tree'; export const ROUTER_CONFIGURATION = new OpaqueToken('ROUTER_CONFIGURATION'); /** * @experimental */ export interface ExtraOptions { enableTracing?: boolean; useHash?: boolean; } export function setupRouter( ref: ApplicationRef, resolver: ComponentResolver, urlSerializer: UrlSerializer, outletMap: RouterOutletMap, location: Location, injector: Injector, loader: NgModuleFactoryLoader, config: Routes, opts: ExtraOptions = {}) { if (ref.componentTypes.length == 0) { throw new Error('Bootstrap at least one component before injecting Router.'); } const componentType = ref.componentTypes[0]; const r = new Router( componentType, resolver, urlSerializer, outletMap, location, injector, loader, config); ref.registerDisposeListener(() => r.dispose()); if (opts.enableTracing) { r.events.subscribe(e => { console.group(`Router Event: ${(<any>e.constructor).name}`); console.log(e.toString()); console.log(e); console.groupEnd(); }); } return r; } export function rootRoute(router: Router): ActivatedRoute { return router.routerState.root; } export function setupRouterInitializer(injector: Injector) { return () => { injector.get(ApplicationRef).registerBootstrapListener(() => { injector.get(Router).initialNavigation(); }); }; } /** * An array of {@link Provider}s. To use the router, you must add this to your application. * * ### Example * * ``` * @Component({directives: [ROUTER_DIRECTIVES]}) * class AppCmp { * // ... * } * * const config = [ * {path: 'home', component: Home} * ]; * * bootstrap(AppCmp, [provideRouter(config)]); * ``` * * @deprecated use RouterModule instead */ export function provideRouter(routes: Routes, config: ExtraOptions = {}): any[] { return [ {provide: ANALYZE_FOR_ENTRY_COMPONENTS, multi: true, useValue: routes}, {provide: ROUTES, useExisting: ROUTER_CONFIG}, {provide: ROUTER_CONFIG, useValue: routes}, {provide: ROUTER_CONFIGURATION, useValue: config}, Location, {provide: LocationStrategy, useClass: PathLocationStrategy}, {provide: UrlSerializer, useClass: DefaultUrlSerializer}, { provide: Router, useFactory: setupRouter, deps: [ ApplicationRef, ComponentResolver, UrlSerializer, RouterOutletMap, Location, Injector, NgModuleFactoryLoader, ROUTES, ROUTER_CONFIGURATION ] }, RouterOutletMap, {provide: ActivatedRoute, useFactory: rootRoute, deps: [Router]}, // Trigger initial navigation {provide: APP_INITIALIZER, multi: true, useFactory: setupRouterInitializer, deps: [Injector]}, {provide: NgModuleFactoryLoader, useClass: SystemJsNgModuleLoader} ]; } /** * Router configuration. * * ### Example * * ``` * @NgModule({providers: [ * provideRoutes([{path: 'home', component: Home}]) * ]}) * class LazyLoadedModule { * // ... * } * ``` * * @deprecated */ export function provideRoutes(routes: Routes): any { return [ {provide: ANALYZE_FOR_ENTRY_COMPONENTS, multi: true, useValue: routes}, {provide: ROUTES, useValue: routes} ]; } /** * Router configuration. * * ### Example * * ``` * @NgModule({providers: [ * provideRouterOptions({enableTracing: true}) * ]}) * class LazyLoadedModule { * // ... * } * ``` * * @deprecated */ export function provideRouterConfig(config: ExtraOptions): any { return {provide: ROUTER_CONFIGURATION, useValue: config}; }
modules/@angular/router/src/common_router_providers.ts
0
https://github.com/angular/angular/commit/a55d796c4b4cbe5bc1256339bd398090f58b4d69
[ 0.0001749593939166516, 0.00016944133676588535, 0.00016350804071407765, 0.00017007335554808378, 0.0000037094991967023816 ]
{ "id": 5, "code_window": [ " MyComp, new ViewMetadata({template: '<div unknown=\"{{ctxProp}}\"></div>'}));\n", "\n", " PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => {\n", " expect(e.message).toEqual(\n", " `Template parse errors:\\nCan't bind to 'unknown' since it isn't a known native property (\"<div [ERROR ->]unknown=\"{{ctxProp}}\"></div>\"): MyComp@0:5`);\n", " async.done();\n", " return null;\n", " });\n", " }));\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " `Template parse errors:\\nCan't bind to 'unknown' since it isn't a known property of 'div'. (\"<div [ERROR ->]unknown=\"{{ctxProp}}\"></div>\"): MyComp@0:5`);\n" ], "file_path": "modules/@angular/core/test/linker/integration_spec.ts", "type": "replace", "edit_start_line_idx": 1000 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Inject, Injectable, OpaqueToken, Optional, SchemaMetadata, SecurityContext} from '@angular/core'; import {Console, MAX_INTERPOLATION_VALUES} from '../../core_private'; import {ListWrapper, StringMapWrapper, SetWrapper,} from '../facade/collection'; import {RegExpWrapper, isPresent, isBlank} from '../facade/lang'; import {BaseException} from '../facade/exceptions'; import {EmptyExpr, AST, Interpolation, ASTWithSource, TemplateBinding, RecursiveAstVisitor, BindingPipe, ParserError} from '../expression_parser/ast'; import {Parser} from '../expression_parser/parser'; import {CompileDirectiveMetadata, CompilePipeMetadata, CompileTokenMetadata, removeIdentifierDuplicates,} from '../compile_metadata'; import {HtmlParser, ParseTreeResult} from '../html_parser/html_parser'; import {splitNsName, mergeNsAndName} from '../html_parser/tags'; import {ParseSourceSpan, ParseError, ParseErrorLevel} from '../parse_util'; import {InterpolationConfig} from '../html_parser/interpolation_config'; import {ElementAst, BoundElementPropertyAst, BoundEventAst, ReferenceAst, TemplateAst, TemplateAstVisitor, templateVisitAll, TextAst, BoundTextAst, EmbeddedTemplateAst, AttrAst, NgContentAst, PropertyBindingType, DirectiveAst, BoundDirectivePropertyAst, VariableAst} from './template_ast'; import {CssSelector, SelectorMatcher} from '../selector'; import {ElementSchemaRegistry} from '../schema/element_schema_registry'; import {preparseElement, PreparsedElementType} from './template_preparser'; import {isStyleUrlResolvable} from '../style_url_resolver'; import * as html from '../html_parser/ast'; import {splitAtColon} from '../util'; import {identifierToken, Identifiers} from '../identifiers'; import {expandNodes} from '../html_parser/icu_ast_expander'; import {ProviderElementContext, ProviderViewContext} from '../provider_analyzer'; // Group 1 = "bind-" // Group 2 = "var-" // Group 3 = "let-" // Group 4 = "ref-/#" // Group 5 = "on-" // Group 6 = "bindon-" // Group 7 = "animate-/@" // Group 8 = the identifier after "bind-", "var-/#", or "on-" // Group 9 = identifier inside [()] // Group 10 = identifier inside [] // Group 11 = identifier inside () const BIND_NAME_REGEXP = /^(?:(?:(?:(bind-)|(var-)|(let-)|(ref-|#)|(on-)|(bindon-)|(animate-|@))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/g; const TEMPLATE_ELEMENT = 'template'; const TEMPLATE_ATTR = 'template'; const TEMPLATE_ATTR_PREFIX = '*'; const CLASS_ATTR = 'class'; const PROPERTY_PARTS_SEPARATOR = '.'; const ATTRIBUTE_PREFIX = 'attr'; const CLASS_PREFIX = 'class'; const STYLE_PREFIX = 'style'; const TEXT_CSS_SELECTOR = CssSelector.parse('*')[0]; /** * Provides an array of {@link TemplateAstVisitor}s which will be used to transform * parsed templates before compilation is invoked, allowing custom expression syntax * and other advanced transformations. * * This is currently an internal-only feature and not meant for general use. */ export const TEMPLATE_TRANSFORMS: any = new OpaqueToken('TemplateTransforms'); export class TemplateParseError extends ParseError { constructor(message: string, span: ParseSourceSpan, level: ParseErrorLevel) { super(span, message, level); } } export class TemplateParseResult { constructor(public templateAst?: TemplateAst[], public errors?: ParseError[]) {} } @Injectable() export class TemplateParser { constructor( private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry, private _htmlParser: HtmlParser, private _console: Console, @Optional() @Inject(TEMPLATE_TRANSFORMS) public transforms: TemplateAstVisitor[]) {} parse( component: CompileDirectiveMetadata, template: string, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[], schemas: SchemaMetadata[], templateUrl: string): TemplateAst[] { const result = this.tryParse(component, template, directives, pipes, schemas, templateUrl); const warnings = result.errors.filter(error => error.level === ParseErrorLevel.WARNING); const errors = result.errors.filter(error => error.level === ParseErrorLevel.FATAL); if (warnings.length > 0) { this._console.warn(`Template parse warnings:\n${warnings.join('\n')}`); } if (errors.length > 0) { const errorString = errors.join('\n'); throw new BaseException(`Template parse errors:\n${errorString}`); } return result.templateAst; } tryParse( component: CompileDirectiveMetadata, template: string, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[], schemas: SchemaMetadata[], templateUrl: string): TemplateParseResult { let interpolationConfig: any; if (component.template) { interpolationConfig = InterpolationConfig.fromArray(component.template.interpolation); } let htmlAstWithErrors = this._htmlParser.parse(template, templateUrl, true, interpolationConfig); const errors: ParseError[] = htmlAstWithErrors.errors; let result: TemplateAst[]; if (errors.length == 0) { // Transform ICU messages to angular directives const expandedHtmlAst = expandNodes(htmlAstWithErrors.rootNodes); errors.push(...expandedHtmlAst.errors); htmlAstWithErrors = new ParseTreeResult(expandedHtmlAst.nodes, errors); } if (htmlAstWithErrors.rootNodes.length > 0) { const uniqDirectives = removeIdentifierDuplicates(directives); const uniqPipes = removeIdentifierDuplicates(pipes); const providerViewContext = new ProviderViewContext(component, htmlAstWithErrors.rootNodes[0].sourceSpan); const parseVisitor = new TemplateParseVisitor( providerViewContext, uniqDirectives, uniqPipes, schemas, this._exprParser, this._schemaRegistry); result = html.visitAll(parseVisitor, htmlAstWithErrors.rootNodes, EMPTY_ELEMENT_CONTEXT); errors.push(...parseVisitor.errors, ...providerViewContext.errors); } else { result = []; } this._assertNoReferenceDuplicationOnTemplate(result, errors); if (errors.length > 0) { return new TemplateParseResult(result, errors); } if (isPresent(this.transforms)) { this.transforms.forEach( (transform: TemplateAstVisitor) => { result = templateVisitAll(transform, result); }); } return new TemplateParseResult(result, errors); } /** @internal */ _assertNoReferenceDuplicationOnTemplate(result: TemplateAst[], errors: TemplateParseError[]): void { const existingReferences: string[] = []; result.filter(element => !!(<any>element).references) .forEach(element => (<any>element).references.forEach((reference: ReferenceAst) => { const name = reference.name; if (existingReferences.indexOf(name) < 0) { existingReferences.push(name); } else { const error = new TemplateParseError( `Reference "#${name}" is defined several times`, reference.sourceSpan, ParseErrorLevel.FATAL); errors.push(error); } })); } } class TemplateParseVisitor implements html.Visitor { selectorMatcher: SelectorMatcher; errors: TemplateParseError[] = []; directivesIndex = new Map<CompileDirectiveMetadata, number>(); ngContentCount: number = 0; pipesByName: Map<string, CompilePipeMetadata>; private _interpolationConfig: InterpolationConfig; constructor( public providerViewContext: ProviderViewContext, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[], private _schemas: SchemaMetadata[], private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry) { this.selectorMatcher = new SelectorMatcher(); const tempMeta = providerViewContext.component.template; if (isPresent(tempMeta) && isPresent(tempMeta.interpolation)) { this._interpolationConfig = { start: tempMeta.interpolation[0], end: tempMeta.interpolation[1] }; } ListWrapper.forEachWithIndex( directives, (directive: CompileDirectiveMetadata, index: number) => { const selector = CssSelector.parse(directive.selector); this.selectorMatcher.addSelectables(selector, directive); this.directivesIndex.set(directive, index); }); this.pipesByName = new Map<string, CompilePipeMetadata>(); pipes.forEach(pipe => this.pipesByName.set(pipe.name, pipe)); } private _reportError( message: string, sourceSpan: ParseSourceSpan, level: ParseErrorLevel = ParseErrorLevel.FATAL) { this.errors.push(new TemplateParseError(message, sourceSpan, level)); } private _reportParserErors(errors: ParserError[], sourceSpan: ParseSourceSpan) { for (const error of errors) { this._reportError(error.message, sourceSpan); } } private _parseInterpolation(value: string, sourceSpan: ParseSourceSpan): ASTWithSource { const sourceInfo = sourceSpan.start.toString(); try { const ast = this._exprParser.parseInterpolation(value, sourceInfo, this._interpolationConfig); if (ast) this._reportParserErors(ast.errors, sourceSpan); this._checkPipes(ast, sourceSpan); if (isPresent(ast) && (<Interpolation>ast.ast).expressions.length > MAX_INTERPOLATION_VALUES) { throw new BaseException( `Only support at most ${MAX_INTERPOLATION_VALUES} interpolation values!`); } return ast; } catch (e) { this._reportError(`${e}`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); } } private _parseAction(value: string, sourceSpan: ParseSourceSpan): ASTWithSource { const sourceInfo = sourceSpan.start.toString(); try { const ast = this._exprParser.parseAction(value, sourceInfo, this._interpolationConfig); if (ast) { this._reportParserErors(ast.errors, sourceSpan); } if (!ast || ast.ast instanceof EmptyExpr) { this._reportError(`Empty expressions are not allowed`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); } this._checkPipes(ast, sourceSpan); return ast; } catch (e) { this._reportError(`${e}`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); } } private _parseBinding(value: string, sourceSpan: ParseSourceSpan): ASTWithSource { const sourceInfo = sourceSpan.start.toString(); try { const ast = this._exprParser.parseBinding(value, sourceInfo, this._interpolationConfig); if (ast) this._reportParserErors(ast.errors, sourceSpan); this._checkPipes(ast, sourceSpan); return ast; } catch (e) { this._reportError(`${e}`, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo); } } private _parseTemplateBindings(value: string, sourceSpan: ParseSourceSpan): TemplateBinding[] { const sourceInfo = sourceSpan.start.toString(); try { const bindingsResult = this._exprParser.parseTemplateBindings(value, sourceInfo); this._reportParserErors(bindingsResult.errors, sourceSpan); bindingsResult.templateBindings.forEach((binding) => { if (isPresent(binding.expression)) { this._checkPipes(binding.expression, sourceSpan); } }); bindingsResult.warnings.forEach( (warning) => { this._reportError(warning, sourceSpan, ParseErrorLevel.WARNING); }); return bindingsResult.templateBindings; } catch (e) { this._reportError(`${e}`, sourceSpan); return []; } } private _checkPipes(ast: ASTWithSource, sourceSpan: ParseSourceSpan) { if (isPresent(ast)) { const collector = new PipeCollector(); ast.visit(collector); collector.pipes.forEach((pipeName) => { if (!this.pipesByName.has(pipeName)) { this._reportError(`The pipe '${pipeName}' could not be found`, sourceSpan); } }); } } visitExpansion(expansion: html.Expansion, context: any): any { return null; } visitExpansionCase(expansionCase: html.ExpansionCase, context: any): any { return null; } visitText(text: html.Text, parent: ElementContext): any { const ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR); const expr = this._parseInterpolation(text.value, text.sourceSpan); if (isPresent(expr)) { return new BoundTextAst(expr, ngContentIndex, text.sourceSpan); } else { return new TextAst(text.value, ngContentIndex, text.sourceSpan); } } visitAttribute(attribute: html.Attribute, contex: any): any { return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan); } visitComment(comment: html.Comment, context: any): any { return null; } visitElement(element: html.Element, parent: ElementContext): any { const nodeName = element.name; const preparsedElement = preparseElement(element); if (preparsedElement.type === PreparsedElementType.SCRIPT || preparsedElement.type === PreparsedElementType.STYLE) { // Skipping <script> for security reasons // Skipping <style> as we already processed them // in the StyleCompiler return null; } if (preparsedElement.type === PreparsedElementType.STYLESHEET && isStyleUrlResolvable(preparsedElement.hrefAttr)) { // Skipping stylesheets with either relative urls or package scheme as we already processed // them in the StyleCompiler return null; } const matchableAttrs: string[][] = []; const elementOrDirectiveProps: BoundElementOrDirectiveProperty[] = []; const elementOrDirectiveRefs: ElementOrDirectiveRef[] = []; const elementVars: VariableAst[] = []; const animationProps: BoundElementPropertyAst[] = []; const events: BoundEventAst[] = []; const templateElementOrDirectiveProps: BoundElementOrDirectiveProperty[] = []; const templateMatchableAttrs: string[][] = []; const templateElementVars: VariableAst[] = []; let hasInlineTemplates = false; const attrs: AttrAst[] = []; const lcElName = splitNsName(nodeName.toLowerCase())[1]; const isTemplateElement = lcElName == TEMPLATE_ELEMENT; element.attrs.forEach(attr => { const hasBinding = this._parseAttr( isTemplateElement, attr, matchableAttrs, elementOrDirectiveProps, animationProps, events, elementOrDirectiveRefs, elementVars); const hasTemplateBinding = this._parseInlineTemplateBinding( attr, templateMatchableAttrs, templateElementOrDirectiveProps, templateElementVars); if (hasTemplateBinding && hasInlineTemplates) { this._reportError( `Can't have multiple template bindings on one element. Use only one attribute named 'template' or prefixed with *`, attr.sourceSpan); } if (!hasBinding && !hasTemplateBinding) { // don't include the bindings as attributes as well in the AST attrs.push(this.visitAttribute(attr, null)); matchableAttrs.push([attr.name, attr.value]); } if (hasTemplateBinding) { hasInlineTemplates = true; } }); const elementCssSelector = createElementCssSelector(nodeName, matchableAttrs); const directiveMetas = this._parseDirectives(this.selectorMatcher, elementCssSelector); const references: ReferenceAst[] = []; const directiveAsts = this._createDirectiveAsts( isTemplateElement, element.name, directiveMetas, elementOrDirectiveProps, elementOrDirectiveRefs, element.sourceSpan, references); const elementProps: BoundElementPropertyAst[] = this._createElementPropertyAsts(element.name, elementOrDirectiveProps, directiveAsts) .concat(animationProps); const isViewRoot = parent.isTemplateElement || hasInlineTemplates; const providerContext = new ProviderElementContext( this.providerViewContext, parent.providerContext, isViewRoot, directiveAsts, attrs, references, element.sourceSpan); const children = html.visitAll( preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this, element.children, ElementContext.create( isTemplateElement, directiveAsts, isTemplateElement ? parent.providerContext : providerContext)); providerContext.afterElement(); // Override the actual selector when the `ngProjectAs` attribute is provided const projectionSelector = isPresent(preparsedElement.projectAs) ? CssSelector.parse(preparsedElement.projectAs)[0] : elementCssSelector; const ngContentIndex = parent.findNgContentIndex(projectionSelector); let parsedElement: TemplateAst; if (preparsedElement.type === PreparsedElementType.NG_CONTENT) { if (isPresent(element.children) && element.children.length > 0) { this._reportError( `<ng-content> element cannot have content. <ng-content> must be immediately followed by </ng-content>`, element.sourceSpan); } parsedElement = new NgContentAst( this.ngContentCount++, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan); } else if (isTemplateElement) { this._assertAllEventsPublishedByDirectives(directiveAsts, events); this._assertNoComponentsNorElementBindingsOnTemplate( directiveAsts, elementProps, element.sourceSpan); parsedElement = new EmbeddedTemplateAst( attrs, events, references, elementVars, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, children, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan); } else { this._assertOnlyOneComponent(directiveAsts, element.sourceSpan); const ngContentIndex = hasInlineTemplates ? null : parent.findNgContentIndex(projectionSelector); parsedElement = new ElementAst( nodeName, attrs, elementProps, events, references, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, children, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan); } if (hasInlineTemplates) { const templateCssSelector = createElementCssSelector(TEMPLATE_ELEMENT, templateMatchableAttrs); const templateDirectiveMetas = this._parseDirectives(this.selectorMatcher, templateCssSelector); const templateDirectiveAsts = this._createDirectiveAsts( true, element.name, templateDirectiveMetas, templateElementOrDirectiveProps, [], element.sourceSpan, []); const templateElementProps: BoundElementPropertyAst[] = this._createElementPropertyAsts( element.name, templateElementOrDirectiveProps, templateDirectiveAsts); this._assertNoComponentsNorElementBindingsOnTemplate( templateDirectiveAsts, templateElementProps, element.sourceSpan); const templateProviderContext = new ProviderElementContext( this.providerViewContext, parent.providerContext, parent.isTemplateElement, templateDirectiveAsts, [], [], element.sourceSpan); templateProviderContext.afterElement(); parsedElement = new EmbeddedTemplateAst( [], [], [], templateElementVars, templateProviderContext.transformedDirectiveAsts, templateProviderContext.transformProviders, templateProviderContext.transformedHasViewContainer, [parsedElement], ngContentIndex, element.sourceSpan); } return parsedElement; } private _parseInlineTemplateBinding( attr: html.Attribute, targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[], targetVars: VariableAst[]): boolean { let templateBindingsSource: string = null; if (this._normalizeAttributeName(attr.name) == TEMPLATE_ATTR) { templateBindingsSource = attr.value; } else if (attr.name.startsWith(TEMPLATE_ATTR_PREFIX)) { const key = attr.name.substring(TEMPLATE_ATTR_PREFIX.length); // remove the star templateBindingsSource = (attr.value.length == 0) ? key : key + ' ' + attr.value; } if (isPresent(templateBindingsSource)) { const bindings = this._parseTemplateBindings(templateBindingsSource, attr.sourceSpan); for (let i = 0; i < bindings.length; i++) { const binding = bindings[i]; if (binding.keyIsVar) { targetVars.push(new VariableAst(binding.key, binding.name, attr.sourceSpan)); } else if (isPresent(binding.expression)) { this._parsePropertyAst( binding.key, binding.expression, attr.sourceSpan, targetMatchableAttrs, targetProps); } else { targetMatchableAttrs.push([binding.key, '']); this._parseLiteralAttr(binding.key, null, attr.sourceSpan, targetProps); } } return true; } return false; } private _parseAttr( isTemplateElement: boolean, attr: html.Attribute, targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[], targetAnimationProps: BoundElementPropertyAst[], targetEvents: BoundEventAst[], targetRefs: ElementOrDirectiveRef[], targetVars: VariableAst[]): boolean { const attrName = this._normalizeAttributeName(attr.name); const attrValue = attr.value; const bindParts = RegExpWrapper.firstMatch(BIND_NAME_REGEXP, attrName); let hasBinding = false; if (isPresent(bindParts)) { hasBinding = true; if (isPresent(bindParts[1])) { // match: bind-prop this._parsePropertyOrAnimation( bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps, targetAnimationProps); } else if (isPresent(bindParts[2])) { // match: var-name / var-name="iden" const identifier = bindParts[8]; if (isTemplateElement) { this._reportError( `"var-" on <template> elements is deprecated. Use "let-" instead!`, attr.sourceSpan, ParseErrorLevel.WARNING); this._parseVariable(identifier, attrValue, attr.sourceSpan, targetVars); } else { this._reportError( `"var-" on non <template> elements is deprecated. Use "ref-" instead!`, attr.sourceSpan, ParseErrorLevel.WARNING); this._parseReference(identifier, attrValue, attr.sourceSpan, targetRefs); } } else if (isPresent(bindParts[3])) { // match: let-name if (isTemplateElement) { const identifier = bindParts[8]; this._parseVariable(identifier, attrValue, attr.sourceSpan, targetVars); } else { this._reportError(`"let-" is only supported on template elements.`, attr.sourceSpan); } } else if (isPresent(bindParts[4])) { // match: ref- / #iden const identifier = bindParts[8]; this._parseReference(identifier, attrValue, attr.sourceSpan, targetRefs); } else if (isPresent(bindParts[5])) { // match: on-event this._parseEvent( bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); } else if (isPresent(bindParts[6])) { // match: bindon-prop this._parsePropertyOrAnimation( bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps, targetAnimationProps); this._parseAssignmentEvent( bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); } else if (isPresent(bindParts[7])) { // match: animate-name if (attrName[0] == '@' && isPresent(attrValue) && attrValue.length > 0) { this._reportError( `Assigning animation triggers via @prop="exp" attributes with an expression is deprecated. Use [@prop]="exp" instead!`, attr.sourceSpan, ParseErrorLevel.WARNING); } this._parseAnimation( bindParts[8], attrValue, attr.sourceSpan, targetMatchableAttrs, targetAnimationProps); } else if (isPresent(bindParts[9])) { // match: [(expr)] this._parsePropertyOrAnimation( bindParts[9], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps, targetAnimationProps); this._parseAssignmentEvent( bindParts[9], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); } else if (isPresent(bindParts[10])) { // match: [expr] this._parsePropertyOrAnimation( bindParts[10], attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps, targetAnimationProps); } else if (isPresent(bindParts[11])) { // match: (event) this._parseEvent( bindParts[11], attrValue, attr.sourceSpan, targetMatchableAttrs, targetEvents); } } else { hasBinding = this._parsePropertyInterpolation( attrName, attrValue, attr.sourceSpan, targetMatchableAttrs, targetProps); } if (!hasBinding) { this._parseLiteralAttr(attrName, attrValue, attr.sourceSpan, targetProps); } return hasBinding; } private _normalizeAttributeName(attrName: string): string { return attrName.toLowerCase().startsWith('data-') ? attrName.substring(5) : attrName; } private _parseVariable( identifier: string, value: string, sourceSpan: ParseSourceSpan, targetVars: VariableAst[]) { if (identifier.indexOf('-') > -1) { this._reportError(`"-" is not allowed in variable names`, sourceSpan); } targetVars.push(new VariableAst(identifier, value, sourceSpan)); } private _parseReference( identifier: string, value: string, sourceSpan: ParseSourceSpan, targetRefs: ElementOrDirectiveRef[]) { if (identifier.indexOf('-') > -1) { this._reportError(`"-" is not allowed in reference names`, sourceSpan); } targetRefs.push(new ElementOrDirectiveRef(identifier, value, sourceSpan)); } private _parsePropertyOrAnimation( name: string, expression: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[], targetAnimationProps: BoundElementPropertyAst[]) { if (name[0] == '@') { this._parseAnimation( name.substr(1), expression, sourceSpan, targetMatchableAttrs, targetAnimationProps); } else { this._parsePropertyAst( name, this._parseBinding(expression, sourceSpan), sourceSpan, targetMatchableAttrs, targetProps); } } private _parseAnimation( name: string, expression: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetAnimationProps: BoundElementPropertyAst[]) { // This will occur when a @trigger is not paired with an expression. // For animations it is valid to not have an expression since */void // states will be applied by angular when the element is attached/detached if (!isPresent(expression) || expression.length == 0) { expression = 'null'; } const ast = this._parseBinding(expression, sourceSpan); targetMatchableAttrs.push([name, ast.source]); targetAnimationProps.push(new BoundElementPropertyAst( name, PropertyBindingType.Animation, SecurityContext.NONE, ast, null, sourceSpan)); } private _parsePropertyInterpolation( name: string, value: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[]): boolean { const expr = this._parseInterpolation(value, sourceSpan); if (isPresent(expr)) { this._parsePropertyAst(name, expr, sourceSpan, targetMatchableAttrs, targetProps); return true; } return false; } private _parsePropertyAst( name: string, ast: ASTWithSource, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetProps: BoundElementOrDirectiveProperty[]) { targetMatchableAttrs.push([name, ast.source]); targetProps.push(new BoundElementOrDirectiveProperty(name, ast, false, sourceSpan)); } private _parseAssignmentEvent( name: string, expression: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetEvents: BoundEventAst[]) { this._parseEvent( `${name}Change`, `${expression}=$event`, sourceSpan, targetMatchableAttrs, targetEvents); } private _parseEvent( name: string, expression: string, sourceSpan: ParseSourceSpan, targetMatchableAttrs: string[][], targetEvents: BoundEventAst[]) { // long format: 'target: eventName' const parts = splitAtColon(name, [null, name]); const target = parts[0]; const eventName = parts[1]; const ast = this._parseAction(expression, sourceSpan); targetMatchableAttrs.push([name, ast.source]); targetEvents.push(new BoundEventAst(eventName, target, ast, sourceSpan)); // Don't detect directives for event names for now, // so don't add the event name to the matchableAttrs } private _parseLiteralAttr( name: string, value: string, sourceSpan: ParseSourceSpan, targetProps: BoundElementOrDirectiveProperty[]) { targetProps.push(new BoundElementOrDirectiveProperty( name, this._exprParser.wrapLiteralPrimitive(value, ''), true, sourceSpan)); } private _parseDirectives(selectorMatcher: SelectorMatcher, elementCssSelector: CssSelector): CompileDirectiveMetadata[] { // Need to sort the directives so that we get consistent results throughout, // as selectorMatcher uses Maps inside. // Also dedupe directives as they might match more than one time! const directives = ListWrapper.createFixedSize(this.directivesIndex.size); selectorMatcher.match(elementCssSelector, (selector, directive) => { directives[this.directivesIndex.get(directive)] = directive; }); return directives.filter(dir => isPresent(dir)); } private _createDirectiveAsts( isTemplateElement: boolean, elementName: string, directives: CompileDirectiveMetadata[], props: BoundElementOrDirectiveProperty[], elementOrDirectiveRefs: ElementOrDirectiveRef[], elementSourceSpan: ParseSourceSpan, targetReferences: ReferenceAst[]): DirectiveAst[] { const matchedReferences = new Set<string>(); let component: CompileDirectiveMetadata = null; const directiveAsts = directives.map((directive: CompileDirectiveMetadata) => { const sourceSpan = new ParseSourceSpan( elementSourceSpan.start, elementSourceSpan.end, `Directive ${directive.type.name}`); if (directive.isComponent) { component = directive; } const hostProperties: BoundElementPropertyAst[] = []; const hostEvents: BoundEventAst[] = []; const directiveProperties: BoundDirectivePropertyAst[] = []; this._createDirectiveHostPropertyAsts( elementName, directive.hostProperties, sourceSpan, hostProperties); this._createDirectiveHostEventAsts(directive.hostListeners, sourceSpan, hostEvents); this._createDirectivePropertyAsts(directive.inputs, props, directiveProperties); elementOrDirectiveRefs.forEach((elOrDirRef) => { if ((elOrDirRef.value.length === 0 && directive.isComponent) || (directive.exportAs == elOrDirRef.value)) { targetReferences.push(new ReferenceAst( elOrDirRef.name, identifierToken(directive.type), elOrDirRef.sourceSpan)); matchedReferences.add(elOrDirRef.name); } }); return new DirectiveAst( directive, directiveProperties, hostProperties, hostEvents, sourceSpan); }); elementOrDirectiveRefs.forEach((elOrDirRef) => { if (elOrDirRef.value.length > 0) { if (!SetWrapper.has(matchedReferences, elOrDirRef.name)) { this._reportError( `There is no directive with "exportAs" set to "${elOrDirRef.value}"`, elOrDirRef.sourceSpan); } } else if (isBlank(component)) { let refToken: CompileTokenMetadata = null; if (isTemplateElement) { refToken = identifierToken(Identifiers.TemplateRef); } targetReferences.push(new ReferenceAst(elOrDirRef.name, refToken, elOrDirRef.sourceSpan)); } }); // fix syntax highlighting issue: ` return directiveAsts; } private _createDirectiveHostPropertyAsts( elementName: string, hostProps: {[key: string]: string}, sourceSpan: ParseSourceSpan, targetPropertyAsts: BoundElementPropertyAst[]) { if (isPresent(hostProps)) { StringMapWrapper.forEach(hostProps, (expression: string, propName: string) => { const exprAst = this._parseBinding(expression, sourceSpan); targetPropertyAsts.push( this._createElementPropertyAst(elementName, propName, exprAst, sourceSpan)); }); } } private _createDirectiveHostEventAsts( hostListeners: {[key: string]: string}, sourceSpan: ParseSourceSpan, targetEventAsts: BoundEventAst[]) { if (isPresent(hostListeners)) { StringMapWrapper.forEach(hostListeners, (expression: string, propName: string) => { this._parseEvent(propName, expression, sourceSpan, [], targetEventAsts); }); } } private _createDirectivePropertyAsts( directiveProperties: {[key: string]: string}, boundProps: BoundElementOrDirectiveProperty[], targetBoundDirectiveProps: BoundDirectivePropertyAst[]) { if (isPresent(directiveProperties)) { const boundPropsByName = new Map<string, BoundElementOrDirectiveProperty>(); boundProps.forEach(boundProp => { const prevValue = boundPropsByName.get(boundProp.name); if (isBlank(prevValue) || prevValue.isLiteral) { // give [a]="b" a higher precedence than a="b" on the same element boundPropsByName.set(boundProp.name, boundProp); } }); StringMapWrapper.forEach(directiveProperties, (elProp: string, dirProp: string) => { const boundProp = boundPropsByName.get(elProp); // Bindings are optional, so this binding only needs to be set up if an expression is given. if (isPresent(boundProp)) { targetBoundDirectiveProps.push(new BoundDirectivePropertyAst( dirProp, boundProp.name, boundProp.expression, boundProp.sourceSpan)); } }); } } private _createElementPropertyAsts( elementName: string, props: BoundElementOrDirectiveProperty[], directives: DirectiveAst[]): BoundElementPropertyAst[] { const boundElementProps: BoundElementPropertyAst[] = []; const boundDirectivePropsIndex = new Map<string, BoundDirectivePropertyAst>(); directives.forEach((directive: DirectiveAst) => { directive.inputs.forEach((prop: BoundDirectivePropertyAst) => { boundDirectivePropsIndex.set(prop.templateName, prop); }); }); props.forEach((prop: BoundElementOrDirectiveProperty) => { if (!prop.isLiteral && isBlank(boundDirectivePropsIndex.get(prop.name))) { boundElementProps.push(this._createElementPropertyAst( elementName, prop.name, prop.expression, prop.sourceSpan)); } }); return boundElementProps; } private _createElementPropertyAst( elementName: string, name: string, ast: AST, sourceSpan: ParseSourceSpan): BoundElementPropertyAst { let unit: string = null; let bindingType: PropertyBindingType; let boundPropertyName: string; const parts = name.split(PROPERTY_PARTS_SEPARATOR); let securityContext: SecurityContext; if (parts.length === 1) { var partValue = parts[0]; if (partValue[0] == '@') { boundPropertyName = partValue.substr(1); bindingType = PropertyBindingType.Animation; securityContext = SecurityContext.NONE; this._reportError( `Assigning animation triggers within host data as attributes such as "@prop": "exp" is deprecated. Use "[@prop]": "exp" instead!`, sourceSpan, ParseErrorLevel.WARNING); } else { boundPropertyName = this._schemaRegistry.getMappedPropName(partValue); securityContext = this._schemaRegistry.securityContext(elementName, boundPropertyName); bindingType = PropertyBindingType.Property; if (!this._schemaRegistry.hasProperty(elementName, boundPropertyName, this._schemas)) { let errorMsg = `Can't bind to '${boundPropertyName}' since it isn't a known native property`; if (elementName.indexOf('-') !== -1) { errorMsg += `. To ignore this error on custom elements, add the "CUSTOM_ELEMENTS_SCHEMA" to the NgModule of this component`; } this._reportError(errorMsg, sourceSpan); } } } else { if (parts[0] == ATTRIBUTE_PREFIX) { boundPropertyName = parts[1]; if (boundPropertyName.toLowerCase().startsWith('on')) { this._reportError( `Binding to event attribute '${boundPropertyName}' is disallowed ` + `for security reasons, please use (${boundPropertyName.slice(2)})=...`, sourceSpan); } // NB: For security purposes, use the mapped property name, not the attribute name. securityContext = this._schemaRegistry.securityContext( elementName, this._schemaRegistry.getMappedPropName(boundPropertyName)); let nsSeparatorIdx = boundPropertyName.indexOf(':'); if (nsSeparatorIdx > -1) { let ns = boundPropertyName.substring(0, nsSeparatorIdx); let name = boundPropertyName.substring(nsSeparatorIdx + 1); boundPropertyName = mergeNsAndName(ns, name); } bindingType = PropertyBindingType.Attribute; } else if (parts[0] == CLASS_PREFIX) { boundPropertyName = parts[1]; bindingType = PropertyBindingType.Class; securityContext = SecurityContext.NONE; } else if (parts[0] == STYLE_PREFIX) { unit = parts.length > 2 ? parts[2] : null; boundPropertyName = parts[1]; bindingType = PropertyBindingType.Style; securityContext = SecurityContext.STYLE; } else { this._reportError(`Invalid property name '${name}'`, sourceSpan); bindingType = null; securityContext = null; } } return new BoundElementPropertyAst( boundPropertyName, bindingType, securityContext, ast, unit, sourceSpan); } private _findComponentDirectiveNames(directives: DirectiveAst[]): string[] { const componentTypeNames: string[] = []; directives.forEach(directive => { const typeName = directive.directive.type.name; if (directive.directive.isComponent) { componentTypeNames.push(typeName); } }); return componentTypeNames; } private _assertOnlyOneComponent(directives: DirectiveAst[], sourceSpan: ParseSourceSpan) { const componentTypeNames = this._findComponentDirectiveNames(directives); if (componentTypeNames.length > 1) { this._reportError(`More than one component: ${componentTypeNames.join(',')}`, sourceSpan); } } private _assertNoComponentsNorElementBindingsOnTemplate( directives: DirectiveAst[], elementProps: BoundElementPropertyAst[], sourceSpan: ParseSourceSpan) { const componentTypeNames: string[] = this._findComponentDirectiveNames(directives); if (componentTypeNames.length > 0) { this._reportError( `Components on an embedded template: ${componentTypeNames.join(',')}`, sourceSpan); } elementProps.forEach(prop => { this._reportError( `Property binding ${prop.name} not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "directives" section.`, sourceSpan); }); } private _assertAllEventsPublishedByDirectives( directives: DirectiveAst[], events: BoundEventAst[]) { const allDirectiveEvents = new Set<string>(); directives.forEach(directive => { StringMapWrapper.forEach(directive.directive.outputs, (eventName: string) => { allDirectiveEvents.add(eventName); }); }); events.forEach(event => { if (isPresent(event.target) || !SetWrapper.has(allDirectiveEvents, event.name)) { this._reportError( `Event binding ${event.fullName} not emitted by any directive on an embedded template. Make sure that the event name is spelled correctly and all directives are listed in the "directives" section.`, event.sourceSpan); } }); } } class NonBindableVisitor implements html.Visitor { visitElement(ast: html.Element, parent: ElementContext): ElementAst { const preparsedElement = preparseElement(ast); if (preparsedElement.type === PreparsedElementType.SCRIPT || preparsedElement.type === PreparsedElementType.STYLE || preparsedElement.type === PreparsedElementType.STYLESHEET) { // Skipping <script> for security reasons // Skipping <style> and stylesheets as we already processed them // in the StyleCompiler return null; } const attrNameAndValues = ast.attrs.map(attrAst => [attrAst.name, attrAst.value]); const selector = createElementCssSelector(ast.name, attrNameAndValues); const ngContentIndex = parent.findNgContentIndex(selector); const children = html.visitAll(this, ast.children, EMPTY_ELEMENT_CONTEXT); return new ElementAst( ast.name, html.visitAll(this, ast.attrs), [], [], [], [], [], false, children, ngContentIndex, ast.sourceSpan); } visitComment(comment: html.Comment, context: any): any { return null; } visitAttribute(attribute: html.Attribute, context: any): AttrAst { return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan); } visitText(text: html.Text, parent: ElementContext): TextAst { const ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR); return new TextAst(text.value, ngContentIndex, text.sourceSpan); } visitExpansion(expansion: html.Expansion, context: any): any { return expansion; } visitExpansionCase(expansionCase: html.ExpansionCase, context: any): any { return expansionCase; } } class BoundElementOrDirectiveProperty { constructor( public name: string, public expression: AST, public isLiteral: boolean, public sourceSpan: ParseSourceSpan) {} } class ElementOrDirectiveRef { constructor(public name: string, public value: string, public sourceSpan: ParseSourceSpan) {} } export function splitClasses(classAttrValue: string): string[] { return classAttrValue.trim().split(/\s+/g); } class ElementContext { static create( isTemplateElement: boolean, directives: DirectiveAst[], providerContext: ProviderElementContext): ElementContext { const matcher = new SelectorMatcher(); let wildcardNgContentIndex: number = null; const component = directives.find(directive => directive.directive.isComponent); if (isPresent(component)) { const ngContentSelectors = component.directive.template.ngContentSelectors; for (let i = 0; i < ngContentSelectors.length; i++) { const selector = ngContentSelectors[i]; if (selector === '*') { wildcardNgContentIndex = i; } else { matcher.addSelectables(CssSelector.parse(ngContentSelectors[i]), i); } } } return new ElementContext(isTemplateElement, matcher, wildcardNgContentIndex, providerContext); } constructor( public isTemplateElement: boolean, private _ngContentIndexMatcher: SelectorMatcher, private _wildcardNgContentIndex: number, public providerContext: ProviderElementContext) {} findNgContentIndex(selector: CssSelector): number { const ngContentIndices: number[] = []; this._ngContentIndexMatcher.match( selector, (selector, ngContentIndex) => { ngContentIndices.push(ngContentIndex); }); ListWrapper.sort(ngContentIndices); if (isPresent(this._wildcardNgContentIndex)) { ngContentIndices.push(this._wildcardNgContentIndex); } return ngContentIndices.length > 0 ? ngContentIndices[0] : null; } } function createElementCssSelector(elementName: string, matchableAttrs: string[][]): CssSelector { const cssSelector = new CssSelector(); let elNameNoNs = splitNsName(elementName)[1]; cssSelector.setElement(elNameNoNs); for (let i = 0; i < matchableAttrs.length; i++) { let attrName = matchableAttrs[i][0]; let attrNameNoNs = splitNsName(attrName)[1]; let attrValue = matchableAttrs[i][1]; cssSelector.addAttribute(attrNameNoNs, attrValue); if (attrName.toLowerCase() == CLASS_ATTR) { const classes = splitClasses(attrValue); classes.forEach(className => cssSelector.addClassName(className)); } } return cssSelector; } const EMPTY_ELEMENT_CONTEXT = new ElementContext(true, new SelectorMatcher(), null, null); const NON_BINDABLE_VISITOR = new NonBindableVisitor(); export class PipeCollector extends RecursiveAstVisitor { pipes: Set<string> = new Set<string>(); visitPipe(ast: BindingPipe, context: any): any { this.pipes.add(ast.name); ast.exp.visit(this); this.visitAll(ast.args, context); return null; } }
modules/@angular/compiler/src/template_parser/template_parser.ts
1
https://github.com/angular/angular/commit/a55d796c4b4cbe5bc1256339bd398090f58b4d69
[ 0.0011432889150455594, 0.00018211751012131572, 0.00016319434507749975, 0.00016861813492141664, 0.00010082637891173363 ]
{ "id": 5, "code_window": [ " MyComp, new ViewMetadata({template: '<div unknown=\"{{ctxProp}}\"></div>'}));\n", "\n", " PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => {\n", " expect(e.message).toEqual(\n", " `Template parse errors:\\nCan't bind to 'unknown' since it isn't a known native property (\"<div [ERROR ->]unknown=\"{{ctxProp}}\"></div>\"): MyComp@0:5`);\n", " async.done();\n", " return null;\n", " });\n", " }));\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " `Template parse errors:\\nCan't bind to 'unknown' since it isn't a known property of 'div'. (\"<div [ERROR ->]unknown=\"{{ctxProp}}\"></div>\"): MyComp@0:5`);\n" ], "file_path": "modules/@angular/core/test/linker/integration_spec.ts", "type": "replace", "edit_start_line_idx": 1000 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */
modules/@angular/platform-browser/dynamic.ts
0
https://github.com/angular/angular/commit/a55d796c4b4cbe5bc1256339bd398090f58b4d69
[ 0.00017507473239675164, 0.00017507473239675164, 0.00017507473239675164, 0.00017507473239675164, 0 ]
{ "id": 5, "code_window": [ " MyComp, new ViewMetadata({template: '<div unknown=\"{{ctxProp}}\"></div>'}));\n", "\n", " PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => {\n", " expect(e.message).toEqual(\n", " `Template parse errors:\\nCan't bind to 'unknown' since it isn't a known native property (\"<div [ERROR ->]unknown=\"{{ctxProp}}\"></div>\"): MyComp@0:5`);\n", " async.done();\n", " return null;\n", " });\n", " }));\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " `Template parse errors:\\nCan't bind to 'unknown' since it isn't a known property of 'div'. (\"<div [ERROR ->]unknown=\"{{ctxProp}}\"></div>\"): MyComp@0:5`);\n" ], "file_path": "modules/@angular/core/test/linker/integration_spec.ts", "type": "replace", "edit_start_line_idx": 1000 }
#!/bin/bash platform=`uname` if [[ "$platform" == 'Linux' ]]; then `google-chrome --js-flags="--expose-gc"` elif [[ "$platform" == 'Darwin' ]]; then `/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary \ --enable-memory-info \ --enable-precise-memory-info \ --enable-memory-benchmarking \ --js-flags="--expose-gc --allow-natives-syntax" \ --disable-web-security \ --remote-debugging-port=9222` fi
scripts/ci/perf_launch_chrome.sh
0
https://github.com/angular/angular/commit/a55d796c4b4cbe5bc1256339bd398090f58b4d69
[ 0.00017081690020859241, 0.00017035834025591612, 0.0001698997657513246, 0.00017035834025591612, 4.585672286339104e-7 ]
{ "id": 5, "code_window": [ " MyComp, new ViewMetadata({template: '<div unknown=\"{{ctxProp}}\"></div>'}));\n", "\n", " PromiseWrapper.catchError(tcb.createAsync(MyComp), (e) => {\n", " expect(e.message).toEqual(\n", " `Template parse errors:\\nCan't bind to 'unknown' since it isn't a known native property (\"<div [ERROR ->]unknown=\"{{ctxProp}}\"></div>\"): MyComp@0:5`);\n", " async.done();\n", " return null;\n", " });\n", " }));\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " `Template parse errors:\\nCan't bind to 'unknown' since it isn't a known property of 'div'. (\"<div [ERROR ->]unknown=\"{{ctxProp}}\"></div>\"): MyComp@0:5`);\n" ], "file_path": "modules/@angular/core/test/linker/integration_spec.ts", "type": "replace", "edit_start_line_idx": 1000 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {bootstrap} from '@angular/platform-browser-dynamic'; import {Component, Directive, Host} from '@angular/core'; import { ControlGroup, NgIf, NgFor, NG_VALIDATORS, FORM_DIRECTIVES, NgControl, Validators, NgForm } from '@angular/common'; import {RegExpWrapper, print, isPresent} from '@angular/core/src/facade/lang'; /** * A domain model we are binding the form controls to. */ class CheckoutModel { firstName: string; middleName: string; lastName: string; country: string = "Canada"; creditCard: string; amount: number; email: string; comments: string; } /** * Custom validator. */ function creditCardValidator(c: any /** TODO #9100 */): {[key: string]: boolean} { if (isPresent(c.value) && RegExpWrapper.test(/^\d{16}$/g, c.value)) { return null; } else { return {"invalidCreditCard": true}; } } const creditCardValidatorBinding = { provide: NG_VALIDATORS, useValue: creditCardValidator, multi: true }; @Directive({selector: '[credit-card]', providers: [creditCardValidatorBinding]}) class CreditCardValidator { } /** * This is a component that displays an error message. * * For instance, * * <show-error control="creditCard" [errors]="['required', 'invalidCreditCard']"></show-error> * * Will display the "is required" error if the control is empty, and "invalid credit card" if the * control is not empty * but not valid. * * In a real application, this component would receive a service that would map an error code to an * actual error message. * To make it simple, we are using a simple map here. */ @Component({ selector: 'show-error', inputs: ['controlPath: control', 'errorTypes: errors'], template: ` <span *ngIf="errorMessage !== null">{{errorMessage}}</span> `, directives: [NgIf] }) class ShowError { formDir: any /** TODO #9100 */; controlPath: string; errorTypes: string[]; constructor(@Host() formDir: NgForm) { this.formDir = formDir; } get errorMessage(): string { var form: ControlGroup = this.formDir.form; var control = form.find(this.controlPath); if (isPresent(control) && control.touched) { for (var i = 0; i < this.errorTypes.length; ++i) { if (control.hasError(this.errorTypes[i])) { return this._errorMessage(this.errorTypes[i]); } } } return null; } _errorMessage(code: string): string { var config = {'required': 'is required', 'invalidCreditCard': 'is invalid credit card number'}; return (config as any /** TODO #9100 */)[code]; } } @Component({ selector: 'template-driven-forms', template: ` <h1>Checkout Form</h1> <form (ngSubmit)="onSubmit()" #f="ngForm"> <p> <label for="firstName">First Name</label> <input type="text" id="firstName" ngControl="firstName" [(ngModel)]="model.firstName" required> <show-error control="firstName" [errors]="['required']"></show-error> </p> <p> <label for="middleName">Middle Name</label> <input type="text" id="middleName" ngControl="middleName" [(ngModel)]="model.middleName"> </p> <p> <label for="lastName">Last Name</label> <input type="text" id="lastName" ngControl="lastName" [(ngModel)]="model.lastName" required> <show-error control="lastName" [errors]="['required']"></show-error> </p> <p> <label for="country">Country</label> <select id="country" ngControl="country" [(ngModel)]="model.country"> <option *ngFor="let c of countries" [value]="c">{{c}}</option> </select> </p> <p> <label for="creditCard">Credit Card</label> <input type="text" id="creditCard" ngControl="creditCard" [(ngModel)]="model.creditCard" required credit-card> <show-error control="creditCard" [errors]="['required', 'invalidCreditCard']"></show-error> </p> <p> <label for="amount">Amount</label> <input type="number" id="amount" ngControl="amount" [(ngModel)]="model.amount" required> <show-error control="amount" [errors]="['required']"></show-error> </p> <p> <label for="email">Email</label> <input type="email" id="email" ngControl="email" [(ngModel)]="model.email" required> <show-error control="email" [errors]="['required']"></show-error> </p> <p> <label for="comments">Comments</label> <textarea id="comments" ngControl="comments" [(ngModel)]="model.comments"> </textarea> </p> <button type="submit" [disabled]="!f.form.valid">Submit</button> </form> `, directives: [FORM_DIRECTIVES, NgFor, CreditCardValidator, ShowError] }) class TemplateDrivenForms { model = new CheckoutModel(); countries = ['US', 'Canada']; onSubmit(): void { print("Submitting:"); print(this.model); } } export function main() { bootstrap(TemplateDrivenForms); }
modules/playground/src/template_driven_forms/index.ts
0
https://github.com/angular/angular/commit/a55d796c4b4cbe5bc1256339bd398090f58b4d69
[ 0.00018560195167083293, 0.00017174951790366322, 0.0001594189670868218, 0.00017220040899701416, 0.000005719551609217888 ]
{ "id": 0, "code_window": [ " isISIN(str: string): boolean;\n", "\n", " // check if the string is a valid ISO 8601 (https://en.wikipedia.org/wiki/ISO_8601) date.\n", " isISO8601(str: string): boolean;\n", "\n", " // check if the string is a valid ISO 3166-1 alpha-2 (https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) officially assigned\n", " // country code.\n", " isISO31661Alpha2(str: string): boolean;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " isISO8601(str: string, options?: IsISO8601Options): boolean;\n" ], "file_path": "types/validator/index.d.ts", "type": "replace", "edit_start_line_idx": 124 }
import * as validator from 'validator'; /************************************************ * * * IMPORT TESTS * * * ************************************************/ import blacklistFunc = require('validator/lib/blacklist'); import containsFunc = require('validator/lib/contains'); import equalsFunc = require('validator/lib/equals'); import escapeFunc = require('validator/lib/escape'); import isAfterFunc = require('validator/lib/isAfter'); import isAlphaFunc = require('validator/lib/isAlpha'); import isAlphanumericFunc = require('validator/lib/isAlphanumeric'); import isAsciiFunc = require('validator/lib/isAscii'); import isBase64Func = require('validator/lib/isBase64'); import isBeforeFunc = require('validator/lib/isBefore'); import isBooleanFunc = require('validator/lib/isBoolean'); import isByteLengthFunc = require('validator/lib/isByteLength'); import isCreditCardFunc = require('validator/lib/isCreditCard'); import isCurrencyFunc = require('validator/lib/isCurrency'); import isDataURIFunc = require('validator/lib/isDataURI'); import isDecimalFunc = require('validator/lib/isDecimal'); import isDivisibleByFunc = require('validator/lib/isDivisibleBy'); import isEmailFunc = require('validator/lib/isEmail'); import isEmptyFunc = require('validator/lib/isEmpty'); import isFQDNFunc = require('validator/lib/isFQDN'); import isFloatFunc = require('validator/lib/isFloat'); import isFullWidthFunc = require('validator/lib/isFullWidth'); import isHalfWidthFunc = require('validator/lib/isHalfWidth'); import isHashFunc = require('validator/lib/isHash'); import isHexColorFunc = require('validator/lib/isHexColor'); import isHexadecimalFunc = require('validator/lib/isHexadecimal'); import isIPFunc = require('validator/lib/isIP'); import isISBNFunc = require('validator/lib/isISBN'); import isISSNFunc = require('validator/lib/isISSN'); import isISINFunc = require('validator/lib/isISIN'); import isISO8601Func = require('validator/lib/isISO8601'); import isISO31661Alpha2Func = require('validator/lib/isISO31661Alpha2'); import isISRCFunc = require('validator/lib/isISRC'); import isInFunc = require('validator/lib/isIn'); import isIntFunc = require('validator/lib/isInt'); import isJSONFunc = require('validator/lib/isJSON'); import isLatLongFunc = require('validator/lib/isLatLong'); import isLengthFunc = require('validator/lib/isLength'); import isLowercaseFunc = require('validator/lib/isLowercase'); import isMACAddressFunc = require('validator/lib/isMACAddress'); import isMD5Func = require('validator/lib/isMD5'); import isMimeTypeFunc = require('validator/lib/isMimeType'); import isMobilePhoneFunc = require('validator/lib/isMobilePhone'); import isMongoIdFunc = require('validator/lib/isMongoId'); import isMultibyteFunc = require('validator/lib/isMultibyte'); import isNumericFunc = require('validator/lib/isNumeric'); import isPortFunc = require('validator/lib/isPort'); import isPostalCodeFunc = require('validator/lib/isPostalCode'); import isSurrogatePairFunc = require('validator/lib/isSurrogatePair'); import isURLFunc = require('validator/lib/isURL'); import isUUIDFunc = require('validator/lib/isUUID'); import isUppercaseFunc = require('validator/lib/isUppercase'); import isVariableWidthFunc = require('validator/lib/isVariableWidth'); import isWhitelistedFunc = require('validator/lib/isWhitelisted'); import ltrimFunc = require('validator/lib/ltrim'); import matchesFunc = require('validator/lib/matches'); import normalizeEmailFunc = require('validator/lib/normalizeEmail'); import rtrimFunc = require('validator/lib/rtrim'); import stripLowFunc = require('validator/lib/stripLow'); import toBooleanFunc = require('validator/lib/toBoolean'); import toDateFunc = require('validator/lib/toDate'); import toFloatFunc = require('validator/lib/toFloat'); import toIntFunc = require('validator/lib/toInt'); import trimFunc = require('validator/lib/trim'); import unescapeFunc = require('validator/lib/unescape'); import whitelistFunc = require('validator/lib/whitelist'); { let _blacklist = validator.blacklist; _blacklist = blacklistFunc; let _contains = validator.contains; _contains = containsFunc; let _equals = validator.equals; _equals = equalsFunc; let _escape = validator.escape; _escape = escapeFunc; let _isAfter = validator.isAfter; _isAfter = isAfterFunc; let _isAlpha = validator.isAlpha; _isAlpha = isAlphaFunc; let _isAlphanumeric = validator.isAlphanumeric; _isAlphanumeric = isAlphanumericFunc; let _isAscii = validator.isAscii; _isAscii = isAsciiFunc; let _isBase64 = validator.isBase64; _isBase64 = isBase64Func; let _isBefore = validator.isBefore; _isBefore = isBeforeFunc; let _isBoolean = validator.isBoolean; _isBoolean = isBooleanFunc; let _isByteLength = validator.isByteLength; _isByteLength = isByteLengthFunc; let _isCreditCard = validator.isCreditCard; _isCreditCard = isCreditCardFunc; let _isCurrency = validator.isCurrency; _isCurrency = isCurrencyFunc; let _isDataURI = validator.isDataURI; _isDataURI = isDataURIFunc; let _isDecimal = validator.isDecimal; _isDecimal = isDecimalFunc; let _isDivisibleBy = validator.isDivisibleBy; _isDivisibleBy = isDivisibleByFunc; let _isEmail = validator.isEmail; _isEmail = isEmailFunc; let _isEmpty = validator.isEmpty; _isEmpty = isEmptyFunc; let _isFQDN = validator.isFQDN; _isFQDN = isFQDNFunc; let _isFloat = validator.isFloat; _isFloat = isFloatFunc; let _isFullWidth = validator.isFullWidth; _isFullWidth = isFullWidthFunc; let _isHalfWidth = validator.isHalfWidth; _isHalfWidth = isHalfWidthFunc; let _isHash = validator.isHash; _isHash = isHashFunc; let _isHexColor = validator.isHexColor; _isHexColor = isHexColorFunc; let _isHexadecimal = validator.isHexadecimal; _isHexadecimal = isHexadecimalFunc; let _isIP = validator.isIP; _isIP = isIPFunc; let _isISBN = validator.isISBN; _isISBN = isISBNFunc; let _isISSN = validator.isISSN; _isISSN = isISSNFunc; let _isISIN = validator.isISIN; _isISIN = isISINFunc; let _isISO8601 = validator.isISO8601; _isISO8601 = isISO8601Func; let _isISO31661Alpha2 = validator.isISO31661Alpha2; _isISO31661Alpha2 = isISO31661Alpha2Func; let _isISRC = validator.isISRC; _isISRC = isISRCFunc; let _isIn = validator.isIn; _isIn = isInFunc; let _isInt = validator.isInt; _isInt = isIntFunc; let _isJSON = validator.isJSON; _isJSON = isJSONFunc; let _isLatLong = validator.isLatLong; _isLatLong = isLatLongFunc; let _isLength = validator.isLength; _isLength = isLengthFunc; let _isLowercase = validator.isLowercase; _isLowercase = isLowercaseFunc; let _isMACAddress = validator.isMACAddress; _isMACAddress = isMACAddressFunc; let _isMD5 = validator.isMD5; _isMD5 = isMD5Func; let _isMimeType = validator.isMimeType; _isMimeType = isMimeTypeFunc; let _isMobilePhone = validator.isMobilePhone; _isMobilePhone = isMobilePhoneFunc; let _isMongoId = validator.isMongoId; _isMongoId = isMongoIdFunc; let _isMultibyte = validator.isMultibyte; _isMultibyte = isMultibyteFunc; let _isNumeric = validator.isNumeric; _isNumeric = isNumericFunc; let _isPort = validator.isPort; _isPort = isPortFunc; let _isPostalCode = validator.isPostalCode; _isPostalCode = isPostalCodeFunc; let _isSurrogatePair = validator.isSurrogatePair; _isSurrogatePair = isSurrogatePairFunc; let _isURL = validator.isURL; _isURL = isURLFunc; let _isUUID = validator.isUUID; _isUUID = isUUIDFunc; let _isUppercase = validator.isUppercase; _isUppercase = isUppercaseFunc; let _isVariableWidth = validator.isVariableWidth; _isVariableWidth = isVariableWidthFunc; let _isWhitelisted = validator.isWhitelisted; _isWhitelisted = isWhitelistedFunc; let _ltrim = validator.ltrim; _ltrim = ltrimFunc; let _matches = validator.matches; _matches = matchesFunc; let _normalizeEmail = validator.normalizeEmail; _normalizeEmail = normalizeEmailFunc; let _rtrim = validator.rtrim; _rtrim = rtrimFunc; let _stripLow = validator.stripLow; _stripLow = stripLowFunc; let _toBoolean = validator.toBoolean; _toBoolean = toBooleanFunc; let _toDate = validator.toDate; _toDate = toDateFunc; let _toFloat = validator.toFloat; _toFloat = toFloatFunc; let _toInt = validator.toInt; _toInt = toIntFunc; let _trim = validator.trim; _trim = trimFunc; let _unescape = validator.unescape; _unescape = unescapeFunc; let _whitelist = validator.whitelist; _whitelist = whitelistFunc; } /************************************************ * * * API TESTS * * * ************************************************/ let any: any; // ************** // * Validators * // ************** { let result: boolean; result = validator.contains('sample', 'sample'); result = validator.equals('sample', 'sample'); result = validator.isAfter('sample'); result = validator.isAfter('sample', new Date().toString()); result = validator.isAlpha('sample'); result = validator.isAlpha('sample', 'ar'); result = validator.isAlpha('sample', 'ar-AE'); result = validator.isAlpha('sample', 'ar-BH'); result = validator.isAlpha('sample', 'ar-DZ'); result = validator.isAlpha('sample', 'ar-EG'); result = validator.isAlpha('sample', 'ar-IQ'); result = validator.isAlpha('sample', 'ar-JO'); result = validator.isAlpha('sample', 'ar-KW'); result = validator.isAlpha('sample', 'ar-LB'); result = validator.isAlpha('sample', 'ar-LY'); result = validator.isAlpha('sample', 'ar-MA'); result = validator.isAlpha('sample', 'ar-QA'); result = validator.isAlpha('sample', 'ar-QM'); result = validator.isAlpha('sample', 'ar-SA'); result = validator.isAlpha('sample', 'ar-SD'); result = validator.isAlpha('sample', 'ar-SY'); result = validator.isAlpha('sample', 'ar-TN'); result = validator.isAlpha('sample', 'ar-YE'); result = validator.isAlpha('sample', 'bg-BG'); result = validator.isAlpha('sample', 'cs-CZ'); result = validator.isAlpha('sample', 'da-DK'); result = validator.isAlpha('sample', 'de-DE'); result = validator.isAlpha('sample', 'el-GR'); result = validator.isAlpha('sample', 'en-AU'); result = validator.isAlpha('sample', 'en-GB'); result = validator.isAlpha('sample', 'en-HK'); result = validator.isAlpha('sample', 'en-IN'); result = validator.isAlpha('sample', 'en-NZ'); result = validator.isAlpha('sample', 'en-US'); result = validator.isAlpha('sample', 'en-ZA'); result = validator.isAlpha('sample', 'en-ZM'); result = validator.isAlpha('sample', 'es-ES'); result = validator.isAlpha('sample', 'fr-FR'); result = validator.isAlpha('sample', 'hu-HU'); result = validator.isAlpha('sample', 'it-IT'); result = validator.isAlpha('sample', 'nb-NO'); result = validator.isAlpha('sample', 'nl-NL'); result = validator.isAlpha('sample', 'nn-NO'); result = validator.isAlpha('sample', 'pl-PL'); result = validator.isAlpha('sample', 'pt-BR'); result = validator.isAlpha('sample', 'pt-PT'); result = validator.isAlpha('sample', 'ru-RU'); result = validator.isAlpha('sample', 'sk-SK'); result = validator.isAlpha('sample', 'sr-RS'); result = validator.isAlpha('sample', 'sr-RS@latin'); result = validator.isAlpha('sample', 'sv-SE'); result = validator.isAlpha('sample', 'tr-TR'); result = validator.isAlpha('sample', 'uk-UA'); result = validator.isAlphanumeric('sample'); result = validator.isAlphanumeric('sample', 'ar'); result = validator.isAlphanumeric('sample', 'ar-AE'); result = validator.isAlphanumeric('sample', 'ar-BH'); result = validator.isAlphanumeric('sample', 'ar-DZ'); result = validator.isAlphanumeric('sample', 'ar-EG'); result = validator.isAlphanumeric('sample', 'ar-IQ'); result = validator.isAlphanumeric('sample', 'ar-JO'); result = validator.isAlphanumeric('sample', 'ar-KW'); result = validator.isAlphanumeric('sample', 'ar-LB'); result = validator.isAlphanumeric('sample', 'ar-LY'); result = validator.isAlphanumeric('sample', 'ar-MA'); result = validator.isAlphanumeric('sample', 'ar-QA'); result = validator.isAlphanumeric('sample', 'ar-QM'); result = validator.isAlphanumeric('sample', 'ar-SA'); result = validator.isAlphanumeric('sample', 'ar-SD'); result = validator.isAlphanumeric('sample', 'ar-SY'); result = validator.isAlphanumeric('sample', 'ar-TN'); result = validator.isAlphanumeric('sample', 'ar-YE'); result = validator.isAlphanumeric('sample', 'bg-BG'); result = validator.isAlphanumeric('sample', 'cs-CZ'); result = validator.isAlphanumeric('sample', 'da-DK'); result = validator.isAlphanumeric('sample', 'de-DE'); result = validator.isAlphanumeric('sample', 'el-GR'); result = validator.isAlphanumeric('sample', 'en-AU'); result = validator.isAlphanumeric('sample', 'en-GB'); result = validator.isAlphanumeric('sample', 'en-HK'); result = validator.isAlphanumeric('sample', 'en-IN'); result = validator.isAlphanumeric('sample', 'en-NZ'); result = validator.isAlphanumeric('sample', 'en-US'); result = validator.isAlphanumeric('sample', 'en-ZA'); result = validator.isAlphanumeric('sample', 'en-ZM'); result = validator.isAlphanumeric('sample', 'es-ES'); result = validator.isAlphanumeric('sample', 'fr-FR'); result = validator.isAlphanumeric('sample', 'hu-HU'); result = validator.isAlphanumeric('sample', 'it-IT'); result = validator.isAlphanumeric('sample', 'nb-NO'); result = validator.isAlphanumeric('sample', 'nl-NL'); result = validator.isAlphanumeric('sample', 'nn-NO'); result = validator.isAlphanumeric('sample', 'pl-PL'); result = validator.isAlphanumeric('sample', 'pt-BR'); result = validator.isAlphanumeric('sample', 'pt-PT'); result = validator.isAlphanumeric('sample', 'ru-RU'); result = validator.isAlphanumeric('sample', 'sk-SK'); result = validator.isAlphanumeric('sample', 'sr-RS'); result = validator.isAlphanumeric('sample', 'sr-RS@latin'); result = validator.isAlphanumeric('sample', 'sv-SE'); result = validator.isAlphanumeric('sample', 'tr-TR'); result = validator.isAlphanumeric('sample', 'uk-UA'); result = validator.isAscii('sample'); result = validator.isBase64('sample'); result = validator.isBefore('sample'); result = validator.isBefore('sample', new Date().toString()); result = validator.isBoolean('sample'); let isByteLengthOptions: ValidatorJS.IsByteLengthOptions = {}; result = validator.isByteLength('sample', isByteLengthOptions); result = validator.isByteLength('sample', 0); result = validator.isByteLength('sample', 0, 42); result = validator.isCreditCard('sample'); let isCurrencyOptions: ValidatorJS.IsCurrencyOptions = {}; result = validator.isCurrency('sample'); result = validator.isCurrency('sample', isCurrencyOptions); result = validator.isDataURI('sample'); let isDecimalOptions: ValidatorJS.IsDecimalOptions = {}; result = validator.isDecimal('sample'); result = validator.isDecimal('sample', isDecimalOptions); result = validator.isDivisibleBy('sample', 2); let isEmailOptions: ValidatorJS.IsEmailOptions = {}; result = validator.isEmail('sample'); result = validator.isEmail('sample', isEmailOptions); result = validator.isEmpty('sample'); let isFQDNOptions: ValidatorJS.IsFQDNOptions = {}; result = validator.isFQDN('sample'); result = validator.isFQDN('sample', isFQDNOptions); let isFloatOptions: ValidatorJS.IsFloatOptions = {}; result = validator.isFloat('sample'); result = validator.isFloat('sample', isFloatOptions); result = validator.isFullWidth('sample'); result = validator.isHalfWidth('sample'); result = validator.isHash('sample', 'md4'); result = validator.isHash('sample', 'md5'); result = validator.isHash('sample', 'sha1'); result = validator.isHash('sample', 'sha256'); result = validator.isHash('sample', 'sha384'); result = validator.isHash('sample', 'sha512'); result = validator.isHash('sample', 'ripemd128'); result = validator.isHash('sample', 'ripemd160'); result = validator.isHash('sample', 'tiger128'); result = validator.isHash('sample', 'tiger160'); result = validator.isHash('sample', 'tiger192'); result = validator.isHash('sample', 'crc32'); result = validator.isHash('sample', 'crc32b'); result = validator.isHexColor('sample'); result = validator.isHexadecimal('sample'); result = validator.isIP('sample'); result = validator.isIP('sample', 6); result = validator.isISBN('sample'); result = validator.isISBN('sample', 13); let isISSNOptions: ValidatorJS.IsISSNOptions = {}; result = validator.isISSN('sample'); result = validator.isISSN('sample', isISSNOptions); result = validator.isISIN('sample'); result = validator.isISO8601('sample'); result = validator.isISO31661Alpha2('sample'); result = validator.isISRC('sample'); result = validator.isIn('sample', []); let isIntOptions: ValidatorJS.IsIntOptions = {}; result = validator.isInt('sample'); result = validator.isInt('sample', isIntOptions); result = validator.isJSON('sample'); result = validator.isLatLong('sample'); let isLengthOptions: ValidatorJS.IsLengthOptions = {}; result = validator.isLength('sample', isLengthOptions); result = validator.isLength('sample', 3); result = validator.isLength('sample', 3, 5); result = validator.isLowercase('sample'); result = validator.isMACAddress('sample'); result = validator.isMD5('sample'); result = validator.isMimeType('sample'); let isMobilePhoneOptions: ValidatorJS.IsMobilePhoneOptions = {}; result = validator.isMobilePhone('sample', 'any', isMobilePhoneOptions); result = validator.isMobilePhone('sample', 'ar-AE'); result = validator.isMobilePhone('sample', 'ar-DZ'); result = validator.isMobilePhone('sample', 'ar-EG'); result = validator.isMobilePhone('sample', 'ar-JO'); result = validator.isMobilePhone('sample', 'ar-SA'); result = validator.isMobilePhone('sample', 'ar-SY'); result = validator.isMobilePhone('sample', 'be-BY'); result = validator.isMobilePhone('sample', 'bg-BG'); result = validator.isMobilePhone('sample', 'cs-CZ'); result = validator.isMobilePhone('sample', 'de-DE'); result = validator.isMobilePhone('sample', 'da-DK'); result = validator.isMobilePhone('sample', 'el-GR'); result = validator.isMobilePhone('sample', 'en-AU'); result = validator.isMobilePhone('sample', 'en-GB'); result = validator.isMobilePhone('sample', 'en-HK'); result = validator.isMobilePhone('sample', 'en-IN'); result = validator.isMobilePhone('sample', 'en-KE'); result = validator.isMobilePhone('sample', 'en-NG'); result = validator.isMobilePhone('sample', 'en-NZ'); result = validator.isMobilePhone('sample', 'en-UG'); result = validator.isMobilePhone('sample', 'en-RW'); result = validator.isMobilePhone('sample', 'en-SG'); result = validator.isMobilePhone('sample', 'en-TZ'); result = validator.isMobilePhone('sample', 'en-PK'); result = validator.isMobilePhone('sample', 'en-US'); result = validator.isMobilePhone('sample', 'en-CA'); result = validator.isMobilePhone('sample', 'en-ZA'); result = validator.isMobilePhone('sample', 'en-ZM'); result = validator.isMobilePhone('sample', 'es-ES'); result = validator.isMobilePhone('sample', 'fa-IR'); result = validator.isMobilePhone('sample', 'fi-FI'); result = validator.isMobilePhone('sample', 'fo-FO'); result = validator.isMobilePhone('sample', 'fr-FR'); result = validator.isMobilePhone('sample', 'he-IL'); result = validator.isMobilePhone('sample', 'hu-HU'); result = validator.isMobilePhone('sample', 'id-ID'); result = validator.isMobilePhone('sample', 'it-IT'); result = validator.isMobilePhone('sample', 'ja-JP'); result = validator.isMobilePhone('sample', 'kk-KZ'); result = validator.isMobilePhone('sample', 'kl-GL'); result = validator.isMobilePhone('sample', 'ko-KR'); result = validator.isMobilePhone('sample', 'lt-LT'); result = validator.isMobilePhone('sample', 'ms-MY'); result = validator.isMobilePhone('sample', 'nb-NO'); result = validator.isMobilePhone('sample', 'nn-NO'); result = validator.isMobilePhone('sample', 'pl-PL'); result = validator.isMobilePhone('sample', 'pt-PT'); result = validator.isMobilePhone('sample', 'ro-RO'); result = validator.isMobilePhone('sample', 'ru-RU'); result = validator.isMobilePhone('sample', 'sr-RS'); result = validator.isMobilePhone('sample', 'sk-SK'); result = validator.isMobilePhone('sample', 'th-TH'); result = validator.isMobilePhone('sample', 'tr-TR'); result = validator.isMobilePhone('sample', 'uk-UA'); result = validator.isMobilePhone('sample', 'vi-VN'); result = validator.isMobilePhone('sample', 'zh-CN'); result = validator.isMobilePhone('sample', 'zh-HK'); result = validator.isMobilePhone('sample', 'zh-TW'); result = validator.isMobilePhone('sample', 'any'); result = validator.isMongoId('sample'); result = validator.isMultibyte('sample'); result = validator.isNumeric('sample'); result = validator.isNumeric('+358', { no_symbols: true }); result = validator.isPort('sample'); result = validator.isPostalCode('sample', 'AT'); result = validator.isPostalCode('sample', 'AU'); result = validator.isPostalCode('sample', 'BE'); result = validator.isPostalCode('sample', 'BG'); result = validator.isPostalCode('sample', 'CA'); result = validator.isPostalCode('sample', 'CH'); result = validator.isPostalCode('sample', 'CZ'); result = validator.isPostalCode('sample', 'DE'); result = validator.isPostalCode('sample', 'DK'); result = validator.isPostalCode('sample', 'DZ'); result = validator.isPostalCode('sample', 'ES'); result = validator.isPostalCode('sample', 'FI'); result = validator.isPostalCode('sample', 'FR'); result = validator.isPostalCode('sample', 'GB'); result = validator.isPostalCode('sample', 'GR'); result = validator.isPostalCode('sample', 'IL'); result = validator.isPostalCode('sample', 'IN'); result = validator.isPostalCode('sample', 'IS'); result = validator.isPostalCode('sample', 'IT'); result = validator.isPostalCode('sample', 'JP'); result = validator.isPostalCode('sample', 'KE'); result = validator.isPostalCode('sample', 'LI'); result = validator.isPostalCode('sample', 'MX'); result = validator.isPostalCode('sample', 'NL'); result = validator.isPostalCode('sample', 'NO'); result = validator.isPostalCode('sample', 'PL'); result = validator.isPostalCode('sample', 'PT'); result = validator.isPostalCode('sample', 'RO'); result = validator.isPostalCode('sample', 'RU'); result = validator.isPostalCode('sample', 'SA'); result = validator.isPostalCode('sample', 'SE'); result = validator.isPostalCode('sample', 'TW'); result = validator.isPostalCode('sample', 'US'); result = validator.isPostalCode('sample', 'ZA'); result = validator.isPostalCode('sample', 'ZM'); result = validator.isPostalCode('sample', 'any'); result = validator.isSurrogatePair('sample'); let isURLOptions: ValidatorJS.IsURLOptions = {}; result = validator.isURL('sample'); result = validator.isURL('sample', isURLOptions); result = validator.isUUID('sample'); result = validator.isUUID('sample', 5); result = validator.isUUID('sample', 'all'); result = validator.isUppercase('sample'); result = validator.isVariableWidth('sample'); result = validator.isWhitelisted('sample', 'abc'); result = validator.isWhitelisted('sample', ['a', 'b', 'c']); result = validator.matches('foobar', 'foo/i'); result = validator.matches('foobar', 'foo', 'i'); } // ************** // * Sanitizers * // ************** { let result: string; result = validator.blacklist('sample', 'abc'); result = validator.escape('sample'); result = validator.unescape('sample'); result = validator.ltrim('sample'); result = validator.ltrim('sample', ' '); let normalizeEmailOptions: ValidatorJS.NormalizeEmailOptions = {}; let normalizeResult: string | false; normalizeResult = validator.normalizeEmail('sample'); normalizeResult = validator.normalizeEmail('sample', normalizeEmailOptions); result = validator.rtrim('sample'); result = validator.rtrim('sample', ' '); result = validator.stripLow('sample'); result = validator.stripLow('sample', true); } { let result: boolean; result = validator.toBoolean(any); result = validator.toBoolean(any, true); } { let result: Date; result = validator.toDate(any); } { let result: number; result = validator.toFloat(any); result = validator.toInt(any); result = validator.toInt(any, 10); } { let result: string; result = validator.trim('sample'); result = validator.trim('sample', ' '); result = validator.whitelist('sample', 'abc'); } { let str: string; str = validator.toString([123, 456, '123', '456', true, false]); } { let ver: string; ver = validator.version; } // ************** // * Extensions * // ************** validator.extend<(str: string, options: {}) => boolean>('isTest', (str: any, options: {}) => !str);
types/validator/validator-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/280c65abb520b173bc39109e01b3c15242e66195
[ 0.9992629885673523, 0.05630003288388252, 0.00016517755284439772, 0.00017282382759731263, 0.22860336303710938 ]
{ "id": 0, "code_window": [ " isISIN(str: string): boolean;\n", "\n", " // check if the string is a valid ISO 8601 (https://en.wikipedia.org/wiki/ISO_8601) date.\n", " isISO8601(str: string): boolean;\n", "\n", " // check if the string is a valid ISO 3166-1 alpha-2 (https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) officially assigned\n", " // country code.\n", " isISO31661Alpha2(str: string): boolean;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " isISO8601(str: string, options?: IsISO8601Options): boolean;\n" ], "file_path": "types/validator/index.d.ts", "type": "replace", "edit_start_line_idx": 124 }
import promptSync = require('prompt-sync'); declare const history: promptSync.History; let prompt: promptSync.Prompt; // without config prompt = promptSync(); // with config prompt = promptSync({ history: history, sigint: false, autocomplete: (input:string) => [input] }); // with empty config prompt = promptSync({}); let name:string = prompt('Enter name: '); let nickname:string = prompt({ask: 'Enter nickname: ', value: 'N/A'}); let gender:string = prompt('Enter gender: ', { autocomplete: complete(['male', 'female']) }); let age:string = prompt('Enter age: ', '18', { echo: '*' }); let password:string = prompt.hide('Enter password: '); let anotherPassword:string = prompt('Enter another password: ', { echo: '', value: '*password*'}); function complete(commands: string[]) { return function (str: string) { const ret:string[] = []; for (let i=0; i< commands.length; i++) { if (commands[i].indexOf(str) == 0) ret.push(commands[i]); } return ret; }; } // History interface let bool: boolean; bool = history.atStart(); bool = history.atPenultimate(); bool = history.pastEnd(); bool = history.atEnd(); let str: string; str = history.prev(); str = history.next(); history.reset(); history.push('aaa'); history.save();
types/prompt-sync/prompt-sync-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/280c65abb520b173bc39109e01b3c15242e66195
[ 0.0021773111075162888, 0.0007146177813410759, 0.00016608739679213613, 0.00018548562366049737, 0.0007933190790936351 ]
{ "id": 0, "code_window": [ " isISIN(str: string): boolean;\n", "\n", " // check if the string is a valid ISO 8601 (https://en.wikipedia.org/wiki/ISO_8601) date.\n", " isISO8601(str: string): boolean;\n", "\n", " // check if the string is a valid ISO 3166-1 alpha-2 (https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) officially assigned\n", " // country code.\n", " isISO31661Alpha2(str: string): boolean;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " isISO8601(str: string, options?: IsISO8601Options): boolean;\n" ], "file_path": "types/validator/index.d.ts", "type": "replace", "edit_start_line_idx": 124 }
{ "extends": "dtslint/dt.json" }
types/lodash.findkey/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/280c65abb520b173bc39109e01b3c15242e66195
[ 0.00017195822147186846, 0.00017195822147186846, 0.00017195822147186846, 0.00017195822147186846, 0 ]
{ "id": 0, "code_window": [ " isISIN(str: string): boolean;\n", "\n", " // check if the string is a valid ISO 8601 (https://en.wikipedia.org/wiki/ISO_8601) date.\n", " isISO8601(str: string): boolean;\n", "\n", " // check if the string is a valid ISO 3166-1 alpha-2 (https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) officially assigned\n", " // country code.\n", " isISO31661Alpha2(str: string): boolean;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " isISO8601(str: string, options?: IsISO8601Options): boolean;\n" ], "file_path": "types/validator/index.d.ts", "type": "replace", "edit_start_line_idx": 124 }
import { Color } from "chroma-js"; import chroma = require("chroma-js"); function test_chroma() { chroma('hotpink'); chroma('#ff3399'); chroma('F39'); chroma.hex("#fff"); chroma(0xff3399); chroma(0xff, 0x33, 0x99); chroma(255, 51, 153); chroma([255, 51, 153]); chroma(330, 1, 0.6, 'hsl'); chroma.hsl(330, 1, 0.6); chroma.lch(80, 40, 130); chroma(80, 40, 130, 'lch'); chroma.cmyk(0.2, 0.8, 0, 0); chroma(0.2, 0.8, 0, 0, 'cmyk'); chroma.gl(0.6, 0, 0.8); chroma.gl(0.6, 0, 0.8, 0.5); chroma(0.6, 0, 0.8, 'gl'); chroma.temperature(2000); chroma.temperature(3500); chroma.temperature(6000); chroma.mix('red', 'blue'); chroma.mix('red', 'blue', 0.25); chroma.mix('red', 'blue', 0.5, 'rgb'); chroma.mix('red', 'blue', 0.5, 'hsl'); chroma.mix('red', 'blue', 0.5, 'lab'); chroma.mix('red', 'blue', 0.5, 'lch'); chroma.blend('4CBBFC', 'EEEE22', 'multiply'); chroma.blend('4CBBFC', 'EEEE22', 'darken'); chroma.blend('4CBBFC', 'EEEE22', 'lighten'); chroma.random(); chroma.contrast('pink', 'hotpink'); chroma.contrast('pink', 'purple'); chroma.brewer.OrRd; const data = [3.0, 3.5, 3.6, 3.8, 3.8, 4.1, 4.3, 4.4, 4.6, 4.9, 5.2, 5.3, 5.4, 5.7, 5.8, 5.9, 6.2, 6.5, 6.8, 7.2, 9]; chroma.limits(data, 'e', 5); chroma.limits(data, 'q', 5); chroma.limits(data, 'k', 5); chroma(0xff3399); chroma.limits(data, 'k', 5); } function test_color() { chroma('red').alpha(0.5); chroma('rgba(255,0,0,0.35)').alpha(); chroma('hotpink').darken(); chroma('hotpink').darken(2); chroma('hotpink').brighten(); chroma('slategray').saturate(); chroma('slategray').saturate(2); chroma('hotpink').desaturate(); chroma('hotpink').desaturate(2); chroma('hotpink').desaturate(3); // change hue to 0 deg (=red) chroma('skyblue').set('hsl.h', 0); // set chromacity to 30 chroma('hotpink').set('lch.c', 30); // half Lab lightness chroma('orangered').set('lab.l', '*0.5'); // double Lch saturation chroma('darkseagreen').set('lch.c', '*2'); chroma('orangered').get('lab.l'); chroma('orangered').get('hsl.l'); chroma('orangered').get('rgb.g'); chroma('white').luminance(); chroma('aquamarine').luminance(); chroma('hotpink').luminance(); chroma('darkslateblue').luminance(); chroma('black').luminance(); chroma('white').luminance(0.5); chroma('aquamarine').luminance(0.5); chroma('hotpink').luminance(0.5); chroma('darkslateblue').luminance(0.5); chroma('aquamarine').luminance(0.5); chroma('aquamarine').luminance(0.5, 'lab'); chroma('aquamarine').luminance(0.5, 'hsl'); chroma('orange').hex(); chroma('orange').hex('auto'); chroma('orange').hex('rgb'); chroma('orange').alpha(0.5).hex('rgba'); chroma('#ffa500').name(); chroma('#ffa505').name(); chroma('teal').css(); chroma('teal').alpha(0.5).css(); chroma('teal').css('hsl'); chroma('orange').rgb(); chroma('orange').hsl(); chroma('white').hsl(); chroma('orange').hsv(); chroma('white').hsv(); chroma('orange').hsi(); chroma('white').hsi(); chroma('orange').lab(); chroma('skyblue').lch(); chroma('skyblue').hcl(); chroma('#ff3300').temperature(); chroma('#ff8a13').temperature(); chroma('#ffe3cd').temperature(); chroma('#cbdbff').temperature(); chroma('#b3ccff').temperature(); chroma('33cc00').gl(); chroma('teal').alpha(0.5).css(); chroma('teal').css('hsl'); chroma('orange').rgb(); chroma('#000000').num(); chroma('#0000ff').num(); chroma('#00ff00').num(); chroma('#ff0000').num(); } function test_scale() { const f = chroma.scale(); f(0.25); f(0.5); f(0.75); chroma.scale(['yellow', '008ae5']); chroma.scale(['yellow', 'red', 'black']); // default domain is [0,1] chroma.scale(['yellow', '008ae5']); // set domain to [0,100] chroma.scale(['yellow', '008ae5']).domain([0, 100]); // default domain is [0,1] chroma.scale(['yellow', 'lightgreen', '008ae5']) .domain([0, 0.25, 1]); chroma.scale(['yellow', '008ae5']); chroma.scale(['yellow', 'navy']); chroma.scale(['yellow', 'navy']).mode('lab'); chroma.scale(['yellow', 'navy']).mode('lab'); chroma.scale(['yellow', 'navy']).mode('hsl'); chroma.scale(['yellow', 'navy']).mode('lch'); chroma.scale('YlGnBu'); chroma.scale('Spectral'); chroma.scale('Spectral').domain([1, 0]); chroma.brewer.OrRd; chroma.scale(['yellow', '008ae5']).mode('lch'); chroma.scale(['yellow', '008ae5']) .mode('lch') .correctLightness(); // linear interpolation chroma.scale(['yellow', 'red', 'black']); // bezier interpolation chroma.bezier(['yellow', 'red', 'black']); // convert bezier interpolator into chroma.scale chroma.bezier(['yellow', 'red', 'black']) .scale().colors(5); // use the default helix... chroma.cubehelix(); // or customize it chroma.cubehelix() .start(200) .rotations(-0.5) .gamma(0.8) .lightness([0.3, 0.8]); chroma.cubehelix() .start(200) .rotations(-0.35) .gamma(0.7) .lightness([0.3, 0.8]) .scale() // convert to chroma.scale .correctLightness() .colors(5); chroma.scale('RdYlBu'); chroma.scale('RdYlBu').padding(0.15); chroma.scale('OrRd'); chroma.scale('OrRd').padding([0.2, 0]); chroma.scale('OrRd').classes(5); chroma.scale('OrRd').classes(8); chroma.cubehelix() .start(200) .rotations(-0.35) .gamma(0.7) .lightness([0.3, 0.8]) .scale() // convert to chroma.scale .correctLightness() .colors(5); chroma.scale('RdYlBu'); chroma.scale('RdYlBu').padding(0.15); } function test_types() { const color: chroma.Color = chroma('orange'); const scale: chroma.Scale = chroma.scale('RdYlBu'); } // the following should actually, pass, but TS can't disambiguate between a parameter // which is passed as undefined/null or not passed at all // const scaleColors1: Color[] = chroma.scale(['black', 'white']).colors(12); const scaleColors2: Color[] = chroma.scale(['black', 'white']).colors(12, null); const scaleColors3: Color[] = chroma.scale(['black', 'white']).colors(12, undefined);
types/chroma-js/chroma-js-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/280c65abb520b173bc39109e01b3c15242e66195
[ 0.00017807779659051448, 0.00017404404934495687, 0.00016968119598459452, 0.00017417955677956343, 0.0000017561656022735406 ]
{ "id": 1, "code_window": [ " gt?: number;\n", " }\n", "\n", " // options for IsLength\n", " interface IsLengthOptions {\n", " min?: number;\n", " max?: number;\n", " }\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // options for isISO8601\n", " interface IsISO8601Options {\n", " strict?: boolean;\n", " }\n", "\n" ], "file_path": "types/validator/index.d.ts", "type": "add", "edit_start_line_idx": 343 }
import * as validator from 'validator'; /************************************************ * * * IMPORT TESTS * * * ************************************************/ import blacklistFunc = require('validator/lib/blacklist'); import containsFunc = require('validator/lib/contains'); import equalsFunc = require('validator/lib/equals'); import escapeFunc = require('validator/lib/escape'); import isAfterFunc = require('validator/lib/isAfter'); import isAlphaFunc = require('validator/lib/isAlpha'); import isAlphanumericFunc = require('validator/lib/isAlphanumeric'); import isAsciiFunc = require('validator/lib/isAscii'); import isBase64Func = require('validator/lib/isBase64'); import isBeforeFunc = require('validator/lib/isBefore'); import isBooleanFunc = require('validator/lib/isBoolean'); import isByteLengthFunc = require('validator/lib/isByteLength'); import isCreditCardFunc = require('validator/lib/isCreditCard'); import isCurrencyFunc = require('validator/lib/isCurrency'); import isDataURIFunc = require('validator/lib/isDataURI'); import isDecimalFunc = require('validator/lib/isDecimal'); import isDivisibleByFunc = require('validator/lib/isDivisibleBy'); import isEmailFunc = require('validator/lib/isEmail'); import isEmptyFunc = require('validator/lib/isEmpty'); import isFQDNFunc = require('validator/lib/isFQDN'); import isFloatFunc = require('validator/lib/isFloat'); import isFullWidthFunc = require('validator/lib/isFullWidth'); import isHalfWidthFunc = require('validator/lib/isHalfWidth'); import isHashFunc = require('validator/lib/isHash'); import isHexColorFunc = require('validator/lib/isHexColor'); import isHexadecimalFunc = require('validator/lib/isHexadecimal'); import isIPFunc = require('validator/lib/isIP'); import isISBNFunc = require('validator/lib/isISBN'); import isISSNFunc = require('validator/lib/isISSN'); import isISINFunc = require('validator/lib/isISIN'); import isISO8601Func = require('validator/lib/isISO8601'); import isISO31661Alpha2Func = require('validator/lib/isISO31661Alpha2'); import isISRCFunc = require('validator/lib/isISRC'); import isInFunc = require('validator/lib/isIn'); import isIntFunc = require('validator/lib/isInt'); import isJSONFunc = require('validator/lib/isJSON'); import isLatLongFunc = require('validator/lib/isLatLong'); import isLengthFunc = require('validator/lib/isLength'); import isLowercaseFunc = require('validator/lib/isLowercase'); import isMACAddressFunc = require('validator/lib/isMACAddress'); import isMD5Func = require('validator/lib/isMD5'); import isMimeTypeFunc = require('validator/lib/isMimeType'); import isMobilePhoneFunc = require('validator/lib/isMobilePhone'); import isMongoIdFunc = require('validator/lib/isMongoId'); import isMultibyteFunc = require('validator/lib/isMultibyte'); import isNumericFunc = require('validator/lib/isNumeric'); import isPortFunc = require('validator/lib/isPort'); import isPostalCodeFunc = require('validator/lib/isPostalCode'); import isSurrogatePairFunc = require('validator/lib/isSurrogatePair'); import isURLFunc = require('validator/lib/isURL'); import isUUIDFunc = require('validator/lib/isUUID'); import isUppercaseFunc = require('validator/lib/isUppercase'); import isVariableWidthFunc = require('validator/lib/isVariableWidth'); import isWhitelistedFunc = require('validator/lib/isWhitelisted'); import ltrimFunc = require('validator/lib/ltrim'); import matchesFunc = require('validator/lib/matches'); import normalizeEmailFunc = require('validator/lib/normalizeEmail'); import rtrimFunc = require('validator/lib/rtrim'); import stripLowFunc = require('validator/lib/stripLow'); import toBooleanFunc = require('validator/lib/toBoolean'); import toDateFunc = require('validator/lib/toDate'); import toFloatFunc = require('validator/lib/toFloat'); import toIntFunc = require('validator/lib/toInt'); import trimFunc = require('validator/lib/trim'); import unescapeFunc = require('validator/lib/unescape'); import whitelistFunc = require('validator/lib/whitelist'); { let _blacklist = validator.blacklist; _blacklist = blacklistFunc; let _contains = validator.contains; _contains = containsFunc; let _equals = validator.equals; _equals = equalsFunc; let _escape = validator.escape; _escape = escapeFunc; let _isAfter = validator.isAfter; _isAfter = isAfterFunc; let _isAlpha = validator.isAlpha; _isAlpha = isAlphaFunc; let _isAlphanumeric = validator.isAlphanumeric; _isAlphanumeric = isAlphanumericFunc; let _isAscii = validator.isAscii; _isAscii = isAsciiFunc; let _isBase64 = validator.isBase64; _isBase64 = isBase64Func; let _isBefore = validator.isBefore; _isBefore = isBeforeFunc; let _isBoolean = validator.isBoolean; _isBoolean = isBooleanFunc; let _isByteLength = validator.isByteLength; _isByteLength = isByteLengthFunc; let _isCreditCard = validator.isCreditCard; _isCreditCard = isCreditCardFunc; let _isCurrency = validator.isCurrency; _isCurrency = isCurrencyFunc; let _isDataURI = validator.isDataURI; _isDataURI = isDataURIFunc; let _isDecimal = validator.isDecimal; _isDecimal = isDecimalFunc; let _isDivisibleBy = validator.isDivisibleBy; _isDivisibleBy = isDivisibleByFunc; let _isEmail = validator.isEmail; _isEmail = isEmailFunc; let _isEmpty = validator.isEmpty; _isEmpty = isEmptyFunc; let _isFQDN = validator.isFQDN; _isFQDN = isFQDNFunc; let _isFloat = validator.isFloat; _isFloat = isFloatFunc; let _isFullWidth = validator.isFullWidth; _isFullWidth = isFullWidthFunc; let _isHalfWidth = validator.isHalfWidth; _isHalfWidth = isHalfWidthFunc; let _isHash = validator.isHash; _isHash = isHashFunc; let _isHexColor = validator.isHexColor; _isHexColor = isHexColorFunc; let _isHexadecimal = validator.isHexadecimal; _isHexadecimal = isHexadecimalFunc; let _isIP = validator.isIP; _isIP = isIPFunc; let _isISBN = validator.isISBN; _isISBN = isISBNFunc; let _isISSN = validator.isISSN; _isISSN = isISSNFunc; let _isISIN = validator.isISIN; _isISIN = isISINFunc; let _isISO8601 = validator.isISO8601; _isISO8601 = isISO8601Func; let _isISO31661Alpha2 = validator.isISO31661Alpha2; _isISO31661Alpha2 = isISO31661Alpha2Func; let _isISRC = validator.isISRC; _isISRC = isISRCFunc; let _isIn = validator.isIn; _isIn = isInFunc; let _isInt = validator.isInt; _isInt = isIntFunc; let _isJSON = validator.isJSON; _isJSON = isJSONFunc; let _isLatLong = validator.isLatLong; _isLatLong = isLatLongFunc; let _isLength = validator.isLength; _isLength = isLengthFunc; let _isLowercase = validator.isLowercase; _isLowercase = isLowercaseFunc; let _isMACAddress = validator.isMACAddress; _isMACAddress = isMACAddressFunc; let _isMD5 = validator.isMD5; _isMD5 = isMD5Func; let _isMimeType = validator.isMimeType; _isMimeType = isMimeTypeFunc; let _isMobilePhone = validator.isMobilePhone; _isMobilePhone = isMobilePhoneFunc; let _isMongoId = validator.isMongoId; _isMongoId = isMongoIdFunc; let _isMultibyte = validator.isMultibyte; _isMultibyte = isMultibyteFunc; let _isNumeric = validator.isNumeric; _isNumeric = isNumericFunc; let _isPort = validator.isPort; _isPort = isPortFunc; let _isPostalCode = validator.isPostalCode; _isPostalCode = isPostalCodeFunc; let _isSurrogatePair = validator.isSurrogatePair; _isSurrogatePair = isSurrogatePairFunc; let _isURL = validator.isURL; _isURL = isURLFunc; let _isUUID = validator.isUUID; _isUUID = isUUIDFunc; let _isUppercase = validator.isUppercase; _isUppercase = isUppercaseFunc; let _isVariableWidth = validator.isVariableWidth; _isVariableWidth = isVariableWidthFunc; let _isWhitelisted = validator.isWhitelisted; _isWhitelisted = isWhitelistedFunc; let _ltrim = validator.ltrim; _ltrim = ltrimFunc; let _matches = validator.matches; _matches = matchesFunc; let _normalizeEmail = validator.normalizeEmail; _normalizeEmail = normalizeEmailFunc; let _rtrim = validator.rtrim; _rtrim = rtrimFunc; let _stripLow = validator.stripLow; _stripLow = stripLowFunc; let _toBoolean = validator.toBoolean; _toBoolean = toBooleanFunc; let _toDate = validator.toDate; _toDate = toDateFunc; let _toFloat = validator.toFloat; _toFloat = toFloatFunc; let _toInt = validator.toInt; _toInt = toIntFunc; let _trim = validator.trim; _trim = trimFunc; let _unescape = validator.unescape; _unescape = unescapeFunc; let _whitelist = validator.whitelist; _whitelist = whitelistFunc; } /************************************************ * * * API TESTS * * * ************************************************/ let any: any; // ************** // * Validators * // ************** { let result: boolean; result = validator.contains('sample', 'sample'); result = validator.equals('sample', 'sample'); result = validator.isAfter('sample'); result = validator.isAfter('sample', new Date().toString()); result = validator.isAlpha('sample'); result = validator.isAlpha('sample', 'ar'); result = validator.isAlpha('sample', 'ar-AE'); result = validator.isAlpha('sample', 'ar-BH'); result = validator.isAlpha('sample', 'ar-DZ'); result = validator.isAlpha('sample', 'ar-EG'); result = validator.isAlpha('sample', 'ar-IQ'); result = validator.isAlpha('sample', 'ar-JO'); result = validator.isAlpha('sample', 'ar-KW'); result = validator.isAlpha('sample', 'ar-LB'); result = validator.isAlpha('sample', 'ar-LY'); result = validator.isAlpha('sample', 'ar-MA'); result = validator.isAlpha('sample', 'ar-QA'); result = validator.isAlpha('sample', 'ar-QM'); result = validator.isAlpha('sample', 'ar-SA'); result = validator.isAlpha('sample', 'ar-SD'); result = validator.isAlpha('sample', 'ar-SY'); result = validator.isAlpha('sample', 'ar-TN'); result = validator.isAlpha('sample', 'ar-YE'); result = validator.isAlpha('sample', 'bg-BG'); result = validator.isAlpha('sample', 'cs-CZ'); result = validator.isAlpha('sample', 'da-DK'); result = validator.isAlpha('sample', 'de-DE'); result = validator.isAlpha('sample', 'el-GR'); result = validator.isAlpha('sample', 'en-AU'); result = validator.isAlpha('sample', 'en-GB'); result = validator.isAlpha('sample', 'en-HK'); result = validator.isAlpha('sample', 'en-IN'); result = validator.isAlpha('sample', 'en-NZ'); result = validator.isAlpha('sample', 'en-US'); result = validator.isAlpha('sample', 'en-ZA'); result = validator.isAlpha('sample', 'en-ZM'); result = validator.isAlpha('sample', 'es-ES'); result = validator.isAlpha('sample', 'fr-FR'); result = validator.isAlpha('sample', 'hu-HU'); result = validator.isAlpha('sample', 'it-IT'); result = validator.isAlpha('sample', 'nb-NO'); result = validator.isAlpha('sample', 'nl-NL'); result = validator.isAlpha('sample', 'nn-NO'); result = validator.isAlpha('sample', 'pl-PL'); result = validator.isAlpha('sample', 'pt-BR'); result = validator.isAlpha('sample', 'pt-PT'); result = validator.isAlpha('sample', 'ru-RU'); result = validator.isAlpha('sample', 'sk-SK'); result = validator.isAlpha('sample', 'sr-RS'); result = validator.isAlpha('sample', 'sr-RS@latin'); result = validator.isAlpha('sample', 'sv-SE'); result = validator.isAlpha('sample', 'tr-TR'); result = validator.isAlpha('sample', 'uk-UA'); result = validator.isAlphanumeric('sample'); result = validator.isAlphanumeric('sample', 'ar'); result = validator.isAlphanumeric('sample', 'ar-AE'); result = validator.isAlphanumeric('sample', 'ar-BH'); result = validator.isAlphanumeric('sample', 'ar-DZ'); result = validator.isAlphanumeric('sample', 'ar-EG'); result = validator.isAlphanumeric('sample', 'ar-IQ'); result = validator.isAlphanumeric('sample', 'ar-JO'); result = validator.isAlphanumeric('sample', 'ar-KW'); result = validator.isAlphanumeric('sample', 'ar-LB'); result = validator.isAlphanumeric('sample', 'ar-LY'); result = validator.isAlphanumeric('sample', 'ar-MA'); result = validator.isAlphanumeric('sample', 'ar-QA'); result = validator.isAlphanumeric('sample', 'ar-QM'); result = validator.isAlphanumeric('sample', 'ar-SA'); result = validator.isAlphanumeric('sample', 'ar-SD'); result = validator.isAlphanumeric('sample', 'ar-SY'); result = validator.isAlphanumeric('sample', 'ar-TN'); result = validator.isAlphanumeric('sample', 'ar-YE'); result = validator.isAlphanumeric('sample', 'bg-BG'); result = validator.isAlphanumeric('sample', 'cs-CZ'); result = validator.isAlphanumeric('sample', 'da-DK'); result = validator.isAlphanumeric('sample', 'de-DE'); result = validator.isAlphanumeric('sample', 'el-GR'); result = validator.isAlphanumeric('sample', 'en-AU'); result = validator.isAlphanumeric('sample', 'en-GB'); result = validator.isAlphanumeric('sample', 'en-HK'); result = validator.isAlphanumeric('sample', 'en-IN'); result = validator.isAlphanumeric('sample', 'en-NZ'); result = validator.isAlphanumeric('sample', 'en-US'); result = validator.isAlphanumeric('sample', 'en-ZA'); result = validator.isAlphanumeric('sample', 'en-ZM'); result = validator.isAlphanumeric('sample', 'es-ES'); result = validator.isAlphanumeric('sample', 'fr-FR'); result = validator.isAlphanumeric('sample', 'hu-HU'); result = validator.isAlphanumeric('sample', 'it-IT'); result = validator.isAlphanumeric('sample', 'nb-NO'); result = validator.isAlphanumeric('sample', 'nl-NL'); result = validator.isAlphanumeric('sample', 'nn-NO'); result = validator.isAlphanumeric('sample', 'pl-PL'); result = validator.isAlphanumeric('sample', 'pt-BR'); result = validator.isAlphanumeric('sample', 'pt-PT'); result = validator.isAlphanumeric('sample', 'ru-RU'); result = validator.isAlphanumeric('sample', 'sk-SK'); result = validator.isAlphanumeric('sample', 'sr-RS'); result = validator.isAlphanumeric('sample', 'sr-RS@latin'); result = validator.isAlphanumeric('sample', 'sv-SE'); result = validator.isAlphanumeric('sample', 'tr-TR'); result = validator.isAlphanumeric('sample', 'uk-UA'); result = validator.isAscii('sample'); result = validator.isBase64('sample'); result = validator.isBefore('sample'); result = validator.isBefore('sample', new Date().toString()); result = validator.isBoolean('sample'); let isByteLengthOptions: ValidatorJS.IsByteLengthOptions = {}; result = validator.isByteLength('sample', isByteLengthOptions); result = validator.isByteLength('sample', 0); result = validator.isByteLength('sample', 0, 42); result = validator.isCreditCard('sample'); let isCurrencyOptions: ValidatorJS.IsCurrencyOptions = {}; result = validator.isCurrency('sample'); result = validator.isCurrency('sample', isCurrencyOptions); result = validator.isDataURI('sample'); let isDecimalOptions: ValidatorJS.IsDecimalOptions = {}; result = validator.isDecimal('sample'); result = validator.isDecimal('sample', isDecimalOptions); result = validator.isDivisibleBy('sample', 2); let isEmailOptions: ValidatorJS.IsEmailOptions = {}; result = validator.isEmail('sample'); result = validator.isEmail('sample', isEmailOptions); result = validator.isEmpty('sample'); let isFQDNOptions: ValidatorJS.IsFQDNOptions = {}; result = validator.isFQDN('sample'); result = validator.isFQDN('sample', isFQDNOptions); let isFloatOptions: ValidatorJS.IsFloatOptions = {}; result = validator.isFloat('sample'); result = validator.isFloat('sample', isFloatOptions); result = validator.isFullWidth('sample'); result = validator.isHalfWidth('sample'); result = validator.isHash('sample', 'md4'); result = validator.isHash('sample', 'md5'); result = validator.isHash('sample', 'sha1'); result = validator.isHash('sample', 'sha256'); result = validator.isHash('sample', 'sha384'); result = validator.isHash('sample', 'sha512'); result = validator.isHash('sample', 'ripemd128'); result = validator.isHash('sample', 'ripemd160'); result = validator.isHash('sample', 'tiger128'); result = validator.isHash('sample', 'tiger160'); result = validator.isHash('sample', 'tiger192'); result = validator.isHash('sample', 'crc32'); result = validator.isHash('sample', 'crc32b'); result = validator.isHexColor('sample'); result = validator.isHexadecimal('sample'); result = validator.isIP('sample'); result = validator.isIP('sample', 6); result = validator.isISBN('sample'); result = validator.isISBN('sample', 13); let isISSNOptions: ValidatorJS.IsISSNOptions = {}; result = validator.isISSN('sample'); result = validator.isISSN('sample', isISSNOptions); result = validator.isISIN('sample'); result = validator.isISO8601('sample'); result = validator.isISO31661Alpha2('sample'); result = validator.isISRC('sample'); result = validator.isIn('sample', []); let isIntOptions: ValidatorJS.IsIntOptions = {}; result = validator.isInt('sample'); result = validator.isInt('sample', isIntOptions); result = validator.isJSON('sample'); result = validator.isLatLong('sample'); let isLengthOptions: ValidatorJS.IsLengthOptions = {}; result = validator.isLength('sample', isLengthOptions); result = validator.isLength('sample', 3); result = validator.isLength('sample', 3, 5); result = validator.isLowercase('sample'); result = validator.isMACAddress('sample'); result = validator.isMD5('sample'); result = validator.isMimeType('sample'); let isMobilePhoneOptions: ValidatorJS.IsMobilePhoneOptions = {}; result = validator.isMobilePhone('sample', 'any', isMobilePhoneOptions); result = validator.isMobilePhone('sample', 'ar-AE'); result = validator.isMobilePhone('sample', 'ar-DZ'); result = validator.isMobilePhone('sample', 'ar-EG'); result = validator.isMobilePhone('sample', 'ar-JO'); result = validator.isMobilePhone('sample', 'ar-SA'); result = validator.isMobilePhone('sample', 'ar-SY'); result = validator.isMobilePhone('sample', 'be-BY'); result = validator.isMobilePhone('sample', 'bg-BG'); result = validator.isMobilePhone('sample', 'cs-CZ'); result = validator.isMobilePhone('sample', 'de-DE'); result = validator.isMobilePhone('sample', 'da-DK'); result = validator.isMobilePhone('sample', 'el-GR'); result = validator.isMobilePhone('sample', 'en-AU'); result = validator.isMobilePhone('sample', 'en-GB'); result = validator.isMobilePhone('sample', 'en-HK'); result = validator.isMobilePhone('sample', 'en-IN'); result = validator.isMobilePhone('sample', 'en-KE'); result = validator.isMobilePhone('sample', 'en-NG'); result = validator.isMobilePhone('sample', 'en-NZ'); result = validator.isMobilePhone('sample', 'en-UG'); result = validator.isMobilePhone('sample', 'en-RW'); result = validator.isMobilePhone('sample', 'en-SG'); result = validator.isMobilePhone('sample', 'en-TZ'); result = validator.isMobilePhone('sample', 'en-PK'); result = validator.isMobilePhone('sample', 'en-US'); result = validator.isMobilePhone('sample', 'en-CA'); result = validator.isMobilePhone('sample', 'en-ZA'); result = validator.isMobilePhone('sample', 'en-ZM'); result = validator.isMobilePhone('sample', 'es-ES'); result = validator.isMobilePhone('sample', 'fa-IR'); result = validator.isMobilePhone('sample', 'fi-FI'); result = validator.isMobilePhone('sample', 'fo-FO'); result = validator.isMobilePhone('sample', 'fr-FR'); result = validator.isMobilePhone('sample', 'he-IL'); result = validator.isMobilePhone('sample', 'hu-HU'); result = validator.isMobilePhone('sample', 'id-ID'); result = validator.isMobilePhone('sample', 'it-IT'); result = validator.isMobilePhone('sample', 'ja-JP'); result = validator.isMobilePhone('sample', 'kk-KZ'); result = validator.isMobilePhone('sample', 'kl-GL'); result = validator.isMobilePhone('sample', 'ko-KR'); result = validator.isMobilePhone('sample', 'lt-LT'); result = validator.isMobilePhone('sample', 'ms-MY'); result = validator.isMobilePhone('sample', 'nb-NO'); result = validator.isMobilePhone('sample', 'nn-NO'); result = validator.isMobilePhone('sample', 'pl-PL'); result = validator.isMobilePhone('sample', 'pt-PT'); result = validator.isMobilePhone('sample', 'ro-RO'); result = validator.isMobilePhone('sample', 'ru-RU'); result = validator.isMobilePhone('sample', 'sr-RS'); result = validator.isMobilePhone('sample', 'sk-SK'); result = validator.isMobilePhone('sample', 'th-TH'); result = validator.isMobilePhone('sample', 'tr-TR'); result = validator.isMobilePhone('sample', 'uk-UA'); result = validator.isMobilePhone('sample', 'vi-VN'); result = validator.isMobilePhone('sample', 'zh-CN'); result = validator.isMobilePhone('sample', 'zh-HK'); result = validator.isMobilePhone('sample', 'zh-TW'); result = validator.isMobilePhone('sample', 'any'); result = validator.isMongoId('sample'); result = validator.isMultibyte('sample'); result = validator.isNumeric('sample'); result = validator.isNumeric('+358', { no_symbols: true }); result = validator.isPort('sample'); result = validator.isPostalCode('sample', 'AT'); result = validator.isPostalCode('sample', 'AU'); result = validator.isPostalCode('sample', 'BE'); result = validator.isPostalCode('sample', 'BG'); result = validator.isPostalCode('sample', 'CA'); result = validator.isPostalCode('sample', 'CH'); result = validator.isPostalCode('sample', 'CZ'); result = validator.isPostalCode('sample', 'DE'); result = validator.isPostalCode('sample', 'DK'); result = validator.isPostalCode('sample', 'DZ'); result = validator.isPostalCode('sample', 'ES'); result = validator.isPostalCode('sample', 'FI'); result = validator.isPostalCode('sample', 'FR'); result = validator.isPostalCode('sample', 'GB'); result = validator.isPostalCode('sample', 'GR'); result = validator.isPostalCode('sample', 'IL'); result = validator.isPostalCode('sample', 'IN'); result = validator.isPostalCode('sample', 'IS'); result = validator.isPostalCode('sample', 'IT'); result = validator.isPostalCode('sample', 'JP'); result = validator.isPostalCode('sample', 'KE'); result = validator.isPostalCode('sample', 'LI'); result = validator.isPostalCode('sample', 'MX'); result = validator.isPostalCode('sample', 'NL'); result = validator.isPostalCode('sample', 'NO'); result = validator.isPostalCode('sample', 'PL'); result = validator.isPostalCode('sample', 'PT'); result = validator.isPostalCode('sample', 'RO'); result = validator.isPostalCode('sample', 'RU'); result = validator.isPostalCode('sample', 'SA'); result = validator.isPostalCode('sample', 'SE'); result = validator.isPostalCode('sample', 'TW'); result = validator.isPostalCode('sample', 'US'); result = validator.isPostalCode('sample', 'ZA'); result = validator.isPostalCode('sample', 'ZM'); result = validator.isPostalCode('sample', 'any'); result = validator.isSurrogatePair('sample'); let isURLOptions: ValidatorJS.IsURLOptions = {}; result = validator.isURL('sample'); result = validator.isURL('sample', isURLOptions); result = validator.isUUID('sample'); result = validator.isUUID('sample', 5); result = validator.isUUID('sample', 'all'); result = validator.isUppercase('sample'); result = validator.isVariableWidth('sample'); result = validator.isWhitelisted('sample', 'abc'); result = validator.isWhitelisted('sample', ['a', 'b', 'c']); result = validator.matches('foobar', 'foo/i'); result = validator.matches('foobar', 'foo', 'i'); } // ************** // * Sanitizers * // ************** { let result: string; result = validator.blacklist('sample', 'abc'); result = validator.escape('sample'); result = validator.unescape('sample'); result = validator.ltrim('sample'); result = validator.ltrim('sample', ' '); let normalizeEmailOptions: ValidatorJS.NormalizeEmailOptions = {}; let normalizeResult: string | false; normalizeResult = validator.normalizeEmail('sample'); normalizeResult = validator.normalizeEmail('sample', normalizeEmailOptions); result = validator.rtrim('sample'); result = validator.rtrim('sample', ' '); result = validator.stripLow('sample'); result = validator.stripLow('sample', true); } { let result: boolean; result = validator.toBoolean(any); result = validator.toBoolean(any, true); } { let result: Date; result = validator.toDate(any); } { let result: number; result = validator.toFloat(any); result = validator.toInt(any); result = validator.toInt(any, 10); } { let result: string; result = validator.trim('sample'); result = validator.trim('sample', ' '); result = validator.whitelist('sample', 'abc'); } { let str: string; str = validator.toString([123, 456, '123', '456', true, false]); } { let ver: string; ver = validator.version; } // ************** // * Extensions * // ************** validator.extend<(str: string, options: {}) => boolean>('isTest', (str: any, options: {}) => !str);
types/validator/validator-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/280c65abb520b173bc39109e01b3c15242e66195
[ 0.9989516735076904, 0.033326853066682816, 0.00016627278819214553, 0.0001777290308382362, 0.16884498298168182 ]
{ "id": 1, "code_window": [ " gt?: number;\n", " }\n", "\n", " // options for IsLength\n", " interface IsLengthOptions {\n", " min?: number;\n", " max?: number;\n", " }\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // options for isISO8601\n", " interface IsISO8601Options {\n", " strict?: boolean;\n", " }\n", "\n" ], "file_path": "types/validator/index.d.ts", "type": "add", "edit_start_line_idx": 343 }
{ "compilerOptions": { "module": "commonjs", "lib": [ "es6", "dom" ], "noImplicitAny": true, "noImplicitThis": false, "strictNullChecks": false, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" ], "paths": { "jquery": [ "jquery/v2" ] }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", "jquery.joyride-tests.ts" ] }
types/jquery.joyride/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/280c65abb520b173bc39109e01b3c15242e66195
[ 0.00017283570196013898, 0.00016972275625448674, 0.00016816571587696671, 0.00016816682182252407, 0.0000022011918190401047 ]
{ "id": 1, "code_window": [ " gt?: number;\n", " }\n", "\n", " // options for IsLength\n", " interface IsLengthOptions {\n", " min?: number;\n", " max?: number;\n", " }\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // options for isISO8601\n", " interface IsISO8601Options {\n", " strict?: boolean;\n", " }\n", "\n" ], "file_path": "types/validator/index.d.ts", "type": "add", "edit_start_line_idx": 343 }
// Type definitions for leaflet-providers 1.1 // Project: https://github.com/leaflet-extras/leaflet-providers#readme // Definitions by: BendingBender <https://github.com/BendingBender> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import * as L from 'leaflet'; declare module 'leaflet' { namespace TileLayer { class Provider extends TileLayer { constructor(provider: string, options?: TileLayerOptions & { [name: string]: string; }) } namespace Provider { const providers: ProvidersMap; interface ProvidersMap { [providerName: string]: ProviderConfig; } interface ProviderConfig { url: string; options?: TileLayerOptions; variants?: {[variantName: string]: string | ProviderConfig}; } } } namespace tileLayer { function provider(provider: string, options?: TileLayerOptions & { [name: string]: string; }): TileLayer.Provider; } }
types/leaflet-providers/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/280c65abb520b173bc39109e01b3c15242e66195
[ 0.00023165748280007392, 0.0002008556912187487, 0.00017323397332802415, 0.0001992656325455755, 0.0000251999736065045 ]
{ "id": 1, "code_window": [ " gt?: number;\n", " }\n", "\n", " // options for IsLength\n", " interface IsLengthOptions {\n", " min?: number;\n", " max?: number;\n", " }\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // options for isISO8601\n", " interface IsISO8601Options {\n", " strict?: boolean;\n", " }\n", "\n" ], "file_path": "types/validator/index.d.ts", "type": "add", "edit_start_line_idx": 343 }
import { geojson2osm } from 'geojson2osm' const features: GeoJSON.FeatureCollection<any> = { type: 'FeatureCollection', features: [{ type: 'Feature', properties: { 'building:colour': '#9F8169', 'building:levels': 21, building: 'yes', height: 57, }, geometry: { type: 'Polygon', coordinates: [ [ [ -434.2249470949173, -13.15996269397843, ], [ -434.2249470949173, -13.159751140560356, ], [ -434.2242631316185, -13.159751140560356, ], [ -434.2242631316185, -13.15996269397843, ], [ -434.2249470949173, -13.15996269397843, ], ], ], }, }, ], } geojson2osm(features)
types/geojson2osm/geojson2osm-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/280c65abb520b173bc39109e01b3c15242e66195
[ 0.0001771269307937473, 0.00017096844385378063, 0.00016523739031981677, 0.00017166447651106864, 0.000004031002845295006 ]
{ "id": 2, "code_window": [ " result = validator.isISSN('sample');\n", " result = validator.isISSN('sample', isISSNOptions);\n", "\n", " result = validator.isISIN('sample');\n", "\n", " result = validator.isISO8601('sample');\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " let isISO8601Options: ValidatorJS.IsISO8601Options = {};\n" ], "file_path": "types/validator/validator-tests.ts", "type": "add", "edit_start_line_idx": 471 }
import * as validator from 'validator'; /************************************************ * * * IMPORT TESTS * * * ************************************************/ import blacklistFunc = require('validator/lib/blacklist'); import containsFunc = require('validator/lib/contains'); import equalsFunc = require('validator/lib/equals'); import escapeFunc = require('validator/lib/escape'); import isAfterFunc = require('validator/lib/isAfter'); import isAlphaFunc = require('validator/lib/isAlpha'); import isAlphanumericFunc = require('validator/lib/isAlphanumeric'); import isAsciiFunc = require('validator/lib/isAscii'); import isBase64Func = require('validator/lib/isBase64'); import isBeforeFunc = require('validator/lib/isBefore'); import isBooleanFunc = require('validator/lib/isBoolean'); import isByteLengthFunc = require('validator/lib/isByteLength'); import isCreditCardFunc = require('validator/lib/isCreditCard'); import isCurrencyFunc = require('validator/lib/isCurrency'); import isDataURIFunc = require('validator/lib/isDataURI'); import isDecimalFunc = require('validator/lib/isDecimal'); import isDivisibleByFunc = require('validator/lib/isDivisibleBy'); import isEmailFunc = require('validator/lib/isEmail'); import isEmptyFunc = require('validator/lib/isEmpty'); import isFQDNFunc = require('validator/lib/isFQDN'); import isFloatFunc = require('validator/lib/isFloat'); import isFullWidthFunc = require('validator/lib/isFullWidth'); import isHalfWidthFunc = require('validator/lib/isHalfWidth'); import isHashFunc = require('validator/lib/isHash'); import isHexColorFunc = require('validator/lib/isHexColor'); import isHexadecimalFunc = require('validator/lib/isHexadecimal'); import isIPFunc = require('validator/lib/isIP'); import isISBNFunc = require('validator/lib/isISBN'); import isISSNFunc = require('validator/lib/isISSN'); import isISINFunc = require('validator/lib/isISIN'); import isISO8601Func = require('validator/lib/isISO8601'); import isISO31661Alpha2Func = require('validator/lib/isISO31661Alpha2'); import isISRCFunc = require('validator/lib/isISRC'); import isInFunc = require('validator/lib/isIn'); import isIntFunc = require('validator/lib/isInt'); import isJSONFunc = require('validator/lib/isJSON'); import isLatLongFunc = require('validator/lib/isLatLong'); import isLengthFunc = require('validator/lib/isLength'); import isLowercaseFunc = require('validator/lib/isLowercase'); import isMACAddressFunc = require('validator/lib/isMACAddress'); import isMD5Func = require('validator/lib/isMD5'); import isMimeTypeFunc = require('validator/lib/isMimeType'); import isMobilePhoneFunc = require('validator/lib/isMobilePhone'); import isMongoIdFunc = require('validator/lib/isMongoId'); import isMultibyteFunc = require('validator/lib/isMultibyte'); import isNumericFunc = require('validator/lib/isNumeric'); import isPortFunc = require('validator/lib/isPort'); import isPostalCodeFunc = require('validator/lib/isPostalCode'); import isSurrogatePairFunc = require('validator/lib/isSurrogatePair'); import isURLFunc = require('validator/lib/isURL'); import isUUIDFunc = require('validator/lib/isUUID'); import isUppercaseFunc = require('validator/lib/isUppercase'); import isVariableWidthFunc = require('validator/lib/isVariableWidth'); import isWhitelistedFunc = require('validator/lib/isWhitelisted'); import ltrimFunc = require('validator/lib/ltrim'); import matchesFunc = require('validator/lib/matches'); import normalizeEmailFunc = require('validator/lib/normalizeEmail'); import rtrimFunc = require('validator/lib/rtrim'); import stripLowFunc = require('validator/lib/stripLow'); import toBooleanFunc = require('validator/lib/toBoolean'); import toDateFunc = require('validator/lib/toDate'); import toFloatFunc = require('validator/lib/toFloat'); import toIntFunc = require('validator/lib/toInt'); import trimFunc = require('validator/lib/trim'); import unescapeFunc = require('validator/lib/unescape'); import whitelistFunc = require('validator/lib/whitelist'); { let _blacklist = validator.blacklist; _blacklist = blacklistFunc; let _contains = validator.contains; _contains = containsFunc; let _equals = validator.equals; _equals = equalsFunc; let _escape = validator.escape; _escape = escapeFunc; let _isAfter = validator.isAfter; _isAfter = isAfterFunc; let _isAlpha = validator.isAlpha; _isAlpha = isAlphaFunc; let _isAlphanumeric = validator.isAlphanumeric; _isAlphanumeric = isAlphanumericFunc; let _isAscii = validator.isAscii; _isAscii = isAsciiFunc; let _isBase64 = validator.isBase64; _isBase64 = isBase64Func; let _isBefore = validator.isBefore; _isBefore = isBeforeFunc; let _isBoolean = validator.isBoolean; _isBoolean = isBooleanFunc; let _isByteLength = validator.isByteLength; _isByteLength = isByteLengthFunc; let _isCreditCard = validator.isCreditCard; _isCreditCard = isCreditCardFunc; let _isCurrency = validator.isCurrency; _isCurrency = isCurrencyFunc; let _isDataURI = validator.isDataURI; _isDataURI = isDataURIFunc; let _isDecimal = validator.isDecimal; _isDecimal = isDecimalFunc; let _isDivisibleBy = validator.isDivisibleBy; _isDivisibleBy = isDivisibleByFunc; let _isEmail = validator.isEmail; _isEmail = isEmailFunc; let _isEmpty = validator.isEmpty; _isEmpty = isEmptyFunc; let _isFQDN = validator.isFQDN; _isFQDN = isFQDNFunc; let _isFloat = validator.isFloat; _isFloat = isFloatFunc; let _isFullWidth = validator.isFullWidth; _isFullWidth = isFullWidthFunc; let _isHalfWidth = validator.isHalfWidth; _isHalfWidth = isHalfWidthFunc; let _isHash = validator.isHash; _isHash = isHashFunc; let _isHexColor = validator.isHexColor; _isHexColor = isHexColorFunc; let _isHexadecimal = validator.isHexadecimal; _isHexadecimal = isHexadecimalFunc; let _isIP = validator.isIP; _isIP = isIPFunc; let _isISBN = validator.isISBN; _isISBN = isISBNFunc; let _isISSN = validator.isISSN; _isISSN = isISSNFunc; let _isISIN = validator.isISIN; _isISIN = isISINFunc; let _isISO8601 = validator.isISO8601; _isISO8601 = isISO8601Func; let _isISO31661Alpha2 = validator.isISO31661Alpha2; _isISO31661Alpha2 = isISO31661Alpha2Func; let _isISRC = validator.isISRC; _isISRC = isISRCFunc; let _isIn = validator.isIn; _isIn = isInFunc; let _isInt = validator.isInt; _isInt = isIntFunc; let _isJSON = validator.isJSON; _isJSON = isJSONFunc; let _isLatLong = validator.isLatLong; _isLatLong = isLatLongFunc; let _isLength = validator.isLength; _isLength = isLengthFunc; let _isLowercase = validator.isLowercase; _isLowercase = isLowercaseFunc; let _isMACAddress = validator.isMACAddress; _isMACAddress = isMACAddressFunc; let _isMD5 = validator.isMD5; _isMD5 = isMD5Func; let _isMimeType = validator.isMimeType; _isMimeType = isMimeTypeFunc; let _isMobilePhone = validator.isMobilePhone; _isMobilePhone = isMobilePhoneFunc; let _isMongoId = validator.isMongoId; _isMongoId = isMongoIdFunc; let _isMultibyte = validator.isMultibyte; _isMultibyte = isMultibyteFunc; let _isNumeric = validator.isNumeric; _isNumeric = isNumericFunc; let _isPort = validator.isPort; _isPort = isPortFunc; let _isPostalCode = validator.isPostalCode; _isPostalCode = isPostalCodeFunc; let _isSurrogatePair = validator.isSurrogatePair; _isSurrogatePair = isSurrogatePairFunc; let _isURL = validator.isURL; _isURL = isURLFunc; let _isUUID = validator.isUUID; _isUUID = isUUIDFunc; let _isUppercase = validator.isUppercase; _isUppercase = isUppercaseFunc; let _isVariableWidth = validator.isVariableWidth; _isVariableWidth = isVariableWidthFunc; let _isWhitelisted = validator.isWhitelisted; _isWhitelisted = isWhitelistedFunc; let _ltrim = validator.ltrim; _ltrim = ltrimFunc; let _matches = validator.matches; _matches = matchesFunc; let _normalizeEmail = validator.normalizeEmail; _normalizeEmail = normalizeEmailFunc; let _rtrim = validator.rtrim; _rtrim = rtrimFunc; let _stripLow = validator.stripLow; _stripLow = stripLowFunc; let _toBoolean = validator.toBoolean; _toBoolean = toBooleanFunc; let _toDate = validator.toDate; _toDate = toDateFunc; let _toFloat = validator.toFloat; _toFloat = toFloatFunc; let _toInt = validator.toInt; _toInt = toIntFunc; let _trim = validator.trim; _trim = trimFunc; let _unescape = validator.unescape; _unescape = unescapeFunc; let _whitelist = validator.whitelist; _whitelist = whitelistFunc; } /************************************************ * * * API TESTS * * * ************************************************/ let any: any; // ************** // * Validators * // ************** { let result: boolean; result = validator.contains('sample', 'sample'); result = validator.equals('sample', 'sample'); result = validator.isAfter('sample'); result = validator.isAfter('sample', new Date().toString()); result = validator.isAlpha('sample'); result = validator.isAlpha('sample', 'ar'); result = validator.isAlpha('sample', 'ar-AE'); result = validator.isAlpha('sample', 'ar-BH'); result = validator.isAlpha('sample', 'ar-DZ'); result = validator.isAlpha('sample', 'ar-EG'); result = validator.isAlpha('sample', 'ar-IQ'); result = validator.isAlpha('sample', 'ar-JO'); result = validator.isAlpha('sample', 'ar-KW'); result = validator.isAlpha('sample', 'ar-LB'); result = validator.isAlpha('sample', 'ar-LY'); result = validator.isAlpha('sample', 'ar-MA'); result = validator.isAlpha('sample', 'ar-QA'); result = validator.isAlpha('sample', 'ar-QM'); result = validator.isAlpha('sample', 'ar-SA'); result = validator.isAlpha('sample', 'ar-SD'); result = validator.isAlpha('sample', 'ar-SY'); result = validator.isAlpha('sample', 'ar-TN'); result = validator.isAlpha('sample', 'ar-YE'); result = validator.isAlpha('sample', 'bg-BG'); result = validator.isAlpha('sample', 'cs-CZ'); result = validator.isAlpha('sample', 'da-DK'); result = validator.isAlpha('sample', 'de-DE'); result = validator.isAlpha('sample', 'el-GR'); result = validator.isAlpha('sample', 'en-AU'); result = validator.isAlpha('sample', 'en-GB'); result = validator.isAlpha('sample', 'en-HK'); result = validator.isAlpha('sample', 'en-IN'); result = validator.isAlpha('sample', 'en-NZ'); result = validator.isAlpha('sample', 'en-US'); result = validator.isAlpha('sample', 'en-ZA'); result = validator.isAlpha('sample', 'en-ZM'); result = validator.isAlpha('sample', 'es-ES'); result = validator.isAlpha('sample', 'fr-FR'); result = validator.isAlpha('sample', 'hu-HU'); result = validator.isAlpha('sample', 'it-IT'); result = validator.isAlpha('sample', 'nb-NO'); result = validator.isAlpha('sample', 'nl-NL'); result = validator.isAlpha('sample', 'nn-NO'); result = validator.isAlpha('sample', 'pl-PL'); result = validator.isAlpha('sample', 'pt-BR'); result = validator.isAlpha('sample', 'pt-PT'); result = validator.isAlpha('sample', 'ru-RU'); result = validator.isAlpha('sample', 'sk-SK'); result = validator.isAlpha('sample', 'sr-RS'); result = validator.isAlpha('sample', 'sr-RS@latin'); result = validator.isAlpha('sample', 'sv-SE'); result = validator.isAlpha('sample', 'tr-TR'); result = validator.isAlpha('sample', 'uk-UA'); result = validator.isAlphanumeric('sample'); result = validator.isAlphanumeric('sample', 'ar'); result = validator.isAlphanumeric('sample', 'ar-AE'); result = validator.isAlphanumeric('sample', 'ar-BH'); result = validator.isAlphanumeric('sample', 'ar-DZ'); result = validator.isAlphanumeric('sample', 'ar-EG'); result = validator.isAlphanumeric('sample', 'ar-IQ'); result = validator.isAlphanumeric('sample', 'ar-JO'); result = validator.isAlphanumeric('sample', 'ar-KW'); result = validator.isAlphanumeric('sample', 'ar-LB'); result = validator.isAlphanumeric('sample', 'ar-LY'); result = validator.isAlphanumeric('sample', 'ar-MA'); result = validator.isAlphanumeric('sample', 'ar-QA'); result = validator.isAlphanumeric('sample', 'ar-QM'); result = validator.isAlphanumeric('sample', 'ar-SA'); result = validator.isAlphanumeric('sample', 'ar-SD'); result = validator.isAlphanumeric('sample', 'ar-SY'); result = validator.isAlphanumeric('sample', 'ar-TN'); result = validator.isAlphanumeric('sample', 'ar-YE'); result = validator.isAlphanumeric('sample', 'bg-BG'); result = validator.isAlphanumeric('sample', 'cs-CZ'); result = validator.isAlphanumeric('sample', 'da-DK'); result = validator.isAlphanumeric('sample', 'de-DE'); result = validator.isAlphanumeric('sample', 'el-GR'); result = validator.isAlphanumeric('sample', 'en-AU'); result = validator.isAlphanumeric('sample', 'en-GB'); result = validator.isAlphanumeric('sample', 'en-HK'); result = validator.isAlphanumeric('sample', 'en-IN'); result = validator.isAlphanumeric('sample', 'en-NZ'); result = validator.isAlphanumeric('sample', 'en-US'); result = validator.isAlphanumeric('sample', 'en-ZA'); result = validator.isAlphanumeric('sample', 'en-ZM'); result = validator.isAlphanumeric('sample', 'es-ES'); result = validator.isAlphanumeric('sample', 'fr-FR'); result = validator.isAlphanumeric('sample', 'hu-HU'); result = validator.isAlphanumeric('sample', 'it-IT'); result = validator.isAlphanumeric('sample', 'nb-NO'); result = validator.isAlphanumeric('sample', 'nl-NL'); result = validator.isAlphanumeric('sample', 'nn-NO'); result = validator.isAlphanumeric('sample', 'pl-PL'); result = validator.isAlphanumeric('sample', 'pt-BR'); result = validator.isAlphanumeric('sample', 'pt-PT'); result = validator.isAlphanumeric('sample', 'ru-RU'); result = validator.isAlphanumeric('sample', 'sk-SK'); result = validator.isAlphanumeric('sample', 'sr-RS'); result = validator.isAlphanumeric('sample', 'sr-RS@latin'); result = validator.isAlphanumeric('sample', 'sv-SE'); result = validator.isAlphanumeric('sample', 'tr-TR'); result = validator.isAlphanumeric('sample', 'uk-UA'); result = validator.isAscii('sample'); result = validator.isBase64('sample'); result = validator.isBefore('sample'); result = validator.isBefore('sample', new Date().toString()); result = validator.isBoolean('sample'); let isByteLengthOptions: ValidatorJS.IsByteLengthOptions = {}; result = validator.isByteLength('sample', isByteLengthOptions); result = validator.isByteLength('sample', 0); result = validator.isByteLength('sample', 0, 42); result = validator.isCreditCard('sample'); let isCurrencyOptions: ValidatorJS.IsCurrencyOptions = {}; result = validator.isCurrency('sample'); result = validator.isCurrency('sample', isCurrencyOptions); result = validator.isDataURI('sample'); let isDecimalOptions: ValidatorJS.IsDecimalOptions = {}; result = validator.isDecimal('sample'); result = validator.isDecimal('sample', isDecimalOptions); result = validator.isDivisibleBy('sample', 2); let isEmailOptions: ValidatorJS.IsEmailOptions = {}; result = validator.isEmail('sample'); result = validator.isEmail('sample', isEmailOptions); result = validator.isEmpty('sample'); let isFQDNOptions: ValidatorJS.IsFQDNOptions = {}; result = validator.isFQDN('sample'); result = validator.isFQDN('sample', isFQDNOptions); let isFloatOptions: ValidatorJS.IsFloatOptions = {}; result = validator.isFloat('sample'); result = validator.isFloat('sample', isFloatOptions); result = validator.isFullWidth('sample'); result = validator.isHalfWidth('sample'); result = validator.isHash('sample', 'md4'); result = validator.isHash('sample', 'md5'); result = validator.isHash('sample', 'sha1'); result = validator.isHash('sample', 'sha256'); result = validator.isHash('sample', 'sha384'); result = validator.isHash('sample', 'sha512'); result = validator.isHash('sample', 'ripemd128'); result = validator.isHash('sample', 'ripemd160'); result = validator.isHash('sample', 'tiger128'); result = validator.isHash('sample', 'tiger160'); result = validator.isHash('sample', 'tiger192'); result = validator.isHash('sample', 'crc32'); result = validator.isHash('sample', 'crc32b'); result = validator.isHexColor('sample'); result = validator.isHexadecimal('sample'); result = validator.isIP('sample'); result = validator.isIP('sample', 6); result = validator.isISBN('sample'); result = validator.isISBN('sample', 13); let isISSNOptions: ValidatorJS.IsISSNOptions = {}; result = validator.isISSN('sample'); result = validator.isISSN('sample', isISSNOptions); result = validator.isISIN('sample'); result = validator.isISO8601('sample'); result = validator.isISO31661Alpha2('sample'); result = validator.isISRC('sample'); result = validator.isIn('sample', []); let isIntOptions: ValidatorJS.IsIntOptions = {}; result = validator.isInt('sample'); result = validator.isInt('sample', isIntOptions); result = validator.isJSON('sample'); result = validator.isLatLong('sample'); let isLengthOptions: ValidatorJS.IsLengthOptions = {}; result = validator.isLength('sample', isLengthOptions); result = validator.isLength('sample', 3); result = validator.isLength('sample', 3, 5); result = validator.isLowercase('sample'); result = validator.isMACAddress('sample'); result = validator.isMD5('sample'); result = validator.isMimeType('sample'); let isMobilePhoneOptions: ValidatorJS.IsMobilePhoneOptions = {}; result = validator.isMobilePhone('sample', 'any', isMobilePhoneOptions); result = validator.isMobilePhone('sample', 'ar-AE'); result = validator.isMobilePhone('sample', 'ar-DZ'); result = validator.isMobilePhone('sample', 'ar-EG'); result = validator.isMobilePhone('sample', 'ar-JO'); result = validator.isMobilePhone('sample', 'ar-SA'); result = validator.isMobilePhone('sample', 'ar-SY'); result = validator.isMobilePhone('sample', 'be-BY'); result = validator.isMobilePhone('sample', 'bg-BG'); result = validator.isMobilePhone('sample', 'cs-CZ'); result = validator.isMobilePhone('sample', 'de-DE'); result = validator.isMobilePhone('sample', 'da-DK'); result = validator.isMobilePhone('sample', 'el-GR'); result = validator.isMobilePhone('sample', 'en-AU'); result = validator.isMobilePhone('sample', 'en-GB'); result = validator.isMobilePhone('sample', 'en-HK'); result = validator.isMobilePhone('sample', 'en-IN'); result = validator.isMobilePhone('sample', 'en-KE'); result = validator.isMobilePhone('sample', 'en-NG'); result = validator.isMobilePhone('sample', 'en-NZ'); result = validator.isMobilePhone('sample', 'en-UG'); result = validator.isMobilePhone('sample', 'en-RW'); result = validator.isMobilePhone('sample', 'en-SG'); result = validator.isMobilePhone('sample', 'en-TZ'); result = validator.isMobilePhone('sample', 'en-PK'); result = validator.isMobilePhone('sample', 'en-US'); result = validator.isMobilePhone('sample', 'en-CA'); result = validator.isMobilePhone('sample', 'en-ZA'); result = validator.isMobilePhone('sample', 'en-ZM'); result = validator.isMobilePhone('sample', 'es-ES'); result = validator.isMobilePhone('sample', 'fa-IR'); result = validator.isMobilePhone('sample', 'fi-FI'); result = validator.isMobilePhone('sample', 'fo-FO'); result = validator.isMobilePhone('sample', 'fr-FR'); result = validator.isMobilePhone('sample', 'he-IL'); result = validator.isMobilePhone('sample', 'hu-HU'); result = validator.isMobilePhone('sample', 'id-ID'); result = validator.isMobilePhone('sample', 'it-IT'); result = validator.isMobilePhone('sample', 'ja-JP'); result = validator.isMobilePhone('sample', 'kk-KZ'); result = validator.isMobilePhone('sample', 'kl-GL'); result = validator.isMobilePhone('sample', 'ko-KR'); result = validator.isMobilePhone('sample', 'lt-LT'); result = validator.isMobilePhone('sample', 'ms-MY'); result = validator.isMobilePhone('sample', 'nb-NO'); result = validator.isMobilePhone('sample', 'nn-NO'); result = validator.isMobilePhone('sample', 'pl-PL'); result = validator.isMobilePhone('sample', 'pt-PT'); result = validator.isMobilePhone('sample', 'ro-RO'); result = validator.isMobilePhone('sample', 'ru-RU'); result = validator.isMobilePhone('sample', 'sr-RS'); result = validator.isMobilePhone('sample', 'sk-SK'); result = validator.isMobilePhone('sample', 'th-TH'); result = validator.isMobilePhone('sample', 'tr-TR'); result = validator.isMobilePhone('sample', 'uk-UA'); result = validator.isMobilePhone('sample', 'vi-VN'); result = validator.isMobilePhone('sample', 'zh-CN'); result = validator.isMobilePhone('sample', 'zh-HK'); result = validator.isMobilePhone('sample', 'zh-TW'); result = validator.isMobilePhone('sample', 'any'); result = validator.isMongoId('sample'); result = validator.isMultibyte('sample'); result = validator.isNumeric('sample'); result = validator.isNumeric('+358', { no_symbols: true }); result = validator.isPort('sample'); result = validator.isPostalCode('sample', 'AT'); result = validator.isPostalCode('sample', 'AU'); result = validator.isPostalCode('sample', 'BE'); result = validator.isPostalCode('sample', 'BG'); result = validator.isPostalCode('sample', 'CA'); result = validator.isPostalCode('sample', 'CH'); result = validator.isPostalCode('sample', 'CZ'); result = validator.isPostalCode('sample', 'DE'); result = validator.isPostalCode('sample', 'DK'); result = validator.isPostalCode('sample', 'DZ'); result = validator.isPostalCode('sample', 'ES'); result = validator.isPostalCode('sample', 'FI'); result = validator.isPostalCode('sample', 'FR'); result = validator.isPostalCode('sample', 'GB'); result = validator.isPostalCode('sample', 'GR'); result = validator.isPostalCode('sample', 'IL'); result = validator.isPostalCode('sample', 'IN'); result = validator.isPostalCode('sample', 'IS'); result = validator.isPostalCode('sample', 'IT'); result = validator.isPostalCode('sample', 'JP'); result = validator.isPostalCode('sample', 'KE'); result = validator.isPostalCode('sample', 'LI'); result = validator.isPostalCode('sample', 'MX'); result = validator.isPostalCode('sample', 'NL'); result = validator.isPostalCode('sample', 'NO'); result = validator.isPostalCode('sample', 'PL'); result = validator.isPostalCode('sample', 'PT'); result = validator.isPostalCode('sample', 'RO'); result = validator.isPostalCode('sample', 'RU'); result = validator.isPostalCode('sample', 'SA'); result = validator.isPostalCode('sample', 'SE'); result = validator.isPostalCode('sample', 'TW'); result = validator.isPostalCode('sample', 'US'); result = validator.isPostalCode('sample', 'ZA'); result = validator.isPostalCode('sample', 'ZM'); result = validator.isPostalCode('sample', 'any'); result = validator.isSurrogatePair('sample'); let isURLOptions: ValidatorJS.IsURLOptions = {}; result = validator.isURL('sample'); result = validator.isURL('sample', isURLOptions); result = validator.isUUID('sample'); result = validator.isUUID('sample', 5); result = validator.isUUID('sample', 'all'); result = validator.isUppercase('sample'); result = validator.isVariableWidth('sample'); result = validator.isWhitelisted('sample', 'abc'); result = validator.isWhitelisted('sample', ['a', 'b', 'c']); result = validator.matches('foobar', 'foo/i'); result = validator.matches('foobar', 'foo', 'i'); } // ************** // * Sanitizers * // ************** { let result: string; result = validator.blacklist('sample', 'abc'); result = validator.escape('sample'); result = validator.unescape('sample'); result = validator.ltrim('sample'); result = validator.ltrim('sample', ' '); let normalizeEmailOptions: ValidatorJS.NormalizeEmailOptions = {}; let normalizeResult: string | false; normalizeResult = validator.normalizeEmail('sample'); normalizeResult = validator.normalizeEmail('sample', normalizeEmailOptions); result = validator.rtrim('sample'); result = validator.rtrim('sample', ' '); result = validator.stripLow('sample'); result = validator.stripLow('sample', true); } { let result: boolean; result = validator.toBoolean(any); result = validator.toBoolean(any, true); } { let result: Date; result = validator.toDate(any); } { let result: number; result = validator.toFloat(any); result = validator.toInt(any); result = validator.toInt(any, 10); } { let result: string; result = validator.trim('sample'); result = validator.trim('sample', ' '); result = validator.whitelist('sample', 'abc'); } { let str: string; str = validator.toString([123, 456, '123', '456', true, false]); } { let ver: string; ver = validator.version; } // ************** // * Extensions * // ************** validator.extend<(str: string, options: {}) => boolean>('isTest', (str: any, options: {}) => !str);
types/validator/validator-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/280c65abb520b173bc39109e01b3c15242e66195
[ 0.9952946305274963, 0.2815106213092804, 0.00016373848484363407, 0.007505020592361689, 0.35705479979515076 ]
{ "id": 2, "code_window": [ " result = validator.isISSN('sample');\n", " result = validator.isISSN('sample', isISSNOptions);\n", "\n", " result = validator.isISIN('sample');\n", "\n", " result = validator.isISO8601('sample');\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " let isISO8601Options: ValidatorJS.IsISO8601Options = {};\n" ], "file_path": "types/validator/validator-tests.ts", "type": "add", "edit_start_line_idx": 471 }
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; declare class MdGrain extends React.Component<IconBaseProps> { } export = MdGrain;
types/react-icons/lib/md/grain.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/280c65abb520b173bc39109e01b3c15242e66195
[ 0.00017521415429655463, 0.00017521415429655463, 0.00017521415429655463, 0.00017521415429655463, 0 ]
{ "id": 2, "code_window": [ " result = validator.isISSN('sample');\n", " result = validator.isISSN('sample', isISSNOptions);\n", "\n", " result = validator.isISIN('sample');\n", "\n", " result = validator.isISO8601('sample');\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " let isISO8601Options: ValidatorJS.IsISO8601Options = {};\n" ], "file_path": "types/validator/validator-tests.ts", "type": "add", "edit_start_line_idx": 471 }
import { sortWith } from '../index'; export default sortWith;
types/ramda/es/sortWith.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/280c65abb520b173bc39109e01b3c15242e66195
[ 0.00018057881970889866, 0.00018057881970889866, 0.00018057881970889866, 0.00018057881970889866, 0 ]
{ "id": 2, "code_window": [ " result = validator.isISSN('sample');\n", " result = validator.isISSN('sample', isISSNOptions);\n", "\n", " result = validator.isISIN('sample');\n", "\n", " result = validator.isISO8601('sample');\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " let isISO8601Options: ValidatorJS.IsISO8601Options = {};\n" ], "file_path": "types/validator/validator-tests.ts", "type": "add", "edit_start_line_idx": 471 }
{ "extends": "dtslint/dt.json" }
types/lodash.tonumber/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/280c65abb520b173bc39109e01b3c15242e66195
[ 0.00017493688210379332, 0.00017493688210379332, 0.00017493688210379332, 0.00017493688210379332, 0 ]
{ "id": 3, "code_window": [ " result = validator.isISO8601('sample');\n", "\n", " result = validator.isISO31661Alpha2('sample');\n", "\n", " result = validator.isISRC('sample');\n" ], "labels": [ "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " result = validator.isISO8601('sample', isISO8601Options);\n" ], "file_path": "types/validator/validator-tests.ts", "type": "add", "edit_start_line_idx": 472 }
import * as validator from 'validator'; /************************************************ * * * IMPORT TESTS * * * ************************************************/ import blacklistFunc = require('validator/lib/blacklist'); import containsFunc = require('validator/lib/contains'); import equalsFunc = require('validator/lib/equals'); import escapeFunc = require('validator/lib/escape'); import isAfterFunc = require('validator/lib/isAfter'); import isAlphaFunc = require('validator/lib/isAlpha'); import isAlphanumericFunc = require('validator/lib/isAlphanumeric'); import isAsciiFunc = require('validator/lib/isAscii'); import isBase64Func = require('validator/lib/isBase64'); import isBeforeFunc = require('validator/lib/isBefore'); import isBooleanFunc = require('validator/lib/isBoolean'); import isByteLengthFunc = require('validator/lib/isByteLength'); import isCreditCardFunc = require('validator/lib/isCreditCard'); import isCurrencyFunc = require('validator/lib/isCurrency'); import isDataURIFunc = require('validator/lib/isDataURI'); import isDecimalFunc = require('validator/lib/isDecimal'); import isDivisibleByFunc = require('validator/lib/isDivisibleBy'); import isEmailFunc = require('validator/lib/isEmail'); import isEmptyFunc = require('validator/lib/isEmpty'); import isFQDNFunc = require('validator/lib/isFQDN'); import isFloatFunc = require('validator/lib/isFloat'); import isFullWidthFunc = require('validator/lib/isFullWidth'); import isHalfWidthFunc = require('validator/lib/isHalfWidth'); import isHashFunc = require('validator/lib/isHash'); import isHexColorFunc = require('validator/lib/isHexColor'); import isHexadecimalFunc = require('validator/lib/isHexadecimal'); import isIPFunc = require('validator/lib/isIP'); import isISBNFunc = require('validator/lib/isISBN'); import isISSNFunc = require('validator/lib/isISSN'); import isISINFunc = require('validator/lib/isISIN'); import isISO8601Func = require('validator/lib/isISO8601'); import isISO31661Alpha2Func = require('validator/lib/isISO31661Alpha2'); import isISRCFunc = require('validator/lib/isISRC'); import isInFunc = require('validator/lib/isIn'); import isIntFunc = require('validator/lib/isInt'); import isJSONFunc = require('validator/lib/isJSON'); import isLatLongFunc = require('validator/lib/isLatLong'); import isLengthFunc = require('validator/lib/isLength'); import isLowercaseFunc = require('validator/lib/isLowercase'); import isMACAddressFunc = require('validator/lib/isMACAddress'); import isMD5Func = require('validator/lib/isMD5'); import isMimeTypeFunc = require('validator/lib/isMimeType'); import isMobilePhoneFunc = require('validator/lib/isMobilePhone'); import isMongoIdFunc = require('validator/lib/isMongoId'); import isMultibyteFunc = require('validator/lib/isMultibyte'); import isNumericFunc = require('validator/lib/isNumeric'); import isPortFunc = require('validator/lib/isPort'); import isPostalCodeFunc = require('validator/lib/isPostalCode'); import isSurrogatePairFunc = require('validator/lib/isSurrogatePair'); import isURLFunc = require('validator/lib/isURL'); import isUUIDFunc = require('validator/lib/isUUID'); import isUppercaseFunc = require('validator/lib/isUppercase'); import isVariableWidthFunc = require('validator/lib/isVariableWidth'); import isWhitelistedFunc = require('validator/lib/isWhitelisted'); import ltrimFunc = require('validator/lib/ltrim'); import matchesFunc = require('validator/lib/matches'); import normalizeEmailFunc = require('validator/lib/normalizeEmail'); import rtrimFunc = require('validator/lib/rtrim'); import stripLowFunc = require('validator/lib/stripLow'); import toBooleanFunc = require('validator/lib/toBoolean'); import toDateFunc = require('validator/lib/toDate'); import toFloatFunc = require('validator/lib/toFloat'); import toIntFunc = require('validator/lib/toInt'); import trimFunc = require('validator/lib/trim'); import unescapeFunc = require('validator/lib/unescape'); import whitelistFunc = require('validator/lib/whitelist'); { let _blacklist = validator.blacklist; _blacklist = blacklistFunc; let _contains = validator.contains; _contains = containsFunc; let _equals = validator.equals; _equals = equalsFunc; let _escape = validator.escape; _escape = escapeFunc; let _isAfter = validator.isAfter; _isAfter = isAfterFunc; let _isAlpha = validator.isAlpha; _isAlpha = isAlphaFunc; let _isAlphanumeric = validator.isAlphanumeric; _isAlphanumeric = isAlphanumericFunc; let _isAscii = validator.isAscii; _isAscii = isAsciiFunc; let _isBase64 = validator.isBase64; _isBase64 = isBase64Func; let _isBefore = validator.isBefore; _isBefore = isBeforeFunc; let _isBoolean = validator.isBoolean; _isBoolean = isBooleanFunc; let _isByteLength = validator.isByteLength; _isByteLength = isByteLengthFunc; let _isCreditCard = validator.isCreditCard; _isCreditCard = isCreditCardFunc; let _isCurrency = validator.isCurrency; _isCurrency = isCurrencyFunc; let _isDataURI = validator.isDataURI; _isDataURI = isDataURIFunc; let _isDecimal = validator.isDecimal; _isDecimal = isDecimalFunc; let _isDivisibleBy = validator.isDivisibleBy; _isDivisibleBy = isDivisibleByFunc; let _isEmail = validator.isEmail; _isEmail = isEmailFunc; let _isEmpty = validator.isEmpty; _isEmpty = isEmptyFunc; let _isFQDN = validator.isFQDN; _isFQDN = isFQDNFunc; let _isFloat = validator.isFloat; _isFloat = isFloatFunc; let _isFullWidth = validator.isFullWidth; _isFullWidth = isFullWidthFunc; let _isHalfWidth = validator.isHalfWidth; _isHalfWidth = isHalfWidthFunc; let _isHash = validator.isHash; _isHash = isHashFunc; let _isHexColor = validator.isHexColor; _isHexColor = isHexColorFunc; let _isHexadecimal = validator.isHexadecimal; _isHexadecimal = isHexadecimalFunc; let _isIP = validator.isIP; _isIP = isIPFunc; let _isISBN = validator.isISBN; _isISBN = isISBNFunc; let _isISSN = validator.isISSN; _isISSN = isISSNFunc; let _isISIN = validator.isISIN; _isISIN = isISINFunc; let _isISO8601 = validator.isISO8601; _isISO8601 = isISO8601Func; let _isISO31661Alpha2 = validator.isISO31661Alpha2; _isISO31661Alpha2 = isISO31661Alpha2Func; let _isISRC = validator.isISRC; _isISRC = isISRCFunc; let _isIn = validator.isIn; _isIn = isInFunc; let _isInt = validator.isInt; _isInt = isIntFunc; let _isJSON = validator.isJSON; _isJSON = isJSONFunc; let _isLatLong = validator.isLatLong; _isLatLong = isLatLongFunc; let _isLength = validator.isLength; _isLength = isLengthFunc; let _isLowercase = validator.isLowercase; _isLowercase = isLowercaseFunc; let _isMACAddress = validator.isMACAddress; _isMACAddress = isMACAddressFunc; let _isMD5 = validator.isMD5; _isMD5 = isMD5Func; let _isMimeType = validator.isMimeType; _isMimeType = isMimeTypeFunc; let _isMobilePhone = validator.isMobilePhone; _isMobilePhone = isMobilePhoneFunc; let _isMongoId = validator.isMongoId; _isMongoId = isMongoIdFunc; let _isMultibyte = validator.isMultibyte; _isMultibyte = isMultibyteFunc; let _isNumeric = validator.isNumeric; _isNumeric = isNumericFunc; let _isPort = validator.isPort; _isPort = isPortFunc; let _isPostalCode = validator.isPostalCode; _isPostalCode = isPostalCodeFunc; let _isSurrogatePair = validator.isSurrogatePair; _isSurrogatePair = isSurrogatePairFunc; let _isURL = validator.isURL; _isURL = isURLFunc; let _isUUID = validator.isUUID; _isUUID = isUUIDFunc; let _isUppercase = validator.isUppercase; _isUppercase = isUppercaseFunc; let _isVariableWidth = validator.isVariableWidth; _isVariableWidth = isVariableWidthFunc; let _isWhitelisted = validator.isWhitelisted; _isWhitelisted = isWhitelistedFunc; let _ltrim = validator.ltrim; _ltrim = ltrimFunc; let _matches = validator.matches; _matches = matchesFunc; let _normalizeEmail = validator.normalizeEmail; _normalizeEmail = normalizeEmailFunc; let _rtrim = validator.rtrim; _rtrim = rtrimFunc; let _stripLow = validator.stripLow; _stripLow = stripLowFunc; let _toBoolean = validator.toBoolean; _toBoolean = toBooleanFunc; let _toDate = validator.toDate; _toDate = toDateFunc; let _toFloat = validator.toFloat; _toFloat = toFloatFunc; let _toInt = validator.toInt; _toInt = toIntFunc; let _trim = validator.trim; _trim = trimFunc; let _unescape = validator.unescape; _unescape = unescapeFunc; let _whitelist = validator.whitelist; _whitelist = whitelistFunc; } /************************************************ * * * API TESTS * * * ************************************************/ let any: any; // ************** // * Validators * // ************** { let result: boolean; result = validator.contains('sample', 'sample'); result = validator.equals('sample', 'sample'); result = validator.isAfter('sample'); result = validator.isAfter('sample', new Date().toString()); result = validator.isAlpha('sample'); result = validator.isAlpha('sample', 'ar'); result = validator.isAlpha('sample', 'ar-AE'); result = validator.isAlpha('sample', 'ar-BH'); result = validator.isAlpha('sample', 'ar-DZ'); result = validator.isAlpha('sample', 'ar-EG'); result = validator.isAlpha('sample', 'ar-IQ'); result = validator.isAlpha('sample', 'ar-JO'); result = validator.isAlpha('sample', 'ar-KW'); result = validator.isAlpha('sample', 'ar-LB'); result = validator.isAlpha('sample', 'ar-LY'); result = validator.isAlpha('sample', 'ar-MA'); result = validator.isAlpha('sample', 'ar-QA'); result = validator.isAlpha('sample', 'ar-QM'); result = validator.isAlpha('sample', 'ar-SA'); result = validator.isAlpha('sample', 'ar-SD'); result = validator.isAlpha('sample', 'ar-SY'); result = validator.isAlpha('sample', 'ar-TN'); result = validator.isAlpha('sample', 'ar-YE'); result = validator.isAlpha('sample', 'bg-BG'); result = validator.isAlpha('sample', 'cs-CZ'); result = validator.isAlpha('sample', 'da-DK'); result = validator.isAlpha('sample', 'de-DE'); result = validator.isAlpha('sample', 'el-GR'); result = validator.isAlpha('sample', 'en-AU'); result = validator.isAlpha('sample', 'en-GB'); result = validator.isAlpha('sample', 'en-HK'); result = validator.isAlpha('sample', 'en-IN'); result = validator.isAlpha('sample', 'en-NZ'); result = validator.isAlpha('sample', 'en-US'); result = validator.isAlpha('sample', 'en-ZA'); result = validator.isAlpha('sample', 'en-ZM'); result = validator.isAlpha('sample', 'es-ES'); result = validator.isAlpha('sample', 'fr-FR'); result = validator.isAlpha('sample', 'hu-HU'); result = validator.isAlpha('sample', 'it-IT'); result = validator.isAlpha('sample', 'nb-NO'); result = validator.isAlpha('sample', 'nl-NL'); result = validator.isAlpha('sample', 'nn-NO'); result = validator.isAlpha('sample', 'pl-PL'); result = validator.isAlpha('sample', 'pt-BR'); result = validator.isAlpha('sample', 'pt-PT'); result = validator.isAlpha('sample', 'ru-RU'); result = validator.isAlpha('sample', 'sk-SK'); result = validator.isAlpha('sample', 'sr-RS'); result = validator.isAlpha('sample', 'sr-RS@latin'); result = validator.isAlpha('sample', 'sv-SE'); result = validator.isAlpha('sample', 'tr-TR'); result = validator.isAlpha('sample', 'uk-UA'); result = validator.isAlphanumeric('sample'); result = validator.isAlphanumeric('sample', 'ar'); result = validator.isAlphanumeric('sample', 'ar-AE'); result = validator.isAlphanumeric('sample', 'ar-BH'); result = validator.isAlphanumeric('sample', 'ar-DZ'); result = validator.isAlphanumeric('sample', 'ar-EG'); result = validator.isAlphanumeric('sample', 'ar-IQ'); result = validator.isAlphanumeric('sample', 'ar-JO'); result = validator.isAlphanumeric('sample', 'ar-KW'); result = validator.isAlphanumeric('sample', 'ar-LB'); result = validator.isAlphanumeric('sample', 'ar-LY'); result = validator.isAlphanumeric('sample', 'ar-MA'); result = validator.isAlphanumeric('sample', 'ar-QA'); result = validator.isAlphanumeric('sample', 'ar-QM'); result = validator.isAlphanumeric('sample', 'ar-SA'); result = validator.isAlphanumeric('sample', 'ar-SD'); result = validator.isAlphanumeric('sample', 'ar-SY'); result = validator.isAlphanumeric('sample', 'ar-TN'); result = validator.isAlphanumeric('sample', 'ar-YE'); result = validator.isAlphanumeric('sample', 'bg-BG'); result = validator.isAlphanumeric('sample', 'cs-CZ'); result = validator.isAlphanumeric('sample', 'da-DK'); result = validator.isAlphanumeric('sample', 'de-DE'); result = validator.isAlphanumeric('sample', 'el-GR'); result = validator.isAlphanumeric('sample', 'en-AU'); result = validator.isAlphanumeric('sample', 'en-GB'); result = validator.isAlphanumeric('sample', 'en-HK'); result = validator.isAlphanumeric('sample', 'en-IN'); result = validator.isAlphanumeric('sample', 'en-NZ'); result = validator.isAlphanumeric('sample', 'en-US'); result = validator.isAlphanumeric('sample', 'en-ZA'); result = validator.isAlphanumeric('sample', 'en-ZM'); result = validator.isAlphanumeric('sample', 'es-ES'); result = validator.isAlphanumeric('sample', 'fr-FR'); result = validator.isAlphanumeric('sample', 'hu-HU'); result = validator.isAlphanumeric('sample', 'it-IT'); result = validator.isAlphanumeric('sample', 'nb-NO'); result = validator.isAlphanumeric('sample', 'nl-NL'); result = validator.isAlphanumeric('sample', 'nn-NO'); result = validator.isAlphanumeric('sample', 'pl-PL'); result = validator.isAlphanumeric('sample', 'pt-BR'); result = validator.isAlphanumeric('sample', 'pt-PT'); result = validator.isAlphanumeric('sample', 'ru-RU'); result = validator.isAlphanumeric('sample', 'sk-SK'); result = validator.isAlphanumeric('sample', 'sr-RS'); result = validator.isAlphanumeric('sample', 'sr-RS@latin'); result = validator.isAlphanumeric('sample', 'sv-SE'); result = validator.isAlphanumeric('sample', 'tr-TR'); result = validator.isAlphanumeric('sample', 'uk-UA'); result = validator.isAscii('sample'); result = validator.isBase64('sample'); result = validator.isBefore('sample'); result = validator.isBefore('sample', new Date().toString()); result = validator.isBoolean('sample'); let isByteLengthOptions: ValidatorJS.IsByteLengthOptions = {}; result = validator.isByteLength('sample', isByteLengthOptions); result = validator.isByteLength('sample', 0); result = validator.isByteLength('sample', 0, 42); result = validator.isCreditCard('sample'); let isCurrencyOptions: ValidatorJS.IsCurrencyOptions = {}; result = validator.isCurrency('sample'); result = validator.isCurrency('sample', isCurrencyOptions); result = validator.isDataURI('sample'); let isDecimalOptions: ValidatorJS.IsDecimalOptions = {}; result = validator.isDecimal('sample'); result = validator.isDecimal('sample', isDecimalOptions); result = validator.isDivisibleBy('sample', 2); let isEmailOptions: ValidatorJS.IsEmailOptions = {}; result = validator.isEmail('sample'); result = validator.isEmail('sample', isEmailOptions); result = validator.isEmpty('sample'); let isFQDNOptions: ValidatorJS.IsFQDNOptions = {}; result = validator.isFQDN('sample'); result = validator.isFQDN('sample', isFQDNOptions); let isFloatOptions: ValidatorJS.IsFloatOptions = {}; result = validator.isFloat('sample'); result = validator.isFloat('sample', isFloatOptions); result = validator.isFullWidth('sample'); result = validator.isHalfWidth('sample'); result = validator.isHash('sample', 'md4'); result = validator.isHash('sample', 'md5'); result = validator.isHash('sample', 'sha1'); result = validator.isHash('sample', 'sha256'); result = validator.isHash('sample', 'sha384'); result = validator.isHash('sample', 'sha512'); result = validator.isHash('sample', 'ripemd128'); result = validator.isHash('sample', 'ripemd160'); result = validator.isHash('sample', 'tiger128'); result = validator.isHash('sample', 'tiger160'); result = validator.isHash('sample', 'tiger192'); result = validator.isHash('sample', 'crc32'); result = validator.isHash('sample', 'crc32b'); result = validator.isHexColor('sample'); result = validator.isHexadecimal('sample'); result = validator.isIP('sample'); result = validator.isIP('sample', 6); result = validator.isISBN('sample'); result = validator.isISBN('sample', 13); let isISSNOptions: ValidatorJS.IsISSNOptions = {}; result = validator.isISSN('sample'); result = validator.isISSN('sample', isISSNOptions); result = validator.isISIN('sample'); result = validator.isISO8601('sample'); result = validator.isISO31661Alpha2('sample'); result = validator.isISRC('sample'); result = validator.isIn('sample', []); let isIntOptions: ValidatorJS.IsIntOptions = {}; result = validator.isInt('sample'); result = validator.isInt('sample', isIntOptions); result = validator.isJSON('sample'); result = validator.isLatLong('sample'); let isLengthOptions: ValidatorJS.IsLengthOptions = {}; result = validator.isLength('sample', isLengthOptions); result = validator.isLength('sample', 3); result = validator.isLength('sample', 3, 5); result = validator.isLowercase('sample'); result = validator.isMACAddress('sample'); result = validator.isMD5('sample'); result = validator.isMimeType('sample'); let isMobilePhoneOptions: ValidatorJS.IsMobilePhoneOptions = {}; result = validator.isMobilePhone('sample', 'any', isMobilePhoneOptions); result = validator.isMobilePhone('sample', 'ar-AE'); result = validator.isMobilePhone('sample', 'ar-DZ'); result = validator.isMobilePhone('sample', 'ar-EG'); result = validator.isMobilePhone('sample', 'ar-JO'); result = validator.isMobilePhone('sample', 'ar-SA'); result = validator.isMobilePhone('sample', 'ar-SY'); result = validator.isMobilePhone('sample', 'be-BY'); result = validator.isMobilePhone('sample', 'bg-BG'); result = validator.isMobilePhone('sample', 'cs-CZ'); result = validator.isMobilePhone('sample', 'de-DE'); result = validator.isMobilePhone('sample', 'da-DK'); result = validator.isMobilePhone('sample', 'el-GR'); result = validator.isMobilePhone('sample', 'en-AU'); result = validator.isMobilePhone('sample', 'en-GB'); result = validator.isMobilePhone('sample', 'en-HK'); result = validator.isMobilePhone('sample', 'en-IN'); result = validator.isMobilePhone('sample', 'en-KE'); result = validator.isMobilePhone('sample', 'en-NG'); result = validator.isMobilePhone('sample', 'en-NZ'); result = validator.isMobilePhone('sample', 'en-UG'); result = validator.isMobilePhone('sample', 'en-RW'); result = validator.isMobilePhone('sample', 'en-SG'); result = validator.isMobilePhone('sample', 'en-TZ'); result = validator.isMobilePhone('sample', 'en-PK'); result = validator.isMobilePhone('sample', 'en-US'); result = validator.isMobilePhone('sample', 'en-CA'); result = validator.isMobilePhone('sample', 'en-ZA'); result = validator.isMobilePhone('sample', 'en-ZM'); result = validator.isMobilePhone('sample', 'es-ES'); result = validator.isMobilePhone('sample', 'fa-IR'); result = validator.isMobilePhone('sample', 'fi-FI'); result = validator.isMobilePhone('sample', 'fo-FO'); result = validator.isMobilePhone('sample', 'fr-FR'); result = validator.isMobilePhone('sample', 'he-IL'); result = validator.isMobilePhone('sample', 'hu-HU'); result = validator.isMobilePhone('sample', 'id-ID'); result = validator.isMobilePhone('sample', 'it-IT'); result = validator.isMobilePhone('sample', 'ja-JP'); result = validator.isMobilePhone('sample', 'kk-KZ'); result = validator.isMobilePhone('sample', 'kl-GL'); result = validator.isMobilePhone('sample', 'ko-KR'); result = validator.isMobilePhone('sample', 'lt-LT'); result = validator.isMobilePhone('sample', 'ms-MY'); result = validator.isMobilePhone('sample', 'nb-NO'); result = validator.isMobilePhone('sample', 'nn-NO'); result = validator.isMobilePhone('sample', 'pl-PL'); result = validator.isMobilePhone('sample', 'pt-PT'); result = validator.isMobilePhone('sample', 'ro-RO'); result = validator.isMobilePhone('sample', 'ru-RU'); result = validator.isMobilePhone('sample', 'sr-RS'); result = validator.isMobilePhone('sample', 'sk-SK'); result = validator.isMobilePhone('sample', 'th-TH'); result = validator.isMobilePhone('sample', 'tr-TR'); result = validator.isMobilePhone('sample', 'uk-UA'); result = validator.isMobilePhone('sample', 'vi-VN'); result = validator.isMobilePhone('sample', 'zh-CN'); result = validator.isMobilePhone('sample', 'zh-HK'); result = validator.isMobilePhone('sample', 'zh-TW'); result = validator.isMobilePhone('sample', 'any'); result = validator.isMongoId('sample'); result = validator.isMultibyte('sample'); result = validator.isNumeric('sample'); result = validator.isNumeric('+358', { no_symbols: true }); result = validator.isPort('sample'); result = validator.isPostalCode('sample', 'AT'); result = validator.isPostalCode('sample', 'AU'); result = validator.isPostalCode('sample', 'BE'); result = validator.isPostalCode('sample', 'BG'); result = validator.isPostalCode('sample', 'CA'); result = validator.isPostalCode('sample', 'CH'); result = validator.isPostalCode('sample', 'CZ'); result = validator.isPostalCode('sample', 'DE'); result = validator.isPostalCode('sample', 'DK'); result = validator.isPostalCode('sample', 'DZ'); result = validator.isPostalCode('sample', 'ES'); result = validator.isPostalCode('sample', 'FI'); result = validator.isPostalCode('sample', 'FR'); result = validator.isPostalCode('sample', 'GB'); result = validator.isPostalCode('sample', 'GR'); result = validator.isPostalCode('sample', 'IL'); result = validator.isPostalCode('sample', 'IN'); result = validator.isPostalCode('sample', 'IS'); result = validator.isPostalCode('sample', 'IT'); result = validator.isPostalCode('sample', 'JP'); result = validator.isPostalCode('sample', 'KE'); result = validator.isPostalCode('sample', 'LI'); result = validator.isPostalCode('sample', 'MX'); result = validator.isPostalCode('sample', 'NL'); result = validator.isPostalCode('sample', 'NO'); result = validator.isPostalCode('sample', 'PL'); result = validator.isPostalCode('sample', 'PT'); result = validator.isPostalCode('sample', 'RO'); result = validator.isPostalCode('sample', 'RU'); result = validator.isPostalCode('sample', 'SA'); result = validator.isPostalCode('sample', 'SE'); result = validator.isPostalCode('sample', 'TW'); result = validator.isPostalCode('sample', 'US'); result = validator.isPostalCode('sample', 'ZA'); result = validator.isPostalCode('sample', 'ZM'); result = validator.isPostalCode('sample', 'any'); result = validator.isSurrogatePair('sample'); let isURLOptions: ValidatorJS.IsURLOptions = {}; result = validator.isURL('sample'); result = validator.isURL('sample', isURLOptions); result = validator.isUUID('sample'); result = validator.isUUID('sample', 5); result = validator.isUUID('sample', 'all'); result = validator.isUppercase('sample'); result = validator.isVariableWidth('sample'); result = validator.isWhitelisted('sample', 'abc'); result = validator.isWhitelisted('sample', ['a', 'b', 'c']); result = validator.matches('foobar', 'foo/i'); result = validator.matches('foobar', 'foo', 'i'); } // ************** // * Sanitizers * // ************** { let result: string; result = validator.blacklist('sample', 'abc'); result = validator.escape('sample'); result = validator.unescape('sample'); result = validator.ltrim('sample'); result = validator.ltrim('sample', ' '); let normalizeEmailOptions: ValidatorJS.NormalizeEmailOptions = {}; let normalizeResult: string | false; normalizeResult = validator.normalizeEmail('sample'); normalizeResult = validator.normalizeEmail('sample', normalizeEmailOptions); result = validator.rtrim('sample'); result = validator.rtrim('sample', ' '); result = validator.stripLow('sample'); result = validator.stripLow('sample', true); } { let result: boolean; result = validator.toBoolean(any); result = validator.toBoolean(any, true); } { let result: Date; result = validator.toDate(any); } { let result: number; result = validator.toFloat(any); result = validator.toInt(any); result = validator.toInt(any, 10); } { let result: string; result = validator.trim('sample'); result = validator.trim('sample', ' '); result = validator.whitelist('sample', 'abc'); } { let str: string; str = validator.toString([123, 456, '123', '456', true, false]); } { let ver: string; ver = validator.version; } // ************** // * Extensions * // ************** validator.extend<(str: string, options: {}) => boolean>('isTest', (str: any, options: {}) => !str);
types/validator/validator-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/280c65abb520b173bc39109e01b3c15242e66195
[ 0.9978284239768982, 0.09853038191795349, 0.00016393937403336167, 0.0181831456720829, 0.15626615285873413 ]
{ "id": 3, "code_window": [ " result = validator.isISO8601('sample');\n", "\n", " result = validator.isISO31661Alpha2('sample');\n", "\n", " result = validator.isISRC('sample');\n" ], "labels": [ "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " result = validator.isISO8601('sample', isISO8601Options);\n" ], "file_path": "types/validator/validator-tests.ts", "type": "add", "edit_start_line_idx": 472 }
/// Demonstrate usage in the browser's window object window.Xrm.Utility.alertDialog( "message", () => {} ); parent.Xrm.Page.context.getOrgLcid(); /// Demonstrate clientglobalcontext.d.ts function _getContext() { const errorMessage = "Context is not available."; if ( typeof GetGlobalContext !== "undefined" ) { return GetGlobalContext(); } else { if ( typeof Xrm !== "undefined" ) { return Xrm.Page.context; } else { throw new Error( errorMessage ); } } } const crmContext = _getContext(); /// Demonstrate iterator typing const grids = Xrm.Page.getControl(( control ) => { return control.getControlType() === "subgrid"; }); const selectedGridReferences: Xrm.Page.LookupValue[] = []; /// Demonstrate iterator typing with v7.1 additions grids.forEach(( gridControl: Xrm.Page.GridControl ) => { gridControl.getGrid().getSelectedRows().forEach(( row ) => { selectedGridReferences.push( row.getData().getEntity().getEntityReference() ); }); }); /// Demonstrate generic overload vs typecast const lookupAttribute = <Xrm.Page.LookupControl>Xrm.Page.getControl( "customerid" ); const lookupAttribute2 = Xrm.Page.getControl<Xrm.Page.LookupControl>( "customerid" ); /// Demonstrate ES6 String literal syntax lookupAttribute.addCustomFilter( `<filter type="and"> <condition attribute="address1_city" operator="eq" value="Redmond" /> </filter>`, "account" ); lookupAttribute.addPreSearch(() => { alert( "A search was performed." ); }); /// Demonstrate strong-typed attribute association with strong-typed control const lookupValues = lookupAttribute.getAttribute().getValue(); if ( lookupValues !== null ) if ( !lookupValues[0].id || !lookupValues[0].entityType ) throw new Error("Invalid value in Lookup control."); /// Demonstrate v7.0 BPF API if (Xrm.Page.data.process != null) Xrm.Page.data.process.moveNext(( status ) => { alert( `Process moved forward with status: ${status}` ); }); /// Demonstrate v7.1 Quick Create form Xrm.Utility.openQuickCreate(( newRecord ) => { alert( `Newly created record Id: ${newRecord.id}` ); }, "account" ); /// Make all controls visible. Xrm.Page.ui.controls.forEach(( control ) => { control.setVisible( true ); }); /// Make all tabs and sections visible. Xrm.Page.ui.tabs.forEach(( tab ) => { tab.setVisible( true ); tab.sections.forEach(( section ) => { section.setVisible( true ); }); }); /// Demonstrate OnSave event context. Xrm.Page.data.entity.addOnSave(( context ) => { const eventArgs = context.getEventArgs(); if ( eventArgs.getSaveMode() === XrmEnum.SaveMode.AutoSave || eventArgs.getSaveMode() === XrmEnum.SaveMode.SaveAndClose ) eventArgs.preventDefault(); }); /// Demonstrate ES6 String literal with templates alert( `The current form type is: ${Xrm.Page.ui.getFormType() }` ); alert( `The current entity type is: ${Xrm.Page.data.entity.getEntityName() }` ); /// Demonstrate Optionset Value as int in Turbo Forms const optionSetAttribute = Xrm.Page.getAttribute<Xrm.Page.OptionSetAttribute>( "statuscode" ); const optionValue: number = optionSetAttribute.getOptions()[0].value; /// Demonstrate Control.setFocus(); optionSetAttribute.controls.get(0).setFocus(); /// Demonstrate setFormNotification let level: Xrm.Page.ui.FormNotificationLevel; level = "ERROR"; Xrm.Page.ui.setFormNotification("Test", level, "uniqueId"); /// Demonstrate Requirement Level and Submit Mode both via string parameters and String Literal Types let requirementLevel: Xrm.Page.RequirementLevel = "none"; let requirementLevelString = "none"; let submitMode: Xrm.Page.SubmitMode = "always"; let submitModeString = "always"; let attribute = Xrm.Page.getAttribute<Xrm.Page.LookupAttribute>("customerid"); attribute.setSubmitMode(submitMode); attribute.setSubmitMode(submitMode); attribute.setRequiredLevel(requirementLevel); attribute.setRequiredLevel(requirementLevelString);
types/xrm/v7/xrm-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/280c65abb520b173bc39109e01b3c15242e66195
[ 0.00017515369108878076, 0.00017139206465799361, 0.00016784148465376347, 0.00017158433911390603, 0.000002310890295120771 ]
{ "id": 3, "code_window": [ " result = validator.isISO8601('sample');\n", "\n", " result = validator.isISO31661Alpha2('sample');\n", "\n", " result = validator.isISRC('sample');\n" ], "labels": [ "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " result = validator.isISO8601('sample', isISO8601Options);\n" ], "file_path": "types/validator/validator-tests.ts", "type": "add", "edit_start_line_idx": 472 }
import * as React from 'react'; import InfiniteScroll = require('react-infinite-scroller'); class Test1 extends React.Component { render() { return ( <InfiniteScroll loadMore={(page) => {}} > <div>Test 1</div> </InfiniteScroll> ); } } class Test2 extends React.Component { render() { return ( <InfiniteScroll loadMore={(page) => {}} element='section' hasMore initialLoad={false} isReverse pageStart={2} threshold={500} useCapture useWindow={false} > <div>Test 2</div> </InfiniteScroll> ); } } class Test3 extends React.Component { inputRef = React.createRef<HTMLDivElement>(); render() { return ( <div ref={this.inputRef}> <InfiniteScroll loadMore={(page) => {}} getScrollParent={() => this.inputRef.current} > <div>Test 3</div> </InfiniteScroll> </div> ); } } class InfiniteScrollOverride extends InfiniteScroll { getParentElement(el: HTMLElement) { if (document.getElementById("scroll-header")) { return document.getElementById("scroll-header"); } return super.getParentElement(el); } render() { return super.render(); } }
types/react-infinite-scroller/react-infinite-scroller-tests.tsx
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/280c65abb520b173bc39109e01b3c15242e66195
[ 0.00017492820916231722, 0.00017235563427675515, 0.00017031094466801733, 0.00017219236178789288, 0.0000015588293535984121 ]
{ "id": 3, "code_window": [ " result = validator.isISO8601('sample');\n", "\n", " result = validator.isISO31661Alpha2('sample');\n", "\n", " result = validator.isISRC('sample');\n" ], "labels": [ "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " result = validator.isISO8601('sample', isISO8601Options);\n" ], "file_path": "types/validator/validator-tests.ts", "type": "add", "edit_start_line_idx": 472 }
import { isSafeInteger } from "./index"; export = isSafeInteger;
types/lodash/isSafeInteger.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/280c65abb520b173bc39109e01b3c15242e66195
[ 0.0001777791912900284, 0.0001777791912900284, 0.0001777791912900284, 0.0001777791912900284, 0 ]
{ "id": 0, "code_window": [ " set: {template: '<code-example title=\"Great Example\"></code-example>'}});\n", " createComponent(oneLineCode);\n", " const actual = codeExampleDe.query(By.css('header')).nativeElement.innerText;\n", " expect(actual).toBe('Great Example');\n", " });\n", "});\n", "\n", "//// Test helpers ////\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " it('should pass hideCopy to CodeComonent', () => {\n", " TestBed.overrideComponent(HostComponent, {\n", " set: {template: '<code-example hideCopy=\"true\"></code-example>'}});\n", " createComponent(oneLineCode);\n", " expect(codeComponent.hideCopy).toBe(true);\n", " });\n" ], "file_path": "aio/src/app/embedded/code/code-example.component.spec.ts", "type": "add", "edit_start_line_idx": 67 }
/* tslint:disable component-selector */ import { Component, ElementRef, OnInit } from '@angular/core'; /** * An embeddable code block that displays nicely formatted code. * Example usage: * * ``` * <code-example language="ts" linenums="2" class="special" title="Do Stuff"> * // a code block * console.log('do stuff'); * </code-example> * ``` */ @Component({ selector: 'code-example', template: ` <header *ngIf="title">{{title}}</header> <aio-code [ngClass]="{'headed-code':title, 'simple-code':!title}" [code]="code" [language]="language" [linenums]="linenums" [path]="path" [region]="region"></aio-code> ` }) export class CodeExampleComponent implements OnInit { code: string; language: string; linenums: boolean | number; path: string; region: string; title: string; constructor(private elementRef: ElementRef) { const element = this.elementRef.nativeElement; this.language = element.getAttribute('language') || ''; this.linenums = element.getAttribute('linenums'); this.path = element.getAttribute('path') || ''; this.region = element.getAttribute('region') || ''; this.title = element.getAttribute('title') || ''; } ngOnInit() { // The `codeExampleContent` property is set by the DocViewer when it builds this component. // It is the original innerHTML of the host element. this.code = this.elementRef.nativeElement.codeExampleContent; } }
aio/src/app/embedded/code/code-example.component.ts
1
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.0018566648941487074, 0.0005041375989094377, 0.00016397172294091433, 0.00016684182628523558, 0.0006762652774341404 ]
{ "id": 0, "code_window": [ " set: {template: '<code-example title=\"Great Example\"></code-example>'}});\n", " createComponent(oneLineCode);\n", " const actual = codeExampleDe.query(By.css('header')).nativeElement.innerText;\n", " expect(actual).toBe('Great Example');\n", " });\n", "});\n", "\n", "//// Test helpers ////\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " it('should pass hideCopy to CodeComonent', () => {\n", " TestBed.overrideComponent(HostComponent, {\n", " set: {template: '<code-example hideCopy=\"true\"></code-example>'}});\n", " createComponent(oneLineCode);\n", " expect(codeComponent.hideCopy).toBe(true);\n", " });\n" ], "file_path": "aio/src/app/embedded/code/code-example.component.spec.ts", "type": "add", "edit_start_line_idx": 67 }
{ "maxLength": 100, "types": [ "build", "ci", "docs", "feat", "fix", "perf", "refactor", "style", "test" ], "scopes": [ "aio", "animations", "benchpress", "common", "compiler", "compiler-cli", "core", "forms", "http", "language-service", "platform-browser", "platform-browser-dynamic", "platform-server", "platform-webworker", "platform-webworker-dynamic", "router", "upgrade", "tsc-wrapped", "packaging", "changelog" ] }
tools/validate-commit-message/commit-message.json
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.0001776260178303346, 0.00017637948621995747, 0.00017483516421634704, 0.00017652839596848935, 0.0000010075000318465754 ]
{ "id": 0, "code_window": [ " set: {template: '<code-example title=\"Great Example\"></code-example>'}});\n", " createComponent(oneLineCode);\n", " const actual = codeExampleDe.query(By.css('header')).nativeElement.innerText;\n", " expect(actual).toBe('Great Example');\n", " });\n", "});\n", "\n", "//// Test helpers ////\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " it('should pass hideCopy to CodeComonent', () => {\n", " TestBed.overrideComponent(HostComponent, {\n", " set: {template: '<code-example hideCopy=\"true\"></code-example>'}});\n", " createComponent(oneLineCode);\n", " expect(codeComponent.hideCopy).toBe(true);\n", " });\n" ], "file_path": "aio/src/app/embedded/code/code-example.component.spec.ts", "type": "add", "edit_start_line_idx": 67 }
/** * Render markdown code blocks as `<code-example>` tags */ module.exports = function code(h, node) { var value = node.value ? ('\n' + node.value + '\n') : ''; var lang = node.lang && node.lang.match(/^[^ \t]+(?=[ \t]|$)/); var props = {}; if (lang) { props.language = lang; } return h(node, 'code-example', props, [{ type: 'text', value }]); };
aio/tools/transforms/remark-package/services/handlers/code.js
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.0001704501628410071, 0.00016972798039205372, 0.0001690057833911851, 0.00016972798039205372, 7.221897249110043e-7 ]
{ "id": 0, "code_window": [ " set: {template: '<code-example title=\"Great Example\"></code-example>'}});\n", " createComponent(oneLineCode);\n", " const actual = codeExampleDe.query(By.css('header')).nativeElement.innerText;\n", " expect(actual).toBe('Great Example');\n", " });\n", "});\n", "\n", "//// Test helpers ////\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " it('should pass hideCopy to CodeComonent', () => {\n", " TestBed.overrideComponent(HostComponent, {\n", " set: {template: '<code-example hideCopy=\"true\"></code-example>'}});\n", " createComponent(oneLineCode);\n", " expect(codeComponent.hideCopy).toBe(true);\n", " });\n" ], "file_path": "aio/src/app/embedded/code/code-example.component.spec.ts", "type": "add", "edit_start_line_idx": 67 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {verifyNoBrowserErrors} from '@angular/testing/src/e2e_util'; import {runClickBenchmark} from '@angular/testing/src/perf_util'; describe('ng2 naive infinite scroll benchmark', function() { const URL = 'benchmarks/src/naive_infinite_scroll/index.html?appSize=3'; afterEach(verifyNoBrowserErrors); it('should not throw errors', function() { browser.get(URL); const expectedRowCount = 18; const expectedCellsPerRow = 27; const allScrollItems = 'scroll-app #testArea scroll-item'; const cells = `${ allScrollItems } .row *`; const stageButtons = `${ allScrollItems } .row stage-buttons button`; const count = function(selector) { return browser.executeScript( `return ` + `document.querySelectorAll("${ selector }").length;`); }; const clickFirstOf = function(selector) { return browser.executeScript(`document.querySelector("${ selector }").click();`); }; const firstTextOf = function(selector) { return browser.executeScript( `return ` + `document.querySelector("${ selector }").innerText;`); }; // Make sure rows are rendered count(allScrollItems).then(function(c) { expect(c).toEqual(expectedRowCount); }); // Make sure cells are rendered count(cells).then(function(c) { expect(c).toEqual(expectedRowCount * expectedCellsPerRow); }); // Click on first enabled button and verify stage changes firstTextOf(`${ stageButtons }:enabled`).then(function(text) { expect(text).toEqual('Pitched'); clickFirstOf(`${ stageButtons }:enabled`).then(function() { firstTextOf(`${ stageButtons }:enabled`).then((text) => expect(text).toEqual('Won')); }); }); $('#reset-btn').click(); $('#run-btn').click(); browser.wait(() => { return $('#done').getText().then(function() { return true; }, function() { return false; }); }, 10000); }); });
modules/benchmarks/e2e_test/old/naive_infinite_scroll_spec.ts
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.00017983686120714992, 0.00017722396296449006, 0.00017161702271550894, 0.0001782213366823271, 0.000002560216898928047 ]
{ "id": 1, "code_window": [ " @Input() code = '';\n", " @Input() language: string;\n", " @Input() linenums: boolean | number;\n", " @Input() path: string;\n", " @Input() region: string;\n", "\n", " get someCode() {\n", " return this.code && this.code.length > 30 ? this.code.substr(0, 30) + '...' : this.code;\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " @Input() hideCopy: boolean;\n" ], "file_path": "aio/src/app/embedded/code/code-example.component.spec.ts", "type": "add", "edit_start_line_idx": 85 }
/* tslint:disable:no-unused-variable */ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { Component, DebugElement } from '@angular/core'; import { MdSnackBarModule, MdSnackBar } from '@angular/material'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { CodeComponent } from './code.component'; import { CopierService } from 'app/shared//copier.service'; import { Logger } from 'app/shared/logger.service'; import { PrettyPrinter } from './pretty-printer.service'; const oneLineCode = 'const foo = "bar";'; const smallMultiLineCode = ` &lt;hero-details&gt; &lt;h2&gt;Bah Dah Bing&lt;/h2&gt; &lt;hero-team&gt; &lt;h3&gt;NYC Team&lt;/h3&gt; &lt;/hero-team&gt; &lt;/hero-details&gt;`; const bigMultiLineCode = smallMultiLineCode + smallMultiLineCode + smallMultiLineCode; describe('CodeComponent', () => { let codeComponentDe: DebugElement; let codeComponent: CodeComponent; let hostComponent: HostComponent; let fixture: ComponentFixture<HostComponent>; // WARNING: Chance of cross-test pollution // CodeComponent injects PrettyPrintService // Once PrettyPrintService runs once _anywhere_, its ctor loads `prettify.js` // which sets `window['prettyPrintOne']` // That global survives these tests unless // we take strict measures to wipe it out in the `afterAll` // and make sure THAT runs after the tests by making component creation async afterAll(() => { delete window['prettyPrint']; delete window['prettyPrintOne']; }); beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ MdSnackBarModule, NoopAnimationsModule ], declarations: [ CodeComponent, HostComponent ], providers: [ PrettyPrinter, CopierService, {provide: Logger, useClass: TestLogger } ] }) .compileComponents(); })); // Must be async because // CodeComponent creates PrettyPrintService which async loads `prettify.js`. // If not async, `afterAll` finishes before tests do! beforeEach(async(() => { fixture = TestBed.createComponent(HostComponent); hostComponent = fixture.componentInstance; codeComponentDe = fixture.debugElement.children[0]; codeComponent = codeComponentDe.componentInstance; fixture.detectChanges(); })); it('should create CodeComponent', () => { expect(codeComponentDe.name).toBe('aio-code', 'selector'); expect(codeComponent).toBeTruthy('CodeComponent'); }); describe('pretty printing', () => { it('should format a one-line code sample', () => { // 'pln' spans are a tell-tale for syntax highlighing const spans = codeComponentDe.nativeElement.querySelectorAll('span.pln'); expect(spans.length).toBeGreaterThan(0, 'formatted spans'); }); function hasLineNumbers() { // presence of `<li>`s are a tell-tale for line numbers return 0 < codeComponentDe.nativeElement.querySelectorAll('li').length; } it('should format a one-line code sample without linenums by default', () => { expect(hasLineNumbers()).toBe(false); }); it('should add line numbers to one-line code sample when linenums set true', () => { hostComponent.linenums = 'true'; fixture.detectChanges(); expect(hasLineNumbers()).toBe(true); }); it('should format a small multi-line code without linenums by default', () => { hostComponent.code = smallMultiLineCode; fixture.detectChanges(); expect(hasLineNumbers()).toBe(false); }); it('should add line numbers to a big multi-line code by default', () => { hostComponent.code = bigMultiLineCode; fixture.detectChanges(); expect(hasLineNumbers()).toBe(true); }); it('should format big multi-line code without linenums when linenums set false', () => { hostComponent.linenums = false; hostComponent.code = bigMultiLineCode; fixture.detectChanges(); expect(hasLineNumbers()).toBe(false); }); }); describe('whitespace handling', () => { it('should remove common indentation from the code before rendering', () => { hostComponent.linenums = false; hostComponent.code = ' abc\n let x = text.split(\'\\n\');\n ghi\n\n jkl\n'; fixture.detectChanges(); const codeContent = codeComponentDe.nativeElement.querySelector('code').innerText; expect(codeContent).toEqual('abc\n let x = text.split(\'\\n\');\nghi\n\njkl'); }); it('should trim whitespace from the code before rendering', () => { hostComponent.linenums = false; hostComponent.code = '\n\n\n' + smallMultiLineCode + '\n\n\n'; fixture.detectChanges(); const codeContent = codeComponentDe.nativeElement.querySelector('code').innerText; expect(codeContent).toEqual(codeContent.trim()); }); it('should trim whitespace from code before computing whether to format linenums', () => { hostComponent.code = '\n\n\n' + hostComponent.code + '\n\n\n'; fixture.detectChanges(); // `<li>`s are a tell-tale for line numbers const lis = codeComponentDe.nativeElement.querySelectorAll('li'); expect(lis.length).toBe(0, 'should be no linenums'); }); }); describe('error message', () => { function getErrorMessage() { const missing: HTMLElement = codeComponentDe.nativeElement.querySelector('.code-missing'); return missing ? missing.innerText : null; } it('should not display "code-missing" class when there is some code', () => { fixture.detectChanges(); expect(getErrorMessage()).toBeNull('should not have element with "code-missing" class'); }); it('should display error message when there is no code (after trimming)', () => { hostComponent.code = ' \n '; fixture.detectChanges(); expect(getErrorMessage()).toContain('missing'); }); it('should show path and region in missing-code error message', () => { hostComponent.code = ' \n '; hostComponent.path = 'fizz/buzz/foo.html'; hostComponent.region = 'something'; fixture.detectChanges(); expect(getErrorMessage()).toMatch(/for[\s\S]fizz\/buzz\/foo\.html#something$/); }); it('should show path only in missing-code error message when no region', () => { hostComponent.code = ' \n '; hostComponent.path = 'fizz/buzz/foo.html'; fixture.detectChanges(); expect(getErrorMessage()).toMatch(/for[\s\S]fizz\/buzz\/foo\.html$/); }); it('should show simple missing-code error message when no path/region', () => { hostComponent.code = ' \n '; fixture.detectChanges(); expect(getErrorMessage()).toMatch(/missing.$/); }); }); describe('copy button', () => { it('should call copier service when clicked', () => { const copierService: CopierService = TestBed.get(CopierService); const spy = spyOn(copierService, 'copyText'); const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement; expect(spy.calls.count()).toBe(0, 'before click'); button.click(); expect(spy.calls.count()).toBe(1, 'after click'); }); it('should copy code text when clicked', () => { const copierService: CopierService = TestBed.get(CopierService); const spy = spyOn(copierService, 'copyText'); const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement; button.click(); expect(spy.calls.argsFor(0)[0]).toEqual(oneLineCode, 'after click'); }); it('should display a message when copy succeeds', () => { const snackBar: MdSnackBar = TestBed.get(MdSnackBar); const copierService: CopierService = TestBed.get(CopierService); spyOn(snackBar, 'open'); spyOn(copierService, 'copyText').and.returnValue(true); const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement; button.click(); expect(snackBar.open).toHaveBeenCalledWith('Code Copied', '', { duration: 800 }); }); it('should display an error when copy fails', () => { const snackBar: MdSnackBar = TestBed.get(MdSnackBar); const copierService: CopierService = TestBed.get(CopierService); spyOn(snackBar, 'open'); spyOn(copierService, 'copyText').and.returnValue(false); const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement; button.click(); expect(snackBar.open).toHaveBeenCalledWith('Copy failed. Please try again!', '', { duration: 800 }); }); }); }); //// Test helpers //// // tslint:disable:member-ordering @Component({ selector: 'aio-host-comp', template: ` <aio-code md-no-ink [code]="code" [language]="language" [linenums]="linenums" [path]="path" [region]="region"></aio-code> ` }) class HostComponent { code = oneLineCode; language: string; linenums: boolean | number | string; path: string; region: string; } class TestLogger { log = jasmine.createSpy('log'); error = jasmine.createSpy('error'); }
aio/src/app/embedded/code/code.component.spec.ts
1
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.014649276621639729, 0.0007665505982004106, 0.0001658903347561136, 0.00017284657224081457, 0.002834498882293701 ]
{ "id": 1, "code_window": [ " @Input() code = '';\n", " @Input() language: string;\n", " @Input() linenums: boolean | number;\n", " @Input() path: string;\n", " @Input() region: string;\n", "\n", " get someCode() {\n", " return this.code && this.code.length > 30 ? this.code.substr(0, 30) + '...' : this.code;\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " @Input() hideCopy: boolean;\n" ], "file_path": "aio/src/app/embedded/code/code-example.component.spec.ts", "type": "add", "edit_start_line_idx": 85 }
const rehype = require('rehype'); /** * @dgProcessor postProcessHtml * * @description * Use the rehype processing engine to manipulate the * `renderedContent` HTML via rehype "plugins" that work with HTML ASTs (HASTs). * See https://github.com/wooorm/rehype * * Each plugin is a factory function that will be called with the "rehype" engine as `this`. * The factory should return a "transform" function that takes a HAST and returns a `boolean` or `undefined`. * The HAST can be mutated by the "transform" function. * If `false` is returned then the processing stops with that plugin. * * @property docTypes {string[]} the `docTypes` of docs that should be post-processed * @property plugins {Function[]} the rehype plugins that will modify the HAST. * */ module.exports = function postProcessHtml(log, createDocMessage) { return { $runAfter: ['docs-rendered'], $runBefore: ['writing-files'], docTypes: [], plugins: [], $process(docs) { const engine = rehype() .data('settings', { fragment: true }); this.plugins.forEach(plugin => engine.use(plugin)); docs .filter(doc => this.docTypes.indexOf(doc.docType) !== -1) .forEach(doc => { const vFile = engine.processSync(doc.renderedContent); vFile.messages.forEach(m => { const message = createDocMessage(m.message, doc); if (m.fatal) { throw new Error(message); } else { log.warn(message); } }); doc.renderedContent = vFile.contents; }); } }; };
aio/tools/transforms/post-process-package/processors/post-process-html.js
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.00017847471463028342, 0.00017387889965903014, 0.000169243648997508, 0.00017514851060695946, 0.000003264902716182405 ]
{ "id": 1, "code_window": [ " @Input() code = '';\n", " @Input() language: string;\n", " @Input() linenums: boolean | number;\n", " @Input() path: string;\n", " @Input() region: string;\n", "\n", " get someCode() {\n", " return this.code && this.code.length > 30 ? this.code.substr(0, 30) + '...' : this.code;\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " @Input() hideCopy: boolean;\n" ], "file_path": "aio/src/app/embedded/code/code-example.component.spec.ts", "type": "add", "edit_start_line_idx": 85 }
<div *ngIf="hasToc" [class.closed]="isClosed"> <div *ngIf="!hasSecondary" class="toc-heading">Contents</div> <div *ngIf="hasSecondary" class="toc-heading secondary" (click)="toggle()" title="Expand/collapse contents" aria-label="Expand/collapse contents"> Contents <button type="button" class="toc-show-all material-icons" [class.closed]="isClosed"> </button> </div> <ul class="toc-list"> <li *ngFor="let toc of tocList" title="{{toc.title}}" class="{{toc.level}}" [class.secondary]="toc.isSecondary"> <a [href]="toc.href" [innerHTML]="toc.content"></a> </li> </ul> <button type="button" (click)="toggle()" *ngIf="hasSecondary" class="toc-more-items material-icons" [class.closed]="isClosed" title="Expand/collapse contents" aria-label="Expand/collapse contents"> </button> </div>
aio/src/app/embedded/toc/toc.component.html
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.00017523705901112407, 0.0001741395826684311, 0.00017268875672016293, 0.00017449291772209108, 0.0000010699214954001945 ]
{ "id": 1, "code_window": [ " @Input() code = '';\n", " @Input() language: string;\n", " @Input() linenums: boolean | number;\n", " @Input() path: string;\n", " @Input() region: string;\n", "\n", " get someCode() {\n", " return this.code && this.code.length > 30 ? this.code.substr(0, 30) + '...' : this.code;\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " @Input() hideCopy: boolean;\n" ], "file_path": "aio/src/app/embedded/code/code-example.component.spec.ts", "type": "add", "edit_start_line_idx": 85 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ (function(global: any) { writeScriptTag('/all/playground/vendor/core.js'); writeScriptTag('/all/playground/vendor/zone.js'); writeScriptTag('/all/playground/vendor/long-stack-trace-zone.js'); writeScriptTag('/all/playground/vendor/system.src.js'); writeScriptTag('/all/playground/vendor/Reflect.js', 'playgroundBootstrap()'); global.playgroundBootstrap = playgroundBootstrap; function playgroundBootstrap() { // check query param const useBundles = location.search.indexOf('bundles=false') == -1; if (useBundles) { System.config({ map: { 'index': 'index.js', '@angular/common': '/packages-dist/common/bundles/common.umd.js', '@angular/animations': '/packages-dist/animation/bundles/animations.umd.js', '@angular/platform-browser/animations': '/packages-dist/platform-browser/animations/bundles/platform-browser-animations.umd.js', '@angular/compiler': '/packages-dist/compiler/bundles/compiler.umd.js', '@angular/core': '/packages-dist/core/bundles/core.umd.js', '@angular/forms': '/packages-dist/forms/bundles/forms.umd.js', '@angular/http': '/packages-dist/http/bundles/http.umd.js', '@angular/platform-browser': '/packages-dist/platform-browser/bundles/platform-browser.umd.js', '@angular/platform-browser-dynamic': '/packages-dist/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js', '@angular/platform-webworker': '/packages-dist/platform-webworker/bundles/platform-webworker.umd.js', '@angular/platform-webworker-dynamic': '/packages-dist/platform-webworker-dynamic/bundles/platform-webworker-dynamic.umd.js', '@angular/router': '/packages-dist/router/bundles/router.umd.js', '@angular/upgrade': '/packages-dist/upgrade/bundles/upgrade.umd.js', '@angular/upgrade/static': '/packages-dist/upgrade/bundles/upgrade-static.umd.js', 'rxjs': '/all/playground/vendor/rxjs', }, packages: { 'app': {defaultExtension: 'js'}, 'rxjs': {defaultExtension: 'js'}, } }); } else { console.warn( 'Not using the Angular bundles. Don\'t use this configuration for e2e/performance tests!'); System.config({ map: { 'index': 'index.js', '@angular': '/all/@angular', 'rxjs': '/all/playground/vendor/rxjs' }, packages: { 'app': {defaultExtension: 'js'}, '@angular/common': {main: 'index.js', defaultExtension: 'js'}, '@angular/animations': {main: 'index.js', defaultExtension: 'js'}, '@angular/compiler': {main: 'index.js', defaultExtension: 'js'}, '@angular/core': {main: 'index.js', defaultExtension: 'js'}, '@angular/forms': {main: 'index.js', defaultExtension: 'js'}, '@angular/http': {main: 'index.js', defaultExtension: 'js'}, '@angular/platform-browser': {main: 'index.js', defaultExtension: 'js'}, '@angular/platform-browser-dynamic': {main: 'index.js', defaultExtension: 'js'}, '@angular/platform-webworker': {main: 'index.js', defaultExtension: 'js'}, '@angular/platform-webworker-dynamic': {main: 'index.js', defaultExtension: 'js'}, '@angular/router': {main: 'index.js', defaultExtension: 'js'}, '@angular/upgrade': {main: 'index.js', defaultExtension: 'js'}, 'rxjs': {defaultExtension: 'js'} } }); } // BOOTSTRAP the app! System.import('index').then(function(m: {main: Function}) { m.main(); }, console.error.bind(console)); } function writeScriptTag(scriptUrl: string, onload?: string) { document.write(`<script src="${scriptUrl}" onload="${onload}"></script>`); } }(window));
modules/playground/src/bootstrap.ts
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.00017747418314684182, 0.0001744417386362329, 0.00016716413665562868, 0.00017530826153233647, 0.0000027651294658426195 ]
{ "id": 2, "code_window": [ "@Component({\n", " selector: 'code-example',\n", " template: `\n", " <header *ngIf=\"title\">{{title}}</header>\n", " <aio-code [ngClass]=\"{'headed-code':title, 'simple-code':!title}\" [code]=\"code\"\n", " [language]=\"language\" [linenums]=\"linenums\" [path]=\"path\" [region]=\"region\"></aio-code>\n", " `\n", "})\n", "export class CodeExampleComponent implements OnInit {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " [language]=\"language\" [linenums]=\"linenums\" [path]=\"path\" [region]=\"region\" [hideCopy]=\"hideCopy\"></aio-code>\n" ], "file_path": "aio/src/app/embedded/code/code-example.component.ts", "type": "replace", "edit_start_line_idx": 19 }
/* tslint:disable:no-unused-variable */ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { Component, DebugElement } from '@angular/core'; import { MdSnackBarModule, MdSnackBar } from '@angular/material'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { CodeComponent } from './code.component'; import { CopierService } from 'app/shared//copier.service'; import { Logger } from 'app/shared/logger.service'; import { PrettyPrinter } from './pretty-printer.service'; const oneLineCode = 'const foo = "bar";'; const smallMultiLineCode = ` &lt;hero-details&gt; &lt;h2&gt;Bah Dah Bing&lt;/h2&gt; &lt;hero-team&gt; &lt;h3&gt;NYC Team&lt;/h3&gt; &lt;/hero-team&gt; &lt;/hero-details&gt;`; const bigMultiLineCode = smallMultiLineCode + smallMultiLineCode + smallMultiLineCode; describe('CodeComponent', () => { let codeComponentDe: DebugElement; let codeComponent: CodeComponent; let hostComponent: HostComponent; let fixture: ComponentFixture<HostComponent>; // WARNING: Chance of cross-test pollution // CodeComponent injects PrettyPrintService // Once PrettyPrintService runs once _anywhere_, its ctor loads `prettify.js` // which sets `window['prettyPrintOne']` // That global survives these tests unless // we take strict measures to wipe it out in the `afterAll` // and make sure THAT runs after the tests by making component creation async afterAll(() => { delete window['prettyPrint']; delete window['prettyPrintOne']; }); beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ MdSnackBarModule, NoopAnimationsModule ], declarations: [ CodeComponent, HostComponent ], providers: [ PrettyPrinter, CopierService, {provide: Logger, useClass: TestLogger } ] }) .compileComponents(); })); // Must be async because // CodeComponent creates PrettyPrintService which async loads `prettify.js`. // If not async, `afterAll` finishes before tests do! beforeEach(async(() => { fixture = TestBed.createComponent(HostComponent); hostComponent = fixture.componentInstance; codeComponentDe = fixture.debugElement.children[0]; codeComponent = codeComponentDe.componentInstance; fixture.detectChanges(); })); it('should create CodeComponent', () => { expect(codeComponentDe.name).toBe('aio-code', 'selector'); expect(codeComponent).toBeTruthy('CodeComponent'); }); describe('pretty printing', () => { it('should format a one-line code sample', () => { // 'pln' spans are a tell-tale for syntax highlighing const spans = codeComponentDe.nativeElement.querySelectorAll('span.pln'); expect(spans.length).toBeGreaterThan(0, 'formatted spans'); }); function hasLineNumbers() { // presence of `<li>`s are a tell-tale for line numbers return 0 < codeComponentDe.nativeElement.querySelectorAll('li').length; } it('should format a one-line code sample without linenums by default', () => { expect(hasLineNumbers()).toBe(false); }); it('should add line numbers to one-line code sample when linenums set true', () => { hostComponent.linenums = 'true'; fixture.detectChanges(); expect(hasLineNumbers()).toBe(true); }); it('should format a small multi-line code without linenums by default', () => { hostComponent.code = smallMultiLineCode; fixture.detectChanges(); expect(hasLineNumbers()).toBe(false); }); it('should add line numbers to a big multi-line code by default', () => { hostComponent.code = bigMultiLineCode; fixture.detectChanges(); expect(hasLineNumbers()).toBe(true); }); it('should format big multi-line code without linenums when linenums set false', () => { hostComponent.linenums = false; hostComponent.code = bigMultiLineCode; fixture.detectChanges(); expect(hasLineNumbers()).toBe(false); }); }); describe('whitespace handling', () => { it('should remove common indentation from the code before rendering', () => { hostComponent.linenums = false; hostComponent.code = ' abc\n let x = text.split(\'\\n\');\n ghi\n\n jkl\n'; fixture.detectChanges(); const codeContent = codeComponentDe.nativeElement.querySelector('code').innerText; expect(codeContent).toEqual('abc\n let x = text.split(\'\\n\');\nghi\n\njkl'); }); it('should trim whitespace from the code before rendering', () => { hostComponent.linenums = false; hostComponent.code = '\n\n\n' + smallMultiLineCode + '\n\n\n'; fixture.detectChanges(); const codeContent = codeComponentDe.nativeElement.querySelector('code').innerText; expect(codeContent).toEqual(codeContent.trim()); }); it('should trim whitespace from code before computing whether to format linenums', () => { hostComponent.code = '\n\n\n' + hostComponent.code + '\n\n\n'; fixture.detectChanges(); // `<li>`s are a tell-tale for line numbers const lis = codeComponentDe.nativeElement.querySelectorAll('li'); expect(lis.length).toBe(0, 'should be no linenums'); }); }); describe('error message', () => { function getErrorMessage() { const missing: HTMLElement = codeComponentDe.nativeElement.querySelector('.code-missing'); return missing ? missing.innerText : null; } it('should not display "code-missing" class when there is some code', () => { fixture.detectChanges(); expect(getErrorMessage()).toBeNull('should not have element with "code-missing" class'); }); it('should display error message when there is no code (after trimming)', () => { hostComponent.code = ' \n '; fixture.detectChanges(); expect(getErrorMessage()).toContain('missing'); }); it('should show path and region in missing-code error message', () => { hostComponent.code = ' \n '; hostComponent.path = 'fizz/buzz/foo.html'; hostComponent.region = 'something'; fixture.detectChanges(); expect(getErrorMessage()).toMatch(/for[\s\S]fizz\/buzz\/foo\.html#something$/); }); it('should show path only in missing-code error message when no region', () => { hostComponent.code = ' \n '; hostComponent.path = 'fizz/buzz/foo.html'; fixture.detectChanges(); expect(getErrorMessage()).toMatch(/for[\s\S]fizz\/buzz\/foo\.html$/); }); it('should show simple missing-code error message when no path/region', () => { hostComponent.code = ' \n '; fixture.detectChanges(); expect(getErrorMessage()).toMatch(/missing.$/); }); }); describe('copy button', () => { it('should call copier service when clicked', () => { const copierService: CopierService = TestBed.get(CopierService); const spy = spyOn(copierService, 'copyText'); const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement; expect(spy.calls.count()).toBe(0, 'before click'); button.click(); expect(spy.calls.count()).toBe(1, 'after click'); }); it('should copy code text when clicked', () => { const copierService: CopierService = TestBed.get(CopierService); const spy = spyOn(copierService, 'copyText'); const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement; button.click(); expect(spy.calls.argsFor(0)[0]).toEqual(oneLineCode, 'after click'); }); it('should display a message when copy succeeds', () => { const snackBar: MdSnackBar = TestBed.get(MdSnackBar); const copierService: CopierService = TestBed.get(CopierService); spyOn(snackBar, 'open'); spyOn(copierService, 'copyText').and.returnValue(true); const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement; button.click(); expect(snackBar.open).toHaveBeenCalledWith('Code Copied', '', { duration: 800 }); }); it('should display an error when copy fails', () => { const snackBar: MdSnackBar = TestBed.get(MdSnackBar); const copierService: CopierService = TestBed.get(CopierService); spyOn(snackBar, 'open'); spyOn(copierService, 'copyText').and.returnValue(false); const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement; button.click(); expect(snackBar.open).toHaveBeenCalledWith('Copy failed. Please try again!', '', { duration: 800 }); }); }); }); //// Test helpers //// // tslint:disable:member-ordering @Component({ selector: 'aio-host-comp', template: ` <aio-code md-no-ink [code]="code" [language]="language" [linenums]="linenums" [path]="path" [region]="region"></aio-code> ` }) class HostComponent { code = oneLineCode; language: string; linenums: boolean | number | string; path: string; region: string; } class TestLogger { log = jasmine.createSpy('log'); error = jasmine.createSpy('error'); }
aio/src/app/embedded/code/code.component.spec.ts
1
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.00048303292714990675, 0.0002060588012682274, 0.000165175020811148, 0.00017179138376377523, 0.00007522311352659017 ]
{ "id": 2, "code_window": [ "@Component({\n", " selector: 'code-example',\n", " template: `\n", " <header *ngIf=\"title\">{{title}}</header>\n", " <aio-code [ngClass]=\"{'headed-code':title, 'simple-code':!title}\" [code]=\"code\"\n", " [language]=\"language\" [linenums]=\"linenums\" [path]=\"path\" [region]=\"region\"></aio-code>\n", " `\n", "})\n", "export class CodeExampleComponent implements OnInit {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " [language]=\"language\" [linenums]=\"linenums\" [path]=\"path\" [region]=\"region\" [hideCopy]=\"hideCopy\"></aio-code>\n" ], "file_path": "aio/src/app/embedded/code/code-example.component.ts", "type": "replace", "edit_start_line_idx": 19 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ApplicationRef, NgModuleRef} from '@angular/core'; import {bindAction, profile} from '../../util'; import {buildTree, emptyTree} from '../util'; import {AppModule, TreeComponent} from './tree'; export function init(moduleRef: NgModuleRef<AppModule>) { let tree: TreeComponent; let appRef: ApplicationRef; let detectChangesRuns = 0; function destroyDom() { tree.data = emptyTree; appRef.tick(); } function createDom() { tree.data = buildTree(); appRef.tick(); } function detectChanges() { for (let i = 0; i < 10; i++) { appRef.tick(); } detectChangesRuns += 10; numberOfChecksEl.textContent = `${detectChangesRuns}`; } function noop() {} const injector = moduleRef.injector; appRef = injector.get(ApplicationRef); const numberOfChecksEl = document.getElementById('numberOfChecks') !; tree = appRef.components[0].instance; bindAction('#destroyDom', destroyDom); bindAction('#createDom', createDom); bindAction('#detectChanges', detectChanges); bindAction('#detectChangesProfile', profile(detectChanges, noop, 'detectChanges')); bindAction('#updateDomProfile', profile(createDom, noop, 'update')); bindAction('#createDomProfile', profile(createDom, destroyDom, 'create')); }
modules/benchmarks/src/tree/ng2/init.ts
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.00017472483159508556, 0.00017262955952901393, 0.00016820948803797364, 0.00017294345889240503, 0.0000021720661607105285 ]
{ "id": 2, "code_window": [ "@Component({\n", " selector: 'code-example',\n", " template: `\n", " <header *ngIf=\"title\">{{title}}</header>\n", " <aio-code [ngClass]=\"{'headed-code':title, 'simple-code':!title}\" [code]=\"code\"\n", " [language]=\"language\" [linenums]=\"linenums\" [path]=\"path\" [region]=\"region\"></aio-code>\n", " `\n", "})\n", "export class CodeExampleComponent implements OnInit {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " [language]=\"language\" [linenums]=\"linenums\" [path]=\"path\" [region]=\"region\" [hideCopy]=\"hideCopy\"></aio-code>\n" ], "file_path": "aio/src/app/embedded/code/code-example.component.ts", "type": "replace", "edit_start_line_idx": 19 }
{ "name": "2.3", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "typescript": "2.3.0" } }
integration/language_service_plugin/typescripts/2.3/package.json
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.0001688844640739262, 0.00016718462575227022, 0.00016548478743061423, 0.00016718462575227022, 0.0000016998383216559887 ]
{ "id": 2, "code_window": [ "@Component({\n", " selector: 'code-example',\n", " template: `\n", " <header *ngIf=\"title\">{{title}}</header>\n", " <aio-code [ngClass]=\"{'headed-code':title, 'simple-code':!title}\" [code]=\"code\"\n", " [language]=\"language\" [linenums]=\"linenums\" [path]=\"path\" [region]=\"region\"></aio-code>\n", " `\n", "})\n", "export class CodeExampleComponent implements OnInit {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " [language]=\"language\" [linenums]=\"linenums\" [path]=\"path\" [region]=\"region\" [hideCopy]=\"hideCopy\"></aio-code>\n" ], "file_path": "aio/src/app/embedded/code/code-example.component.ts", "type": "replace", "edit_start_line_idx": 19 }
/* #docregion */ [class*='col-'] { float: left; padding-right: 20px; padding-bottom: 20px; } [class*='col-']:last-of-type { padding-right: 0; } a { text-decoration: none; } *, *:after, *:before { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } h3 { text-align: center; margin-bottom: 0; } h4 { position: relative; } .grid { margin: 0; } .col-1-4 { width: 25%; } .module { padding: 20px; text-align: center; color: #eee; max-height: 120px; min-width: 120px; background-color: #607D8B; border-radius: 2px; } .module:hover { background-color: #EEE; cursor: pointer; color: #607d8b; } .grid-pad { padding: 10px 0; } .grid-pad > [class*='col-']:last-of-type { padding-right: 20px; } @media (max-width: 600px) { .module { font-size: 10px; max-height: 75px; } } @media (max-width: 1024px) { .grid { margin: 0; } .module { min-width: 60px; } }
aio/content/examples/universal/src/app/dashboard.component.css
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.00017415831098333, 0.0001710777432890609, 0.00016680841508787125, 0.00017200561705976725, 0.000002454173454680131 ]
{ "id": 3, "code_window": [ " language: string;\n", " linenums: boolean | number;\n", " path: string;\n", " region: string;\n", " title: string;\n", "\n", " constructor(private elementRef: ElementRef) {\n", " const element = this.elementRef.nativeElement;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " hideCopy: boolean;\n" ], "file_path": "aio/src/app/embedded/code/code-example.component.ts", "type": "add", "edit_start_line_idx": 30 }
/* tslint:disable:no-unused-variable */ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { Component, DebugElement } from '@angular/core'; import { MdSnackBarModule, MdSnackBar } from '@angular/material'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { CodeComponent } from './code.component'; import { CopierService } from 'app/shared//copier.service'; import { Logger } from 'app/shared/logger.service'; import { PrettyPrinter } from './pretty-printer.service'; const oneLineCode = 'const foo = "bar";'; const smallMultiLineCode = ` &lt;hero-details&gt; &lt;h2&gt;Bah Dah Bing&lt;/h2&gt; &lt;hero-team&gt; &lt;h3&gt;NYC Team&lt;/h3&gt; &lt;/hero-team&gt; &lt;/hero-details&gt;`; const bigMultiLineCode = smallMultiLineCode + smallMultiLineCode + smallMultiLineCode; describe('CodeComponent', () => { let codeComponentDe: DebugElement; let codeComponent: CodeComponent; let hostComponent: HostComponent; let fixture: ComponentFixture<HostComponent>; // WARNING: Chance of cross-test pollution // CodeComponent injects PrettyPrintService // Once PrettyPrintService runs once _anywhere_, its ctor loads `prettify.js` // which sets `window['prettyPrintOne']` // That global survives these tests unless // we take strict measures to wipe it out in the `afterAll` // and make sure THAT runs after the tests by making component creation async afterAll(() => { delete window['prettyPrint']; delete window['prettyPrintOne']; }); beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ MdSnackBarModule, NoopAnimationsModule ], declarations: [ CodeComponent, HostComponent ], providers: [ PrettyPrinter, CopierService, {provide: Logger, useClass: TestLogger } ] }) .compileComponents(); })); // Must be async because // CodeComponent creates PrettyPrintService which async loads `prettify.js`. // If not async, `afterAll` finishes before tests do! beforeEach(async(() => { fixture = TestBed.createComponent(HostComponent); hostComponent = fixture.componentInstance; codeComponentDe = fixture.debugElement.children[0]; codeComponent = codeComponentDe.componentInstance; fixture.detectChanges(); })); it('should create CodeComponent', () => { expect(codeComponentDe.name).toBe('aio-code', 'selector'); expect(codeComponent).toBeTruthy('CodeComponent'); }); describe('pretty printing', () => { it('should format a one-line code sample', () => { // 'pln' spans are a tell-tale for syntax highlighing const spans = codeComponentDe.nativeElement.querySelectorAll('span.pln'); expect(spans.length).toBeGreaterThan(0, 'formatted spans'); }); function hasLineNumbers() { // presence of `<li>`s are a tell-tale for line numbers return 0 < codeComponentDe.nativeElement.querySelectorAll('li').length; } it('should format a one-line code sample without linenums by default', () => { expect(hasLineNumbers()).toBe(false); }); it('should add line numbers to one-line code sample when linenums set true', () => { hostComponent.linenums = 'true'; fixture.detectChanges(); expect(hasLineNumbers()).toBe(true); }); it('should format a small multi-line code without linenums by default', () => { hostComponent.code = smallMultiLineCode; fixture.detectChanges(); expect(hasLineNumbers()).toBe(false); }); it('should add line numbers to a big multi-line code by default', () => { hostComponent.code = bigMultiLineCode; fixture.detectChanges(); expect(hasLineNumbers()).toBe(true); }); it('should format big multi-line code without linenums when linenums set false', () => { hostComponent.linenums = false; hostComponent.code = bigMultiLineCode; fixture.detectChanges(); expect(hasLineNumbers()).toBe(false); }); }); describe('whitespace handling', () => { it('should remove common indentation from the code before rendering', () => { hostComponent.linenums = false; hostComponent.code = ' abc\n let x = text.split(\'\\n\');\n ghi\n\n jkl\n'; fixture.detectChanges(); const codeContent = codeComponentDe.nativeElement.querySelector('code').innerText; expect(codeContent).toEqual('abc\n let x = text.split(\'\\n\');\nghi\n\njkl'); }); it('should trim whitespace from the code before rendering', () => { hostComponent.linenums = false; hostComponent.code = '\n\n\n' + smallMultiLineCode + '\n\n\n'; fixture.detectChanges(); const codeContent = codeComponentDe.nativeElement.querySelector('code').innerText; expect(codeContent).toEqual(codeContent.trim()); }); it('should trim whitespace from code before computing whether to format linenums', () => { hostComponent.code = '\n\n\n' + hostComponent.code + '\n\n\n'; fixture.detectChanges(); // `<li>`s are a tell-tale for line numbers const lis = codeComponentDe.nativeElement.querySelectorAll('li'); expect(lis.length).toBe(0, 'should be no linenums'); }); }); describe('error message', () => { function getErrorMessage() { const missing: HTMLElement = codeComponentDe.nativeElement.querySelector('.code-missing'); return missing ? missing.innerText : null; } it('should not display "code-missing" class when there is some code', () => { fixture.detectChanges(); expect(getErrorMessage()).toBeNull('should not have element with "code-missing" class'); }); it('should display error message when there is no code (after trimming)', () => { hostComponent.code = ' \n '; fixture.detectChanges(); expect(getErrorMessage()).toContain('missing'); }); it('should show path and region in missing-code error message', () => { hostComponent.code = ' \n '; hostComponent.path = 'fizz/buzz/foo.html'; hostComponent.region = 'something'; fixture.detectChanges(); expect(getErrorMessage()).toMatch(/for[\s\S]fizz\/buzz\/foo\.html#something$/); }); it('should show path only in missing-code error message when no region', () => { hostComponent.code = ' \n '; hostComponent.path = 'fizz/buzz/foo.html'; fixture.detectChanges(); expect(getErrorMessage()).toMatch(/for[\s\S]fizz\/buzz\/foo\.html$/); }); it('should show simple missing-code error message when no path/region', () => { hostComponent.code = ' \n '; fixture.detectChanges(); expect(getErrorMessage()).toMatch(/missing.$/); }); }); describe('copy button', () => { it('should call copier service when clicked', () => { const copierService: CopierService = TestBed.get(CopierService); const spy = spyOn(copierService, 'copyText'); const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement; expect(spy.calls.count()).toBe(0, 'before click'); button.click(); expect(spy.calls.count()).toBe(1, 'after click'); }); it('should copy code text when clicked', () => { const copierService: CopierService = TestBed.get(CopierService); const spy = spyOn(copierService, 'copyText'); const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement; button.click(); expect(spy.calls.argsFor(0)[0]).toEqual(oneLineCode, 'after click'); }); it('should display a message when copy succeeds', () => { const snackBar: MdSnackBar = TestBed.get(MdSnackBar); const copierService: CopierService = TestBed.get(CopierService); spyOn(snackBar, 'open'); spyOn(copierService, 'copyText').and.returnValue(true); const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement; button.click(); expect(snackBar.open).toHaveBeenCalledWith('Code Copied', '', { duration: 800 }); }); it('should display an error when copy fails', () => { const snackBar: MdSnackBar = TestBed.get(MdSnackBar); const copierService: CopierService = TestBed.get(CopierService); spyOn(snackBar, 'open'); spyOn(copierService, 'copyText').and.returnValue(false); const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement; button.click(); expect(snackBar.open).toHaveBeenCalledWith('Copy failed. Please try again!', '', { duration: 800 }); }); }); }); //// Test helpers //// // tslint:disable:member-ordering @Component({ selector: 'aio-host-comp', template: ` <aio-code md-no-ink [code]="code" [language]="language" [linenums]="linenums" [path]="path" [region]="region"></aio-code> ` }) class HostComponent { code = oneLineCode; language: string; linenums: boolean | number | string; path: string; region: string; } class TestLogger { log = jasmine.createSpy('log'); error = jasmine.createSpy('error'); }
aio/src/app/embedded/code/code.component.spec.ts
1
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.7772669196128845, 0.031291309744119644, 0.0001673650840530172, 0.0001733114622766152, 0.15227165818214417 ]
{ "id": 3, "code_window": [ " language: string;\n", " linenums: boolean | number;\n", " path: string;\n", " region: string;\n", " title: string;\n", "\n", " constructor(private elementRef: ElementRef) {\n", " const element = this.elementRef.nativeElement;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " hideCopy: boolean;\n" ], "file_path": "aio/src/app/embedded/code/code-example.component.ts", "type": "add", "edit_start_line_idx": 30 }
<div class="resources-container"> <div class="l-flex--column"> <div class="showcase" *ngFor="let category of categories"> <header class="c-resource-header"> <a class="h-anchor-offset" id="{{category.id}}"></a> <h2>{{category.title}}</h2> </header> <div class="shadow-1"> <div *ngFor="let subCategory of category.subCategories"> <a class="h-anchor-offset" id="{{subCategory.id}}"></a> <h3 class="subcategory-title">{{subCategory.title}}</h3> <div *ngFor="let resource of subCategory.resources"> <div class="c-resource" *ngIf="resource.rev"> <a class="l-flex--column resource-row-link" target="_blank" [href]="resource.url"> <div> <h4>{{resource.title}}</h4> <p class="resource-description">{{resource.desc || 'No Description'}}</p> </div> </a> </div> </div> </div> </div> </div> </div> </div>
aio/src/app/embedded/resource/resource-list.component.html
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.0001752704702084884, 0.00017068198940251023, 0.00016825344937387854, 0.00016852206317707896, 0.000003246394953748677 ]
{ "id": 3, "code_window": [ " language: string;\n", " linenums: boolean | number;\n", " path: string;\n", " region: string;\n", " title: string;\n", "\n", " constructor(private elementRef: ElementRef) {\n", " const element = this.elementRef.nativeElement;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " hideCopy: boolean;\n" ], "file_path": "aio/src/app/embedded/code/code-example.component.ts", "type": "add", "edit_start_line_idx": 30 }
// #docregion 'use strict'; // Define the `phonecatApp` AngularJS module angular.module('phonecatApp', [ 'ngAnimate', 'ngRoute', 'core', 'phoneDetail', 'phoneList', ]);
aio/content/examples/upgrade-phonecat-2-hybrid/app/app.module.ajs.ts
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.0001791304093785584, 0.00017591641517356038, 0.00017270242096856236, 0.00017591641517356038, 0.0000032139942049980164 ]
{ "id": 3, "code_window": [ " language: string;\n", " linenums: boolean | number;\n", " path: string;\n", " region: string;\n", " title: string;\n", "\n", " constructor(private elementRef: ElementRef) {\n", " const element = this.elementRef.nativeElement;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " hideCopy: boolean;\n" ], "file_path": "aio/src/app/embedded/code/code-example.component.ts", "type": "add", "edit_start_line_idx": 30 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {NgModule} from '@angular/core'; import {ServerModule} from '@angular/platform-server'; import {HelloWorldModule} from './app'; import {HelloWorldComponent} from './hello-world.component'; @NgModule({ bootstrap: [HelloWorldComponent], imports: [HelloWorldModule, ServerModule], }) export class HelloWorldServerModule { }
packages/platform-server/integrationtest/src/helloworld/app.server.ts
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.00017831346485763788, 0.00017604447202757, 0.00017274689162150025, 0.00017707304505165666, 0.000002386093683526269 ]
{ "id": 4, "code_window": [ " this.linenums = element.getAttribute('linenums');\n", " this.path = element.getAttribute('path') || '';\n", " this.region = element.getAttribute('region') || '';\n", " this.title = element.getAttribute('title') || '';\n", " }\n", "\n", " ngOnInit() {\n", " // The `codeExampleContent` property is set by the DocViewer when it builds this component.\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.hideCopy = element.getAttribute('hideCopy') === 'true';\n" ], "file_path": "aio/src/app/embedded/code/code-example.component.ts", "type": "add", "edit_start_line_idx": 39 }
import { Component, ElementRef, ViewChild, OnChanges, OnDestroy, Input } from '@angular/core'; import { Logger } from 'app/shared/logger.service'; import { PrettyPrinter } from './pretty-printer.service'; import { CopierService } from 'app/shared/copier.service'; import { MdSnackBar } from '@angular/material'; const originalLabel = 'Copy Code'; const copiedLabel = 'Copied!'; const defaultLineNumsCount = 10; // by default, show linenums over this number /** * Formatted Code Block * * Pretty renders a code block, used in the docs and API reference by the code-example and * code-tabs embedded components. * It includes a "copy" button that will send the content to the clipboard when clicked * * Example usage: * * ``` * <aio-code * [code]="variableContainingCode" * [language]="ts" * [linenums]="true" * [path]="ts-to-js/ts/src/app/app.module.ts" * [region]="ng2import"> * </aio-code> * ``` */ @Component({ selector: 'aio-code', template: ` <pre class="prettyprint lang-{{language}}"> <button *ngIf="code" class="material-icons copy-button" (click)="doCopy()">content_copy</button> <code class="animated fadeIn" #codeContainer></code> </pre> ` }) export class CodeComponent implements OnChanges { /** * The code to be formatted, this should already be HTML encoded */ @Input() code: string; /** * The language of the code to render * (could be javascript, dart, typescript, etc) */ @Input() language: string; /** * Whether to display line numbers: * - false: don't display * - true: do display * - number: do display but start at the given number */ @Input() linenums: boolean | number | string; /** * path to the source of the code being displayed */ @Input() path: string; /** * region of the source of the code being displayed */ @Input() region: string; /** * The element in the template that will display the formatted code */ @ViewChild('codeContainer') codeContainer: ElementRef; constructor( private snackbar: MdSnackBar, private pretty: PrettyPrinter, private copier: CopierService, private logger: Logger) {} ngOnChanges() { this.code = this.code && leftAlign(this.code); if (!this.code) { const src = this.path ? this.path + (this.region ? '#' + this.region : '') : ''; const srcMsg = src ? ` for<br>${src}` : '.'; this.setCodeHtml(`<p class="code-missing">The code sample is missing${srcMsg}</p>`); return; } const linenums = this.getLinenums(); this.setCodeHtml(this.code); // start with unformatted code this.pretty.formatCode(this.code, this.language, linenums).subscribe( formattedCode => this.setCodeHtml(formattedCode), err => { /* ignore failure to format */ } ); } private setCodeHtml(formattedCode: string) { // **Security:** `codeExampleContent` is provided by docs authors and as such its considered to // be safe for innerHTML purposes. this.codeContainer.nativeElement.innerHTML = formattedCode; } doCopy() { // We take the innerText because we don't want it to be HTML encoded const code = this.codeContainer.nativeElement.innerText; if (this.copier.copyText(code)) { this.logger.log('Copied code to clipboard:', code); // success snackbar alert this.snackbar.open('Code Copied', '', { duration: 800, }); } else { this.logger.error('ERROR copying code to clipboard:', code); // failure snackbar alert this.snackbar.open('Copy failed. Please try again!', '', { duration: 800, }); } } getLinenums() { const linenums = typeof this.linenums === 'boolean' ? this.linenums : this.linenums === 'true' ? true : this.linenums === 'false' ? false : typeof this.linenums === 'string' ? parseInt(this.linenums, 10) : this.linenums; // if no linenums, enable line numbers if more than one line return linenums == null || linenums === NaN ? (this.code.match(/\n/g) || []).length > defaultLineNumsCount : linenums; } } function leftAlign(text) { let indent = Number.MAX_VALUE; const lines = text.split('\n'); lines.forEach(line => { const lineIndent = line.search(/\S/); if (lineIndent !== -1) { indent = Math.min(lineIndent, indent); } }); return lines.map(line => line.substr(indent)).join('\n').trim(); }
aio/src/app/embedded/code/code.component.ts
1
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.006986118387430906, 0.0012543955817818642, 0.00016403397603426129, 0.00017360199126414955, 0.0019350708462297916 ]
{ "id": 4, "code_window": [ " this.linenums = element.getAttribute('linenums');\n", " this.path = element.getAttribute('path') || '';\n", " this.region = element.getAttribute('region') || '';\n", " this.title = element.getAttribute('title') || '';\n", " }\n", "\n", " ngOnInit() {\n", " // The `codeExampleContent` property is set by the DocViewer when it builds this component.\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.hideCopy = element.getAttribute('hideCopy') === 'true';\n" ], "file_path": "aio/src/app/embedded/code/code-example.component.ts", "type": "add", "edit_start_line_idx": 39 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Component, NgModule} from '@angular/core'; import {RouterModule} from '@angular/router'; @Component({selector: 'feature-component', template: 'foo.html'}) export class FeatureComponent { } @NgModule({ declarations: [FeatureComponent], imports: [RouterModule.forChild([ {path: '', component: FeatureComponent}, {path: 'd', loadChildren: './default.module'} { path: 'e', loadChildren: 'feature/feature.module#FeatureModule' } ])] }) export class Feature2Module { }
packages/compiler-cli/integrationtest/ngtools_src/feature2/feature2.module.ts
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.00017502313130535185, 0.00017008963914122432, 0.00016385575872845948, 0.00017139002738986164, 0.000004650864411814837 ]